-
Notifications
You must be signed in to change notification settings - Fork 8
/
defn.sml
2576 lines (2250 loc) · 98.1 KB
/
defn.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 Defn = struct
(* Local tracing machinery *)
val doTrace = ref false
fun trace ss = if (!doTrace) then LogErr.log ("[defn] " :: ss) else ()
fun error ss = LogErr.defnError ss
(*
* The goal of the definition phase is to put together the fixtures
* of the program, as well as insert class, function and interface
* objects into the global object.
To be specific, the definition phase completes the following tasks:
- fold type expressions
- fold namespace aliases
- translate defnitions to fixtures + initialisers
- check for conflicting fixtures
- hoist fixtures
- inherit super classes and interfaces
- evaluate pragmas
- capture open namespaces in unqualified identifiers
- capture arithmetic modes in arithmetic operators
- disambiguate package / object references
TODO
- fold types
- inheritance checks
*)
datatype LABEL_KIND =
IterationLabel
| SwitchLabel
| StatementLabel
type LABEL = (Ast.IDENT * LABEL_KIND)
type CONTEXT =
{ fixtures: Ast.FIXTURES,
tempOffset: int,
openNamespaces: Ast.NAMESPACE list list,
numericMode: Ast.NUMERIC_MODE,
labels: LABEL list,
packageNames: Ast.IDENT list list,
className: Ast.NAME option,
packageName: Ast.IDENT list,
defaultNamespace: Ast.NAMESPACE }
type ENV = CONTEXT list
fun dumpEnv (e:ENV) : unit =
case e of
{fixtures,...}::p => if (!doTrace) then (Pretty.ppFixtures fixtures; dumpEnv p) else ()
| _ => ()
val defaultNumericMode : Ast.NUMERIC_MODE =
{ numberType = Ast.Number,
roundingMode = Decimal.defaultRoundingMode,
precision = Decimal.defaultPrecision }
val (topFixtures:Ast.FIXTURES ref) = ref []
val (topPackageNames:Ast.IDENT list list ref) = ref []
fun resetTopFixtures _ =
topFixtures := [ (Ast.PropName (Name.public "meta"), Ast.NamespaceFixture Name.metaNS),
(Ast.PropName (Name.public "magic"), Ast.NamespaceFixture Name.magicNS) ]
fun resetTopPackageNames _ =
topPackageNames := []
fun hasFixture (b:Ast.FIXTURES)
(n:Ast.FIXTURE_NAME)
: bool =
let
fun search [] = false
| search ((k,v)::bs) =
if k = n
then true
else search bs
in
search b
end
fun hasNamespace (nl:Ast.NAMESPACE list)
(n:Ast.NAMESPACE)
: bool =
List.exists (fn x => n = x) nl
(*
FIXME: Move this to Mach or Eval. Something like this is used to eval Ast.FieldTypeRef
and ElementTypeRef
Get the type of a field in a field pattern - lookup in a list of field types a field type
with associated a name. if the list is empty then return type '*'. if the list is not
empty and the sought name is not found, then report a syntax error.
*)
(*
fun getFieldType (name : Ast.IDENT) (field_types: Ast.FIELD_TYPE list)
: Ast.TYPE_EXPR =
let
in case field_types of
[] => Ast.SpecialType Ast.Any
| field_type :: field_type_list =>
let
val {name=field_type_name,ty} = field_type
in
if field_type_name = name
then ty
else getFieldType name field_type_list
end
end
*)
fun getFixture (b:Ast.FIXTURES)
(n:Ast.FIXTURE_NAME)
: Ast.FIXTURE =
let
fun search [] = LogErr.hostError ["fixture binding not found: ",
(LogErr.fname n)]
| search ((k,v)::bs) =
if k = n
then v
else search bs
in
search b
end
fun replaceFixture (b:Ast.FIXTURES)
(n:Ast.FIXTURE_NAME)
(v:Ast.FIXTURE)
: Ast.FIXTURES =
let
fun search [] = LogErr.hostError ["fixture binding not found: ",
(LogErr.fname n)]
| search ((k,v0)::bs) =
if k = n
then (k,v) :: bs
else (k,v0) :: (search bs)
in
search b
end
fun inl f (a, b) = (f a, b)
fun inr f (a, b) = (a, f b)
fun isInstanceInit (s:Ast.STMT)
: bool =
let
in case s of
Ast.InitStmt {kind,static,prototype,...} =>
not ((kind=Ast.LetVar) orelse (kind=Ast.LetConst) orelse
prototype orelse static)
| _ => false
end
(*
resolve a multiname to a name and then get the corresponding fixture
for each nested context in the environment, look for a fixture that matches
a multiname. see if a particular scope has a fixture with one of a list of
multinames
multiname = { nss : NAMESPACE list list, id: IDENT }
name = { ns: NAMESPACE, id: IDENT }
*)
fun matchFixtures ((env:ENV),
(searchId:Ast.IDENT),
(nss:Ast.NAMESPACE list))
: Ast.NAME list =
case env of
[] => []
| ({fixtures,...}:CONTEXT)::_ =>
let
fun matchFixture (fxn:Ast.FIXTURE_NAME,_) : Ast.NAME option =
case fxn of
Ast.TempName _ => NONE
| Ast.PropName n =>
let
val {id,ns} = n
fun matchNS candidateNS =
case candidateNS of
Ast.LimitedNamespace (ident,limNS) =>
if id = ident
then ns = limNS
else false
| _ => ns = candidateNS
in
if searchId = id andalso (List.exists matchNS nss)
then SOME n
else NONE
end
in
List.mapPartial matchFixture fixtures
end
fun getEnvParent [] = NONE
| getEnvParent (x::[]) = NONE
| getEnvParent (x::xs) = SOME xs
fun resolveMultinameToFixture (env:ENV)
(mname:Ast.MULTINAME)
: Ast.NAME * Ast.FIXTURE =
case Multiname.resolve mname env matchFixtures getEnvParent of
NONE => LogErr.defnError ["unresolved fixture ", LogErr.multiname mname]
| SOME (({fixtures, ...}::_), n) => (n, getFixture fixtures (Ast.PropName n))
| SOME _ => LogErr.defnError ["fixture lookup error ", LogErr.multiname mname]
fun multinameHasFixture (env:ENV)
(mname:Ast.MULTINAME)
: bool =
case Multiname.resolve mname env matchFixtures getEnvParent of
NONE => false
| SOME (({fixtures, ...}::_), n) => true
| _ => LogErr.defnError ["fixture lookup error ", LogErr.multiname mname]
(*
Since we are in the definition phase the open namespaces have not been
captured yet, so capture them before evaluating an unqualified namespace
expression
*)
fun packageIdentFromPath path ident
: Ast.IDENT =
case (path) of
[] => ident
| (pthid::pth) =>
let
val dot = if ident="" then "" else "."
in
packageIdentFromPath pth (ident^dot^pthid)
end
fun mergeVirtuals (fName:Ast.FIXTURE_NAME)
(vnew:Ast.VIRTUAL_VAL_FIXTURE)
(vold:Ast.VIRTUAL_VAL_FIXTURE) =
let
val ty = if (#ty vnew) = (#ty vold)
then (#ty vnew)
else (if (#ty vnew) = Ast.SpecialType Ast.Any
then (#ty vold)
else (if (#ty vold) = Ast.SpecialType Ast.Any
then (#ty vnew)
else error ["mismatched get/set types on fixture ",
LogErr.fname fName]))
fun either a b =
case (a,b) of
(SOME x, NONE) => SOME x
| (NONE, SOME x) => SOME x
| (NONE, NONE) => NONE
| _ => error ["multiply defined get/set functions on fixture ",
LogErr.fname fName]
in
{ ty = ty,
getter = either (#getter vold) (#getter vnew),
setter = either (#setter vold) (#setter vnew) }
end
fun mergeFixtures ((newName,newFix),oldFixs) =
if hasFixture oldFixs newName
then
case (newFix, getFixture oldFixs newName) of
(Ast.VirtualValFixture vnew,
Ast.VirtualValFixture vold) =>
replaceFixture oldFixs newName
(Ast.VirtualValFixture
(mergeVirtuals newName vnew vold))
| (Ast.ValFixture new, Ast.ValFixture old) =>
if (#ty new) = (#ty old) andalso (#readOnly new) = (#readOnly old)
then (trace ["skipping fixture ",LogErr.name (case newName of Ast.PropName n => n | _ => {ns=Ast.Internal "",id="temp"})]; oldFixs)
else error ["incompatible redefinition of fixture name: ", LogErr.fname newName]
| (Ast.MethodFixture new, Ast.MethodFixture old) =>
replaceFixture oldFixs newName (Ast.MethodFixture new) (* FIXME: types *)
| _ => error ["redefining fixture name: ", LogErr.fname newName]
else
(newName,newFix) :: oldFixs
fun addNamespace (ns,opennss) =
if hasNamespace opennss ns
then (trace ["skipping namespace ",LogErr.namespace ns]; opennss) (* FIXME: should be an error to open namspaces redundantly *)
else (trace ["adding namespace ", LogErr.namespace ns]; ns :: opennss)
fun eraseFixtures oldFixs ((newName,newFix),newFixs) =
(trace ["oldFixs"];
if hasFixture oldFixs newName
then
case (newFix, getFixture oldFixs newName) of
(Ast.VirtualValFixture vnew,
Ast.VirtualValFixture vold) =>
replaceFixture newFixs newName
(Ast.VirtualValFixture
(mergeVirtuals newName vnew vold))
| (Ast.ValFixture new, Ast.ValFixture old) =>
if (#ty new) = (#ty old) andalso (#readOnly new) = (#readOnly old)
then (trace ["erasing fixture ",LogErr.name (case newName of Ast.PropName n => n | _ => {ns=Ast.Internal "",id="temp"})]; newFixs)
else error ["incompatible redefinition of fixture name: ", LogErr.fname newName]
| _ => error ["redefining fixture name: ", LogErr.fname newName]
else
(newName,newFix) :: newFixs)
fun resolveExprToNamespace (env:ENV)
(expr:Ast.EXPR)
: Ast.NAMESPACE =
case expr of
Ast.LiteralExpr (Ast.LiteralNamespace ns) =>
let
val packageName = (#packageName (hd env))
val _ = trace ["packageIdent ",packageIdentFromPath packageName ""]
val ident = case packageName of
[] => ""
| p => packageIdentFromPath p ""
val _ = trace ["packageName ",ident]
in case ns of
Ast.Public _ => Ast.Public ident
| Ast.Internal _ => Ast.Internal ident
| _ => ns
end
| Ast.LexicalRef {ident = Ast.Identifier {ident,...}, pos } =>
let
val _ = LogErr.setPos pos
val mname = {nss = (#openNamespaces (hd env)), id = ident}
in
case resolveMultinameToFixture env mname of
(_,Ast.NamespaceFixture ns) => ns
| _ => LogErr.defnError ["namespace expression resolved ",
"to non-namespace fixture"]
end
| _ => LogErr.defnError ["unexpected expression type ",
"in namespace context"]
and defaultNamespace e = case e of c::_ => (#defaultNamespace c) | _ => LogErr.internalError ["empty environment in defaultNamespace"]
and resolveExprOptToNamespace (env: ENV)
(ns : Ast.EXPR option)
: Ast.NAMESPACE =
case ns of
NONE => defaultNamespace env
| SOME n => resolveExprToNamespace env n
(*
Create a new context initialised with the provided fixtures and
inherited environment
*)
fun extendEnvironment (env:ENV)
(fixtures:Ast.FIXTURES)
: ENV =
case env of
[] => (trace ["extending empty environment"];{ fixtures = fixtures,
tempOffset = 0,
openNamespaces = [[Ast.Internal ""]],
numericMode = defaultNumericMode,
labels = [],
packageNames = [],
className = NONE,
packageName = [],
defaultNamespace = Ast.Internal "" } :: [])
| ({ tempOffset, numericMode, openNamespaces, labels, packageNames, className,
packageName, defaultNamespace, ... }) :: _ =>
{ fixtures = fixtures,
tempOffset = tempOffset,
openNamespaces = openNamespaces,
numericMode = numericMode,
labels = labels,
packageNames = [],
className = className,
packageName = packageName,
defaultNamespace = defaultNamespace } :: env
fun updateFixtures (ctx::ex) (fxtrs:Ast.FIXTURES)
: ENV =
let
in
{ fixtures = List.foldl mergeFixtures fxtrs (#fixtures ctx),
tempOffset = (#tempOffset ctx),
openNamespaces = (#openNamespaces ctx),
numericMode = (#numericMode ctx),
labels = (#labels ctx),
packageNames = (#packageNames ctx),
className = (#className ctx),
packageName = (#packageName ctx),
defaultNamespace = (#defaultNamespace ctx) } :: ex
end
| updateFixtures ([]) (fxtrs:Ast.FIXTURES)
: ENV =
LogErr.defnError ["cannot update an empty environment"]
fun addPackageName ({name,...}:Ast.PACKAGE,(ctx::ex))
: ENV =
let
in
{ fixtures = (#fixtures ctx),
tempOffset = (#tempOffset ctx),
openNamespaces = (#openNamespaces ctx),
numericMode = (#numericMode ctx),
labels = (#labels ctx),
packageNames = name::(#packageNames ctx),
className = (#className ctx),
packageName = (#packageName ctx),
defaultNamespace = (#defaultNamespace ctx) } :: ex
end
| addPackageName (_,[])
: ENV =
LogErr.defnError ["cannot add package name to an empty environment"]
fun updateTempOffset (ctx::ex) (tempOffset:int)
: ENV =
let
in
{ fixtures = (#fixtures ctx),
tempOffset = tempOffset,
openNamespaces = (#openNamespaces ctx),
numericMode = (#numericMode ctx),
labels = (#labels ctx),
packageNames = (#packageNames ctx),
className = (#className ctx),
packageName = (#packageName ctx),
defaultNamespace = (#defaultNamespace ctx) } :: ex
end
| updateTempOffset ([]) (tempOffset:int)
: ENV =
LogErr.defnError ["cannot update an empty environment"]
fun dumpLabels labels = trace ["labels ", concat (map (fn (id,_) => id^" ") labels)]
fun dumpPath path = trace ["path ", concat (map (fn (id) => id^" ") path)]
(*
Add a label to the current environment context. Report an error
if there is a duplicate. Labels on switch and iteration statements
have special meaning. They get lifted into the switch or iteration
statement so the correct continuation value can be returned in case
of break, and the correct control flow produced in case of continue.
Also, the definition phase must distinguish between ordinary statement
labels and iteration and switch labels to validate continue statements.
*)
fun addLabel (env:ENV) (label:LABEL)
: ENV =
let
fun checkLabel (env:ENV) ((labelId,labelKnd):LABEL) =
case env of
{labels,...}::_ =>
(dumpLabels labels;
if List.exists (fn (id,knd) =>
not (id = "") andalso (* ignore empty labels *)
id = labelId andalso (* compare ids *)
knd = labelKnd) labels (* and kinds *)
then LogErr.defnError ["duplicate label ",labelId]
else ())
| [] => LogErr.internalError ["empty environment in addLabel"]
in
checkLabel env label;
case env of
({fixtures,tempOffset,labels,packageNames,openNamespaces,numericMode,className,
packageName,defaultNamespace}::e) =>
{ fixtures=fixtures,
tempOffset=tempOffset,
labels=label::labels,
packageNames=packageNames,
openNamespaces=openNamespaces,
numericMode=numericMode,
className = className,
packageName = packageName,
defaultNamespace = defaultNamespace } :: e
| [] => LogErr.internalError ["addLabels: cannot update an empty environment"]
end
fun addLabels (env:ENV) (labels:LABEL list)
: ENV =
let
in case labels of
[] => env
| _ =>
let
val env' = addLabel env (hd labels)
in
addLabels env' (tl labels)
end
end
fun multinameFromName (n:Ast.NAME) =
{ nss = [[(#ns n)]], id = (#id n) }
(*
Resolve an IDENT_EXPR to a multiname
A qualified name with a literal namespace qualifier (including package qualified)
gets resolved to a multiname with a single namespace
*)
fun identExprToMultiname (env:ENV) (ie:Ast.IDENT_EXPR)
: Ast.MULTINAME =
let
val ie' = defIdentExpr env ie
in case ie' of
Ast.Identifier {ident, ...} =>
let
in
{nss = (#openNamespaces (hd env)), id = ident}
end
| Ast.QualifiedIdentifier {ident, qual,...} =>
let
val ns = resolveExprToNamespace env qual
in
{nss = [[ns]], id = ident}
end
| Ast.TypeIdentifier {ident,typeArgs} =>
let
in
identExprToMultiname env ident
end
| _ => LogErr.defnError ["unhandled form of identifier expression in defIdentExpr"]
end
(*
CLASS_DEFN
The class definer analyzes the class definition into two blocks,
a class block that implements the class object and an instance
block that implements the instance objects.
ClassFixture = {
extends = ...
implements = ...
cblk = {
fxtrs = ... (* static fixtures *)
inits = ... (* static inits, empty? static props are inited by statements *)
body = ... (* static initialiser *)
}
iblk = { ... }
}
The steps taken are:
- analyze class body into instance and class blocks
- resolve extends and implements and do inheritance
- return a fixture binding for the class
*)
and defClass (env: ENV)
(cdef: Ast.CLASS_DEFN)
: (Ast.FIXTURES * Ast.CLASS_DEFN) =
let
val _ = trace ["defining class ",(#ident cdef)]
val class = analyzeClass env cdef
val class = resolveClass env cdef class
val Ast.Cls {name,...} = class
in
([(Ast.PropName name, Ast.ClassFixture class)],cdef)
end
and defInterface (env: ENV)
(idef: Ast.INTERFACE_DEFN)
: (Ast.FIXTURES * Ast.INTERFACE_DEFN) =
let
val _ = trace ["defining interface ",(#ident idef)]
(* FIXME
val class = analyzeClass env cdef
val class = resolveClass env cdef class
val Ast.Cls {name,...} = class
*)
in
([(Ast.PropName {ns=Ast.Public "",id=(#ident idef)}, Ast.InterfaceFixture)],idef)
end
(*
resolveClass
Inherit instance fixtures from the base class. Check fixtures against
interface fixtures
*)
and resolveClass (env:ENV)
({extends,implements,...}: Ast.CLASS_DEFN)
(Ast.Cls {name,classFixtures,instanceFixtures,instanceInits,
constructor,classType,instanceType,...}:Ast.CLS)
: Ast.CLS =
let
val _ = trace ["analyzing class block for ", LogErr.name name]
val (extendsName, instanceFixtures) = resolveExtends env instanceFixtures extends [name]
val (implementsNames, instanceFixtures) = resolveImplements env instanceFixtures implements
in
Ast.Cls {name=name, extends=extendsName,
implements=implementsNames,
classFixtures=classFixtures,
instanceFixtures=instanceFixtures,
instanceInits=instanceInits,
constructor=constructor,
classType=classType,
instanceType=instanceType}
end
(*
Resolve the base class
Steps
- resolve base class reference to a class fixture and its name
- inherit fixtures from the base class
Errors
- base class not found
- inheritance cycle detected
*)
and resolveExtends (env: ENV)
(currInstanceFixtures: Ast.FIXTURES)
(extends: Ast.IDENT_EXPR option)
(children:Ast.NAME list)
: (Ast.NAME option * Ast.FIXTURES) =
let
val _ = trace ["first child ", LogErr.name (hd children)]
fun seenAsChild (n:Ast.NAME) = List.exists (fn ch => ch = n) children
val extends:(Ast.IDENT_EXPR option) = case (extends,hd children) of
(NONE, {id,...}) =>
if (id="Object")
then NONE
else SOME (Ast.Identifier {ident="Object",openNamespaces=[]})
| _ => extends
in case extends of
SOME baseIdentExpr =>
let
val baseClassMultiname = identExprToMultiname env baseIdentExpr
val _ = trace ["inheriting from ",LogErr.multiname baseClassMultiname]
val (baseClassName,baseClassFixture) =
if false (* seenAsChild baseName *)
then LogErr.defnError ["cyclical class inheritence detected at ",
LogErr.multiname baseClassMultiname]
else (resolveMultinameToFixture env baseClassMultiname)
in case baseClassFixture of
Ast.ClassFixture (Ast.Cls {instanceFixtures=baseInstanceFixtures,...}) =>
(SOME baseClassName,inheritFixtures baseInstanceFixtures currInstanceFixtures)
| _ => LogErr.defnError ["base class not found"]
end
| NONE => (NONE,currInstanceFixtures)
end
(*
Resolve each of the expressions in the 'implements' list to an interface
fixture. check that each of the methods declared by each interface is
implemented by the current set of instance fixtures.
Steps
- resolve super interface references to interface fixtures
- inherit fixtures from the super interfaces
Errors
- super interface fixture not found
*)
and resolveImplements (env: ENV)
(currInstanceFixtures: Ast.FIXTURES)
(implements: Ast.IDENT_EXPR list)
: (Ast.NAME list * Ast.FIXTURES) =
let
val implements = map (identExprToMultiname env) implements
in
([],currInstanceFixtures)
end
(*
analyzeClass
The parser has already turned the class body into a block statement with init
statements for setting the value of static and prototype fixtures. This class
definition has a body whose only interesting statements left are init statements
that set the value of instance vars.
*)
and analyzeClass (env:ENV)
(cdef:Ast.CLASS_DEFN)
: Ast.CLS =
case cdef of
{ns, ident, instanceDefns, instanceStmts, classDefns, ctorDefn, (* block=Ast.Block { pragmas, body, ... },*) ...} =>
let
(*
Partition the class definition into a class block
and an instance block, and then define both blocks
*)
val ns = resolveExprOptToNamespace env ns
val name = {id=ident, ns=ns}
val (unhoisted,classFixtures,classInits) = defDefns env [] [] [] classDefns
val staticEnv = extendEnvironment env classFixtures
val (unhoisted,instanceFixtures,_) = defDefns staticEnv [] [] [] instanceDefns
val instanceEnv = extendEnvironment staticEnv instanceFixtures
val ctor =
case ctorDefn of
NONE => NONE
| SOME c => SOME (defCtor instanceEnv c)
val (instanceStmts,_) = defStmts staticEnv instanceStmts (* no hoisted fixture produced *)
(*
The parser separates variable definitions into defns and stmts. The only stmts
in this case will be InitStmts and what we really want is INITs so we translate
to to INITs here.
*)
fun initsFromStmt stmt =
case stmt of
Ast.ExprStmt (Ast.InitExpr (target,(temp_fxtrs,temp_inits),inits)) => (temp_fxtrs,temp_inits@inits)
| _ => LogErr.unimplError ["Defn.bindingsFromStmt"]
val (fxtrs,inits) = ListPair.unzip(map initsFromStmt instanceStmts)
val instanceInits = (List.concat fxtrs, List.concat inits)
in
Ast.Cls {name=name,
extends = NONE,
implements = [],
classFixtures = classFixtures,
instanceFixtures = instanceFixtures,
instanceInits = instanceInits,
constructor = ctor,
classType = Ast.SpecialType Ast.Any,
instanceType = Ast.SpecialType Ast.Any }
end
(*
inheritFixtures
Steps:
-
Errors:
- override by non-override fixture
- override of final fixture
- interface fixture not implemented
Notes:
don't check type compatibility yet; we don't know the value of type
expressions until verify time. In standard mode we need to do a
light weight verification to ensure that overrides are type compatible
before a class is loaded.
*)
and inheritFixtures (base:Ast.FIXTURES)
(derived:Ast.FIXTURES)
: Ast.FIXTURES =
let
(*
Recurse through the fixtures of a base class to see if the
given fixture binding is allowed. if so, then add it
return the updated fixtures
TODO: check for name conflicts:
Any name can be overridden by any other name with the same
identifier and a namespace that is at least as visible. Visibility
is an attribute of the builtin namespaces: private, protected,
internal and public. These are related by:
private < protected
protected < public
private < internal
internal < public
where < means less visible
Note that protected and internal are overlapping namespaces and
therefore it is an error to attempt to override a name in one
with a name in another.
It is an error for there to be a derived fixture with a name that is:
- less visible than a base fixture
- as visible or more visible than a base fixture but not overriding it
(this case is caught by the override check below)
*)
fun inheritFixture ((n,fb):(Ast.FIXTURE_NAME * Ast.FIXTURE))
: Ast.FIXTURES =
let
fun targetFixture _ = if (hasFixture derived n)
then SOME (getFixture derived n)
else NONE
val _ = trace ["checking override of ", LogErr.fname n]
in
case n of
(* Private fixtures never "inherit", so it's meaningless to ask. *)
Ast.PropName {ns=Ast.Private _, ...} => derived
| _ => case targetFixture () of
NONE => (n,fb)::derived (* not in the derived class, so inherit it *)
| SOME fd =>
case (canOverride fb fd) of
true => derived (* return current fixtures *)
| _ => LogErr.defnError ["illegal override of ", LogErr.fname n]
end
(*
Given two fixtures, one base and other derived, check to see if
the derived fixture can override the base fixture. Specifically,
check that:
- the base fixture is not 'final'
- the derived fixture is 'override'
- they have same number of type parameters and parameters
- they both have the return type void or neither has the return type void
- what else?
Type compatibility of parameter and return types is done by the evaluator
(or verifier in strict mode) and not here because type annotations can have
forward references
*)
and canOverride (fb:Ast.FIXTURE) (fd:Ast.FIXTURE)
: bool =
let
fun isVoid ty = case ty of Ast.SpecialType Ast.VoidType => true
| _ => false
val isCompatible = case (fb,fd) of
(Ast.MethodFixture
{ty=(Ast.FunctionType
{typeParams=tpb,params=pb,result=rtb,minArgs=mb,...}),
func=(Ast.Func {fsig=Ast.FunctionSignature {defaults=db, ...}, ...}),...},
Ast.MethodFixture
{ty=(Ast.FunctionType
{typeParams=tpd,params=pd,result=rtd,minArgs=md,...}),
func=(Ast.Func {fsig=Ast.FunctionSignature {defaults=dd, ...}, ...}),...}) =>
let
val _ = trace ["length tpb ",Int.toString (length tpb),
" length tpd ",Int.toString (length tpd),"\n"]
val _ = trace ["mb ",Int.toString mb, " md ",Int.toString md,"\n"]
val _ = trace ["length pb ",Int.toString (length pb),
" length pd ",Int.toString (length pd),"\n"]
val _ = trace ["length db ",Int.toString (length db),
" length dd ",Int.toString (length dd),"\n"]
in
(length tpb)=(length tpd)
andalso true (* FIXME: mb=md *)
andalso (((isVoid rtb) andalso (isVoid rtd))
orelse
((not (isVoid rtb)) andalso (not (isVoid rtd))))
(* FIXME: check compatibility of return types? *)
end
| _ => false
val _ = trace ["isCompatible = ",Bool.toString isCompatible]
in case (fb,fd) of
(Ast.MethodFixture {final,...}, Ast.MethodFixture {override,...}) =>
(not final) andalso override andalso isCompatible
(* FIXME: what are the rules for getter/setter overriding? *)
| (Ast.VirtualValFixture vb,
Ast.VirtualValFixture vd) =>
(#ty vb) = (#ty vd)
| _ => false
end
in case base of
[] => derived (* done *)
| first::follows => inheritFixtures follows (inheritFixture first)
end
and inheritFixtureOpts (base:Ast.FIXTURES option)
(derived:Ast.FIXTURES option)
: Ast.FIXTURES option =
case (base,derived) of
(NONE, NONE) => NONE
| (SOME x, NONE) => SOME x
| (SOME x, SOME y) => SOME (inheritFixtures x y)
| (NONE, SOME x) => SOME x
(*
BINDING
During parsing, variable definitions are split into a var binding
and optional init stmt. During the definition phase, the var binding
is translated into a fixture and optional initialiser. The init stmt
initalises the property value and its type
var v : t = x
A type annotation is an attribute of a fixture, evaluated
before the fixture is used to create a property. Light weight
implementations may evaluate type annotations when instantiating
a block scope for the first time. This lazy evaluation of type
annotations means that unresolved reference errors shall not
be reported until runtime in standard mode.
The definition above translates into the following psuedo
code during the definition phase
Block = {
fxtrs = [ val {id='v'} ]
inits = [ ref(v).type = t ]
stmts = [ v = x to ref(v).type ]
}
The fxtrs and inits of a var definition might be hoisted
out of their defining block. It is a definition error for
a type annotation to resolve to a local, non-type fixture.
This is to avoid changing the meaning of type annotations
by hoisting
Here's a problem case:
function f()
{
type t = {i:I,s:S}
{
type t = {i:int,s:string}
var v : t = {i:10,s:"hi"}
function g() : t {} {}
}
}
Without a definition error, the meaning of 't' changes
after hoisting of 'v' and 'g'
*)
and defVar (env:ENV)
(kind:Ast.VAR_DEFN_TAG)
(ns:Ast.NAMESPACE)
(var:Ast.BINDING)
: (Ast.FIXTURE_NAME*Ast.FIXTURE) =
case var of
Ast.Binding { ident, ty } =>
let
val ty' = defTyExpr env ty
val readOnly' = case kind of
Ast.Const => true
| Ast.LetConst => true
| _ => false
val offset = (#tempOffset (hd env))
val name' = fixtureNameFromPropIdent env (SOME ns) ident offset
in
(name', Ast.ValFixture {ty=ty',readOnly=readOnly'})
end
(*
(BINDING list * INIT_STEP list) -> (FIXTURES * INITS)
and INIT_STEP = (* used to encode init of bindings *)
InitStep of (BINDING_IDENT * EXPR)
| AssignStep of (EXPR * EXPR)
and BINDING_IDENT =
TempIdent of int
| PropIdent of IDENT
-->
and INITS = (FIXTURE_NAME * EXPR) list
and FIXTURE_NAME = TempName of int
| PropName of NAME
*)
and fixtureNameFromPropIdent (env:ENV) (ns:Ast.NAMESPACE option) (ident:Ast.BINDING_IDENT) (tempOffset:int)
: Ast.FIXTURE_NAME =
case ident of
Ast.TempIdent n => Ast.TempName (n+tempOffset)
| Ast.ParamIdent n => Ast.TempName n
| Ast.PropIdent id =>
let
in case ns of
SOME ns => Ast.PropName {ns=ns,id=id}
| _ =>
let
val mname = identExprToMultiname env (Ast.Identifier {ident=id,openNamespaces=[]})
val ({ns,id},f) = resolveMultinameToFixture env mname
in
Ast.PropName {ns=ns,id=id}
end
end
and defInitStep (env:ENV)
(ns:Ast.NAMESPACE option)
(step:Ast.INIT_STEP)
: (Ast.FIXTURE_NAME * Ast.EXPR) =
let
in case step of
Ast.InitStep (ident,expr) =>
let
val tempOffset = (#tempOffset (hd env))
val name = fixtureNameFromPropIdent env ns ident tempOffset
val expr = defExpr env expr