-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStaticTyping.grace
More file actions
2273 lines (1983 loc) · 82.9 KB
/
Copy pathStaticTyping.grace
File metadata and controls
2273 lines (1983 loc) · 82.9 KB
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
dialect "none"
import "standardGrace" as sg
import "ast" as ast
import "lexer" as lex
import "parser" as parser
import "xmodule" as xmodule
import "io" as io
import "sys" as sys
import "SharedTypes" as share
import "ScopeModule" as sc
import "ObjectTypeModule" as ot
inherit sg.methods
// Give imported types shorter names
// Types of AST nodes
type MethodType = share.MethodType
type MethodTypeFactory = share.MethodTypeFactory
type GenericType = share.GenericType
type GenericTypeFactory = share.GenericTypeFactory
type ObjectType = share.ObjectType
type ObjectTypeFactory = share.ObjectTypeFactory
type AstNode = share.AstNode
type MixPart = share.MixPart
type Param = share.Param
type Parameter = share.Parameter
type ParamFactory = share.ParamFactory
//This type is used for checking subtyping
type TypePair = share.TypePair
// Error resulting from type checking
def StaticTypingError: ExceptionKind is public = share.StaticTypingError
// imported constants relating to cacheing type info
def cache: Dictionary = sc.cache
def allCache: Dictionary = sc.allCache
def aMethodType : MethodTypeFactory = ot.aMethodType
def aGenericType : GenericTypeFactory = ot.aGenericType
def anObjectType : ObjectTypeFactory = ot.anObjectType
def scope: sc.Scope = sc.scope
def aParam: ParamFactory = ot.aParam
// TODO Remove eventually
def preludeTypes: Set[[String]] = share.preludeTypes
// debugging prints will print if debug is true
def debug: Boolean = false
// return the return type of the block (as declared)
method objectTypeFromBlock(block: AstNode) → ObjectType
is confidential {
def bType = typeOf(block)
if (debug) then {
io.error.write "\n48: bType of block is {bType}"
}
if(bType.isDynamic) then { return anObjectType.dynamic }
def numParams: Number = block.params.size
def applyName: String = if (numParams == 0) then {
"apply"
} else {
"apply({numParams})"
}
def apply: MethodType = bType.getMethod(applyName)
match(apply) case { (ot.noSuchMethod) →
def strip = {x → x.nameString}
StaticTypingError.raise ("1000: the expression " ++
"`{share.stripNewLines(block.toGrace(0))}` " ++
"of type '{bType}' on line {block.line} does "++
"not satisfy the type 'Block'")with(block)
} case { meth : MethodType →
if (debug) then {
io.error.write ("\n66: look up method to get {meth} returning {meth.retType}")
}
return meth.retType
}
}
// Return the return type of the block as obtained by type-checking
// the last expression in the block
method objectTypeFromBlockBody(body: Sequence⟦AstNode⟧) → ObjectType
is confidential {
if(body.size == 0) then {
anObjectType.doneType
} else {
typeOf(body.last)
}
}
// check the type of node and insert into cache associated with the node
method checkTypes (node: AstNode) → Done is confidential{
def debug3: Boolean = false
if (debug3) then {
io.error.write "\n233: checking types of {node.nameString}"
}
cache.at (node) ifAbsent {
if (debug3) then {
io.error.write "\n235: {node.nameString} not in cache"
}
node.accept (astVisitor)
}
}
// check type of node, put in cache & then return type
method typeOf (node: AstNode) → ObjectType {
checkTypes (node)
cache.at (node) ifAbsent {
StaticTypingError.raise(
"cannot type non-expression {node} on line " ++
"{node.line}") with (node)
}
}
// retrieve from cache the inheritable type of an object
method inheritableTypeOf (node: AstNode) → ObjectType
is confidential {
allCache.at (node) ifAbsent {
StaticTypingError.raise("cannot find confidential type of " ++
"{node} on line {node.line}") with (node)
}
}
// Exceptions while type-checking. (Currently not used)DialectErr
//def ObjectError: outer.ExceptionKind =
// TypeError.refine("ObjectError")
// Class declaration error. (Currently not used)
//def ClassError: outer.ExceptionKind =
// TypeError.refine("Class TypeError")
// Declaration of method does not correspond to actual type
// def MethodError = TypeError.refine("Method TypeError")
// Def and var declarations. Type of def or var declaration does not
// correspond to value associated with it
//def DialectError: outer.ExceptionKind = TypeError.refine("Def TypeError")
// Scoping error declaration with imports
//def ScopingError: outer.ExceptionKind = TypeError.refine("ScopingError")
// type of part of method request (actual call, not declaration)
type RequestPart = {
args → List⟦AstNode⟧
args:=(a: List⟦AstNode⟧) → Done
}
// Check if the signature and parameters of a request match
// the declaration, return the type of the result
method check (req : share.Request) against(meth' : MethodType)
→ ObjectType is confidential {
def debug3: Boolean = false
if (debug3) then {
io.error.write(
"\n134 checking {req} of kind {req.kind} against {meth'}")
}
var meth : MethodType := meth'
// instantiate generics if necessary
if ((req.kind == "call") || (req.kind == "member")
|| (req.kind == "identifier")) then {
if ((false ≠ req.generics) && (meth.hasTypeParams)) then {
meth := meth.apply(req.generics)
}
}
def name: String = meth.nameString
for(meth.signature) and (req.parts) do
{sigPart: MixPart, reqPart: RequestPart →
def params: List⟦Param⟧ = sigPart.parameters
def args: Collection⟦AstNode⟧ = reqPart.args
checkParamArgsLengthSame (req, sigPart, params, args)
for (params) and (args) do { param: Param, arg: AstNode →
def pType: ObjectType = param.typeAnnotation
def aType: ObjectType = typeOf(arg)
if (debug) then {
io.error.write (
"\n171 Checking {arg} of type {aType} is " ++
"subtype of {pType} while checking {req} " ++
"against {meth}")
io.error.write("\n172 aType: {aType}, pType: {pType}")
}
// Make sure types of args are subtypes of parameter types
if (aType.isConsistentSubtypeOf (pType).not) then {
StaticTypingError.raise("the expression " ++
"`{share.stripNewLines(arg.toGrace(0))}` of type "++
"'{aType}' on line {args.at(1).line} does " ++
"not satisfy the type of parameter '{param}' " ++
"in the method '{name}'") with(arg)
}
}
}
meth.retType
}
// If number of parameters and args differ,
// throw a StaticTypingError exception
method checkParamArgsLengthSame(req, sigPart, params, args) -> Done
is confidential {
def pSize: Number = params.size
def aSize: Number = args.size
if(aSize != pSize) then {
def which: String = if (aSize > pSize) then {
"many"
} else {
"few"
}
def whereError: Number = if (aSize > pSize) then {
args.at (pSize + 1)
} else {
// Can we get beyond the final argument?
req.value
}
StaticTypingError.raise(
"too {which} arguments to method part " ++
"'{sigPart.name}' on line {req.line}, " ++
"expected {pSize} but got {aSize}") with (whereError)
}
}
//method DialectError(message: String) with (node) → Done {
// io.error.write(message)
// sys.exit(2)
//}
// Check the type of node to make sure it matches eType.
// Throw error only if type of node is not consistent subtype of eType
method check (node: AstNode) matches (eType : ObjectType)
inMethod (name : String) → Done is confidential {
def aType: ObjectType = typeOf(node)
if (aType.isConsistentSubtypeOf (eType).not) then {
StaticTypingError.raise("the method '{name}' on line {node.line} "++
"declares a result of type '{eType}', but returns an " ++
"expression of type '{aType}'") with (node)
}
}
// break up input string into list of strings as divided by separator
method split (input : String, separator : String) → List⟦String⟧
is confidential {
var start: Number := 1
var end: Number := 1
var output: List⟦ List⟦String⟧ ⟧ := list[]
while {end < input.size} do {
if (input.at(end) == separator) then {
var cand := input.substringFrom(start)to(end-1)
if (cand.size > 0) then {
output.push(cand)
}
start := end + 1
}
end := end + 1
}
output.push(input.substringFrom(start)to(end))
return output
}
// Pair of public and confidential types of an expression
// Generating objects
type PublicConfidential = {
publicType → ObjectType
inheritableType → ObjectType | false
}
// Returns pair of public and confidential type of expression that
// can be inherited from
class pubConf (pType: ObjectType, cType: ObjectType ) →
PublicConfidential is confidential {
method publicType → ObjectType {pType}
method inheritableType → ObjectType {cType}
method asString → String {
"confidential type is {cType}\npublic type is {pType}"
}
}
// ******************************VISITOR CODE**************************
// Static type checker visitor
// methods return false if goes no further recursively
def astVisitor: ast.AstVisitor is public = object {
inherit ast.baseVisitor
// Default behavior serving as placeholder only
// for cases not yet implemented
method checkMatch(node: AstNode) → Boolean {
if (debug) then {
io.error.write "1436: checkMatch in astVisitor"
}
true
}
// type-check if statement
method visitIf (ifnode: share.If) → Boolean {
def cond: AstNode = ifnode.value
// make sure condition is compatible with Boolean
if (typeOf (cond).isConsistentSubtypeOf
(anObjectType.boolean).not) then {
StaticTypingError.raise ("1366: the expression "++
"`{share.stripNewLines (cond.toGrace (0))}` on " ++
"line {cond.line} does not satisfy the type "++
"'Boolean' for an 'if' condition'") with (cond)
}
def thenType: ObjectType = objectTypeFromBlock (
ifnode.thenblock)
def hasElse: Boolean = ifnode.elseblock.body.size > 0
def elseType: ObjectType = if (hasElse) then {
objectTypeFromBlock(ifnode.elseblock)
} else { // if no else clause then type must be Done
anObjectType.doneType
}
// type of expression is whichever branch has largest type.
// If incompatible return variant formed by the two types
def ifType: ObjectType = if (hasElse) then {
if (thenType.isConsistentSubtypeOf (elseType)) then {
elseType
} elseif {elseType.isConsistentSubtypeOf(thenType)} then {
thenType
} else {
thenType | elseType
}
} else {
anObjectType.doneType
}
// save type in cache
cache.at (ifnode) put (ifType)
false
}
// Type check block. Fails if don't give types to
// block parameters
method visitBlock (block: AstNode) → Boolean {
// Raise exception if block parameters not given types
for (block.params) do {p→
if (((p.kind == "identifier") || {p.wildcard.not})
&& {p.decType.value == "Unknown"}) then {
StaticTypingError.raise("no type given to declaration of"++
" parameter '{p.value}' on line {p.line}") with (p)
}
}
def body = sequence(block.body)
// return type of block (computed)
var retType: ObjectType
// Type check body of block in new scope with parameters
scope.enter {
// add parameters & their types to new scope
for(block.params) do { param →
if (("string" ≠ param.dtype.kind)
&& {"num" ≠ param.dtype.kind}) then {
if (debug) then {
io.error.write(
"\n1517: {param.value} has {param.dtype}")
}
scope.variables.at(param.value)
put (anObjectType.fromDType (param.dtype)
with (emptyList))
}
}
// check type of all statements in block
for(body) do { stmt: AstNode →
checkTypes(stmt)
}
retType := objectTypeFromBlockBody(body)
}
// At this point, know block type checks.
// Now compute type of block and put in cache
def parameters = list[]
for(block.params) do { param: AstNode →
if (param.dtype.kind == "string") then {
parameters.push (aParam.withName (param.value)
ofType (anObjectType.string))
} elseif {param.dtype.kind == "num"} then {
parameters.push (aParam.withName (param.value)
ofType (anObjectType.number))
} else {
def newType: ObjectType =
anObjectType.fromDType (param.dtype) with (emptyList)
if (debug) then {
io.error.write "\n355: newType is {newType}"
}
parameters.push(aParam.withName (param.value)
ofType(newType))
}
}
// The type of the block
def blockType: ObjectType =
anObjectType.blockTaking(parameters) returning (retType)
cache.at (block) put (blockType)
if (debug) then {
io.error.write "block has type {blockType}"
}
false
}
//type checks match-case statements. Makes sure that the types
//of the matchee and the params match, and puts the return type
//of the match-case in the cache.
method visitMatchCase (node: share.MatchCase) → Boolean {
def debug3: Boolean = false
// expression being matched and its type
def matchee = node.value
var matcheeType: ObjectType := typeOf(matchee)
//Note: currently only one matchee is supported
// Keep track of parameter types and return types in case
def paramTypesList: List⟦ObjectType⟧ =
emptyList⟦ObjectType⟧
def returnTypesList: List⟦ObjectType⟧ =
emptyList⟦ObjectType⟧
//goes through each case and accumulates its parameter and
//return types
for (node.cases) do {block →
if(block.isMatchingBlock.not) then{
StaticTypingError.raise("1518: The case you are " ++
"matching to, {share.stripNewLines(block.toGrace(0))} " ++
"on line {block.line}, has more than one " ++
"argument on the left side. This is not currently "++
"allowed.") with (matchee)
}
//If param is a general case(ie. n:Number), accumulate
//its type to paramTypesList; ignore if it is a specific
//case(ie. 47)
def blockParam : AstNode = block.params.at(1)
if (debug3) then {
io.error.write"\nMy dtype is {blockParam.dtype}"
}
if (("string" ≠ blockParam.dtype.kind)
&& {"num" ≠ blockParam.dtype.kind}) then {
def typeOfParam =
anObjectType.fromDType (blockParam.dtype)
with (emptyList)
if (paramTypesList.contains(typeOfParam).not) then {
paramTypesList.add(typeOfParam)
}
}
//Build return type collection
def blockReturnType : ObjectType =
objectTypeFromBlock (block)
if (returnTypesList.contains(blockReturnType).not) then {
returnTypesList.add (blockReturnType)
}
}
// Type covered by parameters in case (types are variants)
def paramType: ObjectType =
ot.fromObjectTypeList (paramTypesList)
// Type returned by variant of all return types in cases
def returnType: ObjectType =
ot.fromObjectTypeList (returnTypesList)
if (debug3) then {
io.error.write "\nmatcheeType now equals: {matcheeType}"
io.error.write "\nparamType now equals: {paramType}"
io.error.write "\nreturnType now equals: {returnType}"
}
// If matchee not covered by cases then raise a type error
if (matcheeType.isSubtypeOf(paramType).not) then {
StaticTypingError.raise("1519: the matchee " ++
"`{share.stripNewLines(matchee.toGrace(0))}` of type "++
"{matcheeType} on line {matchee.line} does not " ++
"match the type(s) {paramTypesList} of the case(s)")
with (matchee)
}
// returnType is type of the match-case statement
cache.at(node) put (returnType)
false
}
// Type check try-catch-finally clause. If finally clause,
// then type of entire term is that of finally. Otherwise
// disjunction of try and all case blocks.
// BUG: Return statements in try and cases should be ignored
// if there is a finally clause. Currently they must match
// the return type of the method. Not sure if this is worth
// fixing or just put in type-checking rules.
method visitTryCatch (node: share.TryCatch) → Boolean {
// expression being matched and its type
def body = node.value
var bodyType: ObjectType := objectTypeFromBlock(body)
if (debug) then {
io.error.write "\n440: body with {node} with type {bodyType}"
}
// Keep track of return types of try and catch blocks
def returnTypesList: List⟦ObjectType⟧ =
list⟦ObjectType⟧[bodyType]
// goes through each case and accumulates its parameter
// and return types
for (node.cases) do {block →
if(block.isMatchingBlock.not) then{
StaticTypingError.raise("1518: The exception block you " ++
"are matching to, {share.stripNewLines(block.toGrace(0))}" ++
" on line {block.line}, has more than one parameter." ++
"This is not allowed.") with (block)
}
//Build return type collection
def blockReturnType : ObjectType =
objectTypeFromBlock(block)
if (debug) then {io.error.write (
"\n460: blockReturnType is {blockReturnType}")
}
if (returnTypesList.contains (blockReturnType).not) then {
returnTypesList.add(blockReturnType)
}
}
// type of the try-catch
var returnType: ObjectType
// if there is a finally clause then try-catch returns that
// value, so use its type
if (false != node.finally) then {
returnType := objectTypeFromBlock (node.finally)
if (debug) then {io.error.write
"\n470: using type of finally clause: {returnType}"
}
} else { // return type is variant of all block types.
// Type returned by variant of all return types in cases
returnType := ot.fromObjectTypeList(returnTypesList)
if (debug) then {
io.error.write ("\n475: no finally: " ++ "using types from try catch: {returnType}")
}
}
if (debug) then {
io.error.write "\nreturnType now equals: {returnType}\n"
}
// returnType is type of the match-case statement
cache.at(node) put (returnType)
false
}
// method visitMethodType (node) → Boolean {
// io.error.write
// "\n1549: visiting method type {node} not implemented\n"
//
// runRules (node)
//
// node.parametersDo { param →
// runRules (parameterFromNode(param))
// }
//
// return false
// }
// method visitType (node) → Boolean {
// io.error.write
// "\n1561: visiting type {node} (not implemented)\n"
// checkMatch (node)
//// io.error.write "432: done visiting type {node}"
// }
// type check method declaration
method visitMethod (meth: AstNode) → Boolean {
def debug3: Boolean = false
if (debug3) then {
io.error.write "\n515: Visiting method {meth}\n"
}
// ensure all parameters have known types and
// method has return type
ensureKnown (meth)
// meth.value is Identifier Node
def name: String = meth.value.value
// declared type of the method being introduced
var mType: MethodType
var returnType: ObjectType
scope.enter {
// Enter new scope with parameters to type-check body of method
if (debug3) then {
io.error.write "\n1585: Entering scope for {meth}\n"
}
//returns the type parameters associated with meth: AstNode to be added to the scope
def transferBundle : ot.VisitMethodHelperBundle = obtainTypeParams (meth, name)
//update mType and returnType accordingly
mType := transferBundle.mType
returnType := transferBundle.returnType
// def typeParams: List[[String]] = transferBundle.typeParams
}
// if method is just a member name then can record w/variables
if (isMember(mType)) then {
scope.variables.at(name) put(returnType)
}
// always record it as a method
scope.methods.at(name) put(mType)
// Declaration statement always has type Done
cache.at(meth) put (anObjectType.doneType)
false
}
//Helper method of visitMethod
//returns the type parameters associated with meth: AstNode to be added to the scope
method obtainTypeParams (meth: AstNode, name: String) -> ot.VisitMethodHelperBundle is confidential {
def debug3: Boolean = false
var mType: MethodType
var returnType: ObjectType
var typeParams: List⟦String⟧ := emptyList⟦String⟧
if (false != meth.typeParams) then {
if (debug3) then {
io.error.write "\n634: meth.signature: {meth.signature}"
io.error.write "\n634: meth.typeParams.params: {meth.typeParams.params}"
io.error.write "\n634: meth.value: {meth.value}"
}
if (debug) then {
io.error.write "\n546st: In has type params"
}
typeParams := ot.getTypeParams(meth.typeParams.params)
}
if (debug) then {
io.error.write "\n547st: typeParams: {typeParams}"
}
mType := aMethodType.fromNode(meth) with (typeParams)
returnType := mType.retType
for (mType.typeParams) do { typeParamName : String →
scope.types.at(typeParamName)
put (anObjectType.typeVble (typeParamName))
}
//enter all the parameters to the scope
for(meth.signature) do { part: AstNode →
for(part.params) do { param: AstNode →
scope.variables.at(param.value)
put (anObjectType.fromDType (param.dtype)
with (typeParams))
}
}
// We used to collect the type definitions in method
// bodies but those are currently not allowed
// collectTypes((meth.body))
if (debug) then {
io.error.write
"\n595: collected types for {list(meth.body)}\n"
}
// Check types of all methods in the body.
// Special case for returns
checkMethodTypes (meth, returnType, name)
if (debug) then {
io.error.write "\n594: Done checking body"
}
// If no body then the method must return type Done
if(meth.body.size == 0) then {
if (anObjectType.doneType.isConsistentSubtypeOf
(returnType).not) then {
StaticTypingError.raise(
"the method '{name}' on line {meth.line} " ++
"declares a result of type '{returnType}'," ++
" but has no body") with (meth)
}
} else {
calculateLastExpression(meth,returnType, name)
}
return ot.visitMethodHelperBundle (mType, returnType, typeParams)
}
//Helper method for obtainTypeParams
// Calculate type of last expression in body and
// make sure it is a subtype of the declared
// return type
method calculateLastExpression (meth: AstNode, returnType: ObjectType, name:String) -> Done is confidential {
def lastNode: AstNode = meth.body.last
if (share.Return.matches(lastNode).not) then {
if (debug) then {
io.error.write("\n694: meth.body.last: {meth.body.last}")
}
def lastType = typeOf(lastNode)
if (debug) then {
io.error.write
"\n607st: type of lastNode is {lastType}"
}
if(lastType.isConsistentSubtypeOf
(returnType).not) then {
StaticTypingError.raise(
"the method '{name}' on line " ++
"{meth.line} declares a result of " ++
"type '{returnType}', but returns " ++
"an expression of type '{lastType}'")
with (lastNode)
} else {
if (debug) then {
io.error.write ("\n707: {lastType} is consistent subtype of {returnType}")
}
}
}
if (debug) then {
io.error.write (
"\n2048 type of lastNode in method " ++
"{meth.nameString} is {lastNode.kind}")
}
// If last node is an object definition, the
// method can be inherited from so calculate the
// supertype (confidential) and put in allCache
if (lastNode.kind == "object") then {
visitObject(lastNode)
def confidType: ObjectType = allCache.at(lastNode)
allCache.at(meth.nameString) put (confidType)
if (debug) then {
io.error.write (
"\n2053 confidType is {confidType} " ++
"for {meth.nameString}")
}
}
}
// ensure all parameters have known types and
// method has return type
//Helper method for visitMethod
method ensureKnown (meth:AstNode) -> Done is confidential {
for (meth.signature) do {s: AstNode →
for (s.params) do {p: AstNode →
if (((p.kind == "identifier") && {p.wildcard.not})
&& {p.decType.value=="Unknown"}) then {
StaticTypingError.raise("no type given to declaration" ++
" of parameter '{p.value}' on line {p.line}")
with (p)
}
}
}
if (meth.decType.value=="Unknown") then {
StaticTypingError.raise(
"no return type given to declaration of method"++
" '{meth.value.value}' on line {meth.line}")
with (meth.value)
}
}
// Check types of all methods in the body.
// Special case for returns
//HElper method for visitMethod
method checkMethodTypes (meth: AstNode, returnType: ObjectType, name : String) -> Done {
for(meth.body) do { stmt: AstNode →
checkTypes(stmt)
// Write visitor to make sure return statements
// have right type
stmt.accept(object {
inherit ast.baseVisitor
// Make sure return statement return a value
// of same type as the method return type
method visitReturn(ret) → Boolean is override {
check (ret.value) matches (returnType)
inMethod (name)
// note sure why record returnType?
cache.at(ret) put (returnType)
return false
}
// Don't check inside embedded methods as they
// have different return type from the
// outer method
method visitMethod(node) → Boolean is override {
false
}
})
}
}
// type check a method request
method visitCall (req: AstNode) → Boolean {
// Receiver of request
def rec: AstNode = req.receiver
def debug3 = false
if (debug3) then {
io.error.write ("\n1673: visitCall's call is: "++
"{rec.toGrace(0)}.{req.nameString}"++
" with kind {rec.kind}")
}
// type of receiver of request
def rType: ObjectType = typeOfReceiver(rec)
def callType: ObjectType = if (rType.isDynamic) then {
if (debug) then {
io.error.write "\n624: rType: {rType} is dynamic}"
}
anObjectType.dynamic
} else {
//Since we can't have a method or a type with the
//same name. A call on a name can be searched in
//both method and type lists. Just have to assume
//that the programmer used nonconflicting names
var name: String := req.nameString
if (name.contains "$object(") then {
//Adjust name for weird addition when used
// in inherit node
def dollarAt = name.indexOf("$object(")
name := name.substringFrom(1) to (dollarAt - 1)
}
// String showing what call looks like
def completeCall : String =
"{req.receiver.toGrace(0)}.{req.nameString}"
++ " with kind {req.receiver.kind}"
if (debug3) then {
io.error.write "\n2154: {completeCall}"
io.error.write "\n2155: {req.nameString}"
io.error.write
"\n2000: rType.methods is: {rType.methods}"
}
getResultType(req, rec, rType, name, completeCall)
}
if (debug3) then {
io.error.write "\n1701: callType: {callType}"
}
cache.at(req) put (callType)
// tells the callNode to typecheck its receiver,
// arguments, and generics
true
}
// compute and return type of the receiver of method request
method typeOfReceiver (rec: AstNode) -> ObjectType
is confidential {
// type of receiver of request
def debug3: Boolean = false
if (rec.nameString == "self") then {
if (debug3) then {
io.error.write "\n1675: looking for type of self"
}
scope.variables.find("$elf") butIfMissing {
StaticTypingError.raise "type of self missing" with(rec)
}
} elseif {rec.nameString == "module()object"} then {
// item from prelude
if (debug3) then {
io.error.write "\n602: looking for type of module"
}
scope.variables.findFromLeastRecent("$elf") butIfMissing {
StaticTypingError.raise "type of self missing" with(rec)
}
} elseif {rec.kind == "outer"} then {
if (debug3) then {
io.error.write "\n610: looking for type of outer"
io.error.write "\n611: levels: {rec.numberOfLevels}"
}
def outerMethodType: MethodType =
scope.methods.findOuter (rec.numberOfLevels)
butIfMissing {
StaticTypingError.raise "type of outer missing"
with(rec)
}
outerMethodType.retType
} else { // general case returns type of the receiver
if (debug3) then {
io.error.write "\n2085 rec.kind = {rec.kind}"
}
typeOf(rec)
}
}
method getResultType (req: AstNode, rec: AstNode,
rType: ObjectType, name: String,
completeCall: String) -> ObjectType is confidential {
// look for method name in type of receiver
match(rType.getMethod(name))
case { (ot.noSuchMethod) →
if (debug) then {
io.error.write "\n2001: got to case noSuchMethod "++
"while looking for {name}"
io.error.write
"\n2002: method scope here is {scope.methods}"
}
StaticTypingError.raise(
"no such method or type '{req.nameString}' in " ++
"`{share.stripNewLines(rec.toGrace(0))}` of type\n" ++
" '{rType}' \nin type \n '{rType.methods}'" ++
" used on line {rec.line}")
with(req)
} case { meth : MethodType →
// found the method, make sure arguments match
// parameter types
if (debug) then {
io.error.write
"\nchecking request {req} against {meth}"
}
// returns type of result
check(req) against(meth)
}
}
// Type check an object. Must get both public and
// confidential types
method visitObject (obj: AstNode) → Boolean {
def debug3: Boolean = false
// type check body of the method
if (debug3) then {
io.error.write "\n684 Ready to type check {obj}***"
}
visitObjectHelper(obj, false)
}
method visitObjectHelper (obj: AstNode, hasImports: Boolean) → Boolean {
def debug3: Boolean = false
def pcType: PublicConfidential = scope.enter {
var withoutImport: AstNode
if(hasImports) then {
def importNodes: List⟦AstNode⟧ = emptyList⟦AstNode⟧
// All statements in module
def bodyNodes: List⟦AstNode⟧ = list(obj.value)
// Goes through the body of the module and processes imports
for (bodyNodes) do{ nd : AstNode →
match (nd)
case {imp: share.Import →
// Visitimport processes the import and puts its type
// on the variable scope and method scope
visitImport(imp)
importNodes.add(imp)
} else { } // Ignore non-import nodes
}
// Removes import statements from the body of the module
for(importNodes) do{nd : AstNode →
bodyNodes.remove(nd)
}
// Create equivalent module without imports
withoutImport := ast.moduleNode.body(bodyNodes)
named (obj.nameString) scope (obj.scope)
visitObjectHelper(withoutImport, false)
}
if(hasImports) then {
// Collect types declared in obj into new level of scope
collectTypes (list (withoutImport.value))
processBody (list (withoutImport.value), withoutImport.superclass)
} else {
collectTypes (list (obj.value))
processBody (list (obj.value), obj.superclass)
}
}
// Record both public and confidential methods
// (for inheritance)
cache.at(obj) put (pcType.publicType)
allCache.at(obj) put (pcType.inheritableType)
if (debug3) then {
io.error.write "\n1971: *** Visited object {obj}***"
io.error.write
"\n1973 public type is {pcType.publicType}"
io.error.write
"\n1973 inheritable type is {pcType.inheritableType}"
io.error.write(
"\n2153: Methods scope at end of visitObject is: " ++
scope.methods)
}
false