-
Notifications
You must be signed in to change notification settings - Fork 8
/
eval.sml
3859 lines (3405 loc) · 143 KB
/
eval.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 -*- *)
structure Eval = struct
(* Local tracing machinery *)
val traceStack = ref false
val (stack:string list list ref) = ref []
fun resetStack _ =
stack := []
val ObjectClassIdentity = ref (~1)
val ArrayClassIdentity = ref (~1)
val FunctionClassIdentity = ref (~1)
val StringClassIdentity = ref (~1)
val NumberClassIdentity = ref (~1)
val booleanTrue : (Mach.VAL option) ref = ref NONE
val booleanFalse : (Mach.VAL option) ref = ref NONE
fun join sep ss =
case ss of
[] => ""
| [x] => x
| x :: xs => x ^ sep ^ (join sep xs)
fun stackString _ =
"[" ^ (join " | " (map String.concat (List.rev (!stack)))) ^ "]"
fun push ss =
(stack := (ss) :: (!stack);
if !traceStack
then LogErr.log ("[stack] " :: [stackString ()])
else ())
fun pop _ =
(stack := tl (!stack);
if !traceStack
then LogErr.log ("[stack] " :: [stackString()])
else ())
fun log ss = LogErr.log ("[eval] " :: ss)
val doTrace = ref false
fun fmtName n = if (!doTrace) then LogErr.name n else ""
fun fmtMultiname n = if (!doTrace) then LogErr.multiname n else ""
fun trace ss = if (!doTrace) then log ss else ()
fun error ss =
(LogErr.log ("[stack] " :: [stackString()]);
LogErr.evalError ss)
(* Exceptions for object-language control transfer. *)
exception ContinueException of (Ast.IDENT option)
exception BreakException of (Ast.IDENT option)
exception TailCallException of (unit -> Mach.VAL)
exception ThrowException of Mach.VAL
exception ReturnException of Mach.VAL
exception InternalError
fun mathOp (v:Mach.VAL)
(decimalFn:(Decimal.DEC -> 'a) option)
(doubleFn:(Real64.real -> 'a) option)
(intFn:(Int32.int -> 'a) option)
(uintFn:(Word32.word -> 'a) option)
(default:'a)
: 'a =
let
fun fnOrDefault fo v = case fo of
NONE => default
| SOME f => f v
in
case v of
Mach.Object (Mach.Obj ob) =>
(case !(#magic ob) of
SOME (Mach.Decimal d) => fnOrDefault decimalFn d
| SOME (Mach.Double d) => fnOrDefault doubleFn d
| SOME (Mach.Int i) => fnOrDefault intFn i
| SOME (Mach.UInt u) => fnOrDefault uintFn u
| _ => default)
| _ => default
end
fun extendScope (p:Mach.SCOPE)
(ob:Mach.OBJ)
(kind:Mach.SCOPE_KIND)
: Mach.SCOPE =
Mach.Scope { parent = (SOME p),
object = ob,
temps = ref [],
kind = kind }
fun extendScopeReg (r:Mach.REGS)
(ob:Mach.OBJ)
(kind:Mach.SCOPE_KIND)
: Mach.REGS =
let
val {scope,this} = r
in
{scope=extendScope scope ob kind,
this=this}
end
fun getObjId (obj:Mach.OBJ)
: Mach.OBJ_IDENT =
case obj of
Mach.Obj { ident, ... } => ident
fun getScopeObj (scope:Mach.SCOPE)
: Mach.OBJ =
case scope of
Mach.Scope { object, ... } => object
fun getScopeId (scope:Mach.SCOPE)
: Mach.OBJ_IDENT = getObjId (getScopeObj scope)
fun getScopeTemps (scope:Mach.SCOPE)
: Mach.TEMPS =
case scope of
Mach.Scope { temps, ... } => temps
fun needNamespace (v:Mach.VAL)
: Ast.NAMESPACE =
case v of
Mach.Object (Mach.Obj ob) =>
(case !(#magic ob) of
SOME (Mach.Namespace n) => n
| _ => error ["need namespace"])
| _ => error ["need namespace"]
fun needObj (v:Mach.VAL)
: Mach.OBJ =
case v of
Mach.Object ob => ob
| _ => error ["need object"]
(*
* The global object and scope.
*)
val (globalObject:(Mach.OBJ option) ref) = ref NONE
val (globalScope:(Mach.SCOPE option) ref) = ref NONE
fun getGlobalObject _
: Mach.OBJ =
case !globalObject of
NONE => error ["missing global object"]
| SOME ob => ob
fun getGlobalScope _
: Mach.SCOPE =
case !globalScope of
NONE => error ["missing global scope"]
| SOME ob => ob
fun getInitialRegs _ =
{ this = getGlobalObject (),
scope = getGlobalScope () }
(*
* A small number of functions do not fully evaluate to Mach.VAL
* values, but instead to REFs; these are temporary artifacts of
* evaluation, not first-class values in the language.
*)
type REF = (Mach.OBJ * Ast.NAME)
(* Fundamental object methods *)
(* FIXME: possibly move this to mach.sml *)
fun allocFixtures (regs:Mach.REGS)
(obj:Mach.OBJ)
(this:Mach.OBJ option)
(temps:Mach.TEMPS)
(f:Ast.FIXTURES)
: unit =
case obj of
Mach.Obj { props, ident, ... } =>
let
val _ = trace ["allocating fixtures on object id #", Int.toString ident]
val {scope, ...} = regs
val methodScope = extendScope scope obj Mach.ActivationScope
fun valAllocState (t:Ast.TYPE_EXPR)
: Mach.PROP_STATE =
(* Every value fixture has a type, and every type has an
* associated "allocated state". Note that
* this is *not* the same as saying that every type
* has an associated default value; for *some* types
* the allocated state is a default value; for
* types that are non-nullable, however, the allocated
* state is Mach.UninitProp. This property
* state should never be observable to a user. It is
* always a hard error to read a property in
* Mach.UninitProp state, and it is always a hard
* error to complete the initialization phase of an
* object with any properties remaining in
* Mach.UninitProp state. *)
case t of
Ast.SpecialType (Ast.Any) =>
Mach.ValProp (Mach.Undef)
| Ast.SpecialType (Ast.Null) =>
Mach.ValProp (Mach.Null)
| Ast.SpecialType (Ast.Undefined) =>
Mach.ValProp (Mach.Undef)
| Ast.SpecialType (Ast.VoidType) =>
error ["attempt to allocate void-type property"]
(* FIXME: is this correct? Maybe we need to check them all to be nullable? *)
| Ast.UnionType _ =>
Mach.ValProp (Mach.Null)
| Ast.ArrayType _ =>
Mach.ValProp (Mach.Null)
| Ast.TypeName ident =>
(* FIXME: resolve nominal type to class or interface, check to see if
* it is nullable, *then* decide whether to set to null or uninit. *)
Mach.ValProp (Mach.Null)
| Ast.FunctionType _ =>
Mach.UninitProp
| Ast.ObjectType _ =>
Mach.ValProp (Mach.Null)
| Ast.AppType {base, ...} =>
valAllocState base
| Ast.NullableType { expr, nullable=true } =>
Mach.ValProp (Mach.Null)
| Ast.NullableType { expr, nullable=false } =>
Mach.UninitProp
| Ast.ElementTypeRef _ =>
Mach.ValProp (Mach.Undef) (* FIXME: should get the type of the element from the array type *)
| Ast.FieldTypeRef _ => (* FIXME: get type from object type *)
Mach.ValProp (Mach.Undef)
| _ => error ["Shouldn't happen: failed to match in Eval.allocFixtures#valAllocState."]
fun tempPadding n =
if n = 0
then []
else (Ast.SpecialType Ast.Any, Mach.UninitTemp)::(tempPadding (n-1))
fun allocFixture (n, f) =
case n of
Ast.TempName t =>
(case f of
Ast.ValFixture { ty, ... } => (* FIXME: temp types are not needed, use the value tag for rt typechecking *)
(if t = (List.length (!temps))
then (trace ["allocating fixture for temporary ", Int.toString t];
temps := (Ast.SpecialType Ast.Any, Mach.UninitTemp)::(!temps))
else if t < (List.length (!temps))
then (trace ["ignoring fixture, already allocated ", Int.toString t];
temps := (List.take (!temps,((length (!temps))-t-1)))@((ty, Mach.UninitTemp)::(List.drop (!temps,(length (!temps)-t)))))
else (trace ["allocating fixtures for temporaries ", Int.toString (length (!temps)), " to ", Int.toString t];
temps := (Ast.SpecialType Ast.Any, Mach.UninitTemp)
::(((tempPadding (t-(length (!temps))))@(!temps)))))
| _ => error ["allocating non-value temporary"])
| Ast.PropName pn =>
let
val _ = trace ["allocating fixture for property ", fmtName pn]
fun allocProp state p =
if Mach.hasProp props pn
(* FIXME: make a detailed check of fixture-compatibility here! *)
(* error ["allocating duplicate property name: ",
fmtName pn] *)
then (trace ["replacing fixture for ", state, " property ",
fmtName pn];
Mach.delProp props pn; Mach.addProp props pn p)
else (trace ["allocating fixture for ", state, " property ",
fmtName pn];
Mach.addProp props pn p)
in
case f of
Ast.TypeFixture te =>
allocProp "type"
{ ty = te,
state = Mach.TypeProp,
attrs = { dontDelete = true,
dontEnum = true,
readOnly = true,
isFixed = true } }
| Ast.MethodFixture { func, ty, readOnly, ... } =>
let
val Ast.Func { isNative, ... } = func
val p = if isNative
then Mach.NativeFunctionProp (Mach.getNativeFunction pn)
else Mach.MethodProp (newFunClosure methodScope func this)
in
allocProp "method"
{ ty = ty,
state = p,
attrs = { dontDelete = true,
dontEnum = true,
readOnly = readOnly,
isFixed = true } }
end
| Ast.ValFixture { ty, readOnly, ... } =>
allocProp "value"
{ ty = ty,
state = valAllocState ty,
attrs = { dontDelete = true,
dontEnum = false,
readOnly = readOnly,
isFixed = true } }
| Ast.VirtualValFixture { ty, getter, setter, ... } =>
let
val getFn = case getter of
NONE => NONE
| SOME f => SOME (newFunClosure methodScope (#func f) this)
val setFn = case setter of
NONE => NONE
| SOME f => SOME (newFunClosure methodScope (#func f) this)
in
allocProp "virtual value"
{ ty = ty,
state = Mach.VirtualValProp { getter = getFn,
setter = setFn },
attrs = { dontDelete = true,
dontEnum = false,
readOnly = true,
isFixed = true } }
end
| Ast.ClassFixture cls =>
let
val Ast.Cls {classFixtures, ...} = cls
val _ = trace ["allocating class object for class ", fmtName pn]
val classObj = needObj (newClass scope cls)
val _ = trace ["allocating class fixtures on class ", fmtName pn]
(* FIXME: 'this' binding in class objects might be wrong here. *)
val _ = allocObjFixtures regs classObj NONE classFixtures
in
allocProp "class"
{ ty = (Name.typename Name.public_Class),
state = Mach.ValProp (Mach.Object classObj),
attrs = { dontDelete = true,
dontEnum = true,
readOnly = true,
isFixed = true } }
end
| Ast.NamespaceFixture ns =>
allocProp "namespace"
{ ty = (Name.typename Name.public_Namespace),
state = Mach.NamespaceProp ns,
attrs = { dontDelete = true,
dontEnum = true,
readOnly = true,
isFixed = true } }
| Ast.TypeVarFixture =>
allocProp "type variable"
{ ty = (Name.typename Name.public_Type),
state = Mach.TypeVarProp,
attrs = { dontDelete = true,
dontEnum = true,
readOnly = true,
isFixed = true } }
| Ast.InterfaceFixture => (* FIXME *)
()
(* | _ => error ["Shouldn't happen: failed to match in Eval.allocFixtures#allocFixture."] *)
end
in
List.app allocFixture f
end
and allocObjFixtures (regs:Mach.REGS)
(obj:Mach.OBJ)
(this:Mach.OBJ option)
(f:Ast.FIXTURES)
: unit =
let
val (temps:Mach.TEMPS) = ref []
in
allocFixtures regs obj this temps f;
if not ((length (!temps)) = 0)
then error ["allocated temporaries in non-scope object"]
else ()
end
and allocScopeFixtures (regs:Mach.REGS)
(f:Ast.FIXTURES)
: unit =
case (#scope regs) of
Mach.Scope { object, temps, ... } =>
allocFixtures regs object NONE temps f
and asArrayIndex (v:Mach.VAL)
: Word32.word =
case v of
Mach.Object (Mach.Obj ob) =>
(case !(#magic ob) of
SOME (Mach.Int i) => if i >= 0 then
Word32.fromInt (Int32.toInt i)
else
0wxFFFFFFFF
| SOME (Mach.UInt u) => u
| SOME (Mach.Double d) => if Real64.compare(Real64.realFloor d, d) = EQUAL andalso
d >= 0.0 andalso
d < 4294967295.0
then
Word32.fromLargeInt (Real64.toLargeInt IEEEReal.TO_NEAREST d)
else
0wxFFFFFFFF
| SOME (Mach.Decimal d) => 0wxFFFFFFFF (* FIXME *)
| _ => 0wxFFFFFFFF)
| _ => 0wxFFFFFFFF
and hasOwnValue (obj:Mach.OBJ)
(n:Ast.NAME)
: bool =
case obj of
Mach.Obj { props, ... } =>
Mach.hasProp props n
and hasValue (obj:Mach.OBJ)
(n:Ast.NAME)
: bool =
if hasOwnValue obj n
then true
else (case obj of
Mach.Obj { proto, ... } =>
case (!proto) of
Mach.Object p => hasValue p n
| _ => false)
(*
* *Similar to* ES-262-3 8.7.1 GetValue(V), there's
* no Reference type in ES4.
*)
and getValueOrVirtual (obj:Mach.OBJ)
(name:Ast.NAME)
(doVirtual:bool)
: Mach.VAL =
let
val Mach.Obj { props, ... } = obj
in
case Mach.findProp props name of
SOME prop =>
(case (#state prop) of
Mach.TypeProp =>
error ["getValue on a type property: ",
fmtName name]
| Mach.TypeVarProp =>
error ["getValue on a type variable property: ",
fmtName name]
| Mach.UninitProp =>
error ["getValue on an uninitialized property: ",
fmtName name]
| Mach.VirtualValProp { getter, ... } =>
if doVirtual
then
case getter of
SOME g =>
invokeFuncClosure obj g []
| NONE =>
error ["getValue on a virtual property w/o getter: ",
fmtName name]
else
(* FIXME: possibly throw here? *)
Mach.Undef
| Mach.NamespaceProp n =>
newNamespace n
| Mach.NativeFunctionProp nf =>
newNativeFunction nf
| Mach.MethodProp closure =>
newFunctionFromClosure closure
| Mach.ValListProp vals =>
(* FIXME: The 'arguments' object can't be an array. *)
newArray vals
| Mach.ValProp v => v)
| NONE =>
let
fun catchAll _ =
(* FIXME: need to use builtin Name.es object here, when that file exists. *)
evalCallMethodByRef obj (obj, Name.meta_get) [newString (#id name)]
in
case Mach.findProp props Name.meta_get of
SOME { state = Mach.MethodProp _, ... } => catchAll ()
| SOME { state = Mach.NativeFunctionProp _, ... } => catchAll ()
| _ => Mach.Undef
end
end
and getValue (obj:Mach.OBJ)
(name:Ast.NAME)
: Mach.VAL =
getValueOrVirtual obj name true
and setValueOrVirtual (obj:Mach.OBJ)
(name:Ast.NAME)
(v:Mach.VAL)
(doVirtual:bool)
: unit =
let
val Mach.Obj { props, ... } = obj
in
case Mach.findProp props name of
SOME existingProp =>
let
val existingAttrs = (#attrs existingProp)
val newProp = { state = Mach.ValProp v,
ty = (#ty existingProp),
attrs = existingAttrs }
fun write _ =
((* FIXME: insert typecheck here *)
Mach.delProp props name;
Mach.addProp props name newProp)
in
case (#state existingProp) of
Mach.UninitProp =>
error ["setValue on uninitialized property",
fmtName name]
| Mach.TypeVarProp =>
error ["setValue on type variable property:",
fmtName name]
| Mach.TypeProp =>
error ["setValue on type property: ",
fmtName name]
| Mach.NamespaceProp _ =>
error ["setValue on namespace property: ",
fmtName name]
| Mach.NativeFunctionProp _ =>
error ["setValue on native function property: ",
fmtName name]
| Mach.MethodProp _ =>
error ["setValue on method property: ",
fmtName name]
| Mach.ValListProp _ =>
error ["setValue on value-list property: ",
fmtName name]
| Mach.VirtualValProp { setter = SOME s, ... } =>
if doVirtual
then (invokeFuncClosure obj s [v]; ())
else write ()
| Mach.VirtualValProp { setter = NONE, ... } =>
if doVirtual
then error ["setValue on virtual property w/o setter: ",
fmtName name]
else write ()
| Mach.ValProp _ =>
if (#readOnly existingAttrs)
then () (* ignore it *)
else write ()
end
| NONE =>
let
fun newProp _ =
let
val prop = { state = Mach.ValProp v,
ty = Ast.SpecialType Ast.Any,
attrs = { dontDelete = false,
dontEnum = false,
readOnly = false,
isFixed = false } }
in
Mach.addProp props name prop
end
fun catchAll _ =
(* FIXME: need to use builtin Name.es object here, when that file exists. *)
(evalCallMethodByRef obj (obj, Name.meta_set) [newString (#id name), v]; ())
in
if doVirtual
then
case Mach.findProp props Name.meta_set of
SOME { state = Mach.MethodProp _, ... } => catchAll ()
| SOME { state = Mach.NativeFunctionProp _, ... } => catchAll ()
| _ => newProp ()
else
newProp ()
end
end
and setValue (base:Mach.OBJ)
(name:Ast.NAME)
(v:Mach.VAL)
: unit =
setValueOrVirtual base name v true
(* A "defValue" call occurs when assigning a property definition's
* initial value, as specified by the user. All other assignments
* to a property go through "setValue". *)
and defValue (base:Mach.OBJ)
(name:Ast.NAME)
(v:Mach.VAL)
: unit =
case base of
Mach.Obj { props, ... } =>
if not (Mach.hasProp props name)
then error ["defValue on missing property: ", LogErr.name name]
else
(*
* defProp has relaxed rules: you can write to an
* uninitialized property or a read-only property.
*)
let
val existingProp = Mach.getProp props name
val newProp = { state = Mach.ValProp v,
ty = (#ty existingProp),
attrs = (#attrs existingProp) }
fun writeProp _ =
((* FIXME: insert typecheck here *)
Mach.delProp props name;
Mach.addProp props name newProp)
in
case (#state existingProp) of
Mach.TypeVarProp =>
error ["defValue on type variable property: ",
fmtName name]
| Mach.TypeProp =>
error ["defValue on type property: ",
fmtName name]
| Mach.NamespaceProp _ =>
error ["defValue on namespace property: ",
fmtName name]
| Mach.NativeFunctionProp _ =>
error ["defValue on native function property: ",
fmtName name]
| Mach.MethodProp _ =>
error ["defValue on method property: ",
fmtName name]
| Mach.ValListProp _ =>
error ["defValue on value-list property: ",
fmtName name]
| Mach.VirtualValProp { setter = SOME s, ... } =>
(invokeFuncClosure base s [v]; ())
| Mach.VirtualValProp { setter = NONE, ... } =>
error ["defValue on virtual property w/o setter: ",
fmtName name]
| Mach.UninitProp => writeProp ()
| Mach.ValProp _ => writeProp ()
end
and instantiateGlobalClass (n:Ast.NAME)
(args:Mach.VAL list)
: Mach.VAL =
let
val _ = trace ["instantiating global class ", fmtName n];
val (cls:Mach.VAL) = getValue (getGlobalObject ()) n
in
case cls of
Mach.Object ob => evalNewExpr ob args
| _ => error ["global class name ", fmtName n,
" did not resolve to object"]
end
and newObject _ =
instantiateGlobalClass Name.public_Object []
and newObj _ =
needObj (instantiateGlobalClass Name.public_Object [])
and newRootBuiltin (n:Ast.NAME) (m:Mach.MAGIC)
: Mach.VAL =
(*
* Five of our builtin types require special handling when it comes
* to constructing them: we wish to run the builtin ctors with no
* arguments at all, then clobber the magic slot in the resulting
* object. All other builtins we can pass a tagless "ur-Objects" into the
* builtin ctor and let it modify its own magic slot using magic::setValue.
*
* For these cases (Function, Class, Namespace, Boolean and boolean) we
* cannot rely on the builtin ctor calling magic::setValue, as they need
* to exist in order to *execute* a call to magic::setValue (or execute
* the tiny amount of surrounding control flow that is used to bottom our
* of the conversion functions in Conversion.es).
*)
let
val obj = needObj (instantiateGlobalClass n [])
val _ = trace ["finished building root builtin ", fmtName n]
in
Mach.Object (Mach.setMagic obj (SOME m))
end
and newArray (vals:Mach.VAL list)
: Mach.VAL =
(*
* NB: Do not reorganize this to call the public Array constructor with the val list
* directly: that constructor is a bit silly. It interprets a single-argument list as
* a number, and sets the array to that length. We want to always return an array from
* this call containing as many values as we were passed, no more no less.
*)
let val a = instantiateGlobalClass Name.public_Array [newInt (Int32.fromInt (List.length vals))]
fun init a _ [] = ()
| init a k (x::xs) =
(setValue a (Name.public (Ustring.fromInt k)) x ;
init a (k+1) xs)
in
init (needObj a) 0 vals;
a
end
and newRegExp (pattern:Ustring.STRING)
(flags:Ustring.STRING)
: Mach.VAL =
instantiateGlobalClass Name.public_RegExp [newString pattern, newString flags]
and newBuiltin (n:Ast.NAME) (m:Mach.MAGIC option)
: Mach.VAL =
instantiateGlobalClass n [Mach.Object (Mach.setMagic (Mach.newObjNoTag()) m)]
and newDouble (n:Real64.real)
: Mach.VAL =
newBuiltin Name.public_double (SOME (Mach.Double n))
and newDecimal (n:Decimal.DEC)
: Mach.VAL =
newBuiltin Name.public_decimal (SOME (Mach.Decimal n))
and newInt (n:Int32.int)
: Mach.VAL =
newBuiltin Name.public_int (SOME (Mach.Int n))
and newUInt (n:Word32.word)
: Mach.VAL =
newBuiltin Name.public_uint (SOME (Mach.UInt n))
and newString (s:Ustring.STRING)
: Mach.VAL =
newBuiltin Name.public_string (SOME (Mach.String s))
and newByteArray (b:Word8Array.array)
: Mach.VAL =
newBuiltin Name.public_ByteArray (SOME (Mach.ByteArray b))
and newBoolean (b:bool)
: Mach.VAL =
let
val refcell = if b then booleanTrue else booleanFalse
in
case !refcell of
SOME v => v
| NONE =>
let
val v = newBuiltin Name.public_boolean (SOME (Mach.Boolean b))
in
refcell := SOME v;
v
end
end
and newNamespace (n:Ast.NAMESPACE)
: Mach.VAL =
newRootBuiltin Name.public_Namespace (Mach.Namespace n)
and newClsClosure (env:Mach.SCOPE)
(cls:Ast.CLS)
: Mach.CLS_CLOSURE =
{ cls = cls,
(* FIXME: are all types bound? *)
allTypesBound = true,
env = env }
and newClass (e:Mach.SCOPE)
(cls:Ast.CLS)
: Mach.VAL =
let
val closure = newClsClosure e cls
in
newRootBuiltin Name.public_Class (Mach.Class closure)
end
and newFunClosure (e:Mach.SCOPE)
(f:Ast.FUNC)
(this:Mach.OBJ option)
: Mach.FUN_CLOSURE =
let
val Ast.Func { fsig, ... } = f
val allTypesBound = (case fsig of
Ast.FunctionSignature { typeParams, ... }
=> (length typeParams) = 0)
in
{ func = f,
this = this,
allTypesBound = allTypesBound,
env = e }
end
and newFunctionFromClosure (closure:Mach.FUN_CLOSURE) =
let
val { func, ... } = closure
val Ast.Func { fsig, ... } = func
val tag = Mach.FunctionTag fsig
val res = newRootBuiltin Name.public_Function (Mach.Function closure)
in
(*
* FIXME: modify the returned object to have the proper tag, a subtype
* of Function.
*)
res
end
and newFunctionFromFunc (e:Mach.SCOPE)
(f:Ast.FUNC)
: Mach.VAL =
newFunctionFromClosure (newFunClosure e f NONE)
and newNativeFunction (f:Mach.NATIVE_FUNCTION) =
newRootBuiltin Name.public_Function (Mach.NativeFunction f)
(* An approximation of an invocation argument list, for debugging. *)
and callApprox (idStr:string) (args:Mach.VAL list)
: string =
let
fun approx arg =
case arg of
Mach.Null => "null"
| Mach.Undef => "undefined"
| Mach.Object ob =>
if Mach.hasMagic ob
then
if Mach.isString arg
then "\"" ^ (Ustring.toAscii (toUstring arg)) ^ "\""
else Ustring.toAscii (toUstring arg)
else
"obj"
in
idStr ^ "(" ^ (join ", " (map approx args)) ^ ")"
end
(* FIXME: this is not the correct toString *)
(*
* 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
and magicToUstring (magic:Mach.MAGIC)
: Ustring.STRING =
case magic of
Mach.Double n => NumberToString n
| Mach.Decimal d => Ustring.fromString (Decimal.toString d)
| Mach.Int i => Ustring.fromInt32 i
| Mach.UInt u => Ustring.fromString (LargeInt.toString (Word32.toLargeInt u))
| Mach.String s => s
| Mach.Boolean true => Ustring.true_
| Mach.Boolean false => Ustring.false_
| Mach.Namespace (Ast.Private _) => Ustring.fromString "[private namespace]"
| Mach.Namespace (Ast.Protected _) => Ustring.fromString "[protected namespace]"
| Mach.Namespace Ast.Intrinsic => Ustring.fromString "[intrinsic namespace]"
| Mach.Namespace Ast.OperatorNamespace => Ustring.fromString "[operator namespace]"
| Mach.Namespace (Ast.Public id) => Ustring.append [Ustring.fromString "[public namespace: ", id, Ustring.fromString "]"]
| Mach.Namespace (Ast.Internal _) => Ustring.fromString "[internal namespace]"
| Mach.Namespace (Ast.UserNamespace id) => Ustring.append [Ustring.fromString "[user-defined namespace ", id, Ustring.fromString "]"]
| Mach.Class _ => Ustring.fromString "[class Class]"
| Mach.Interface _ => Ustring.fromString "[interface Interface]"
| Mach.Function _ => Ustring.fromString "[function Function]"
| Mach.Type _ => Ustring.fromString "[type Function]"
| Mach.ByteArray _ => Ustring.fromString "[ByteArray]"
| Mach.NativeFunction _ => Ustring.fromString "[function Function]"
| _ => error ["Shouldn't happen: failed to match in Eval.magicToUstring."]
(*
* ES-262-3 9.8 ToString.
*
* We do it down here because we have some actual callers who
* need it inside the implementation of the runtime. Most of the rest
* is done up in Conversions.es.
*)
and toUstring (v:Mach.VAL)
: Ustring.STRING =
case v of
Mach.Undef => Ustring.undefined_
| Mach.Null => Ustring.null_
| Mach.Object obj =>
let
val Mach.Obj ob = obj
in
case !(#magic ob) of
SOME magic => magicToUstring magic
| NONE => toUstring (callGlobal Name.intrinsic_ToPrimitive
[v, newString Ustring.String_])
end
(*
* ES-262-3 9.2: The ToBoolean operation
*)
and toBoolean (v:Mach.VAL) : bool =
case v of
Mach.Undef => false
| Mach.Null => false
| Mach.Object (Mach.Obj ob) =>
(case !(#magic ob) of