-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathObjectTypeModule.grace
More file actions
executable file
·2665 lines (2294 loc) · 110 KB
/
Copy pathObjectTypeModule.grace
File metadata and controls
executable file
·2665 lines (2294 loc) · 110 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 "lexer" as lexer
import "parser" as parser
import "ast" as ast
import "xmodule" as xmodule
import "io" as io
import "ScopeModule" as sc
import "SharedTypes" as share
inherit sg.methods
// Rename imported types for convenience
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 Parameter = share.Parameter
type ObjectTypeFromOp = share.ObjectTypeFromOp
type ObjectTypeFromMeths = share.ObjectTypeFromMeths
def scope: sc.Scope = sc.scope
// Error resulting from type checking
def StaticTypingError: ExceptionKind is public = share.StaticTypingError
// Scoping error declaration
def ScopingError: ExceptionKind is public = TypeError.refine("ScopingError")
// If true prints extra info
def debug : Boolean = false
// Collection of method types in type
var methodtypes: List[[MethodType]] := emptyList[[MethodType]]
def trails: List[[TypePair]] = emptyList[[TypePair]]
// visitor to convert a type expression to a string
// Makes printing them a bit clearer. Used in gct?
def typeVisitor: ast.AstVisitor = object {
inherit ast.baseVisitor
var literalCount := 1
// Convert type with list of method types to string
method visitTypeLiteral(lit) {
for (lit.methods) do { meth →
var mtstr := "{literalCount} "
for (meth.signature) do { part →
mtstr := mtstr ++ part.name
if (part.params.size > 0) then {
mtstr := mtstr ++ "("
for (part.params.indices) do { pnr →
var p := part.params.at(pnr)
if (p.dtype != false) then {
mtstr := mtstr ++ p.toGrace(1)
} else {
// if parameter type not listed, give it type Unknown
if (p.wildcard) then {
mtstr := mtstr ++ "_"
} else {
mtstr := mtstr ++ p.value
}
mtstr := mtstr ++ ":" ++ ast.unknownType.value
if (false != p.generics) then {
mtstr := mtstr ++ "⟦"
for (1..(p.generics.size - 1)) do {ix →
mtstr := mtstr ++ p.generics.at(ix).toGrace(1) ++ ", "
}
mtstr := mtstr ++ p.generics.last.toGrace(1) ++ "⟧"
}
}
if (pnr < part.params.size) then {
mtstr := mtstr ++ ", "
}
}
mtstr := mtstr ++ ")"
}
}
if (meth.rtype != false) then {
mtstr := mtstr ++ " → " ++ meth.rtype.toGrace(1)
}
methodtypes.add(mtstr)
}
return false
}
// Get string representation of type built using & or |
method visitOp(op) {
if ((op.value=="&") || (op.value=="|")) then {
def leftkind = op.left.kind
def rightkind = op.right.kind
if ((leftkind=="identifier") || (leftkind=="member")) then {
var typeIdent := op.left.toGrace(0)
methodtypes.add("{op.value} {typeIdent}")
} elseif { leftkind=="typeliteral" } then {
literalCount := literalCount + 1
methodtypes.add("{op.value} {literalCount}")
visitTypeLiteral(op.left)
} elseif { leftkind=="op" } then {
visitOp(op.left)
}
if ((rightkind=="identifier") || (rightkind=="member")) then {
var typeIdent := op.right.toGrace(0)
methodtypes.add("{op.value} {typeIdent}")
} elseif { rightkind=="typeliteral" } then {
literalCount := literalCount + 1
methodtypes.add("{op.value} {literalCount}")
visitTypeLiteral(op.right)
} elseif { rightkind=="op" } then {
visitOp(op.right)
}
}
return false
}
}
// Convert type expression to string for debugging
// Suggestion: print typeLiteral by calling dtype.toGrace(0)
method dtypeToString(dtype) {
if (false == dtype) then {
"Unknown"
} elseif {dtype.kind == "typeliteral"} then {
methodtypes := []
dtype.accept(typeVisitor)
methodtypes.at (1)
} else {
dtype.value
}
}
// -------------------------------------------------------------------
// Type declarations for type representations to use for type checking
// -------------------------------------------------------------------
// Used in match statements to catch indicate no method found
// Method returns these when no method found.
def noSuchMethod: Pattern is readable = object {
use BasicPattern
method matches (obj : Object) -> Boolean {
if (isMe(obj)) then {
true
} else {
false
}
}
}
// Used in match statements to indicate no type found
def noSuchType: Pattern = object {
use BasicPattern
method matches (obj : Object) -> Boolean {
if (isMe(obj)) then {
true
} else {
false
}
}
}
// This type is used for checking subtyping
type TypePair = share.TypePair
// Pair of types, used in coinductive check of subtyping
class typePair (first':ObjectType, second':ObjectType) →
TypePair is confidential {
method first → ObjectType {
first'
}
method second → ObjectType {
second'
}
// TODO:
// More correct implementation of typePair equality?
// Seems to work in conjuction with switching the order of cases in
// isSubtypeHelper in fromMethods.
method == (other:Object) → Boolean {
(first.asString == other.first.asString) &&
{second.asString == other.second.asString}
}
method asString {
"<{first'}, {second'}>"
}
}
//Used in publicType, publicTypeElse, and gatherTypesForMethods Methods
//All of which are helper methods for processBody in staticTyping
type SetMethodTypePair = share.SetMethodTypePair
//holds and returns two objects of type Set⟦MethodType⟧
class setMethodTypePair (first': Set⟦MethodType⟧,
second': Set⟦MethodType⟧ ) -> SetMethodTypePair {
method first → Set⟦MethodType⟧ {
first'
}
method second → Set⟦MethodType⟧ {
second'
}
}
//Used in the publicType method in staticTyping
type PublicTypeReturnBundle = share.PublicTypeReturnBundle
//holds and returns three objects of type Set⟦MethodType⟧ and ObjectType
class publicTypeReturnBundle (allMethods':Set⟦MethodType⟧, publicMethods': Set⟦MethodType⟧,
internalType': ObjectType) -> PublicTypeReturnBundle {
method allMethods → Set⟦MethodType⟧ {
allMethods'
}
method publicMethods → Set⟦MethodType⟧ {
publicMethods'
}
method internalType -> ObjectType {
internalType'
}
}
//Used in the visitMethod method in staticTyping
type VisitMethodHelperBundle = share.VisitMethodHelperBundle
//holds and returns two objects of type MethodType and ObjectType
class visitMethodHelperBundle (mType': MethodType, returnType' : ObjectType,
typeParams': List⟦String⟧) -> VisitMethodHelperBundle {
method mType -> MethodType {
mType'
}
method returnType -> ObjectType {
returnType'
}
method typeParams -> List⟦String⟧ {
typeParams'
}
}
// This type is used for checking subtyping
type Answer = share.Answer
// Responds that keeps trail of types checked in subtyping
class answerConstructor (ans':Boolean) → Answer {
method ans → Boolean {
ans'
}
method asString → String{
"Answer is {ans'}\nTrails is {trails}"
}
}
type TypeOp = share.TypeOp
// Stores needed information used when type-checking a type defined by an opNode
// I.e., & or |
class typeOp (op' : String, left' : ObjectType, right' : ObjectType) → TypeOp {
method op → String {
op'
}
method left → ObjectType {
left'
}
method right → ObjectType {
right'
}
}
// Type of a parameter
type Param = share.Param
type ParamFactory = share.ParamFactory
// Create parameter with given name' and type'
// if no name then use wildcard "_"
def aParam: ParamFactory is readable = object {
method withName(name': String) ofType(type' : ObjectType) → Param {
object {
def name : String is public = name'
def typeAnnotation : ObjectType is public = type'
method asString → String is override {
"{name} : {typeAnnotation}"
}
}
}
method ofType (type': ObjectType) → Param {
withName("_") ofType(type')
}
}
// MixPart is a "segment" of a method: Ex. for (param1) do (param2), for(param1)
// and do(param2) are separate "MixParts."
type MixPart = share.MixPart
// Create a mixpart with given name' and parameters'
class aMixPartWithName(name' : String)
parameters(parameters' : List⟦Param⟧) → MixPart {
def name : String is public = name'
def parameters : List⟦Param⟧ is public = parameters'
}
// =================================
// METHOD TYPES
// =================================
// Factory for creating method types from various inputs
def aMethodType: MethodTypeFactory is public = object {
// Create method type from signature (including parameters
// and their types) and return type
method signature (signature' : List⟦MixPart⟧)
returnType (retType' : ObjectType) → MethodType {
signature (signature') with (emptyList[[String]])
returnType (retType')
}
// Create method type from signature (including parameters
// and their types) and return type, as well as type parameters
method signature (signature' : List⟦MixPart⟧)
with (typeParams': List[[String]])
returnType (retType' : ObjectType) → MethodType {
object {
// Public defs of MethodType
var name : String is readable := ""
var nameString : String is readable := ""
def signature : List⟦MixPart⟧ is public = signature'
def retType : ObjectType is public = retType'
def typeParams : List⟦String⟧ is public = typeParams'
// Initialize name, nameString, and show (for the method asString)
var show : String := ""
def fst: MixPart = signature.first
if (fst.parameters.isEmpty) then {
name := fst.name
nameString := fst.name
show := name
} else {
var onceType : Boolean := true
for (signature) do { part →
if (onceType && (typeParams != emptyList[[String]])) then {
name := "{name}{part.name}[{typeParams}]()"
nameString := ("{nameString}{part.name}[{typeParams}]" ++
"({part.parameters.size})")
} else {
onceType := false
name := "{name}{part.name}()"
nameString := ("{nameString}{part.name}" ++
"({part.parameters.size})")
}
show := "{show}{part.name}("
var first: Boolean := false
for (part.parameters) do { param →
if (first) then {
show := "{show}, "
}
show := "{show}{param}"
first := true
}
show := "{show})"
}
// Throw away ", " at end of name
name := name.substringFrom (1) to (name.size - 2)
}
show := "{show} → {retType}"
method hash → Number is override {
nameString.hash
}
// Does method take type parameters
method hasTypeParams → Boolean {
typeParams.size > 0
}
//Two method types are considered equal if they have the same
//nameString, parameter types, and return type
method == (other: MethodType) → Boolean {
//Check part names and number of parameters
if (nameString ≠ other.nameString) then {
return false
}
//Check parameter types and return type
def sameSignature: Boolean = sameSignatureTypes(signature, other.signature)
if(sameSignature.not) then { return false }
return (retType == other.retType)
}
// Mask unknown fields in corresponding methods
// Assume that the methods share a signature.
// Results in stripped down signature
// Used for gradual typing NOT CHECKED FOR CORRECTNESS!
method restriction (other : MethodType) → MethodType is confidential {
var restrictParts: List⟦MixPart⟧ := list[]
restrictParts:= restrictParts(other)
return signature (restrictParts) with (typeParams)
returnType (retType)
}
method restrictParts (other : MethodType)-> List⟦MixPart⟧ {
def restrictParts: List⟦MixPart⟧ = list[]
if (other.signature.size != signature.size) then {
return self
}
for (signature) and (other.signature)
do {part: MixPart, part': MixPart →
if (part.name == part'.name) then {
def restrictParams: List⟦Param⟧ = list[]
if (part.parameters.size != part'.parameters.size) then{
ProgrammingError.raise("part {part.name} has " ++
"{part.parameters.size} while part " ++
"{part'.name} has {part'.parameters.size}")
}
for (part.parameters) and (part'.parameters)
do { p: Param, p': Param →
def pt': ObjectType = p'.typeAnnotation
// Contravariant in parameter types.
if (pt'.isDynamic) then {
restrictParams.add(aParam.withName (p.name)
ofType (anObjectType.dynamic))
} else {
restrictParams.add(p)
}
}
restrictParts.add (
aMixPartWithName (part.name)
parameters (restrictParams))
} else {
restrictParts.add (part)
}
}
return restrictParts
}
// Determines if this method is a specialisation (<:) of
// the given one.
method isSpecialisationOf (other: MethodType) → Answer {
// Check part names and number of parameters
if (nameString != other.nameString) then {
return answerConstructor(false)
}
// Check that both methods have the same number of type params
if (typeParams.size ≠ other.typeParams.size) then {
return answerConstructor(false)
}
// Determine whether each method still have uninitialized
// type params
if (typeParams.size > 0) then {
return genericSpecialisationOf(other)
} else {
return nongenericSpecialisationOf(other)
}
}
// Initialize self's and other's type params with type Object, then
// perform specialisation check
//
// pre: self and other has the same # of uninitialized type params
// TODO: Hack which is not right!!!
method genericSpecialisationOf(other: MethodType) → Answer {
// We use '$Object$' instead of 'Object' because Object can be
// overwritten by the programmer
def baseList : List⟦AstNode⟧ = emptyList⟦AstNode⟧
for (typeParams.indices) do { index : Number →
baseList.add(ast.identifierNode.new("$Object$", false))
}
// Initialize both methods
def appliedSelf : MethodType = apply(baseList)
def appliedOther : MethodType = other.apply(baseList)
if (debug) then {
io.error.write("\n351 about to check appliedSelf " ++
"{appliedSelf} against {appliedOther}")
}
return appliedSelf.isSpecialisationOf(appliedOther)
}
// Perform specialisation check on a pair of MethodTypes that have
// no uninitialized type params
method nongenericSpecialisationOf(other: MethodType) → Answer {
def debug3: Boolean = false
if(debug3) then {
io.error.write("\n458: Entering nongenericSpecialisationOf")
}
//Shortcut for when self and other have the exact same param
//types and return type
if (isMe(other)) then {
return answerConstructor(true)
}
if(debug3) then {
io.error.write("\n471: signature = {signature}")
io.error.write("\n471: other.signature = {other.signature}")
}
// Check subtyping of param and return types
for (signature) and (other.signature)
do { part: MixPart, part': MixPart →
for (part.parameters) and (part'.parameters)
do { p: Param, p': Param →
def pt: ObjectType = p.typeAnnotation
def pt': ObjectType = p'.typeAnnotation
// Contravariant in parameter types.
def paramSubtyping : Answer = pt'.isSubtypeHelper(pt)
if (paramSubtyping.ans.not) then {
return paramSubtyping
}
}
}
if(debug3) then {
io.error.write("\n488: retType = {retType}")
io.error.write("\n489: other.retType = {other.retType}")
io.error.write("\n490: trails = {trails}")
}
retType.isSubtypeHelper (other.retType)
}
// Update this method's type params with the replacementTypes
// Returns a different MethodType with the correct types
// TODO: Modify or delete
method apply(replacementTypes : List⟦AstNode⟧) → MethodType {
def debug3: Boolean = false
if(replacementTypes.size ≠ typeParams.size) then {
StaticTypingError.raise("Wrong number of type parameters " ++
"given when instantiating generic method " ++
"{nameString}. Attempted to replace " ++
"{typeParams} with {replacementTypes}.")
}
// Create a mapping of GenericTypes-to-ObjectTypes
if (debug3) then {
io.error.write ("\n444: updating {self} with replacement "++
"types: {replacementTypes}")
}
def replacementOT: List[[ObjectType]] = list(replacementTypes.map[[ObjectType]]{ node -> anObjectType.fromDType(node) with (emptyList)})
def replacements : Dictionary⟦String, ObjectType]] = makeDictionary(typeParams, replacementOT)
updateTypeWith(replacements)
}
// Takes a mapping of generic-to-ObjectType and returns a copy of
// self with all of the generics replaced with their corresponding
// ObjectType
//
// Note: Does not need 'replacements.size == typeParams.size'
method updateTypeWith (replacements :
Dictionary⟦String, ObjectType⟧) → MethodType {
if (debug) then {
io.error.write "\n457: updating method: {self}"
}
//Construct the list of mixParts of the new MethodType
var newMixParts : List⟦MixPart⟧ := emptyList⟦MixPart⟧
newMixParts := newMixParts (replacements)
def debug3 = false
if(debug3) then {
io.error.write "\n469: new mix parts {newMixParts.at (1).name}"
io.error.write "\n471: replace {retType} with {replacements}"
io.error.write "\n599: retType.isTypeVble: {retType.isTypeVble}"
}
// Update the return type of the method
def newReturn : ObjectType = retType.updateTypeWith (replacements)
if(debug3) then {
io.error.write "\n486: new return type: {newReturn}"
}
// Return with new MethodType
// TODO: start with empty typeParams???
def newMeth : MethodType = signature(newMixParts) with (typeParams)
returnType(newReturn)
if {debug3} then {
io.error.write "\n481: newMeth is {newMeth}"
}
//Save any type params that weren't initialized
// TODO: Shouldn't be necessary!!
def newTypeParams : List⟦String⟧ = emptyList⟦String⟧
for (typeParams) do { each : String →
if (replacements.containsKey(each).not) then {
newTypeParams.add(each)
}
}
newMeth.typeParams.addAll(newTypeParams)
newMeth
}
//Construct the list of mixParts of the new MethodType
method newMixParts (replacements) -> List⟦MixPart⟧ is confidential {
def newMixParts : List⟦MixPart⟧ = emptyList⟦MixPart⟧
def debug3 = false
for (signature) do { mPart : MixPart →
def newParams : List⟦Param⟧ = emptyList⟦Param⟧
for (mPart.parameters) do { param : Param →
def newTypeAnno : ObjectType =
param.typeAnnotation.updateTypeWith(replacements)
if (debug3) then {
io.error.write("\n389 newTypeAnno is {newTypeAnno}")
}
newParams.add(aParam.withName (param.name)
ofType (newTypeAnno))
}
newMixParts.add(aMixPartWithName(mPart.name)
parameters(newParams))
}
return newMixParts
}
method asString → String is override { show }
}
}
// Create method type with no parameters, but returning rType
method member (name : String) ofType (rType : ObjectType) → MethodType {
signature(list[aMixPartWithName (name) parameters (list[])]) with (emptyList[[String]])
returnType (rType)
}
// If node is a method, class, method signature,
// def, or var, create appropriate method type
// Included just to catch errors
method fromNode (node: AstNode) → MethodType {
ProgrammingError.raise("Wrong version of fromNode in 566")
}
// If node is a method, class, method signature,
// def, or var, create appropriate method type
method fromNode (node: AstNode) with (typeParams: List[[String]]) → MethodType {
def debug3 = false
match(node)
case {
meth :share.Method|share.Class|share.MethodSignature →
if (debug3) then {
io.error.write "\n575: create method from {node} with type vars:{typeParams}"
}
fromNodeMethCase(meth, typeParams)
}
case { defd : share.Def | share.Var →
def signature: List⟦MixPart⟧ =
list[aMixPartWithName (defd.name.value) parameters (list[])]
def dtype: ObjectType = if (defd.dtype == false) then {
anObjectType.dynamic
} else {
// Used to use definedByNode
anObjectType.fromDType (defd.dtype) with (typeParams)
}
def methType = signature (signature) with (typeParams) returnType (dtype)
if (debug3) then {
io.error.write "\n607 created method type {methType} from def or var {node}"
}
methType
}
else {
Exception.raise "unrecognised method node" with(node)
}
}
//Helper method for fromNode
//Handles the case where the node is of type Method, Class or MethodSignature
method fromNodeMethCase (meth:AstNode, typeParams: List⟦MixPart⟧)
-> MethodType is confidential {
def debug3: Boolean = false
var signature: List⟦MixPart⟧ := list[]
signature := paramDef (meth, typeParams)
// Return type of the method or class
def rType: AstNode = match (meth)
case { m : share.Method | share.Class →
m.dtype
}
case { m : share.MethodSignature →
m.rtype
}
if (debug3) then {
io.error.write "\n627: creating returntype for {rType}"
io.error.write "\n628: rType.kind: {rType.kind}"
}
// Full method type
// used to use definedByNode
// Add type parameters to the method type
def newTypeParams: List[[String]] = emptyList[[String]]
if (false ≠ meth.typeParams) then {
for (meth.typeParams.params) do { ident : share.Identifier →
newTypeParams.add(ident.nameString)
}
}
def mType : MethodType = signature (signature) with (newTypeParams)
returnType (anObjectType.fromDType (rType) with (typeParams))
if (debug3) then {
io.error.write "\n588: created method type {mType}"
io.error.write "\n678: created return type {anObjectType.fromDType (rType) with (typeParams)}"
}
mType
}
//Helper method of fromNodeMethCase
//Updates the signature by looking at all of the parameters
//of meth
method paramDef (meth, typeParams ) -> List[[MixPart]] is confidential {
def debug1 = false
var signature: List⟦MixPart⟧ :=list[]
for (meth.signature) do { part:AstNode →
def params: List⟦Param⟧ = list[]
if (debug1) then {
io.error.write "\n568 creating type for {part}"
}
// Collect parameters for each part
for (part.params) do { param: AstNode →
if (debug1) then {
io.error.write "\n571 creating type for {param}:{param.dtype}"
}
params.add (aParam.withName (param.value)
// Used to be definedByNode
ofType (anObjectType.fromDType (param.dtype) with (typeParams)))
}
// Add this mixpart to signature list
signature.add (aMixPartWithName (part.name) parameters (params))
if (debug1) then {
io.error.write "\n579 finished with {part}"
}
}
if(debug1) then {
io.error.write "\n765 signature: {signature}"
}
return signature
}
}
// =====================
// GENERIC TYPES
// =====================
// Factory to create generic types (and instantiate them)
def aGenericType : GenericTypeFactory is public = object{
// Create a GenericType from name, type params, & base type
class fromName (name': String) parameters (typeParams' : List⟦String⟧)
objectType(oType' : ObjectType) → GenericType {
// May be unnecessary since we already store 'name' as the key in scope
def name : String is public = name'
// The generic type names used within this type
def typeParams : List⟦String⟧ is public = typeParams'
// The ObjectType belonging to this generic type
var oType : ObjectType is public:= oType'
// Takes a list of replacement ObjectTypes and replaces references to the
// typeParams stored in oType with their counterpart in the list
method apply(replacementTypes : List⟦ObjectType⟧) → ObjectType {
if(replacementTypes.size ≠ typeParams.size) then {
StaticTypingError.raise("Wrong number of type parameters given when " ++
"instantiating generic type {name}. Attempted to" ++
" replace {typeParams} with {replacementTypes}.")
}
// First, resolve the oType if needed
oType := oType.resolve
// Create a mapping of GenericTypes-to-ObjectTypes
def replacements : Dictionary⟦String, ObjectType⟧ =
makeDictionary(typeParams, replacementTypes)
// Tells each method to replace references to any of the typeParams
def appliedMethods : Set⟦MethodType⟧ = emptySet⟦MethodType⟧
for (oType.methods) do { meth : MethodType →
appliedMethods.add(meth.updateTypeWith(replacements))
}
// Returns an ObjectType with the generics replaced
anObjectType.fromMethods(appliedMethods)
}
method asString → String {
var s : String := name ++ "⟦"
var first : Boolean := true
for (typeParams) do {typeParam : String →
if (first.not) then {
s := "{s}, {typeParam}"
} else {
first := false
s := "{s}{typeParam}"
}
}
"{s}⟧ : {oType.asString}"
}
}
// Create a GenericType from a typeDecNode
method fromTypeDec(typeDec : AstNode) → GenericType {
def debug3: Boolean = false
def name : String = typeDec.nameString
if (debug3) then {
io.error.write "\n661 typeDec is {name}"
}
def typeParams : List⟦String⟧ = getTypeParams(typeDec.typeParams.params)
if (debug3) then {io.error.write "\n699: new typeParams: {typeParams}"}
var oType : ObjectType := anObjectType.fromDType(typeDec.value)
with (typeParams)
def genType = fromName(name) parameters(typeParams) objectType(oType)
if (debug) then {
io.error.write "\n691: Created {genType} from type dec {typeDec}"
}
genType
}
def placeholder: GenericType is public = object {
method name -> String { "placeholder" }
method typeParams -> List[[typeParams]] { emptyList }
method oType -> ObjectType { anObjectType.placeholder }
method apply (_: List⟦ObjectType⟧) -> ObjectType { anObjectType.placeholder }
}
}
// Convert type parameters on type or method declaration to list of strings
method getTypeParams(params: List[[AstNode]]) -> List[[String]] {
def typeParams : List⟦String⟧ = emptyList[[String]]
for (params) do {param: AstNode ->
typeParams.add(param.nameString)
}
typeParams
}
// Object type information.
def anObjectType: ObjectTypeFactory is public = object {
// super class providing default implementations of methods
class superObjectType -> ObjectType {
use equality
// Returns self or an object type from scope when an object type
// is built from identifier
method resolve -> ObjectType { self }
// Is type built with & or |
method isOp -> Boolean { false }
// Is it a type name
method isId -> Boolean { false }
// Does this represent a type variable?
method isTypeVble -> Boolean { false }
// Is this object type built from a collection of methods?
method isMeths -> Boolean { false }
// Is this object type done?
method isDone -> Boolean { false }
// Return set of methods of the type
method methods -> Set[[MethodType]] {emptySet}
// Returns a list of sets of methods of an object type
//
// Needed to construct a normal-form representation of possible method
// combinations in a variant type. If type is not a variant or & type,
// normalFormMeths returns the same set of methods as methods method.
method normalFormMeths -> List[[Set[[MethodType]]]] {
list[[Set[[MethodType]]]] [methods]
}
// Returns a single-element list that contains self object type
method toList -> List[[ObjectType]] {
list[[ObjectType]] [self]
}
// Does this type represent the dynamic or unknown type
method isDynamic -> Boolean {false}
// Does this type represent the dynamic or unknown type
method isPlaceholder -> Boolean {false}
// Create new object type from self and other using op
method withOp(op: String, other: ObjectType) -> ObjectTypeFromOp {
if (debug) then {
io.error.write"\n697 calling makeWithOp for {self}, {other}"
}
anObjectType.makeWithOp(op, self, other)
}
// Is it a consistent subtype of other (for gradual typing
method isConsistentSubtypeOf(other: ObjectType) {
isSubtypeOf(other)
}
// Is it a subtype of other
method isSubtypeOf(other: ObjectType) -> Boolean {
resolve.isSubtypeHelper(other.resolve).ans
}
method isSubtypeHelper(other: ObjectType) -> Answer {
resolve.isSubtypeHelper(other.resolve)
}
// Construct a variant type from two object types.
// Note: variant types can only be created by this constructor.
method | (other' : ObjectType) → ObjectType {
// TODO Optimize this later
// if(isSubtypeOf(other')) then {
// other'
// } elseif{other'.isSubtypeOf(self)} then {
// self
// } else {
// withOp("|", other')
// }
withOp("|", other')
}
// Construct an & type from self and other'
method & (other': ObjectType) -> ObjectType {
withOp("&", other')
}
// A == B iff A <: B && B <: A
method == (other: ObjectType) → Boolean {
isSubtypeOf(other) && other.isSubtypeOf(self)
}
// Instantiate generic parameters with tparams
// For now, just return self
// TODO: Not sure if this is ever used!
method replaceTypeParams(tparams: List[[String]]) -> ObjectType {
self
}
// Replace type variables with object types using replacements
method updateTypeWith(replacements: Dictionary[[String,ObjectType]])
-> ObjectType {
def debug3: Boolean = false
if (debug3) then {
io.error.write "\n740 default updateType with {self}"
}
self
}
}
def placeholder: ObjectType is public = object{
inherit superObjectType
method isPlaceholder -> Boolean { true }
}
// Create an ObjectType from a collection of method signatures and a name
class fromMethods (methods' : Set⟦MethodType⟧) withName (name : String)
→ ObjectType {
inherit fromMethods(methods')