-
Notifications
You must be signed in to change notification settings - Fork 8
/
mach.sml
1254 lines (1075 loc) · 38.3 KB
/
mach.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.
*)
(* "Virtual machine" for executing ES4 code. *)
structure Mach = struct
(* Local tracing machinery *)
val doTrace = ref false
val traceStack = ref false
fun log ss = LogErr.log ("[mach] " :: ss)
fun trace ss = if (!doTrace) then log ss else ()
fun error ss = LogErr.machError ss
fun error0 ss = LogErr.machError ss
structure StrListKey = struct type ord_key = string list val compare = List.collate String.compare end
structure StrListMap = SplayMapFn (StrListKey);
structure NsKey = struct type ord_key = Ast.NAMESPACE val compare = NameKey.cmpNS end
structure NsMap = SplayMapFn (NsKey);
structure NmKey = struct type ord_key = Ast.NAME val compare = NameKey.compare end
structure NmMap = SplayMapFn (NmKey);
structure StrKey = struct type ord_key = Ustring.STRING val compare = NameKey.cmp end
structure StrMap = SplayMapFn (StrKey);
structure Real64Key = struct type ord_key = Real64.real val compare = Real64.compare end
structure Real64Map = SplayMapFn (Real64Key);
fun nameEq (a:Ast.NAME) (b:Ast.NAME) = ((#id a) = (#id b) andalso (#ns a) = (#ns b))
val cachesz = 1024
type ATTRS = { dontDelete: bool,
dontEnum: bool,
readOnly: bool,
isFixed: bool }
datatype VAL = Object of OBJ
| Wrapped of (VAL * Ast.TYPE_EXPR)
| Null
| Undef
and OBJ =
Obj of { ident: OBJ_IDENT,
tag: VAL_TAG,
props: PROP_BINDINGS,
proto: VAL ref,
magic: (MAGIC option) ref }
and VAL_TAG =
ObjectTag of Ast.FIELD_TYPE list
| ArrayTag of Ast.TYPE_EXPR list
| FunctionTag of Ast.FUNC_TYPE
| ClassTag of Ast.INSTANCE_TYPE
| NoTag (*
* NoTag objects are made for scopes and
* temporaries passed as arguments during
* builtin construction.
*)
and OBJ_CACHE =
ObjCache of
{
doubleCache: (OBJ Real64Map.map) ref,
intCache: (OBJ Real64Map.map) ref,
uintCache: (OBJ Real64Map.map) ref,
byteCache: (OBJ Real64Map.map) ref,
nsCache: (OBJ NsMap.map) ref,
nmCache: (OBJ NmMap.map) ref,
strCache: (OBJ StrMap.map) ref
}
and PROFILER =
Profiler of
{
profileMap: (int StrListMap.map) ref, (* = ref StrListMap.empty *)
doProfile: (int option) ref (* = ref NONE *)
}
and SPECIAL_OBJS =
SpecialObjs of
{
classClass : (OBJ option) ref,
interfaceClass : (OBJ option) ref,
namespaceClass : (OBJ option) ref,
objectClass : (OBJ option) ref,
arrayClass : (OBJ option) ref,
functionClass : (OBJ option) ref,
stringClass : (OBJ option) ref,
stringWrapperClass : (OBJ option) ref,
numberClass : (OBJ option) ref,
intClass : (OBJ option) ref,
uintClass : (OBJ option) ref,
byteClass : (OBJ option) ref,
doubleClass : (OBJ option) ref,
decimalClass : (OBJ option) ref,
booleanClass : (OBJ option) ref,
booleanWrapperClass : (OBJ option) ref,
booleanTrue : (OBJ option) ref,
booleanFalse : (OBJ option) ref,
doubleNaN : (OBJ option) ref
}
and FRAME =
Frame of { name: string, args: VAL list }
(*
* Magic is visible only to the interpreter;
* it is not visible to users.
*)
and MAGIC =
Boolean of bool
| Double of Real64.real
| Decimal of Decimal.DEC
| String of Ustring.STRING
| Namespace of Ast.NAMESPACE
| Class of CLS_CLOSURE
| Interface of IFACE_CLOSURE
| Function of FUN_CLOSURE
| Type of Ast.TY
| NativeFunction of NATIVE_FUNCTION
and SCOPE =
Scope of { object: OBJ,
parent: SCOPE option,
temps: TEMPS,
decimal: DECIMAL_CONTEXT,
kind: SCOPE_KIND }
and SCOPE_KIND =
WithScope
| GlobalScope
| InstanceScope
| ActivationScope
| BlockScope
| TypeArgScope
and TEMP_STATE = UninitTemp
| ValTemp of VAL
and PROP_STATE = TypeVarProp
| TypeProp
| UninitProp
| ValProp of VAL
(* One might imagine that namespaces, methods and
* the 'arguments' object in a function can all be stored
* as instances of the classes Namespace, Function and
* Array, respectively. This works in some contexts, but leads
* to feedback loops when constructing the classes Function,
* Namespace and Array themselves. So instead of eagerly instantiating
* such values, we allocate them as the following 3 "lazy"
* property states. If anyone performs a "get" on these property
* states, a Namespace, Function or Array object (respectively) is
* constructed. We then ensure that the Namespace, Function and Array
* constructors, settings and initializers (in the builtins)
* do *not* cause any "get" operations on properties in these states.
*
* FIXME: The 'arguments' object can't be an array.
*)
| NamespaceProp of Ast.NAMESPACE
| MethodProp of FUN_CLOSURE
| ValListProp of VAL list
| NativeFunctionProp of NATIVE_FUNCTION
| VirtualValProp of
{ getter: FUN_CLOSURE option,
setter: FUN_CLOSURE option }
and AUX =
Aux of
{
(*
* Auxiliary machine/eval data structures, not exactly
* spec-normative, but important! Embedded in REGS.
*)
booting: bool ref,
specials: SPECIAL_OBJS,
stack: FRAME list ref,
objCache: OBJ_CACHE,
profiler: PROFILER
}
withtype FUN_CLOSURE =
{ func: Ast.FUNC,
this: OBJ option,
env: SCOPE }
and CLS_CLOSURE =
{ cls: Ast.CLS,
env: SCOPE }
and IFACE_CLOSURE =
{ iface: Ast.IFACE,
env: SCOPE }
and DECIMAL_CONTEXT =
{ precision: int,
mode: DecimalParams.ROUNDING_MODE }
and REGS =
{
scope: SCOPE,
this: OBJ,
global: OBJ,
prog: Fixture.PROGRAM,
aux: AUX
}
and NATIVE_FUNCTION =
{ func: ({ scope: SCOPE,
this: OBJ,
global: OBJ,
prog: Fixture.PROGRAM,
aux: AUX } (* REGS *)
-> VAL list -> VAL),
length: int }
and OBJ_IDENT =
int
(* Important to model "fixedness" separately from
* "dontDelete-ness" because fixedness affects
* which phase of name lookup the name is found during.
*)
and TEMPS = (Ast.TYPE_EXPR * TEMP_STATE) list ref
and PROP = { ty: Ast.TY,
state: PROP_STATE,
attrs: ATTRS }
and PROP_BINDINGS = { max_seq: int,
bindings: { seq: int,
prop: (* PROP *)
{ ty: Ast.TY,
state: PROP_STATE,
attrs: ATTRS } } NameMap.map } ref
(* Exceptions for control transfer. *)
exception ContinueException of (Ast.IDENT option)
exception BreakException of (Ast.IDENT option)
exception TailCallException of (unit -> VAL)
exception ThrowException of VAL
exception ReturnException of VAL
exception StopIterationException
fun isObject (v:VAL) : bool =
case v of
Object _ => true
| _ => false
fun isDouble (v:VAL) : bool =
case v of
Object (Obj ob) =>
(case !(#magic ob) of
SOME (Double _) => true
| _ => false)
| _ => false
fun isDecimal (v:VAL) : bool =
case v of
Object (Obj ob) =>
(case !(#magic ob) of
SOME (Decimal _) => true
| _ => false)
| _ => false
fun isString (v:VAL)
: bool =
case v of
Object (Obj ob) =>
(case !(#magic ob) of
SOME (String _) => true
| _ => false)
| _ => false
fun isBoolean (v:VAL) : bool =
case v of
Object (Obj ob) =>
(case !(#magic ob) of
SOME (Boolean _) => true
| _ => false)
| _ => false
fun isNamespace (v:VAL) : bool =
case v of
Object (Obj ob) =>
(case !(#magic ob) of
SOME (Namespace _) => true
| _ => false)
| _ => false
fun isClass (v:VAL) : bool =
case v of
Object (Obj ob) =>
(case !(#magic ob) of
SOME (Class _) => true
| _ => false)
| _ => false
fun isInterface (v:VAL) : bool =
case v of
Object (Obj ob) =>
(case !(#magic ob) of
SOME (Interface _) => true
| _ => false)
| _ => false
fun isFunction (v:VAL) : bool =
case v of
Object (Obj ob) =>
(case !(#magic ob) of
SOME (Function _) => true
| _ => false)
| _ => false
fun isType (v:VAL) : bool =
case v of
Object (Obj ob) =>
(case !(#magic ob) of
SOME (Type _) => true
| _ => false)
| _ => false
fun isNativeFunction (v:VAL) : bool =
case v of
Object (Obj ob) =>
(case !(#magic ob) of
SOME (NativeFunction _) => true
| _ => false)
| _ => false
fun isNumeric (v:VAL) : bool =
case v of
Object (Obj ob) =>
(case !(#magic ob) of
SOME (Double _) => true
| SOME (Decimal _) => true
| _ => false)
| _ => false
fun isNull (v:VAL) : bool =
case v of
Null => true
| _ => false
fun isUndef (v:VAL) : bool =
case v of
Undef => true
| _ => false
(*
* The "machine type" of a value here is an ES3-ism. It exists only for
* compatibility, and has nothing to do with the ES4 type system.
*
* The important part is that in ES3 algorithms, a machine value has
* exactly *one* of these types. No overlap!
*)
datatype MACHTY = TYNULL | TYUNDEF | TYNUMBER | TYSTRING | TYBOOLEAN | TYOBJECT
fun es3Type (v:VAL) : MACHTY =
if isNull v then TYNULL
else if isUndef v then TYUNDEF
else if isNumeric v then TYNUMBER
else if isString v then TYSTRING
else if isBoolean v then TYBOOLEAN
else TYOBJECT
fun isSameType (va:VAL) (vb:VAL) : bool =
es3Type va = es3Type vb
(* Binding operations. *)
fun newPropBindings _ : PROP_BINDINGS =
ref { max_seq = 0, bindings = NameMap.empty }
fun addProp (b:PROP_BINDINGS)
(n:Ast.NAME)
(x:PROP)
: unit =
let
val { max_seq, bindings } = !b
val s = max_seq + 1
val binding = { seq = s, prop = x }
val bindings = NameMap.insert (bindings, n, binding)
in
b := { max_seq = s, bindings = bindings }
end
fun delProp (b:PROP_BINDINGS)
(n:Ast.NAME)
: unit =
let
val { max_seq, bindings } = !b
val (bindings, _) = NameMap.remove (bindings, n)
in
b := { max_seq = max_seq, bindings = bindings }
end
fun findProp (b:PROP_BINDINGS)
(n:Ast.NAME)
: PROP option =
let
val { bindings, ... } = !b
in
case NameMap.find (bindings, n) of
NONE => NONE
| SOME { prop, ... } => SOME prop
end
fun matchProps (fixedProps:bool)
(b:PROP_BINDINGS)
(searchId:Ast.IDENT)
(nss:Ast.NAMESPACE list)
: Ast.NAME list =
let
fun tryNS ns =
let
val name = {id=searchId, ns=ns}
in
case findProp b name of
NONE => NONE
| SOME _ => SOME name
end
in
List.mapPartial tryNS nss
end
fun makeTy (te:Ast.TYPE_EXPR)
: Ast.TY =
Ast.Ty { expr = te,
ribId = NONE }
fun getProp (b:PROP_BINDINGS)
(n:Ast.NAME)
: PROP =
case findProp b n of
SOME p => p
| NONE =>
(*
* If not found, then cons up a temporary property
* with value undefined. Any property not found
* errors would have been caught by evalRefExpr
*)
{ty=makeTy (Ast.SpecialType Ast.Undefined),
state=ValProp Undef,
attrs={dontDelete=false, (* unused attrs *)
dontEnum=false,
readOnly=false,
isFixed=false}}
fun hasProp (b:PROP_BINDINGS)
(n:Ast.NAME)
: bool =
case findProp b n of
NONE => false
| SOME _ => true
fun hasMagic (ob:OBJ) =
case ob of
Obj { magic, ... } =>
case !magic of
SOME _ => true
| NONE => false
fun setPropDontEnum (props:PROP_BINDINGS)
(n:Ast.NAME)
(dontEnum:bool)
: unit =
case findProp props n of
SOME prop =>
let
val attrs = (#attrs prop)
val newProp = { ty = (#ty prop),
state = (#state prop),
attrs = { dontDelete = (#dontDelete attrs),
dontEnum = dontEnum,
readOnly = (#readOnly attrs),
isFixed = (#isFixed attrs) } }
in
delProp props n;
addProp props n newProp
end
| NONE => ()
(* Safe: will overflow when it runs out of identities. *)
val currIdent = ref 0
fun nextIdent _ =
(currIdent := (((!currIdent) + 1)
handle Overflow => error ["overflowed maximum object ID"]);
!currIdent)
fun newObj (t:VAL_TAG)
(p:VAL)
(m:MAGIC option)
: OBJ =
Obj { ident = nextIdent (),
tag = t,
props = newPropBindings (),
proto = ref p,
magic = ref m }
fun newObjNoTag _
: OBJ =
newObj NoTag Null NONE
fun getProto (ob:OBJ)
: VAL =
let
val Obj {proto, ...} = ob
in
!proto
end
fun setProto (ob:OBJ) (p:VAL)
: OBJ =
let
val Obj {proto, ...} = ob
in
proto := p;
ob
end
fun getTemp (temps:TEMPS)
(n:int)
: VAL =
let
val _ = trace ["getTemp ",Int.toString n]
in
if n >= length (!temps)
then LogErr.machError ["getting out-of-bounds temporary"]
else
case List.nth ((!temps), n) of
(_, UninitTemp) => LogErr.machError ["getting uninitialized temporary ",Int.toString n]
| (_, ValTemp v) => v
end
fun defTemp (temps:TEMPS)
(n:int)
(v:VAL)
: unit =
let
val _ = trace ["defTemp ",Int.toString n]
fun replaceNth k [] = LogErr.machError ["temporary-definition error"]
| replaceNth k (x::xs) =
if k = 0
then (case x of
(t, UninitTemp) =>
((* FIXME: put typecheck here *)
(t, ValTemp v) :: xs)
| (t, _) =>
(t, ValTemp v) :: xs)
(* ISSUE: we allow redef of temps: LogErr.machError ["re-defining temporary"]) *)
else x :: (replaceNth (k-1) xs)
in
if n >= (length (!temps))
then LogErr.machError ["defining out-of-bounds temporary"]
else temps := replaceNth n (!temps)
end
fun isIntegral d =
let
val truncated = Real64.realTrunc d
in
if Real64.isFinite d
then Real64.==(truncated, d)
else false
end
fun isInRange (low:Real64.real)
(high:Real64.real)
(d:Real64.real)
: bool =
low <= d andalso d <= high
fun fitsInByte (d:Real64.real)
: bool = isIntegral d andalso isInRange 0.0 255.0 d
fun fitsInUInt (d:Real64.real) : bool
= isIntegral d andalso isInRange 0.0 4294967295.0 d
fun fitsInInt (d:Real64.real) : bool
= isIntegral d andalso isInRange (~2147483647.0) 2147483647.0 d
(*
* Some stringification helpers on low-level values.
*)
fun magicToUstring (magic:MAGIC)
: Ustring.STRING =
case magic of
Double n => NumberToString n
| Decimal d => Ustring.fromString (Decimal.toString d)
| String s => s
| Boolean true => Ustring.true_
| Boolean false => Ustring.false_
| Namespace ns => Ustring.fromString (LogErr.namespace ns)
| Class _ => Ustring.fromString "[class Class]"
| Interface _ => Ustring.fromString "[interface Interface]"
| Function _ => Ustring.fromString "[function Function]"
| Type _ => Ustring.fromString "[type Type]"
| NativeFunction _ => Ustring.fromString "[function Function]"
(*
* ES-262-3 9.8.1: ToString applied to the Number (double) type.
*)
and NumberToString (r:Real64.real)
: Ustring.STRING =
if Real64.isNan r
then Ustring.NaN_
else
if Real64.==(0.0, r) orelse Real64.==(~0.0, r)
then Ustring.zero
else
if Real64.<(r, 0.0)
then Ustring.append [Ustring.dash, NumberToString (Real64.~(r))]
else
if Real64.==(Real64.posInf, r)
then Ustring.Infinity_
else
let
(*
* Unfortunately SML/NJ has a pretty deficient selection of the numerical
* primitives; about the best we can get from it is a high-precision SCI
* conversion that we then parse. This is significantly more fun than
* writing your own dtoa.
*)
val x = Real64.fmt (StringCvt.SCI (SOME 30)) r
val (mantissaSS,expSS) = Substring.splitr (fn c => not (c = #"E")) (Substring.full x)
val mantissaSS = Substring.dropr (fn c => (c = #"E") orelse (c = #"0")) mantissaSS
val (preDot,postDot) = Substring.position "." mantissaSS
val postDot = Substring.triml 1 postDot
val exp = valOf (Int.fromString (Substring.string expSS))
val digits = (Substring.explode preDot) @ (Substring.explode postDot)
val k = length digits
val n = exp + 1
fun zeroes z = List.tabulate (z, (fn _ => #"0"))
fun expstr _ = (#"e" ::
(if (n-1) < 0 then #"-" else #"+") ::
(String.explode (Int.toString (Int.abs (n-1)))))
in
Ustring.fromString
(String.implode
(if k <= n andalso n <= 21
then digits @ (zeroes (n-k))
else
if 0 < n andalso n <= 21
then (List.take (digits, n)) @ [#"."] @ (List.drop (digits, n))
else
if ~6 < n andalso n <= 0
then [#"0", #"."] @ (zeroes (~n)) @ digits
else
if k = 1
then digits @ (expstr())
else (hd digits) :: #"." :: ((tl digits) @ expstr())))
end
fun inspect (v:VAL)
(d:Int32.int)
: unit =
let
val pad = " "
fun p 0 s = List.app TextIO.print s
| p n s = (TextIO.print pad; p (n-1) s)
fun nl _ = TextIO.print "\n";
fun att {dontDelete,dontEnum,readOnly,isFixed} =
if not dontDelete
andalso not dontEnum
andalso not readOnly
andalso not isFixed
then ""
else
(" ("
^ (if dontDelete then "DD," else "")
^ (if dontEnum then "DE," else "")
^ (if readOnly then "RO," else "")
^ (if isFixed then "FX" else "")
^ ") ")
fun id (Obj ob) = Int.toString (#ident ob)
fun typ t = LogErr.ty t
fun ty (Ast.Ty { expr, ... }) = typ expr
fun magType t =
case t of
Class { cls = Ast.Cls { instanceType, classType, ... }, ... } =>
(" : instanceType=" ^ (ty instanceType) ^ ", classType=" ^ (ty classType))
| Interface { iface = Ast.Iface { instanceType, ... }, ... } =>
(" : instanceType=" ^ (ty instanceType))
| Function { func = Ast.Func { ty=ty0, ... }, ... } =>
(" : " ^ (ty ty0))
| Type t => (" = " ^ (ty t))
| _ => ""
fun tag (Obj ob) =
case (#tag ob) of
(* FIXME: elaborate printing of structural tags. *)
ObjectTag _ => "<Obj>"
| ArrayTag _ => "<Arr>"
| FunctionTag t => "<Fn " ^ (typ (Ast.FunctionType t)) ^ ">"
| ClassTag t => "<Class " ^ (typ (Ast.InstanceType t)) ^ ">"
| NoTag => "<NoTag>"
(* FIXME: elaborate printing of type expressions. *)
fun mag m = case m of
String s => ("\"" ^ (Ustring.toAscii s) ^ "\"")
| m => Ustring.toAscii (magicToUstring m) ^ (magType m)
fun printVal indent _ Undef = TextIO.print "undefined\n"
| printVal indent _ Null = TextIO.print "null\n"
| printVal indent n (Wrapped (v, t)) =
(TextIO.print ("wrapped " ^ (typ t) ^ ":\n");
printVal (indent+1) n v)
| printVal indent 0 (Object (Obj ob)) =
(TextIO.print (case !(#magic ob) of
NONE => tag (Obj ob)
| SOME m => mag m);
TextIO.print "\n")
| printVal indent n (Object obj) =
let
fun subVal i v = printVal (i+1) (n-1) v
fun prop np =
let
val (n,binding) = np
val {prop={ty=ty0, state, attrs}, seq} = binding
val indent = indent + 1
val stateStr =
case state of
TypeVarProp => "[typeVar]"
| TypeProp => "[type]"
| UninitProp => "[uninit]"
| ValProp v => "[val]"
| VirtualValProp _ => "[virtual val]"
| MethodProp _ => "[method]"
| NativeFunctionProp _ => "[native function]"
| NamespaceProp _ => "[namespace]"
| ValListProp _ => "[val list]"
in
p indent [" prop = ", LogErr.name n, ": ", ty ty0, att attrs, " = "];
case state of
ValProp v => subVal indent v
| _ => TextIO.print (stateStr ^ "\n")
end
val Obj { magic, props, proto, ... } = obj
val { bindings, ... } = !props
in
TextIO.print "Obj {\n";
(case !magic of
SOME m => (p indent [" magic = ", (mag m)]; nl())
| NONE => ());
p indent [" tag = ", (tag obj)]; nl();
p indent [" ident = ", (id obj)]; nl();
p indent [" proto = "]; subVal indent (!proto);
p indent [" props = ["]; nl();
NameMap.appi prop bindings;
p indent [" ] }"]; nl()
end
in
printVal 0 d v
end
fun magStr (SOME mag) = Ustring.toAscii (magicToUstring mag)
| magStr NONE = "<none>"
fun setMagic (ob:OBJ) (m:MAGIC option)
: OBJ =
let
val Obj {magic, ident, ...} = ob
in
trace ["changing magic on obj #", Int.toString ident,
" from ", magStr (!magic), " to ", magStr m];
magic := m;
ob
end
fun newObject (t:VAL_TAG)
(p:VAL)
(m:MAGIC option)
: VAL =
let
val obj = newObj t p m
val Obj { magic, ident, ... } = obj
in
trace ["setting initial magic on obj #", Int.toString ident,
" to ", magStr (!magic)];
Object (obj)
end
(*
* To get from any object to its CLS, you work out the
* "nominal base" of the object's tag. You can then find
* a fixed prop in the global object that has a "Class"
* magic value pointing to the CLS.
*)
fun nominalBaseOfTag (t:VAL_TAG)
: Ast.NAME =
case t of
ObjectTag _ => Name.nons_Object
| ArrayTag _ => Name.nons_Array
| FunctionTag _ => Name.nons_Function
| ClassTag ity => (#name ity)
| NoTag => error ["searching for nominal base of no-tag object"]
fun getObjMagic (ob:OBJ)
: (MAGIC option) =
case ob of
Obj ob' => !(#magic ob')
fun getMagic (v:VAL)
: (MAGIC option) =
case v of
Object (Obj ob) => !(#magic ob)
| _ => NONE
fun needMagic (v:VAL)
: (MAGIC) =
case v of
Object (Obj ob) => valOf (!(#magic ob))
| _ => (inspect v 1;
error ["require object with magic"])
fun needClass (v:VAL)
: (CLS_CLOSURE) =
case needMagic v of
Class cls => cls
| _ => (inspect v 1;
error ["require class object"])
fun needInterface (v:VAL)
: (IFACE_CLOSURE) =
case needMagic v of
Interface iface => iface
| _ => (inspect v 1;
error ["require interface object"])
fun needFunction (v:VAL)
: (FUN_CLOSURE) =
case needMagic v of
Function f => f
| _ => (inspect v 1;
error ["require function object"])
fun needType (v:VAL)
: (Ast.TY) =
case needMagic v of
Type t => t
| _ => (inspect v 1;
error ["require type object"])
(* Call stack and debugging stuff *)
(* An approximation of an invocation argument list, for debugging. *)
fun approx (arg:VAL)
: string =
case arg of
Null => "null"
| Undef => "undefined"
| Wrapped (v, t) => "wrapped(" ^ (approx v) ^ ")"
| Object ob =>
if hasMagic ob
then
let
val str = Ustring.toAscii (magicToUstring (needMagic arg))
in
if isString arg
then "\"" ^ str ^ "\""
else str
end
else
"obj"
fun stackOf (regs:REGS)
: (FRAME list) =
let
val { aux = Aux { stack, ...}, ... } = regs
in
!stack
end
fun stackString (stack:FRAME list) =
let
fun fmtFrame (Frame { name, args }) =
name ^ "(" ^ (LogErr.join ", " (map approx args)) ^ ")"
in
"[" ^ (LogErr.join " | " (map fmtFrame (List.rev (stack)))) ^ "]"
end
fun resetProfile (regs:REGS) : unit =
let
val { aux =
Aux { profiler =
Profiler { profileMap, ... },
...},
... } = regs
in
profileMap := StrListMap.empty
end
fun resetStack (regs:REGS) : unit =
let
val { aux =
Aux { stack, ...},
... } = regs
in
stack := []
end
fun push (regs:REGS)
(name:string)
(args:VAL list)
: unit =
let
val { aux =
Aux { stack,
profiler =
Profiler { doProfile,
profileMap },
... },
... } = regs
val newStack = (Frame { name = name, args = args }) :: (!stack)
in
stack := newStack;
if !traceStack