-
Notifications
You must be signed in to change notification settings - Fork 8
/
native.sml
1272 lines (1128 loc) · 41.7 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.VAL list)
(n:int)
: Mach.VAL =
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.VAL -> 'a)
(vals:Mach.VAL list)
(n:int)
: 'a =
f (rawNth vals n)
fun nthAsObj (vals:Mach.VAL list)
(n:int)
: Mach.OBJ =
let
fun f Mach.Undef = error ["Wanted Object, got Undef"]
| f Mach.Null = error ["Wanted Object, got Null"]
| f (Mach.Object ob) = ob
in
nthAsA f vals n
end
fun nthAsObjAndCls (vals:Mach.VAL list)
(n:int)
: (Mach.OBJ * Mach.CLS_CLOSURE) =
let
val obj = nthAsObj vals n
val Mach.Obj { magic, ... } = obj
in
case !magic of
SOME (Mach.Class c) => (obj, c)
| _ => error ["Wanted class, got other"]
end
fun nthAsUstr (vals:Mach.VAL list)
(n:int)
: Ustring.STRING =
let
val Mach.Obj { magic, ... } = nthAsObj vals n
in
case !magic of
SOME (Mach.String s) => s
| _ => error ["Wanted string, got other"]
end
fun nthAsName (vals:Mach.VAL list)
(n:int)
: Ast.NAME =
let
val v = rawNth vals n
in
Eval.needNameOrString v
end
fun nthAsFn (vals:Mach.VAL list)
(n:int)
: Mach.FUN_CLOSURE =
let
val Mach.Obj { magic, ... } = nthAsObj vals n
in
case !magic of
SOME (Mach.Function f) => f
| _ => error ["Wanted function, got other"]
end
fun nthAsInt (vals:Mach.VAL list)
(n:int)
: Int32.int =
let
val Mach.Obj { magic, ... } = nthAsObj vals n
in
case !magic of
SOME (Mach.Int n) => n
| _ => error ["Wanted int, got other"]
end
fun nthAsUInt (vals:Mach.VAL list)
(n:int)
: Word32.word =
let
val Mach.Obj { magic, ... } = nthAsObj vals n
in
case !magic of
SOME (Mach.UInt n) => n
| _ => error ["Wanted uint, got other"]
end
fun nthAsDouble (vals:Mach.VAL list)
(n:int)
: Real64.real =
let
val Mach.Obj { magic, ... } = nthAsObj vals n
in
case !magic of
SOME (Mach.Double d) => d
| _ => error ["Wanted double, got other"]
end
fun nthAsBool (vals:Mach.VAL list)
(n:int)
: bool =
let
val Mach.Obj { magic, ... } = nthAsObj vals n
in
case !magic of
SOME (Mach.Boolean b) => b
| _ => error ["Wanted Boolean, got other"]
end
fun nthAsByteArray (vals:Mach.VAL list)
(n:int)
: Word8Array.array =
let
val Mach.Obj { magic, ... } = nthAsObj vals n
in
case !magic of
SOME (Mach.ByteArray b) => b
| _ => error ["Wanted ByteArray, got other"]
end
fun propQuery (vals:Mach.VAL list)
(f:(Mach.PROP_BINDINGS -> Ast.NAME -> bool))
: Mach.VAL =
let
val Mach.Obj { props, ...} = nthAsObj vals 0
val n = nthAsName vals 1
in
Eval.newBoolean (f props n)
end
fun arrayToList (arr:Mach.OBJ)
: Mach.VAL list =
let
val len = Word32.toInt
(Eval.toUInt32
(Eval.getValue arr Name.nons_length))
fun build i vs =
if i < 0
then vs
else
let
val n = Name.nons (Ustring.fromInt i)
val curr = if Eval.hasValue arr n
then Eval.getValue arr n
else Mach.Undef
in
build (i-1) (curr::vs)
end
in
build (len-1) []
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!
*
* magic native function construct(cls:Class!, args:[*]) : Object!;
*)
fun construct (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val (obj, cls) = nthAsObjAndCls vals 0
val args = arrayToList (nthAsObj vals 1)
in
Eval.constructClassInstance obj cls args
end
(*
* Retrieve the [[Class]] property of o
*
* magic native function getClassName(o : Object!) : string;
*)
fun getClassName (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val Mach.Obj { magic, tag, ... } = nthAsObj vals 0
(* FIXME: is this right? *)
val ustr = case !magic of
SOME (Mach.Function _) => Ustring.Function_
| SOME (Mach.NativeFunction _) => Ustring.Function_
| SOME (Mach.String _) => Ustring.String_
| SOME (Mach.Decimal _) => Ustring.Number_
| SOME (Mach.Int _) => Ustring.Number_
| SOME (Mach.UInt _) => Ustring.Number_
| SOME (Mach.Double _) => Ustring.Number_
| SOME (Mach.Boolean _) => Ustring.Boolean_
| _ =>
(case tag of
Mach.ObjectTag _ => Ustring.Object_
| Mach.ArrayTag _ => Ustring.Array_
| Mach.FunctionTag _ => Ustring.Function_
| Mach.ClassTag {ns, id} => id
| Mach.NoTag => Ustring.Object_)
in
Eval.newString ustr
end
(*
* Meta-object interface:
* Retrieve the class of an object instance.
*
* magic native function getClassOfObject(o: Object!) : Class;
*)
fun getClassOfObject (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val Mach.Obj { magic, tag, ... } = nthAsObj vals 0
val globalScope = Eval.getGlobalScope ()
in
(* This is wrong, because eg "Number" is classified as "Double" because it
* stores a double value magically.
case !magic of
SOME (Mach.Function _) => Eval.findVal globalScope Name.nons_Function
| SOME (Mach.NativeFunction _) => Eval.findVal globalScope Name.nons_Function
| SOME (Mach.String _) => Eval.findVal globalScope Name.intrinsic_string
| SOME (Mach.Decimal _) => Eval.findVal globalScope Name.intrinsic_decimal
| SOME (Mach.Int _) => Eval.findVal globalScope Name.intrinsic_int
| SOME (Mach.UInt _) => Eval.findVal globalScope Name.intrinsic_uint
| SOME (Mach.Double _) => Eval.findVal globalScope Name.intrinsic_double
| SOME (Mach.Boolean _) => Eval.findVal globalScope Name.intrinsic_boolean
| _ =>
(case tag of
Mach.ObjectTag _ => Eval.findVal globalScope Name.nons_Object
| Mach.ArrayTag _ => Eval.findVal globalScope Name.nons_Array
| Mach.FunctionTag _ => Eval.findVal globalScope Name.nons_Function
| Mach.ClassTag name => Eval.findVal globalScope name
| Mach.NoTag => Eval.findVal globalScope Name.nons_Object)
*)
case tag of
Mach.ObjectTag _ => Eval.findVal globalScope Name.nons_Object
| Mach.ArrayTag _ => Eval.findVal globalScope Name.nons_Array
| Mach.FunctionTag _ => Eval.findVal globalScope Name.nons_Function
| Mach.ClassTag name => Eval.findVal globalScope name
| Mach.NoTag => Eval.findVal globalScope Name.nons_Object
end
(*
* Meta-object interface:
* Retrieve the possibly null base class of cls.
*
* magic native function getSuperClass(cls : Class!) : Class;
*)
fun getSuperClass (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val { cls, env, ... } = Mach.needClass (rawNth vals 0)
val Ast.Cls { extends, ... } = cls
in
(case extends of
SOME name => Eval.findVal env name
| _ => Mach.Null)
end
(*
* Meta-object interface:
* Retrieve the possibly null kth implemented interface of cls.
*
* magic native function getClassExtends(cls : Class!, k: uint) : Class;
*)
fun getImplementedInterface (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val { cls, env, ... } = Mach.needClass (rawNth vals 0)
val k = Word32.toInt(nthAsUInt vals 1)
val Ast.Cls { implements, ... } = cls
in
if k >= (List.length implements) then
Mach.Null
else
Eval.findVal env (List.nth(implements, k))
end
(*
* Meta-object interface:
* Retrieve the possibly null kth base interface of iface.
*
* magic native function getSuperInterface(iface: Interface!, k: uint): Interface;
*)
fun getSuperInterface (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val { iface, env, ... } = Mach.needInterface (rawNth vals 0)
val k = Word32.toInt(nthAsUInt vals 1)
val Ast.Iface { extends, ... } = iface
in
if k >= (List.length extends) then
Mach.Null
else
Eval.findVal env (List.nth(extends, k))
end
(*
* Retrieve the possibly null [[Prototype]] property of o
*
* magic native function getPrototype(o : Object!) : Object;
*)
fun getPrototype (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val Mach.Obj { proto, ... } = nthAsObj vals 0
in
!proto
end
(*
* Return true iff o has a local property named by p.
*
* magic native function hasOwnProperty(o : Object!, p : string) : Boolean;
*)
fun hasOwnProperty (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
propQuery vals Mach.hasProp
(*
* Return true if the property p does exists locally on o and its
* DontEnum bit is set
*
* magic native function getPropertyIsDontEnum(o : Object!, p : string) : Boolean;
*)
fun getPropertyIsDontEnum (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
fun f props n =
if Mach.hasProp props n
then (#dontEnum (#attrs (Mach.getProp props n)))
else false
in
propQuery vals f
end
(*
* Return true if the property p does exists locally on o and its
* DontDelete bit is set
*
* magic native function getPropertyIsDontDelete(o : Object!, p : string) : Boolean;
*)
fun getPropertyIsDontDelete (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
fun f props n =
if Mach.hasProp props n
then (#dontDelete (#attrs (Mach.getProp props n)))
else false
in
propQuery vals f
end
(* Provided that the property p exists locally on o, set its DontEnum
* flag according to f. If the property p does not exist locally on
* o, it does nothing.
*
* magic native function setPropertyIsDontEnum(o : Object!, p : string, f : Boolean) : void;
*)
fun setPropertyIsDontEnum (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val Mach.Obj { props, ...} = nthAsObj vals 0
val id = nthAsUstr vals 1
val ns = Ast.Internal Ustring.empty
val n = { id = id, ns = ns }
val b = nthAsBool vals 2
in
Mach.setPropDontEnum props n b;
Mach.Undef
end
fun isPrimitive (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
Eval.newBoolean (Eval.isPrimitive (rawNth vals 0))
fun toPrimitive (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val v = rawNth vals 0
val hint = rawNth vals 1
in
if Mach.isString hint
then Eval.toPrimitive v (Eval.toUstring hint)
else Eval.toPrimitive v Ustring.empty
end
fun defaultValue (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val obj = nthAsObj vals 0
val hint = nthAsUstr vals 1
in
Eval.defaultValue obj hint
end
fun convertAndBindMagic (vals:Mach.VAL list)
(cvt:(Mach.VAL -> 'a))
(mag:('a -> Mach.MAGIC))
: Mach.VAL =
let
val ob = nthAsObj vals 0
val v = rawNth vals 1
val p = cvt v
val m = mag p
in
Mach.setMagic ob (SOME m);
Mach.Undef
end
(*
* Given a target object and a value, select a magic representation for
* the value, of the type implied by the function name, and set the
* target's magic slot to that representation.
*
* magic native function bindInt(target : Object!, value : * );
* magic native function bindUInt(target : Object!, value : * );
* magic native function bindBoolean(target : Object!, value : * );
* magic native function bindDouble(target : Object!, value : * );
* magic native function bindDecimal(target : Object!, value : * );
* magic native function bindString(target : Object!, value : * );
*)
fun bindUInt (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
convertAndBindMagic vals (Eval.toUInt32) (Mach.UInt)
fun bindInt (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
convertAndBindMagic vals (Eval.toInt32) (Mach.Int)
fun bindBoolean (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
convertAndBindMagic vals (Eval.toBoolean) (Mach.Boolean)
fun bindDouble (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
convertAndBindMagic vals (Eval.toDouble) (Mach.Double)
fun bindDecimal (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
convertAndBindMagic vals (Eval.toDecimal
Decimal.defaultPrecision
Decimal.defaultRoundingMode) (Mach.Decimal)
fun bindString (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
convertAndBindMagic vals Eval.toUstring Mach.String
fun newBoolean (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
Eval.newBoolean (Eval.toBoolean (rawNth vals 0))
fun newString (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
Eval.newString (Eval.toUstring (rawNth vals 0))
fun newInt (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
Eval.newInt (Eval.toInt32 (rawNth vals 0))
fun newUInt (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
Eval.newUInt (Eval.toUInt32 (rawNth vals 0))
fun newDouble (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
Eval.newDouble (Eval.toDouble (rawNth vals 0))
(*
* Given a function object, a this object, and an array of argument
* values, call the function with the this object and arguments.
*
* magic native function apply(fn : Function!, t : Object!, args : Array) : *;
*)
fun apply (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val fnObj = nthAsObj vals 0
val thisObj = nthAsObj vals 1
val argsObj = nthAsObj vals 2
val argsList = arrayToList argsObj
in
Eval.evalCallExpr (Eval.withThis (Eval.getInitialRegs()) thisObj) fnObj argsList
end
fun fnLength (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val Mach.Obj { magic, ... } = nthAsObj vals 0
val len = case !magic of
SOME (Mach.Function {func=Ast.Func{ty, ...}, ...}) => (length (#params ty))
| SOME (Mach.NativeFunction {length, ...}) => length
| _ => error ["wrong kind of magic to fnLength"]
in
Eval.newUInt (Word32.fromInt len)
end
(* Given a string and a position in that string, return the
* numeric value of the character at that position in the
* string.
*
* magic native function charCodeAt(s : string, pos : uint) : uint;
*)
fun charCodeAt (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val s = nthAsUstr vals 0
val i = nthAsUInt vals 1
in
Eval.newUInt (Word32.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.
*
* magic native function fromCharCode(ch : uint) : string;
*)
fun fromCharCode (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val i = nthAsUInt vals 0
in
Eval.newString (Ustring.fromCharCode (Word32.toInt (Word32.andb(i, 0wx1FFFFF))))
end
(*
* Given a string object, return the number of characters in the
* string.
*
* magic native function stringLength(s : string) : uint;
*)
fun stringLength (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val s = nthAsUstr vals 0
in
Eval.newUInt (Word32.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.
*
* magic native function stringAppend(a : string, b : string) : string;
*)
fun stringAppend (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val a = nthAsUstr vals 0
val b = nthAsUstr vals 1
in
Eval.newString (Ustring.stringAppend a b)
end
(*
* Get the byte at index idx. Unspecified behavior if that index
* does not have data (it's OK to crash the system).
*
* magic native function getByteArrayByte(ba : ByteArray!, idx : uint) : uint;
*)
fun getByteArrayByte (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val b = nthAsByteArray vals 0
val i = nthAsUInt vals 1
in
Eval.newUInt (Word32.fromInt (Word8.toInt (Word8Array.sub (b, (Word32.toInt i)))))
end
(*
* Set the byte at index idx to val, which will be truncated to
* the low 8 bits before being stored.
*
* magic native function setByteArrayByte(ba : ByteArray!, idx : uint, val : uint) : void;
*)
fun setByteArrayByte (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val b = nthAsByteArray vals 0
val i = nthAsUInt vals 1
val v = nthAsUInt vals 2
in
Word8Array.update(b, Word32.toInt i, Word8.fromInt (Word32.toInt v));
Mach.Undef
end
(*
* 15.1.2.1
* intrinsic native function eval(x)
*)
fun eval (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
if length vals = 0
then Mach.Undef
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 (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)
in
(*
* FIXME: maybe don't want to permit the full set of
* program constructs (classes?) so possibly sanitize the
* result of parsing a bit, strip out some sorts of things...
*)
Eval.evalProgram regs (Verify.verifyProgram (Defn.defProgram prog))
handle LogErr.DefnError de => raise Eval.ThrowException (str de)
| LogErr.VerifyError ve => raise Eval.ThrowException (str ve)
| 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.VAL list)
: Mach.VAL =
LogErr.unimplError ["intrinsic::parseFloat"]
(*
* intrinsic function get (obj: Object!, name: string) : *
*)
fun get (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val obj = (nthAsObj vals 0)
val name = (nthAsName vals 1)
fun propNotFound (curr:Mach.OBJ) : Mach.VAL =
Eval.throwRefErr1 ["getting nonexistent property ", LogErr.name name]
in
Eval.getValueOrVirtual obj name false propNotFound
end
(*
* intrinsic function set (obj: Object!, name: string, val: * ) : void
*)
fun set (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
(Eval.setValueOrVirtual
(nthAsObj vals 0)
(nthAsName vals 1)
(rawNth vals 2)
false;
Mach.Undef)
(*
* 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.VAL list)
: Mach.VAL =
Eval.newDouble (Real.realFloor ((Time.toReal (Time.now())) * 1000.0))
val random_state = Random.rand (37, 79)
fun random (regs:Mach.REGS)
(v:Mach.VAL list)
: Mach.VAL =
Eval.newDouble (Random.randReal random_state)
fun unaryDoubleFn (f:(Real64.real -> Real64.real)) :
(Mach.REGS -> (Mach.VAL list) -> Mach.VAL) =
fn regs =>
fn vals => if length vals = 0
then Eval.newDouble (0.0/0.0)
else Eval.newDouble (f (Eval.toDouble (rawNth vals 0)))
fun unaryDecimalFn (f:(Decimal.DEC -> Decimal.DEC)) :
(Mach.REGS -> (Mach.VAL list) -> Mach.VAL) =
fn regs =>
fn vals => if length vals = 0
then Eval.newDecimal Decimal.NaN
else Eval.newDecimal (f (Eval.toDecimal Decimal.defaultPrecision Decimal.defaultRoundingMode (rawNth vals 0)))
fun binaryDoubleFn (f:((Real64.real * Real64.real) -> Real64.real)) :
(Mach.REGS -> (Mach.VAL list) -> Mach.VAL) =
fn regs =>
fn vals => if length vals = 0 orelse length vals = 1
then Eval.newDouble (0.0/0.0)
else Eval.newDouble (f ((Eval.toDouble (rawNth vals 0)),
(Eval.toDouble (rawNth vals 1))))
fun binaryDecimalFn (f:((Decimal.DEC * Decimal.DEC) -> Decimal.DEC)) :
(Mach.REGS -> (Mach.VAL list) -> Mach.VAL) =
fn regs =>
fn vals => if length vals = 0 orelse length vals = 1
then Eval.newDecimal Decimal.NaN
else Eval.newDecimal (f ((Eval.toDecimal Decimal.defaultPrecision Decimal.defaultRoundingMode (rawNth vals 0)),
(Eval.toDecimal Decimal.defaultPrecision Decimal.defaultRoundingMode (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.VAL list)
: Mach.VAL =
let val p1 = nthAsDouble vals 0
val p2 = nthAsUInt vals 1
val r = Real64.toManExp p1
val k = Real64.toLargeInt IEEEReal.TO_ZERO ((#man r) * 9007199254740992.0)
fun assemble hi lo =
Word32.orb(Word32.<<(Word32.fromLargeInt hi, 0w16), Word32.fromLargeInt lo)
in
Eval.newUInt(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.VAL list)
: Mach.VAL =
let
fun printOne v = TextIO.print (Ustring.toAscii (Eval.toUstring v))
in
List.app printOne vals;
TextIO.print "\n";
Mach.Undef
end
fun load (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val fname = Ustring.toFilename (nthAsUstr vals 0)
in
Eval.evalProgram regs (Verify.verifyProgram (Defn.defProgram (Parser.parseFile fname)))
handle x => raise Eval.ThrowException (Eval.newString (Ustring.fromString "error while loading"));
Mach.Undef
end
fun readFile (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
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 (Ustring.fromString(str))
end
fun writeFile (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
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.Undef
end
val bytes : Word8.word list ref = ref []; (*: Word8Array.array ref = ref (Word8Array.fromList []) *)
fun beginBytes (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
(bytes := [ ];
Mach.Undef)
fun pushByte (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let
val u = nthAsUInt vals 0
val b = Word8.fromLarge u
in
bytes := b :: (!bytes);
Mach.Undef
end
fun writeBytes (regs:Mach.REGS)
(vals:Mach.VAL list)
: Mach.VAL =
let