forked from dherman/es4
-
Notifications
You must be signed in to change notification settings - Fork 1
/
native.sml
1138 lines (999 loc) · 37.1 KB
/
native.sml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(* -*- mode: sml; mode: font-lock; tab-width: 4; insert-tabs-mode: nil; indent-tabs-mode: nil -*- *)
(*
* The following licensing terms and conditions apply and must be
* accepted in order to use the Reference Implementation:
*
* 1. This Reference Implementation is made available to all
* interested persons on the same terms as Ecma makes available its
* standards and technical reports, as set forth at
* http://www.ecma-international.org/publications/.
*
* 2. All liability and responsibility for any use of this Reference
* Implementation rests with the user, and not with any of the parties
* who contribute to, or who own or hold any copyright in, this Reference
* Implementation.
*
* 3. THIS REFERENCE IMPLEMENTATION IS PROVIDED BY THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* End of Terms and Conditions
*
* Copyright (c) 2007 Adobe Systems Inc., The Mozilla Foundation, Opera
* Software ASA, and others.
*)
(* Host functions provided to implement standard library. *)
structure Native = struct
(* Local tracing machinery *)
val doTrace = ref false
fun trace ss = if (!doTrace) then LogErr.log ("[native] " :: ss) else ()
fun error ss = LogErr.hostError ss
fun rawNth (vals:Mach.VALUE list)
(n:int)
: Mach.VALUE =
if n >= length vals
then error ["trying to fetch arg #",
(Int.toString n),
" from arg list of length ",
(Int.toString (length vals))]
else
List.nth (vals, n)
fun nthAsA (f:Mach.VALUE -> 'a)
(vals:Mach.VALUE list)
(n:int)
: 'a =
f (rawNth vals n)
fun nthAsObj (vals:Mach.VALUE list)
(n:int)
: Mach.OBJECT =
let
fun f Mach.UndefinedValue = error ["Wanted ObjectValue, got UndefinedValue"]
| f Mach.NullValue = error ["Wanted ObjectValue, got NullValue"]
| f (Mach.ObjectValue ob) = ob
in
nthAsA f vals n
end
fun nthAsObjAndClass (vals:Mach.VALUE list)
(n:int)
: (Mach.OBJECT * Ast.CLASS) =
let
val obj = nthAsObj vals n
val c = Mach.needClass (Mach.ObjectValue obj)
in
(obj, c)
end
fun nthAsUstr (vals:Mach.VALUE list)
(n:int)
: Ustring.STRING =
Mach.needString (rawNth vals n)
fun nthAsName (regs:Mach.REGS)
(vals:Mach.VALUE list)
(n:int)
: Ast.NAME =
let
val v = rawNth vals n
in
Eval.needNameOrString regs v
end
fun nthAsFn (vals:Mach.VALUE list)
(n:int)
: Mach.CLOSURE =
Mach.needFunction (rawNth vals n)
fun nthAsInt (regs:Mach.REGS)
(vals:Mach.VALUE list)
(n:int)
: Int32.int =
Eval.doubleToInt (Eval.toInt32 regs (rawNth vals n))
fun nthAsUInt (regs:Mach.REGS)
(vals:Mach.VALUE list)
(n:int)
: Word32.word =
Eval.doubleToWord (Eval.toUInt32 regs (rawNth vals n))
fun nthAsDouble (vals:Mach.VALUE list)
(n:int)
: Real64.real =
Mach.needDouble (rawNth vals n)
fun nthAsBool (vals:Mach.VALUE list)
(n:int)
: bool =
Mach.needBoolean (rawNth vals n)
fun propQuery (regs:Mach.REGS)
(vals:Mach.VALUE list)
(f:(Mach.PROPERTY_MAP -> Ast.NAME -> bool))
: Mach.VALUE =
let
val Mach.Object { propertyMap, ...} = nthAsObj vals 0
val n = nthAsName regs vals 1
in
Eval.newBoolean regs (f propertyMap n)
end
(*
* Given a class object, run the standard object-construction
* protocol for it (and its base classes, initializers, settings,
* ctors). Return the resulting instance, always an Object!
*
* helper native function construct(cls:Class!, args:[*]) : Object!;
*)
fun construct (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val (obj, cls) = nthAsObjAndClass vals 0
val args = Eval.arrayToList regs (nthAsObj vals 1)
in
Eval.constructClassInstance regs obj cls args
end
(*
* Retrieve the [[Class]] property of o
*
* informative native function getClassName(o : Object!) : string;
*)
fun getClassName (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val Mach.Object { tag, ... } = nthAsObj vals 0
in
Eval.newString regs (#id (Mach.nominalBaseOfTag tag))
end
(*
* Meta-object interface:
* Retrieve the class of an object instance.
*
* helper native function getClassOfObject(o: Object!) : Class;
*)
fun getClassOfObject (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val Mach.Object { tag, ... } = nthAsObj vals 0
in
Eval.getPropertyValue regs (#global regs) (Mach.nominalBaseOfTag tag)
end
(*
* Meta-object interface:
* Retrieve the possibly null base class of cls.
*
* helper native function getSuperClass(cls : Class!) : Class;
*)
fun getSuperClass (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val (classObj, Ast.Class { extends, ... }) = nthAsObjAndClass vals 0
val regs = Eval.withScope regs (Eval.getClassScope regs classObj)
in
(case extends of
SOME ty => Mach.ObjectValue
(Eval.getClassObjOfInstanceType regs (Eval.evalTy regs ty))
| _ => Mach.NullValue)
end
(*
* Meta-object interface:
* Retrieve the possibly null kth implemented interface of cls.
*
* helper native function getClassExtends(cls : Class!, k: uint) : Class;
*)
fun getImplementedInterface (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val cls = Mach.needClass (rawNth vals 0)
val k = Word32.toInt (nthAsUInt regs vals 1)
val Ast.Class { implements, ... } = cls
in
if k >= (List.length implements) then
Mach.NullValue
else
Mach.ObjectValue
(Eval.getInstanceInterface regs
(Eval.evalTy
regs (List.nth(implements, k))))
end
(*
* Meta-object interface:
* Retrieve the possibly null kth base interface of iface.
*
* helper native function getSuperInterface(iface: Interface!, k: uint): Interface;
*)
fun getSuperInterface (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val Ast.Interface { extends, ... } = Mach.needInterface (rawNth vals 0)
val k = Word32.toInt(nthAsUInt regs vals 1)
in
if k >= (List.length extends) then
Mach.NullValue
else
Mach.ObjectValue
(Eval.getInstanceInterface
regs (Eval.evalTy
regs (List.nth(extends, k))))
end
(*
* Retrieve the array of enumerable properties of o, in property creation order.
*
* helper native function getEnumerableIds(o : Object) : iterator::EnumerableIdArray;
*)
fun getEnumerableIds (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val v = rawNth vals 0
in
case v of
Mach.UndefinedValue => Eval.newArray regs []
| Mach.NullValue => Eval.newArray regs []
| Mach.ObjectValue (Mach.Object { propertyMap, ... }) =>
let
val { bindings, ... } = !propertyMap
val bindingList = NameMap.listItemsi bindings
fun select (name, { seq, prop }) =
case prop of
{ state = Mach.ValueProperty _,
attrs = { enumerable = true, removable, writable, fixed },
ty } => SOME (name, seq)
| _ => NONE
val filteredList = List.mapPartial select bindingList
val bindingArray = Array.fromList filteredList
fun sort ((_, seq1), (_, seq2)) = Int.compare (seq2,seq1)
val _ = ArrayQSort.sort sort bindingArray
fun project ((name:Ast.NAME, _), (curr:Mach.VALUE list)) =
(* FIXME: what about numeric? string? *)
(Eval.newName regs name) :: curr
val vals = Array.foldl project [] bindingArray
(*val iterator = Eval.needObj regs (Eval.newArray regs vals)*)
in
Eval.newArray regs vals
end
end
(*
* Retrieve the possibly null [[Prototype]] property of o
*
* helper native function getPrototype(o : Object!) : Object;
*)
fun getPrototype (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val Mach.Object { proto, ... } = nthAsObj vals 0
in
proto
end
(*
* Return true iff o has a local property named by p.
*
* helper native function hasOwnProperty(o : Object!, p : string) : Boolean;
*)
fun hasOwnProperty (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
propQuery regs vals Mach.hasProp
(*
* Return true if the property p does exists locally on o and its
* Enumerable bit is set
*
* helper native function getPropertyIsEnumerable(o : Object!, p : string) : Boolean;
*)
fun getPropertyIsEnumerable (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
fun f propertyMap n =
if Mach.hasProp propertyMap n
then (#enumerable (#attrs (Mach.getProp propertyMap n)))
else false
in
propQuery regs vals f
end
(*
* Return true if the property p does exists locally on o and its
* removable bit is set
*
* helper native function getPropertyIsRemovable(o : Object!, p : string) : Boolean;
*)
fun getPropertyIsRemovable (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
fun f propertyMap n =
if Mach.hasProp propertyMap n
then (#removable (#attrs (Mach.getProp propertyMap n)))
else false
in
propQuery regs vals f
end
(* Provided that the property p exists locally on o, set its Enumerable
* flag according to f. If the property p does not exist locally on
* o, it does nothing.
*
* helper native function setPropertyIsEnumerable(o : Object!, p : string, f : Boolean) : void;
*)
fun setPropertyIsEnumerable (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val Mach.Object { propertyMap, ...} = nthAsObj vals 0
val n = nthAsName regs vals 1
val b = nthAsBool vals 2
in
Mach.setPropEnumerable propertyMap n b;
Mach.UndefinedValue
end
fun isPrimitive (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
Eval.newBoolean regs (Eval.isPrimitive (rawNth vals 0))
fun toPrimitive (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val v = rawNth vals 0
val hint = rawNth vals 1
in
if Mach.isString hint
then Eval.toPrimitive regs v (Eval.toUstring regs hint)
else Eval.toPrimitive regs v Ustring.empty
end
fun defaultValue (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val obj = nthAsObj vals 0
val hint = nthAsUstr vals 1
in
Eval.defaultValue regs obj hint
end
(*
* Given a function object, a this object, and an array of argument
* values, call the function with the this object and arguments.
*
* helper native function apply(fn : Function!, t : Object!, args : Array) : *;
*)
fun apply (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val fnObj = nthAsObj vals 0
val thisObj = nthAsObj vals 1
val argsObj = nthAsObj vals 2
val argsList = Eval.arrayToList regs argsObj
in
Eval.evalCallByObj (Eval.withThis regs thisObj) fnObj argsList
end
fun fnLength (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val Mach.Object { tag, ... } = nthAsObj vals 0
val len =
case tag of
Mach.PrimitiveTag (Mach.FunctionPrimitive ({ func = Ast.Func { ty, ... }, ...}))
=> AstQuery.minArgsOfFuncTy ty
| Mach.PrimitiveTag (Mach.NativeFunctionPrimitive {length, ...}) => length
| _ => error ["wrong kind of object to fnLength"]
in
Eval.newDouble regs (Real64.fromInt len)
end
fun genSend (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val Mach.Object { tag, ... } = nthAsObj vals 0
val arg = rawNth vals 1
in
case tag of
Mach.PrimitiveTag (Mach.GeneratorPrimitive gen) => Eval.sendToGenerator regs gen arg
| _ => error ["wrong kind of object to genSend"]
end
fun genThrow (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val Mach.Object { tag, ... } = nthAsObj vals 0
val arg = rawNth vals 1
in
case tag of
Mach.PrimitiveTag (Mach.GeneratorPrimitive gen) => Eval.throwToGenerator regs gen arg
| _ => error ["wrong kind of object to genSend"]
end
fun genClose (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val Mach.Object { tag, ... } = nthAsObj vals 0
in
case tag of
Mach.PrimitiveTag (Mach.GeneratorPrimitive gen) => Eval.closeGenerator regs gen
| _ => error ["wrong kind of object to genSend"];
Mach.UndefinedValue
end
fun argsLength (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val obj = rawNth vals 0
val scope = Mach.needArguments obj
val temps = Eval.getScopeTemps scope
in
Eval.newDouble regs (Real64.fromInt (length (!temps)))
end
fun getArg (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val obj = rawNth vals 0
val n = Int32.toInt (nthAsInt regs vals 1)
val scope = Mach.needArguments obj
val temps = Eval.getScopeTemps scope
in
Mach.getTemp temps n
end
fun setArg (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
(* FIXME: Implement. *)
Mach.UndefinedValue
(* Given a string and a position in that string, return the
* numeric value of the character at that position in the
* string.
*
* informative native function charCodeAt(s : string, pos : uint) : uint;
*)
fun charCodeAt (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val s = nthAsUstr vals 0
val i = nthAsUInt regs vals 1
in
Eval.newDouble
regs
(Real64.fromInt
(Ustring.charCodeAt s (Word32.toInt i)))
end
(*
* Given a numeric character value, return a string of length 1
* whose element 0 is the character with that same value.
*
* informative native function fromCharCode(ch : uint) : string;
*)
fun fromCharCode (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val i = nthAsUInt regs vals 0
in
Eval.newString
regs
(Ustring.fromCharCode
(Word32.toInt
(Word32.andb(i, 0wx1FFFFF))))
end
(*
* Given a string object, return the number of characters in the
* string.
*
* informative native function stringLength(s : string) : uint;
*)
fun stringLength (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val s = nthAsUstr vals 0
in
Eval.newDouble regs (Real64.fromInt (Ustring.stringLength s))
end
(*
* Given two string objects A and B , return a new string object
* containing the characters from A followed by the characters
* from B.
*
* informative native function stringAppend(a : string, b : string) : string;
*)
fun stringAppend (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val a = nthAsUstr vals 0
val b = nthAsUstr vals 1
in
Eval.newString regs (Ustring.stringAppend a b)
end
(*
* 15.1.2.1
* intrinsic native function eval(x)
*)
fun eval (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
if length vals = 0
then Mach.UndefinedValue
else
let
val x = rawNth vals 0
in
if not (Mach.isString x)
then x
else
let
val s = nthAsUstr vals 0
val lines = [Ustring.sourceFromUstring s] (* FIXME: split lines *)
(*
* FIXME: catch parse errors and throw a user SyntaxError
* exception here once natives grow the ability to throw
* user exceptions.
*)
fun str s = Eval.newString regs (Ustring.fromString s)
val prog = Parser.parseLines lines
handle LogErr.LexError le => raise Eval.ThrowException (str le)
| LogErr.ParseError pe => raise Eval.ThrowException (str pe)
val (rootFixtureMap, prog) = (Defn.defProgram (#rootFixtureMap regs) prog (Mach.getLangEd regs)
handle
LogErr.DefnError de => raise Eval.ThrowException (str de))
val _ = (Verify.verifyProgram rootFixtureMap false prog
handle
LogErr.VerifyError ve => raise Eval.ThrowException (str ve))
val regs = Eval.withRootFixtureMap regs rootFixtureMap
val regs = Eval.withScope regs (Eval.getGlobalScope regs)
in
(*
* FIXME: maybe don't want to permit the full set of
* program constructs (classes?) so possibly set a flag in defn's env
* that says we're in an eval context, and should only permit a
* subset of definitions.
*)
Eval.evalProgram regs prog
handle
LogErr.NameError ne => raise Eval.ThrowException (str ne)
| LogErr.EvalError ee => raise Eval.ThrowException (str ee)
end
end
(*
* 15.1.2.3
* intrinsic native function parseFloat(string:string);
*)
fun parseFloat (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
LogErr.unimplError ["intrinsic::parseFloat"]
(*
* intrinsic function get (obj: Object!, name: string) : *
*)
fun get (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val obj = (nthAsObj vals 0)
val name = (nthAsName regs vals 1)
in
Eval.getPropertyValueOrVirtual regs obj name false
end
(*
* intrinsic function set (obj: Object!, name: string, val: * ) : void
*)
fun set (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
(Eval.setPropertyValueOrVirtual
regs
(nthAsObj vals 0)
(nthAsName regs vals 1)
(rawNth vals 2)
false;
Mach.UndefinedValue)
(*
* informative native function objectHash ( ob:Object! ) : uint;
*)
fun objectHash (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val Mach.Object { ident, ... } = nthAsObj vals 0
in
Eval.newDouble regs (Real64.fromInt ident)
end
(*
* Return the current time in milliseconds since January 1 1970 00:00:00 UTC.
*
* static intrinsic native function now() : double;
*)
fun now (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
Eval.newDouble regs
(Real.realFloor
((Time.toReal (Time.now())) * 1000.0))
val random_state = Random.rand (37, 79)
fun random (regs:Mach.REGS)
(v:Mach.VALUE list)
: Mach.VALUE =
Eval.newDouble regs (Random.randReal random_state)
fun unaryDoubleFn (f:(Real64.real -> Real64.real)) :
(Mach.REGS -> (Mach.VALUE list) -> Mach.VALUE) =
fn regs =>
fn vals => if length vals = 0
then Eval.newDouble regs (0.0/0.0)
else Eval.newDouble regs (f (Eval.toDouble (rawNth vals 0)))
fun unaryDecimalFn (f:(Decimal.DEC -> Decimal.DEC)) :
(Mach.REGS -> (Mach.VALUE list) -> Mach.VALUE) =
fn regs =>
fn vals => if length vals = 0
then Eval.newDecimal regs Decimal.NaN
else Eval.newDecimal regs (f (Eval.toDecimal (rawNth vals 0)))
fun binaryDoubleFn (f:((Real64.real * Real64.real) -> Real64.real)) :
(Mach.REGS -> (Mach.VALUE list) -> Mach.VALUE) =
fn regs =>
fn vals => if length vals = 0 orelse length vals = 1
then Eval.newDouble regs (0.0/0.0)
else Eval.newDouble regs (f ((Eval.toDouble (rawNth vals 0)),
(Eval.toDouble (rawNth vals 1))))
fun binaryDecimalFn (f:((Decimal.DEC * Decimal.DEC) -> Decimal.DEC)) :
(Mach.REGS -> (Mach.VALUE list) -> Mach.VALUE) =
fn regs =>
fn vals => if length vals = 0 orelse length vals = 1
then Eval.newDecimal regs Decimal.NaN
else Eval.newDecimal regs (f ((Eval.toDecimal (rawNth vals 0)),
(Eval.toDecimal (rawNth vals 1))))
val ceilDouble = unaryDoubleFn Real64.realCeil
val ceilDecimal = unaryDecimalFn Decimal.ceil
val floorDouble = unaryDoubleFn Real64.realFloor
val floorDecimal = unaryDecimalFn Decimal.floor
val roundDouble = unaryDoubleFn Real64.realRound
val roundDecimal = unaryDecimalFn Decimal.round
val acosDouble = unaryDoubleFn Math.acos
val acosDecimal = unaryDecimalFn Decimal.acos
val asinDouble = unaryDoubleFn Math.asin
val asinDecimal = unaryDecimalFn Decimal.asin
val atanDouble = unaryDoubleFn Math.atan
val atanDecimal = unaryDecimalFn Decimal.atan
val atan2Double = binaryDoubleFn Math.atan2
val atan2Decimal = binaryDecimalFn Decimal.atan2
val cosDouble = unaryDoubleFn Math.cos
val cosDecimal = unaryDecimalFn Decimal.cos
val expDouble = unaryDoubleFn Math.exp
val expDecimal = unaryDecimalFn Decimal.exp
val logDouble = unaryDoubleFn Math.ln
val logDecimal = unaryDecimalFn Decimal.log
val sinDouble = unaryDoubleFn Math.sin
val sinDecimal = unaryDecimalFn Decimal.sin
val sqrtDouble = unaryDoubleFn Math.sqrt
val sqrtDecimal = unaryDecimalFn Decimal.sqrt
val tanDouble = unaryDoubleFn Math.tan
val tanDecimal = unaryDecimalFn Decimal.tan
val powDouble = binaryDoubleFn Math.pow
val powDecimal = binaryDecimalFn Decimal.pow
(* Math.pow in smlnj 110.60 has an error of 3.33e~6 on computing 2^32! *)
val pow = binaryDoubleFn (fn (a,b) =>
if Real64.compare((Real64.realFloor b), b) = EQUAL andalso b >= 0.0 andalso b <= 2147483647.0 then
let fun exponentiate expt =
if expt = 0 then
1.0
else if Int.mod(expt, 2) = 1 then
a * (exponentiate (expt - 1))
else
let val v = exponentiate (expt div 2)
in
v * v
end
in
exponentiate (Real64.floor b)
end
else
Math.pow (a,b))
(* Takes a double and 0u or 1u and returns the high part
* (sign+expt+high bits of significand) or low part (low 32 bits of
* significand), respectively, as an unsigned integer.
*
* Uses LargeInt, among other things. There is an optional library
* in SML for unpacking doubles (PackReal), but it's not supported
* by SML/NJ from what I can tell.
*
* This function is here to support ESC, but it is generally useful
* and it should probably be added to the standard set of builtins.
*)
fun explodeDouble (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let val p1 = nthAsDouble vals 0
val p2 = nthAsUInt regs vals 1
val r = Real64.toManExp p1
val k = Real64.toLargeInt IEEEReal.TO_ZERO ((#man r) * 9007199254740992.0)
fun assemble hi lo =
Eval.wordToDouble (Word32.orb(Word32.<<(Word32.fromLargeInt hi, 0w16), Word32.fromLargeInt lo))
in
Eval.newDouble regs
(if p2 = 0w0 then
let val hi_lo = IntInf.andb(IntInf.~>>(k, 0w32), IntInf.fromInt 65535)
val sign_exp = IntInf.orb(IntInf.fromInt(if p1 < 0.0 then 2048 else 0),
IntInf.fromInt((#exp r) + 1022))
val hi_hi = IntInf.orb(IntInf.<<(sign_exp, 0w4),
IntInf.andb(IntInf.~>>(k, 0w48), IntInf.fromInt 15))
in
assemble hi_hi hi_lo
end
else
let val lo_lo = IntInf.andb(k, IntInf.fromInt 65535)
val lo_hi = IntInf.andb(IntInf.~>>(k, 0w16), IntInf.fromInt 65535)
in
assemble lo_hi lo_lo
end)
end
(* Some helpers not specified in the wiki at the moment. Maybe get rid
* of them eventually? *)
fun print (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
fun printOne v = TextIO.print (Ustring.toAscii (Eval.toUstring regs v))
in
List.app printOne vals;
TextIO.print "\n";
Mach.UndefinedValue
end
fun load (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
fun str s = Eval.newString regs (Ustring.fromString s)
val fname = Ustring.toFilename (nthAsUstr vals 0)
val prog = Parser.parseFile fname
handle LogErr.LexError le => raise Eval.ThrowException (str le)
| LogErr.ParseError pe => raise Eval.ThrowException (str pe)
val (rootFixtureMap, prog) = (Defn.defProgram (#rootFixtureMap regs) prog (Mach.getLangEd regs)
handle
LogErr.DefnError de => raise Eval.ThrowException (str de))
val _ = (Verify.verifyProgram rootFixtureMap false prog
handle
LogErr.VerifyError ve => raise Eval.ThrowException (str ve))
val regs = Eval.withRootFixtureMap regs rootFixtureMap
in
Eval.evalProgram regs prog
handle
LogErr.NameError ne => raise Eval.ThrowException (str ne)
| LogErr.EvalError ee => raise Eval.ThrowException (str ee)
end
fun readFile (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
fun mkReader filename =
let
val stream = TextIO.openIn filename
in
fn _ => case TextIO.inputLine stream of
SOME line => (trace ["read line ", line]; SOME line)
| NONE => (TextIO.closeIn stream; NONE)
end
val fname = Ustring.toFilename (nthAsUstr vals 0)
val reader = mkReader fname
fun readSrc (src: Ustring.SOURCE)
: Ustring.SOURCE =
case reader() of
NONE => src
| SOME newSrc => readSrc (src @ (Ustring.fromSource newSrc))
val str = implode (map Ustring.wcharToChar (readSrc Ustring.emptySource))
in
Eval.newString regs (Ustring.fromString str)
end
fun readHTTP (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val server = Ustring.toAscii (nthAsUstr vals 0)
val port = nthAsUInt regs vals 1
val page = Ustring.toAscii (nthAsUstr vals 2)
val method = Ustring.toAscii (nthAsUstr vals 3)
val headers = Ustring.toAscii (nthAsUstr vals 4)
fun str s = Eval.newString regs (Ustring.fromString s)
val addr = case NetHostDB.getByName server of
SOME ip => INetSock.toAddr (NetHostDB.addr ip, Word32.toInt port)
| NONE => raise Eval.ThrowException (str "unknown host")
val sock = INetSock.TCP.socket ()
fun close () =
Socket.close sock handle OS.SysErr _ => ()
fun throw s = (close(); raise Eval.ThrowException (str s))
val bufSize = 16384
val buf = Word8Array.array (bufSize, Word8.fromInt 0)
fun send s =
Socket.sendVec (sock, Word8VectorSlice.full (Byte.stringToBytes s))
fun recv () =
Socket.recvArr (sock, Word8ArraySlice.full buf)
fun slicePrefix n = Word8ArraySlice.slice (buf, 0, SOME n)
fun sliceSource slice =
let
fun cons (b, ls) = (Char.chr (Word8.toInt b))::ls
val chars = Word8ArraySlice.foldr cons [] slice
in
Ustring.fromSource (String.implode chars)
end
fun reader () : Ustring.SOURCE option =
(case recv () of
0 => NONE
| bytesRead => SOME (sliceSource (slicePrefix bytesRead)))
fun readSrc (chunks:Ustring.SOURCE list)
: Ustring.SOURCE =
(case reader() of
NONE => (close(); List.concat (List.rev chunks))
| SOME chunk => readSrc (chunk::chunks))
in
let
val _ = Socket.connect (sock, addr)
val _ = send (method ^ " " ^ page ^ " HTTP/1.0\r\n")
val _ = send headers
val _ = send "\r\n"
in
str (implode (map Ustring.wcharToChar (readSrc [])))
end
handle OS.SysErr (msg, _) => (close(); throw ("socket error: " ^ msg))
end
fun writeFile (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let val s = Ustring.toAscii (nthAsUstr vals 0)
val filename = Ustring.toFilename (nthAsUstr vals 1)
val out = TextIO.openOut filename
in
TextIO.output(out, s);
TextIO.closeOut out;
Mach.UndefinedValue
end
fun assert (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
if nthAsBool vals 0
then Mach.UndefinedValue
else error ["intrinsic::assert() failed"]
fun typename (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
case hd vals of
Mach.NullValue => Eval.newString regs Ustring.null_
| Mach.UndefinedValue => Eval.newString regs Ustring.undefined_
| Mach.ObjectValue (Mach.Object {tag, ...}) =>
let
val name = Mach.nominalBaseOfTag tag
in
Eval.newString regs (#id name)
end
fun dumpFunc (regs:Mach.REGS)
(vals:Mach.VALUE list)
: Mach.VALUE =
let
val v = rawNth vals 0
in
if Mach.isFunction v
then
case Mach.needPrimitive v of
Mach.FunctionPrimitive { func, ... } => Pretty.ppFunc func
| _ => ()
else
();
Mach.UndefinedValue