-
Notifications
You must be signed in to change notification settings - Fork 8
/
verify.sml
1799 lines (1570 loc) · 61.9 KB
/
verify.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 Verify = struct
open LogErr
type RIB = Ast.FIXTURES
(* ENV contains all type checking context, including ribs (variable-type bindings),
* strict vs standard mode, and the expected return type, if any.
*)
type ENV = { returnType: Ast.TYPE_EXPR option,
strict: bool,
ribs: RIB list }
fun withReturnType { returnType=_, strict, ribs } returnType =
{ returnType=returnType, strict=strict, ribs=ribs }
fun withRibs { returnType, strict, ribs=_ } ribs =
{ returnType=returnType, strict=strict, ribs=ribs }
fun withStrict { returnType, strict=_, ribs } strict =
{ returnType=returnType, strict=strict, ribs=ribs }
fun withRib { returnType, strict, ribs} extn =
{ returnType=returnType, strict=strict, ribs=extn :: ribs }
structure NmKey = struct type ord_key = Ast.NAME val compare = NameKey.compare end
structure NmMap = SplayMapFn (NmKey);
structure NmVecKey = struct type ord_key = (Ast.NAME vector) val compare = (Vector.collate NameKey.compare) end
structure NmVecMap = SplayMapFn (NmVecKey);
val (fixtureCache:(Ast.FIXTURE NmMap.map) ref) = ref NmMap.empty
val (instanceOfCache:(bool NmVecMap.map) ref) = ref NmVecMap.empty
val cachesz = 1024
(* Local tracing machinery *)
val doTrace = ref false
val doTraceProg = ref false
fun trace ss = if (!doTrace) then LogErr.log ("[verify] " :: ss) else ()
fun error ss = LogErr.verifyError ss
fun logType ty = (Pretty.ppType ty; TextIO.print "\n")
fun traceType ty = if (!doTrace) then logType ty else ()
(*
fun typeToString ty = ...
*)
fun fmtName n = if !doTrace
then LogErr.name n
else ""
fun fmtType ty = if !doTrace
then Type.toString ty
else ""
(* Mapping the rib structure to multiname lookup. *)
fun parentRib [] = NONE
| parentRib (x::[]) = NONE
| parentRib (x::xs) = SOME xs
fun resolve (ribs:RIB list) (mname:Ast.MULTINAME) =
case ribs of
[] => NONE
| _ => Multiname.resolveInFixtures mname ribs List.hd parentRib
fun findFixture (ribs:RIB list) (mname:Ast.MULTINAME) =
case resolve ribs mname of
NONE => error ["unable to resolve fixture for multiname: ", LogErr.multiname mname]
| SOME (fixs, n) => Fixture.getFixture fixs (Ast.PropName n)
fun resolveExprToNamespace (env:ENV)
(expr:Ast.EXPR)
: Ast.NAMESPACE =
case expr of
Ast.LiteralExpr (Ast.LiteralNamespace ns) => ns
| Ast.LexicalRef {ident = Ast.Identifier {ident, openNamespaces}, loc } =>
(case findFixture (#ribs env) {nss = openNamespaces, id = ident} of
Ast.NamespaceFixture ns => ns
| _ => error ["namespace expression resolved ",
"to non-namespace fixture"])
| _ => error ["unexpected expression type ",
"in namespace context"]
(****************************** standard types *************************)
fun instanceTypeExpr (n:Ast.NAME) : Ast.TYPE_EXPR =
Ast.InstanceType (Fixture.instanceType (!Defn.topFixtures) n)
val undefinedType = Ast.SpecialType Ast.Undefined
val nullType = Ast.SpecialType Ast.Null
val anyType = Ast.SpecialType Ast.Any
(****************************** misc auxiliary functions *************************)
fun assert b s = if b then () else (raise Fail s)
fun checkForDuplicates [] = ()
| checkForDuplicates (x::xs) =
if List.exists (fn y => x = y) xs
then error ["concurrent definition"]
else checkForDuplicates xs
fun unOptionDefault NONE def = def
| unOptionDefault (SOME v) _ = v
fun flattenOptionList NONE = []
| flattenOptionList (SOME l) = l
val gensymCounter : int ref = ref 0
fun gensym (s:Ustring.STRING) : Ustring.STRING =
let
in
gensymCounter := 1+(!gensymCounter);
Ustring.append [s, Ustring.dollar, Ustring.fromInt (!gensymCounter)]
end
(************************* Substitution on Types *********************************)
(* TODO: normalized types?? *)
fun substTypeExpr (s:(Ast.IDENT*Type.TYPE_VALUE) list)
(t:Type.TYPE_VALUE)
: Ast.TYPE_EXPR =
let in
case t of
Ast.UnionType ts =>
Ast.UnionType (map (substTypeExpr s) ts)
| Ast.ArrayType ts =>
Ast.ArrayType (map (substTypeExpr s) ts)
| Ast.AppType {base, args} =>
Ast.AppType {base=substTypeExpr s base, args=map (substTypeExpr s) args}
| Ast.NullableType {expr, nullable}
=> Ast.NullableType {expr=substTypeExpr s expr, nullable=nullable}
| Ast.TypeName ((Ast.Identifier {ident=ident, openNamespaces=_})) =>
let in
case List.find
(fn (id,ty) => id=ident)
s
of
(* TODO: we're dropping the nullable here, is that right? *)
SOME (_,ty) => ty
| NONE => t
end
| Ast.ObjectType fields =>
Ast.ObjectType (map (fn {name,ty} =>
{name=name,ty=substTypeExpr s ty})
fields)
| Ast.SpecialType st => Ast.SpecialType st
| Ast.FunctionType { typeParams, params, result, thisType, hasRest, minArgs } =>
(* Need to uniquify typeParams to avoid capture *)
let val oldNew = map (fn id => (id, gensym id)) typeParams
val nuSub =
map
(fn (oldId,newId) =>
(oldId,
Ast.TypeName (Ast.Identifier {ident=newId,openNamespaces=[]})))
oldNew
val bothSubs = fn t => substTypeExpr s (substTypeExpr nuSub t)
val nuTypeParams = map (fn (oldId,newId) => newId) oldNew
(* val nuParams = map (fn t => substVarBinding s (substVarBinding nuSub t)) params *)
in
Ast.FunctionType {typeParams=nuTypeParams,
params = List.map bothSubs params,
result = bothSubs result,
thisType = Option.map bothSubs thisType,
hasRest=hasRest, minArgs = minArgs }
end
end
(************************* Handling Types *********************************)
fun verifyTypeExpr (env:ENV)
(ty:Ast.TYPE_EXPR)
: Type.TYPE_VALUE =
let in
trace ["verifyTypeExpr: ", fmtType ty];
case ty of
(*
Ast.TypeName
*)
Ast.SpecialType _ =>
ty
| Ast.UnionType tys =>
Ast.UnionType (verifyTypeExprs env tys)
| Ast.ArrayType tys =>
Ast.ArrayType (verifyTypeExprs env tys)
| Ast.NullableType {expr=ty,nullable} =>
Ast.NullableType {expr=verifyTypeExpr env ty, nullable=nullable}
| Ast.AppType {base,args} =>
let val base' = verifyTypeExpr env base
val args' = verifyTypeExprs env args
in case base' of
Ast.FunctionType {typeParams,params,result,thisType,hasRest,minArgs} =>
let val _ = assert (length args = length typeParams);
val sub = ListPair.zip (typeParams,args)
fun applySub t = substTypeExpr sub t
val result =
Ast.FunctionType { typeParams=[],
params=map (substTypeExpr sub) params,
result=substTypeExpr sub result,
thisType= Option.map (substTypeExpr sub) thisType,
hasRest=hasRest, minArgs=minArgs }
in
verifyTypeExpr env result
end
| _ => Ast.AppType {base=base', args=args'}
end
| Ast.FunctionType {typeParams, params, result, thisType, hasRest, minArgs} =>
let
(* Add the type parameters to the environment. *)
val env' : ENV =
withRib env (List.map
(fn id => (Ast.PropName (Name.nons id),
Ast.TypeVarFixture))
typeParams)
val params' = verifyTypeExprs env' params
val result' = verifyTypeExpr env' result
val thisType' = Option.map (verifyTypeExpr env') thisType
in
Ast.FunctionType { typeParams=typeParams, params=params', result=result',
thisType=thisType', hasRest=hasRest, minArgs=minArgs }
end
| Ast.ObjectType fields =>
let val fields' =
map (fn {name,ty} => {name=name, ty=verifyTypeExpr env ty})
fields
val names = map (fn {name,ty} => name) fields
val _ = checkForDuplicates names
in
Ast.ObjectType fields'
end
| Ast.TypeName ie =>
let
fun findType id nss =
let
fun tryRibs ribs =
case findFixture ribs {nss=nss, id=id} of
(* FIXME: re-resolve result ... in which environment? *)
Ast.TypeFixture ty => ty
| Ast.ClassFixture (Ast.Cls cls) => Ast.InstanceType (#instanceType cls)
| Ast.InterfaceFixture (Ast.Iface iface) => Ast.InstanceType (#instanceType iface)
| _ => error ["multiname ", LogErr.multiname {nss=nss, id=id},
" resolved to non-type fixture"]
(*
| _ => case ribs of
(r :: rs) => tryRibs rs
| [] => error ["multiname ", LogErr.multiname {nss=nss, id=id},
" resolved to non-type fixture"]
*)
in
tryRibs (#ribs env)
end
val resolved = case ie of
Ast.Identifier { ident, openNamespaces } => findType ident openNamespaces
| Ast.QualifiedIdentifier { qual, ident } => findType ident [[resolveExprToNamespace env qual]]
| Ast.WildcardIdentifier => Ast.SpecialType Ast.Any
| _ => error ["unexpected identifier form in type name" ]
in
(*
* FIXME: this is a bug: we should re-resolve in the environment the type definition was found in,
* not our own environment. Since type definitions are only about lexical scope though, we should
* be in an extension of the defining environment, so unless there are shadowing relations we
* should get a tolerable approximation of correct
* behavior here. Fix later.
*)
verifyTypeExpr env resolved
end
| Ast.ElementTypeRef ((Ast.ArrayType fields), idx) =>
let
val t = if idx < length fields
then List.nth (fields, idx)
else
if length fields > 0
then List.last fields
else Ast.SpecialType Ast.Any
in
verifyTypeExpr env t
end
| Ast.ElementTypeRef (Ast.SpecialType Ast.Any, _) =>
Ast.SpecialType Ast.Any
| Ast.ElementTypeRef (Ast.ElementTypeRef _, _) =>
Ast.SpecialType Ast.Any (* FIXME may be able to get a more specific type *)
| Ast.ElementTypeRef (t, _) =>
error ["ElementTypeRef on non-ArrayType: ", Type.toString t]
| Ast.FieldTypeRef ((Ast.ObjectType fields), ident) =>
let
fun f [] = error ["FieldTypeRef on unknown field: ", Ustring.toAscii ident]
| f ({name,ty}::fields) = if name = ident
then verifyTypeExpr env ty
else f fields
in
f fields
end
| Ast.FieldTypeRef (Ast.SpecialType Ast.Any, _) =>
Ast.SpecialType Ast.Any
| Ast.FieldTypeRef (t, ident) =>
error ["FieldTypeRef to ", Ustring.toAscii ident, " on non-ObjectType: ", Type.toString t]
| _ => ty
(*
| _ =>
let in
logType ty;
unimplError ["verifyTypeExpr"]
end
*)
end
and verifyTypeExprs (env:ENV)
(tys:Ast.TYPE_EXPR list)
: Type.TYPE_VALUE list =
(List.map (verifyTypeExpr env) tys)
(*
* TODO: when type checking a function body, handle CalledEval
* TODO: during type checking, if you see naked invocations of "eval" (that
* exact name), raise CalledEval
*)
fun mergeTypes t1 t2 =
(*FIXME*)
t1
fun funcSigType (env:ENV)
(fsig:Ast.FUNC_SIG)
: Type.TYPE_VALUE =
(* TODO: implement this *)
anyType
(******************* Subtyping and Compatibility *************************)
infix 4 <:;
fun (tsub <: tsup) =
Type.isSubtype (!Defn.topFixtures) tsub tsup
infix 4 ~:;
fun (tleft ~: tright) =
Type.isCompatible (!Defn.topFixtures) tleft tright
fun checkCompatible (t1:Type.TYPE_VALUE)
(t2:Type.TYPE_VALUE)
: unit =
if t1 ~: t2
then ()
else let in
TextIO.print ("checkCompatible failed: " ^ (Type.toString t1) ^ " vs. " ^ (Type.toString t2) ^ "\n");
verifyError ["Types are not compatible"]
end
fun checkBicompatible (ty1:Type.TYPE_VALUE)
(ty2:Type.TYPE_VALUE)
: unit =
let in
checkCompatible ty1 ty2;
checkCompatible ty2 ty1
end
fun checkConvertible (ty1:Type.TYPE_VALUE)
(ty2:Type.TYPE_VALUE)
: unit =
(* TODO: int to float, etc, and to() methods *)
checkCompatible ty1 ty2
fun leastUpperBound (t1:Type.TYPE_VALUE)
(t2:Type.TYPE_VALUE)
: Type.TYPE_VALUE =
let
in
if t1 <: t2 then
t2
else if t2 <: t1 then
t1
else
Ast.UnionType [t1, t2]
end
(******************** Verification **************************************************)
(*
HEAD
*)
and verifyInits (env:ENV) (inits:Ast.INITS)
: Ast.INITS =
List.map (fn (name, expr) => (name, verifyExprOnly env expr))
inits
and verifyInitsOption (env:ENV)
(inits:Ast.INITS option)
: Ast.INITS =
case inits of
SOME inits => verifyInits env inits
| _ => internalError ["missing inits"]
and verifyHead (env:ENV) ((Ast.Head (fixtures, inits)):Ast.HEAD)
: Ast.HEAD =
(trace ["verifying head with ", Int.toString (length fixtures), " fixtures"];
(Ast.Head (verifyFixtures env fixtures, verifyInits env inits)))
(*
EXPR
*)
and verifyExpr (env:ENV)
(expr:Ast.EXPR)
: (Ast.EXPR * Type.TYPE_VALUE) =
let
fun verifySub e = verifyExpr env e
fun verifySubList es = verifyExprs env es
fun verifySubOption NONE = (NONE, NONE)
| verifySubOption (SOME e) =
let
val (e', t) = verifySub e
in
(SOME e', SOME t)
end
fun return (e, t) =
(Ast.ExpectedTypeExpr (t, e), t)
val dummyType = Ast.SpecialType Ast.Any
val { strict, ... } = env
fun whenStrict (thunk:unit -> unit) : unit =
if strict
then thunk ()
else ()
val booleanType = instanceTypeExpr Name.intrinsic_boolean
in
case expr of
Ast.TernaryExpr (e1, e2, e3) =>
let
val (e1', t1) = verifySub e1
val (e2', t2) = verifySub e2
val (e3', t3) = verifySub e3
in
whenStrict (fn () => checkConvertible t1 booleanType);
(* FIXME: this produces a union type. is that right? *)
return (Ast.TernaryExpr (e1', e2', e3'), leastUpperBound t2 t3)
end
| Ast.BinaryExpr (b, e1, e2) =>
let
val (e1', t1) = verifySub e1
val (e2', t2) = verifySub e2
val NumericType = verifyTypeExpr env (Name.typename Name.intrinsic_Numeric)
val AdditionType = Ast.UnionType [ NumericType, instanceTypeExpr Name.nons_String ]
(* FIXME: these are way wrong. *)
(* FIXME: need to deal with operator overloading *)
val (expectedType1, expectedType2, resultType) =
case b of
Ast.Plus mode => (AdditionType, AdditionType, AdditionType)
| Ast.Minus mode => (NumericType, NumericType, NumericType)
| Ast.Times mode => (NumericType, NumericType, NumericType)
| Ast.Divide mode => (NumericType, NumericType, NumericType)
| Ast.Remainder mode => (NumericType, NumericType, NumericType)
| Ast.LeftShift => (NumericType, NumericType, NumericType)
| Ast.RightShift => (NumericType, NumericType, NumericType)
| Ast.RightShiftUnsigned => (NumericType, NumericType, NumericType)
| Ast.BitwiseAnd => (NumericType, NumericType, NumericType)
| Ast.BitwiseOr => (NumericType, NumericType, NumericType)
| Ast.BitwiseXor => (NumericType, NumericType, NumericType)
| Ast.LogicalAnd => (booleanType, booleanType, booleanType)
| Ast.LogicalOr => (booleanType, booleanType, booleanType)
| Ast.InstanceOf => (anyType, anyType, booleanType)
| Ast.In => (anyType, anyType, booleanType)
| Ast.Equals mode => (anyType, anyType, booleanType)
| Ast.NotEquals mode => (anyType, anyType, booleanType)
| Ast.StrictEquals mode => (anyType, anyType, booleanType)
| Ast.StrictNotEquals mode => (anyType, anyType, booleanType)
| Ast.Less mode => (NumericType, NumericType, booleanType)
| Ast.LessOrEqual mode => (NumericType, NumericType, booleanType)
| Ast.Greater mode => (NumericType, NumericType, booleanType)
| Ast.GreaterOrEqual mode => (NumericType, NumericType, booleanType)
| Ast.Comma => (anyType, anyType, t2)
in
whenStrict (fn () =>
let
in
checkCompatible t1 expectedType1;
checkCompatible t2 expectedType2
end);
return (Ast.BinaryExpr (b, e1', e2'), resultType)
end
| Ast.ExpectedTypeExpr (t, e) =>
(*
* If we got here, we're re-verifying an already-verified expression.
* This means we've already put expectations on all subexpressions, and
* we don't want to re-wrap any subexpressions, so we just bottom out here.
*)
(Ast.ExpectedTypeExpr (t, e), t)
| Ast.BinaryTypeExpr (b, e, te) =>
let
val (e', t1) = verifySub e
val t2 = verifyTypeExpr env te
val resultType = case b of
Ast.Is => booleanType
| _ => t2
in
whenStrict (fn () => case b of
Ast.To => checkConvertible t1 t2
| _ => checkCompatible t1 t2);
return (Ast.BinaryTypeExpr (b, e', t2), resultType)
end
| Ast.UnaryExpr (u, e) =>
let
val (e', t) = verifySub e
val NumericType = verifyTypeExpr env (Name.typename Name.intrinsic_Numeric)
val resultType = case u of
(* FIXME: these are probably mostly wrong *)
Ast.Delete => booleanType
| Ast.Void => undefinedType
| Ast.Typeof => instanceTypeExpr Name.intrinsic_string
| Ast.PreIncrement mode => NumericType
| Ast.PreDecrement mode => NumericType
| Ast.PostIncrement mode => NumericType
| Ast.PostDecrement mode => NumericType
| Ast.UnaryPlus mode => NumericType
| Ast.UnaryMinus mode => NumericType
| Ast.BitwiseNot => NumericType
| Ast.LogicalNot => booleanType
(* TODO: isn't this supposed to be the prefix of a type expression? *)
| Ast.Type => instanceTypeExpr Name.intrinsic_Type
in
whenStrict (fn () =>
case u of
(* FIXME: these are probably wrong *)
Ast.Delete => ()
| Ast.PreIncrement mode => checkCompatible t NumericType
| Ast.PostIncrement mode => checkCompatible t NumericType
| Ast.PreDecrement mode => checkCompatible t NumericType
| Ast.PostDecrement mode => checkCompatible t NumericType
| Ast.UnaryPlus mode => checkCompatible t NumericType
| Ast.UnaryMinus mode => checkCompatible t NumericType
| Ast.BitwiseNot => checkCompatible t NumericType
| Ast.LogicalNot => checkConvertible t booleanType
(* TODO: Ast.Type? *)
| _ => ());
return (Ast.UnaryExpr (u, e'), resultType)
end
| Ast.TypeExpr t =>
let
val t' = verifyTypeExpr env t
in
return (Ast.TypeExpr t', instanceTypeExpr Name.intrinsic_Type)
end
| Ast.ThisExpr =>
(* FIXME: type of current class, if any... also Self type? *)
return (Ast.ThisExpr, dummyType)
| Ast.YieldExpr eo =>
let
val (eo', t) = verifySubOption eo
in
(* TODO: strict check that returnType is Generator.<t> *)
return (Ast.YieldExpr eo', anyType)
end
| Ast.SuperExpr eo =>
let
val (eo', t) = verifySubOption eo
in
(* TODO: what is this AST form again? *)
return (Ast.SuperExpr eo', dummyType)
end
| Ast.LiteralExpr le =>
let
val resultType = case le of
Ast.LiteralNull => nullType
| Ast.LiteralUndefined => undefinedType
| Ast.LiteralDouble _ => instanceTypeExpr Name.intrinsic_double
| Ast.LiteralDecimal _ => instanceTypeExpr Name.intrinsic_decimal
| Ast.LiteralInt _ => instanceTypeExpr Name.intrinsic_int
| Ast.LiteralUInt _ => instanceTypeExpr Name.intrinsic_uint
| Ast.LiteralBoolean _ => instanceTypeExpr Name.intrinsic_boolean
| Ast.LiteralString _ => instanceTypeExpr Name.intrinsic_string
| Ast.LiteralArray { ty=SOME ty, ... } => verifyTypeExpr env ty
(* FIXME: how do we want to represent [*] ? *)
| Ast.LiteralArray { ty=NONE, ... } => Ast.ArrayType [Ast.SpecialType Ast.Any]
(* TODO: define this *)
| Ast.LiteralXML _ => anyType
| Ast.LiteralNamespace _ => instanceTypeExpr Name.intrinsic_Namespace
| Ast.LiteralObject { ty=SOME ty, ... } => verifyTypeExpr env ty
(* FIXME: how do we want to represent {*} ? *)
| Ast.LiteralObject { ty=NONE, ... } => anyType
| Ast.LiteralFunction (Ast.Func { fsig, ... }) => funcSigType env fsig
| Ast.LiteralRegExp _ => instanceTypeExpr Name.nons_RegExp
| _ => internalError ["unprocessed literal returned by Defn"]
fun verifyField { kind, name, init } =
{ kind = kind,
name = name,
init = verifyExprOnly env init }
val le = case le of
Ast.LiteralFunction func =>
Ast.LiteralFunction (verifyFunc env func)
| Ast.LiteralObject { expr, ty } =>
Ast.LiteralObject { expr = map verifyField expr,
ty = case ty of
NONE => NONE
| SOME ty' => SOME (verifyTypeExpr env ty') }
| Ast.LiteralArray { exprs, ... } =>
Ast.LiteralArray { exprs = map (verifyExprOnly env) exprs,
ty = SOME resultType }
| x => x
in
return (Ast.LiteralExpr le, resultType)
end
| Ast.CallExpr {func, actuals} =>
let
val (func', t) = verifySub func
val (actuals', ts) = verifySubList actuals
val resultType = case t of
Ast.FunctionType { result, ... } => result
| _ => anyType
in
whenStrict (fn () =>
case t of
(* FIXME: deal with type parameters *)
Ast.FunctionType { typeParams, params, result, thisType, hasRest, minArgs } =>
if (List.length actuals) < minArgs then
verifyError ["too few actuals"]
else if (not hasRest) andalso
((List.length actuals) > (List.length params)) then
verifyError ["too many actuals"]
else
List.app (fn (formal, actual) => checkCompatible formal actual)
(ListPair.zip (params, ts))
| Ast.SpecialType Ast.Any => ()
| _ => verifyError ["ill-typed call"]);
return (Ast.CallExpr { func = func', actuals = actuals' }, resultType)
end
(* TODO: what is this? *)
| Ast.ApplyTypeExpr { expr, actuals } =>
let
val (expr', t) = verifySub expr
val actuals' = List.map (verifyTypeExpr env) actuals
in
return (Ast.ApplyTypeExpr { expr = expr',
actuals = actuals' }, dummyType)
end
(* TODO: ---------- left off here ---------- *)
| Ast.LetExpr { defs, body, head } =>
let
val defs' = defs (* TODO *)
val head' = Option.map (verifyHead env) head
(* TODO: verify body with `head' fixtures in env *)
val (body', t) = verifySub body
in
return (Ast.LetExpr { defs = defs',
body = body',
head = head' }, dummyType)
end
| Ast.NewExpr { obj, actuals } =>
let
val (obj', t) = verifySub obj
val (actuals', ts) = verifySubList actuals
in
return (Ast.NewExpr { obj = obj',
actuals = actuals' }, dummyType)
end
| Ast.ObjectRef { base, ident, loc } =>
let
val _ = LogErr.setLoc loc
val (base', t) = verifySub base
val _ = LogErr.setLoc loc
val ident' = ident (* TODO *)
in
return (Ast.ObjectRef { base=base', ident=ident', loc=loc }, dummyType)
end
| Ast.LexicalRef { ident, loc } =>
let
val _ = LogErr.setLoc loc
val ident' = ident (* TODO *)
val _ = LogErr.setLoc loc
in
return (Ast.LexicalRef { ident=ident', loc=loc }, dummyType)
end
| Ast.SetExpr (a, le, re) =>
let
val (le', t1) = verifySub le
val (re', t2) = verifySub re
in
return (Ast.SetExpr (a, le', re'), dummyType)
end
| Ast.GetTemp n =>
(* TODO: these only occur on the RHS of compiled destructuring assignments. how to type-check? *)
return (Ast.GetTemp n, dummyType)
| Ast.GetParam n =>
internalError ["GetParam not eliminated by Defn"]
| Ast.ListExpr es =>
let
val (es', ts) = verifySubList es
in
return (Ast.ListExpr es', dummyType)
end
| Ast.SliceExpr (a, b, c) =>
let
val (a', t1) = verifySub a
val (b', t2) = verifySub b
val (c', t3) = verifySub c
in
return (Ast.SliceExpr (a, b, c), dummyType)
end
| Ast.InitExpr (it, head, inits) =>
let
val it' = it (* TODO *)
val head' = verifyHead env head
val inits' = verifyInits env inits
in
return (Ast.InitExpr (it', head', inits'), dummyType)
end
end
and verifyExprOnly (env:ENV)
(expr:Ast.EXPR)
: Ast.EXPR =
let
val (e, _) = verifyExpr env expr
in
e
end
and verifyExprs (env:ENV)
(exprs:Ast.EXPR list)
: Ast.EXPR list * Ast.TYPE_EXPR list =
let
val es = ListPair.unzip (map (verifyExpr env) exprs)
in
es
end
and verifyExprAndCheck (env:ENV)
(expr:Ast.EXPR)
(expectedType:Type.TYPE_VALUE)
: Ast.EXPR =
let val (expr',ty') = verifyExpr env expr
val _ = if #strict env
then checkCompatible ty' expectedType
else ()
in
expr'
end
(*
STMT
*)
and verifyStmt (env:ENV)
(stmt:Ast.STMT)
: Ast.STMT =
let fun verifySub s = verifyStmt env s
val booleanType = instanceTypeExpr Name.intrinsic_boolean
in
case stmt of
Ast.EmptyStmt =>
Ast.EmptyStmt
| Ast.ExprStmt e =>
Ast.ExprStmt (verifyExprOnly env e)
| Ast.ForInStmt {isEach, defn, obj, fixtures, next, labels, body} =>
let
val obj = verifyExprOnly env obj
val fixtures = valOf fixtures
val fixtures = verifyFixtures env fixtures
val env = withRib env fixtures
val next = verifyStmt env next
val body = verifyStmt env body
in
Ast.ForInStmt { isEach = isEach,
defn = defn,
obj = obj,
fixtures = SOME fixtures,
next = next,
labels = labels,
body = body }
end
| Ast.ThrowStmt es =>
Ast.ThrowStmt (verifyExprOnly env es)
| Ast.ReturnStmt es =>
let val (es',ty) = verifyExpr env es
in
if #strict env
then
case #returnType env of
NONE => verifyError ["return not allowed here"]
| SOME retTy => checkCompatible ty retTy
else ();
Ast.ReturnStmt es'
end
| Ast.BreakStmt i =>
Ast.BreakStmt i
| Ast.ContinueStmt i =>
Ast.ContinueStmt i
| Ast.BlockStmt block =>
Ast.BlockStmt (verifyBlock env block)
| Ast.ClassBlock { ns, ident, name, block } =>
Ast.ClassBlock { ns=ns, ident=ident, name=name,
block=verifyBlock env block }
| Ast.LabeledStmt (id, s) =>
Ast.LabeledStmt (id, verifySub s)
| Ast.LetStmt block =>
Ast.LetStmt (verifyBlock env block)
| Ast.WhileStmt {cond,body,labels,fixtures=NONE} =>
Ast.WhileStmt {cond=verifyExprAndCheck env cond booleanType,
body=verifySub body,
labels=labels,
fixtures=NONE}
| Ast.DoWhileStmt {cond,body,labels,fixtures=NONE} =>
Ast.DoWhileStmt {cond=verifyExprAndCheck env cond booleanType,
body=verifySub body,
labels=labels,
fixtures=NONE}
| Ast.ForStmt { defn=_, fixtures, init, cond, update, labels, body } =>
let val fixtures' = verifyFixturesOption env fixtures
val env' = withRib env fixtures'
val init' = verifyStmts env' init
val cond' = verifyExprAndCheck env' cond booleanType
val update' = verifyExprOnly env' update
val body' = verifyStmt env' body
in
Ast.ForStmt { defn=NONE, fixtures=SOME fixtures', init=init', cond=cond',
update=update', labels=labels, body=body' }
end
| Ast.IfStmt {cnd, els, thn} =>
Ast.IfStmt {cnd=verifyExprAndCheck env cnd booleanType,
els=verifySub els,
thn=verifySub thn}
| Ast.WithStmt {obj, ty, body} => (*TODO*)
Ast.WithStmt {obj=obj, ty=ty, body=body}
| Ast.TryStmt {block, catches, finally} =>
Ast.TryStmt {block=verifyBlock env block,
catches=List.map (verifyCatchClause env) catches,
finally=Option.map (verifyBlock env) finally }
| Ast.SwitchStmt {cond, cases, mode, labels} =>
let
fun verifyCase { label, inits, body } =
{ label = Option.map (verifyExprOnly env) label,
inits = Option.map (verifyInits env) inits,
body = verifyBlock env body }
in
Ast.SwitchStmt {cond = verifyExprOnly env cond,
cases = map verifyCase cases,
mode = mode,
labels = labels}
end
| Ast.SwitchTypeStmt {cond, ty, cases} =>
Ast.SwitchTypeStmt {cond = verifyExprOnly env cond,
ty = verifyTypeExpr env ty,
cases = List.map (verifyCatchClause env) cases}
| Ast.DXNStmt x => (*TODO*)
Ast.DXNStmt x
| _ => error ["Shouldn't happen: failed to match in Verify.verifyStmt"]
end
and verifyCatchClause (env:ENV)
({bindings, ty, fixtures, inits, block}:Ast.CATCH_CLAUSE)
: Ast.CATCH_CLAUSE =
let
val ty = verifyTypeExpr env ty
val fixtures' = verifyFixturesOption env fixtures
val inits' = verifyInitsOption env inits
val env' = withRib env fixtures'
val block' = verifyBlock env' block
in
{bindings=bindings, ty=ty,
fixtures=SOME fixtures', inits=SOME inits', block=block'}
end
and verifyStmts (env) (stmts:Ast.STMT list)
: Ast.STMT list =
List.map (verifyStmt env) stmts
and verifyBlock (env:ENV)
(b:Ast.BLOCK)
: Ast.BLOCK =
let
in case b of
Ast.Block { head, body, loc, pragmas=pragmas, defns=defns } =>
let
val _ = LogErr.setLoc loc
val (Ast.Head (fixtures, _)) = valOf head
val env = withRib env fixtures
val head = Option.map (verifyHead env) head
val body = verifyStmts env body
in
Ast.Block { pragmas = pragmas,
defns = defns,
body = body,
head = head,
loc = loc }
end
end
(*
FIXTURES
*)
and verifyFunc (env:ENV)
(func:Ast.FUNC)
: Ast.FUNC =
let
val Ast.Func { name, fsig, native, block, param, defaults, ty, loc } = func
val Ast.FunctionType ty = verifyTypeExpr env (Ast.FunctionType ty)
val param = verifyHead env param