-
Notifications
You must be signed in to change notification settings - Fork 8
/
defn.sml
2364 lines (2026 loc) · 84.3 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 -*- *)
(*
* 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.
*)
structure Defn = struct
(* Local tracing machinery *)
val doTrace = ref false
val doTraceSummary = ref false
fun log ss = LogErr.log ("[defn] " :: ss)
fun error ss = LogErr.defnError ss
fun trace ss = if (!doTrace) then log ss else ()
fun trace2 (s, us) = if (!doTrace) then log [s, (Ustring.toAscii us)] else ()
fun fmtName n = if (!doTrace) then LogErr.name n else ""
fun fmtNs n = if (!doTrace) then LogErr.namespace n else ""
(*
* We use a globally unique numbering of type variables, assigned once when
* we walk the AST during definition. They are inserted in any fixtureMaps formed
* under a type binder. This includes the activation fixtureMap of any type-parametric
* function, the instance fixtureMap of any type-parametric interface or class, and
* -- depending on how we resolve the interaction of type parameters and
* class objects -- possibly the class fixtureMap of any type-parametric class.
*
* We do not insetrt them anywhere in type terms, because those have no fixtureMaps.
*)
val typeVarCounter = ref 0
fun mkTypeVarFixture _ =
(typeVarCounter := (!typeVarCounter) + 1;
Ast.TypeVarFixture (!typeVarCounter))
fun mkParamFixtureMap (idents:Ast.IDENTIFIER list)
: Ast.FIXTURE_MAP =
map (fn id => (Ast.PropName (Name.public id), (mkTypeVarFixture()))) idents
(*
* The goal of the definition phase is to put together the fixtureMaps
* 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
- translate defnitions to fixtureMap + initialisers
- check for conflicting fixtures
- hoist fixtureMap
- inherit super classes and interfaces
- evaluate pragmas
- capture open namespaces in unqualified identifiers
TODO
- fold types
- inheritance checks
*)
datatype LABEL_KIND =
IterationLabel
| SwitchLabel
| StatementLabel
type LABEL = (Ast.IDENTIFIER * LABEL_KIND)
(*
*
* The type ENV carrise *two* lists of FIXTURE_MAPs, outer and inner. The
* outer fixtureMaps are those including and containing the current hoisting
* scope. The inner fixtureMaps are any lexical scopes defined *inside* the
* current hoisting scope.
*
* Any time you add a hoisted definition to an environment, you are
* extending the head of the outerFixtureMaps. Any time you add a non-hoisted
* definition to an environment, you are extending the head of the
* innerFixtureMaps.
*
* The concatenation of the inner and outer fixtureMaps is the full fixtureMaps,
* which is the combined FIXTURE_MAPs you should use to look up any bindings
* in.
*)
type ENV =
{ innerFixtureMaps: Ast.FIXTURE_MAP list,
outerFixtureMaps: Ast.FIXTURE_MAP list,
tempOffset: int,
openNamespaces: Ast.NAMESPACE list list,
labels: LABEL list,
defaultNamespace: Ast.NAMESPACE,
rootFixtureMap: Ast.FIXTURE_MAP,
func: Ast.FUNC option }
val (initFixtureMap:Ast.FIXTURE_MAP) =
[
(* This is the new name that non-backward-compatibly pollutes the ES3 unqualified global. *)
(Ast.PropName Name.public_ES4, Ast.NamespaceFixture Name.ES4NS),
(* These are the namespaces in ES4 that have spec-defined, normative roles and meanings. *)
(Ast.PropName Name.ES4_public, Ast.NamespaceFixture Name.publicNS),
(Ast.PropName Name.ES4_meta, Ast.NamespaceFixture Name.metaNS),
(Ast.PropName Name.ES4_intrinsic, Ast.NamespaceFixture Name.intrinsicNS),
(*
* These are a namespaces that *would* be defined in the standard library except that we
* define a bunch of native methods in them, and therefore wish to have access to them here.
* In theory we could back off and look it up once the interpreter boots. They're just here
* to be convenient.
*)
(Ast.PropName Name.ES4_helper, Ast.NamespaceFixture Name.helperNS),
(Ast.PropName Name.ES4_informative, Ast.NamespaceFixture Name.informativeNS),
(*
* These are namespaces that *could* be defined in the boot process, but that code is
* sufficiently tangly and order-sensitive that it's much easier to define them here.
*)
(Ast.PropName Name.ES4_Unicode, Ast.NamespaceFixture Name.UnicodeNS),
(Ast.PropName Name.ES4_RegExpInternals, Ast.NamespaceFixture Name.RegExpInternalsNS)
]
fun getFullFixtureMaps (env:ENV)
: Ast.FIXTURE_MAPS =
let
val { innerFixtureMaps, outerFixtureMaps, ... } = env
in
innerFixtureMaps @ outerFixtureMaps
end
fun dumpEnv (e:ENV) : unit =
if (!doTrace)
then
let
val fixtureMaps = getFullFixtureMaps e
in
List.app Fixture.printFixtureMap fixtureMaps
end
else ()
fun makeTy (e:ENV)
(tyExpr:Ast.TYPE)
: Ast.TYPE =
(*
* FIXME: controversial? This attempts to normalize each type term the first
* time we see it. We ignore type errors since it's not technically
* our job to try this here; if someone wants early typechecking they can
* use the verifier.
*)
Type.normalize (getFullFixtureMaps e) tyExpr
handle LogErr.TypeError _ => tyExpr
fun inl f (a, b) = (f a, b)
fun isInstanceInit (s:Ast.STATEMENT)
: 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
(*
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 addNamespace (ns:Ast.NAMESPACE)
(opennss:Ast.NAMESPACE list) =
if List.exists (fn x => ns = x) opennss
(* FIXME: should be an error to open namspaces redundantly *)
then (trace ["skipping namespace ",fmtNs ns]; opennss)
else (trace ["adding namespace ", fmtNs ns]; ns :: opennss)
(*
NAME_EXPRESSION and NAMESPACE_EXPRESSION
*)
fun defNamespaceExpr (env:ENV)
(nse:Ast.NAMESPACE_EXPRESSION)
: Ast.NAMESPACE_EXPRESSION =
case nse of
Ast.NamespaceName nameExpr => Ast.NamespaceName (defNameExpr env nameExpr)
| _ => nse
and defNameExpr (env:ENV)
(ne:Ast.NAME_EXPRESSION)
: Ast.NAME_EXPRESSION =
let
val openNamespaces = (#openNamespaces env)
(* FIXME: this is a kludge; in the future the goal is to do a first pass
* and *collect* all the global names defined in a compilation unit, then
* run the definer with that collected set. For now we just work with the
* rootFixtureMap "up to this point in the file", which serves to disambiguate
* the same *most* of the time. Sometimes it's a bit too constrictive.
* Spec it with the set of all names declared, of course.
*)
fun getName ((Ast.PropName pn),_) = SOME pn
| getName _ = NONE
val globalNames = List.mapPartial getName (List.last (#outerFixtureMaps env)) (* not currently used *)
in
case ne of
Ast.UnqualifiedName { identifier, ... } =>
Ast.UnqualifiedName { identifier=identifier,
openNamespaces=openNamespaces }
| Ast.QualifiedName { namespace, identifier } =>
Ast.QualifiedName { namespace = defNamespaceExpr env namespace,
identifier = identifier }
end
fun resolveNamespaceOption (env: ENV)
(nse:Ast.NAMESPACE_EXPRESSION option)
: Ast.NAMESPACE =
case nse of
NONE => (#defaultNamespace env)
| SOME nse => Fixture.resolveNamespaceExpr (getFullFixtureMaps env) (defNamespaceExpr env nse)
fun resolveNamespace (env: ENV)
(nse:Ast.NAMESPACE_EXPRESSION)
: Ast.NAMESPACE =
Fixture.resolveNamespaceExpr (getFullFixtureMaps env) (defNamespaceExpr env nse)
fun resolve (env:ENV)
(nameExpr:Ast.NAME_EXPRESSION)
: (Ast.FIXTURE_MAPS * Ast.NAME * Ast.FIXTURE) =
Fixture.resolveNameExpr (getFullFixtureMaps env) (defNameExpr env nameExpr)
fun extendEnvironment (env:ENV)
(fixtureMap:Ast.FIXTURE_MAP)
(hoistingPoint:bool)
: ENV =
let
val { innerFixtureMaps, outerFixtureMaps, tempOffset, openNamespaces,
labels, defaultNamespace, rootFixtureMap, func } = env
val (newInnerFixtureMaps, newOuterFixtureMaps) = if hoistingPoint
then ([], fixtureMap :: (innerFixtureMaps @ outerFixtureMaps))
else (fixtureMap :: innerFixtureMaps, outerFixtureMaps)
in
{ innerFixtureMaps = newInnerFixtureMaps,
outerFixtureMaps = newOuterFixtureMaps,
tempOffset = tempOffset,
openNamespaces = openNamespaces,
labels = labels,
defaultNamespace = defaultNamespace,
rootFixtureMap = rootFixtureMap,
func = func }
end
fun mergeFixtureMaps (rootFixtureMap:Ast.FIXTURE_MAP)
(oldFixtureMap:Ast.FIXTURE_MAP)
(additions:Ast.FIXTURE_MAP)
: Ast.FIXTURE_MAP =
Fixture.mergeFixtureMaps (Type.matches rootFixtureMap []) oldFixtureMap additions
(* FIXME: calls some pretty-hairy type code - needed? *)
fun headAndTailOfFixtureMaps (fixtureMaps:Ast.FIXTURE_MAP list)
: (Ast.FIXTURE_MAP * Ast.FIXTURE_MAP list) =
case fixtureMaps of
[] => ([],[])
| (x::xs) => (x, xs)
fun addToInnerFixtureMap (env:ENV)
(additions:Ast.FIXTURE_MAP)
: ENV =
let
val { innerFixtureMaps, outerFixtureMaps, tempOffset, openNamespaces,
labels, defaultNamespace, rootFixtureMap, func } = env
val (innerFixtureMap, rest) = headAndTailOfFixtureMaps innerFixtureMaps
val newInnerFixtureMap = mergeFixtureMaps (#rootFixtureMap env) innerFixtureMap additions
val newInnerFixtureMaps = newInnerFixtureMap :: rest
in
{ innerFixtureMaps = newInnerFixtureMaps,
outerFixtureMaps = outerFixtureMaps,
tempOffset = tempOffset,
openNamespaces = openNamespaces,
labels = labels,
defaultNamespace = defaultNamespace,
rootFixtureMap = rootFixtureMap,
func = func }
end
fun addToOuterFixtureMap (env:ENV)
(additions:Ast.FIXTURE_MAP)
: ENV =
let
val { innerFixtureMaps, outerFixtureMaps, tempOffset, openNamespaces,
labels,
defaultNamespace, rootFixtureMap, func } = env
val (outerFixtureMap, rest) = headAndTailOfFixtureMaps outerFixtureMaps
val newOuterFixtureMap = mergeFixtureMaps (#rootFixtureMap env) outerFixtureMap additions
val newOuterFixtureMaps = newOuterFixtureMap :: rest
in
{ innerFixtureMaps = innerFixtureMaps,
outerFixtureMaps = newOuterFixtureMaps,
tempOffset = tempOffset,
openNamespaces = openNamespaces,
labels = labels,
defaultNamespace = defaultNamespace,
rootFixtureMap = rootFixtureMap,
func = func }
end
fun updateTempOffset (env:ENV) (newTempOffset:int)
: ENV =
let
val { innerFixtureMaps, outerFixtureMaps, tempOffset, openNamespaces,
labels, defaultNamespace, rootFixtureMap, func } = env
in
{ innerFixtureMaps = innerFixtureMaps,
outerFixtureMaps = outerFixtureMaps,
tempOffset = newTempOffset,
openNamespaces = openNamespaces,
labels = labels,
defaultNamespace = defaultNamespace,
rootFixtureMap = rootFixtureMap,
func = func }
end
fun enterClass (env:ENV)
(privateNS:Ast.NAMESPACE)
(protectedNS:Ast.NAMESPACE)
(parentProtectedNSs:Ast.NAMESPACE list)
: (ENV * Ast.FIXTURE_MAP) =
let
val localNamespaceFixtureMap = [ (Ast.PropName (Name.private privateNS),
Ast.NamespaceFixture privateNS),
(Ast.PropName (Name.protected privateNS),
Ast.NamespaceFixture protectedNS) ]
val env = extendEnvironment env localNamespaceFixtureMap true
val { innerFixtureMaps, outerFixtureMaps, tempOffset, openNamespaces,
labels, defaultNamespace, rootFixtureMap, func } = env
val openNamespaces = ([privateNS, protectedNS] @ parentProtectedNSs) :: openNamespaces
in
({ innerFixtureMaps = innerFixtureMaps,
outerFixtureMaps = outerFixtureMaps,
tempOffset = tempOffset,
openNamespaces = openNamespaces,
labels = labels,
defaultNamespace = defaultNamespace,
rootFixtureMap = rootFixtureMap,
func = func }, localNamespaceFixtureMap )
end
fun enterFuncBody (env:ENV) (newFunc:Ast.FUNC)
: ENV =
let
val { innerFixtureMaps, outerFixtureMaps, tempOffset, openNamespaces,
labels,
defaultNamespace, rootFixtureMap, func } = env
in
{ innerFixtureMaps = innerFixtureMaps,
outerFixtureMaps = outerFixtureMaps,
tempOffset = tempOffset,
openNamespaces = openNamespaces,
labels = labels,
defaultNamespace = defaultNamespace,
rootFixtureMap = rootFixtureMap,
func = SOME newFunc }
end
fun dumpLabels (labels : LABEL list) =
trace ["labels ", concat (map (fn (id,_) => (Ustring.toAscii id) ^ " ") labels)]
(*
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 ((label:LABEL),(env:ENV))
: ENV =
let
val { innerFixtureMaps, outerFixtureMaps, tempOffset, openNamespaces,
labels, defaultNamespace, rootFixtureMap, func } = env
val (labelId,labelKnd) = label
in
dumpLabels labels;
if List.exists (fn ((id,knd):LABEL) =>
not (id = Ustring.empty) andalso (* ignore empty labels *)
id = labelId andalso (* compare ids *)
knd = labelKnd) labels (* and kinds *)
then LogErr.defnError ["duplicate label ", Ustring.toAscii labelId]
else ();
{ innerFixtureMaps = innerFixtureMaps,
outerFixtureMaps = outerFixtureMaps,
tempOffset = tempOffset,
openNamespaces = openNamespaces,
labels = label::labels,
defaultNamespace = defaultNamespace,
rootFixtureMap = rootFixtureMap,
func = func }
end
fun addLabels (env:ENV) (labels:LABEL list)
: ENV =
List.foldl addLabel env labels
(*
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 fixtureMap *)
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.FIXTURE_MAP * Ast.CLASS_DEFN) =
let
val class = analyzeClassBody env cdef
val class = resolveClassInheritance env cdef class
val Ast.Class {name,...} = class
in
([(Ast.PropName name, Ast.ClassFixture class)],cdef)
end
(*
Defining an interface
- unpack the interface definition
- construct the interface name
- resolve super interfaces
- define current interface definitions
- inherit base fixtureMap
- construct instance type
- construct interface
- return interface fixture
*)
and defInterface (env: ENV)
(idef: Ast.INTERFACE_DEFN)
: (Ast.FIXTURE_MAP * Ast.INTERFACE_DEFN) =
let
val { ident, ns, nonnullable, params, extends, instanceDefns } = idef
val namespace = resolveNamespaceOption env ns
(* Make the interface name *)
val name = {id = ident, ns = namespace}
(* Resolve base interface's super interfaces and fixtureMap *)
val (superInterfaces:Ast.TYPE list, inheritedFixtureMap:Ast.FIXTURE_MAP) = resolveInterfaces env extends
(* val groundSuperInterfaceExprs = map (Type.groundExpr o (makeTy env) o (fn t => Type.normalize (getFullFixtureMaps env) t)) superInterfaces *)
val groundSuperInterfaceExprs = map (makeTy env) superInterfaces
val instanceEnv = extendEnvironment env [] true
val (typeParamFixtureMap:Ast.FIXTURE_MAP) = mkParamFixtureMap params
val instanceEnv = addToInnerFixtureMap instanceEnv typeParamFixtureMap
(* Define the current fixtureMap *)
val (unhoisted,instanceFixtureMap,_) = defDefns instanceEnv instanceDefns
(* Inherit fixtureMap and check overrides *)
val instanceFixtureMap:Ast.FIXTURE_MAP = inheritFixtureMap NONE NONE inheritedFixtureMap instanceFixtureMap
val iface:Ast.INTERFACE =
Ast.Interface { name=name,
typeParams=params,
nonnullable=nonnullable,
extends=superInterfaces,
instanceFixtureMap=instanceFixtureMap }
in
([(Ast.PropName name, Ast.InterfaceFixture iface)],idef)
end
(*
inheritFixtureMap
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.
*)
(*
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 parameters
- they both have the return type void or neither has the return type void
- what else?
- FIXME: perhaps we ought to permit overriding fixtures with
parametric types; we used to but the problem is more complex with general
lambda types. Currently disabled.
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.VoidType => true
| _ => false
*)
val isCompatible = case (fb,fd) of
(Ast.MethodFixture
{ty=Ast.FunctionType {params=pb,
result=rtb,
minArgs=mb,
...},
func=Ast.Func
{fsig=Ast.FunctionSignature
{defaults=db,
...},
...},
...},
Ast.MethodFixture
{ty=Ast.FunctionType {params=pd,
result=rtd,
minArgs=md,
...},
func=Ast.Func
{fsig=Ast.FunctionSignature
{defaults=dd,
...},
...},
...}) =>
let
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
true
(*
((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,func,...},
Ast.MethodFixture {override,...}) =>
(((not final) andalso override) orelse (AstQuery.funcIsAbstract func))
andalso isCompatible
(* FIXME: what are the rules for getter/setter overriding?
1/base fixture is not final
2/derived fixture is override
3/getter is compatible
4/setter is compatible
*)
| (Ast.VirtualValFixture vb,
Ast.VirtualValFixture vd) =>
let
val _ = trace ["checking override of VirtualValFixture"]
in
true
end
| _ => LogErr.unimplError ["checkOverride"]
end
and inheritFixtureMap (privateNS:Ast.NAMESPACE option)
(baseClass:Ast.CLASS option)
(base:Ast.FIXTURE_MAP)
(derived:Ast.FIXTURE_MAP)
: Ast.FIXTURE_MAP =
let
(*
Recurse through the fixtureMap of a base class to see if the
given fixture binding is allowed. if so, then add it
return the updated fixtureMap
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:Ast.FIXTURE_NAME, fb:Ast.FIXTURE)
: Ast.FIXTURE_MAP =
let
fun targetFixture _ = if (Fixture.hasFixture derived n)
then SOME (Fixture.getFixture derived n)
else NONE
val canInherit =
case (n, privateNS) of
(* NB: you can -- and must -- *inherit* the private fixtures,
* in the sense that other inherited fixtures may refer to them
* as helpers. What you *can't* inherit is the binding for the
* name "private". Nor can you *see* any of the inherited privates,
* since you have no access to the base private namespace.
*)
(Ast.PropName name, SOME pns) => not (name = (Name.private pns))
| (Ast.PropName _, _) => true
| (Ast.TempName _, _) => error ["inheriting temp fixture"]
val fb = case fb of
Ast.MethodFixture { func, ty, writable, override, final, inheritedFrom=NONE }
=> Ast.MethodFixture { func=func, ty=ty, writable=writable,
override=override, final=final,
inheritedFrom=baseClass }
| Ast.VirtualValFixture { ty, getter, setter }
=>
let
fun f (SOME (x, NONE)) = SOME (x, baseClass)
| f x = x
in
Ast.VirtualValFixture { ty = ty,
getter = f getter,
setter = f setter }
end
| _ => fb
in
if canInherit
then 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]
else derived
end
in case base of
[] => derived (* done *)
| first::follows => inheritFixtureMap privateNS baseClass follows (inheritFixture first)
end
(*
implementFixtures
Steps:
-
Errors:
- interface fixture not implemented
*)
and implementFixtures (base:Ast.FIXTURE_MAP)
(derived:Ast.FIXTURE_MAP)
: unit =
let
(*
*)
fun implementFixture ((n,fb):(Ast.FIXTURE_NAME * Ast.FIXTURE))
: Ast.FIXTURE_MAP =
let
fun targetFixture _ = if (Fixture.hasFixture derived n)
then SOME (Fixture.getFixture derived n)
else NONE
in
case targetFixture () of
NONE => LogErr.defnError ["unimplemented interface method ", LogErr.fname n]
| SOME fd =>
case (canOverride fb fd) of
true => derived (* return current fixtures *)
| _ => LogErr.defnError ["illegal implementation of ", LogErr.fname n]
end
in case base of
[] => () (* done *)
| first::follows => implementFixtures follows (implementFixture first)
end
(*
resolveClassInheritance
Inherit instance fixtures from the base class. Check fixtures against
interface fixtures
*)
and resolveClassInheritance (env:ENV)
({extends,implements,...}: Ast.CLASS_DEFN)
(cls:Ast.CLASS)
: Ast.CLASS =
let
val Ast.Class {name, privateNS, protectedNS, parentProtectedNSs,
typeParams, nonnullable, dynamic, classFixtureMap,
instanceFixtureMap, instanceInits, constructor, ...} = cls
val _ = trace ["analyzing inheritance for ", fmtName name]
val (extendsTy:Ast.TYPE option,
instanceFixtureMap0:Ast.FIXTURE_MAP) = resolveExtends env instanceFixtureMap extends name
val (implementsTys:Ast.TYPE list,
instanceFixtureMap1:Ast.FIXTURE_MAP) = resolveImplements env instanceFixtureMap0 implements
in
Ast.Class {name=name,
privateNS=privateNS,
protectedNS=protectedNS,
parentProtectedNSs=parentProtectedNSs,
typeParams=typeParams,
nonnullable=nonnullable,
dynamic=dynamic,
extends=extendsTy,
implements=implementsTys,
classFixtureMap=classFixtureMap,
instanceFixtureMap=instanceFixtureMap1,
instanceInits=instanceInits,
constructor=constructor}
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)
(currInstanceFixtureMap:Ast.FIXTURE_MAP)
(extends:Ast.TYPE option)
(currName:Ast.NAME)
: (Ast.TYPE option * Ast.FIXTURE_MAP) =
let
val baseClassNameExpr:Ast.NAME_EXPRESSION option =
case extends of
NONE => if currName = Name.public_Object
then NONE
else SOME (Name.nameExprOf Name.public_Object)
| SOME te => SOME (extractNameExprFromTypeName te)
in
case baseClassNameExpr of
NONE => (NONE, currInstanceFixtureMap)
| SOME bcm =>
let
val (_,
baseClassName:Ast.NAME,
baseClassFixture:Ast.FIXTURE) =
resolve env bcm
val baseClass = needClassFixture baseClassFixture
val Ast.Class { privateNS, instanceFixtureMap, ... } = baseClass
in
(SOME (Ast.InstanceType baseClass),
inheritFixtureMap (SOME privateNS)
(SOME baseClass)
instanceFixtureMap
currInstanceFixtureMap)
end
end
and resolveImplements (env: ENV)
(instanceFixtureMap: Ast.FIXTURE_MAP)
(implements: Ast.TYPE list)
: (Ast.TYPE list * Ast.FIXTURE_MAP) =
let
val (superInterfaces, abstractFixtureMap) = resolveInterfaces env implements
val _ = implementFixtures abstractFixtureMap instanceFixtureMap
in
(superInterfaces,instanceFixtureMap)
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 fixtureMaps.
Steps
- resolve super interface references to interface fixtures
- inherit fixtureMaps from the super interfaces
Errors
- super interface fixture not found
*)
and interfaceMethods (ifxtr:Ast.FIXTURE)
: Ast.FIXTURE_MAP =
case ifxtr of
Ast.InterfaceFixture (Ast.Interface {instanceFixtureMap,...}) => instanceFixtureMap
|_ => LogErr.internalError ["interfaceMethods"]
and interfaceExtends (ifxtr:Ast.FIXTURE)
: Ast.TYPE list =
case ifxtr of
Ast.InterfaceFixture (Ast.Interface {extends,...}) => extends
|_ => LogErr.internalError ["interfaceExtends"]
and interfaceInstanceType (ifxtr:Ast.FIXTURE)
: Ast.TYPE =
case ifxtr of
Ast.InterfaceFixture i => Ast.InterfaceType i
|_ => LogErr.internalError ["interfaceInstanceType"]
and needClassFixture (cfxtr:Ast.FIXTURE)
: Ast.CLASS =
case cfxtr of
Ast.ClassFixture cf => cf
| _ => error ["need class fixture"]
(*
resolve a list of interface names to their super interfaces and
method fixtureMaps
interface I { function m() }
interface J extends I { function n() } // [I],[m]
interface K extends J {} // [I,J] [m,n]
*)
(* FIXME: for the time being we're only going to handle inheriting from
* TYPEs of a simple form: those which name a 0-parameter interface.
* Generalize later.
*)
and extractNameExprFromTypeName (Ast.TypeName (ne, _)) : Ast.NAME_EXPRESSION = ne
| extractNameExprFromTypeName _ =
error ["can only presently handle inheriting from simple named interfaces"]
and resolveInterfaces (env: ENV)
(types: Ast.TYPE list)
: (Ast.TYPE list * Ast.FIXTURE_MAP) =
case types of
[] => ([],[])
| _ =>
let
val nameExprs:Ast.NAME_EXPRESSION list = map extractNameExprFromTypeName types
fun resolveToFix ne = let val (_, _, fix) = resolve env ne in fix end
val ifaces = map resolveToFix nameExprs
val ifaceInstanceTypes:Ast.TYPE list = map interfaceInstanceType ifaces
val superInterfaceTypes:Ast.TYPE list = List.concat (map interfaceExtends ifaces)
val methodFixtureMap:Ast.FIXTURE_MAP = List.concat (map interfaceMethods ifaces)
in
(ifaceInstanceTypes @ superInterfaceTypes, methodFixtureMap)
end
(*
analyzeClassBody
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 analyzeClassBody (env:ENV)
(cdef:Ast.CLASS_DEFN)
: Ast.CLASS =
let
val {ns, privateNS, protectedNS, ident,
nonnullable, dynamic, params, classDefns, instanceDefns,
instanceStmts, ctorDefn, ...} = cdef
(*
* Partition the class definition into a class block
* and an instance block, and then define both blocks.
*)
val ns = resolveNamespaceOption env ns
val name = {id=ident, ns=ns}
val _ = trace ["defining class ", fmtName name]
val (staticEnv, localNamespaceFixtureMap) = enterClass env privateNS protectedNS []
val (unhoisted,classFixtureMap,classInits) = defDefns staticEnv classDefns
val classFixtureMap = (mergeFixtureMaps (#rootFixtureMap env) unhoisted classFixtureMap)
val classFixtureMap = (mergeFixtureMaps (#rootFixtureMap env) classFixtureMap localNamespaceFixtureMap)
(* namespace and type definitions aren't normally hoisted *)
val instanceEnv = extendEnvironment staticEnv [] true
(* FIXME: there is some debate about whether type parameters live in the
* instance fixtureMap or the class fixtureMap. This needs to be resolved.
*)
val (typeParamFixtureMap:Ast.FIXTURE_MAP) = mkParamFixtureMap params
val instanceEnv = addToInnerFixtureMap instanceEnv typeParamFixtureMap
val (unhoisted,instanceFixtureMap,_) = defDefns instanceEnv instanceDefns
val instanceEnv = addToInnerFixtureMap instanceEnv instanceFixtureMap
val ctor:Ast.CTOR option =
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