forked from gracelang/minigrace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
identifierresolution.grace
1496 lines (1428 loc) · 58.9 KB
/
identifierresolution.grace
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
import "io" as io
import "sys" as sys
import "ast" as ast
import "util" as util
import "xmodule" as xmodule
import "fastDict" as map
import "mirrors" as mirrors
import "errormessages" as errormessages
import "identifierKinds" as k
def completed = Singleton.named "completed"
def inProgress = Singleton.named "inProgress"
def undiscovered = Singleton.named "undiscovered"
// constants used in detecting cyclic inheritance
var stSerial := 100
def reserved = ["self", "outer", "true", "false"]
// reserved names that cannot be re-assigned or re-declared
method newScopeKind(variety') {
// for the top of the scope chain
def s = newScopeIn(object {})kind(variety')
s.hasParent := false
s
}
def keyOrdering = { a, b -> a.key.compare(b.key) }
type DeclKind = k.T
class newScopeIn(parent') kind(variety') {
use identityEquality
def elements is public = map.dictionary.empty
def elementScopes is public = map.dictionary.empty
def elementLines is public = map.dictionary.empty
def elementTokens is public = map.dictionary.empty
def parent is public = parent'
var hasParent is public := true
def variety is public = variety'
var node is public := ast.nullNode // the outermost ast node that I'm in
var inheritedNames is public := undiscovered
stSerial := stSerial + 1
def serialNumber is public = stSerial
def hash is public = serialNumber.hash
if (isObjectScope) then {
addName "self" asA(k.selfDef)
at "self" putScope(self)
}
method isEmpty { elements.size == 0 }
method addName(n) {
elements.at(n)put(k.methdec)
elementLines.at(n)put(util.linenum)
}
method addName (n) asA (kind:DeclKind) {
def oldKind = elements.at(n) ifAbsent {
elements.at(n)put(kind)
elementLines.at(n)put(util.linenum)
return
}
if (kind.isImplicit) then {
return // don't overwrite local id with id from trait or super
}
if (oldKind.isImplicit) then {
elements.at(n)put(kind)
elementLines.at(n)put(util.linenum)
return
}
errormessages.syntaxError("'{n}' cannot be" ++
" redefined as {kind} because it is already declared as {oldKind}")
atRange(util.linenum, util.linepos, util.linepos + n.size - 1)
}
method addNode (nd) asA (kind) {
def ndName = nd.value
checkShadowing(nd) asA(kind)
def oldKind = elements.at(ndName) ifAbsent {
elements.at(ndName)put(kind)
elementLines.at(ndName)put(nd.line)
return
}
if (kind.isImplicit) then {
return // don't overwrite local id with id from trait or super
}
if (oldKind.isImplicit) then {
elements.at(ndName)put(kind)
elementLines.at(ndName)put(nd.line)
return
}
var more := " in this scope"
if (elementLines.containsKey(ndName)) then {
more := " as a {oldKind}"
++ " on line {elementLines.at(ndName)}"
}
errormessages.syntaxError("'{nd.canonicalName}' cannot be"
++ " redeclared because it is already declared" ++ more )
atRange(nd.range)
}
method contains (n) {
if (elements.containsKey(n)) then { return true }
if (isInBeginningStudentDialect.not) then { return false }
if (self ≠ preludeScope) then { return false }
return isSpecial(n)
}
method withSurroundingScopesDo (b) {
// do b in this scope and all surounding scopes.
var cur := self
while {b.apply(cur); cur.hasParent} do {
cur := cur.parent
}
}
method keysAsList {
def result = emptyList
elements.keysDo { each -> result.addLast(each) }
result
}
method keysAndKindsDo (action) {
elements.keysAndValuesDo(action)
}
method kind (n) {
if { isInBeginningStudentDialect } then {
if (isSpecial(n)) then { return k.methdec }
}
elements.at(n)
}
method kind (n) ifAbsent (action) {
if { isInBeginningStudentDialect } then {
if (isSpecial(n)) then { return k.methdec }
}
elements.at(n) ifAbsent (action)
}
method at(n) putScope(scp) {
elementScopes.at(n)put(scp)
}
method getScope(n) {
if (elementScopes.containsKey(n)) then {
return elementScopes.at(n)
}
// util.log 70 verbose ("scope {self}: elements.containsKey({n}) = {elements.containsKey(n)}" ++
// " but elementScopes.containsKey({n}) = {elementScopes.containsKey(n)}")
// This occurs for names like `true` that are built-in, but for which there
// is no symbolTable describing their atttributes.
// TODO: add complete information for the built-in names.
// in the meantime:
return universalScope
}
method asStringWithParents {
var result := "\nCurrent: {self}"
var s := self
while {s.hasParent} do {
s := s.parent
result := result ++ "\nParent: {s}"
}
result ++ "\n"
}
method asString {
var result := "({variety} ST: "
withSurroundingScopesDo { each ->
result := result ++ each.serialNumber
if (each.hasParent) then { result := result ++ "➞" }
}
result := result ++ "):\n "
elements.bindings.sortedBy(keyOrdering).do { each ->
result := "{result} {each.key}({kind(each.key)}) "
}
result ++ "\n"
}
method asDebugString { "(ST {serialNumber})" }
method elementScopesAsString {
def referencedScopes = emptySet
var result := "\n [elementScopes:"
elementScopes.bindings.sortedBy(keyOrdering).do { each ->
result := "{result} {each.key}➞{each.value.asDebugString}"
referencedScopes.add (each.value)
}
result := result ++ "]\n____________\n"
list.withAll(referencedScopes)
.sortBy { a, b -> a.serialNumber.compare(b.serialNumber) }
.do { each -> result := result ++ each.asString }
result ++ "____________\n"
}
method hasDefinitionInNest(nm) {
withSurroundingScopesDo { s ->
if (s.contains(nm)) then {
return true
}
}
if { isInBeginningStudentDialect } then {
if (isSpecial(nm)) then { return true }
}
return false
}
method kindInNest(nm) {
// NEVER answers `inherited` or `fromTrait` !
withSurroundingScopesDo {s->
if (s.contains(nm)) then {
def kd = s.kind(nm)
if (kd.fromParent) then {
return k.methdec
} else {
return kd
}
}
}
if { isInBeginningStudentDialect } then {
if (isSpecial(nm)) then { return k.methdec }
}
return k.undefined
}
method scopeInNest(nm) {
// answers the elementScope associated with nm, or universalScope
// if there is none
withSurroundingScopesDo { s->
if (s.contains(nm)) then {
return s.getScope(nm)
}
}
if { isInBeginningStudentDialect } then {
if (isSpecial(nm)) then { return preludeScope }
}
return universalScope
}
method thatDefines(name) ifNone(action) {
withSurroundingScopesDo { s->
if (s.contains(name)) then { return s }
}
if { isInBeginningStudentDialect } then {
if (isSpecial(name)) then { return preludeScope }
}
action.apply
}
method thatDefines(name) {
withSurroundingScopesDo { s->
if (s.contains(name)) then { return s }
}
if { isInBeginningStudentDialect } then {
if (isSpecial(name)) then { return preludeScope }
}
print(self.asStringWithParents)
ProgrammingError.raise "no scope defines {name}"
}
method receiverScope(rcvrNode) {
// rcvrNode is the receiver of a request. Answer the scope
// associated with it. So, if the receiver is a.b.c,
// find the scope associated with c in the scope associated with b
// in the scope associated with a in this scope. Answers
// universalScope if we don't have enough information to be exact.
if (rcvrNode.isIdentifier) then {
scopeInNest(rcvrNode.nameString)
} elseif { rcvrNode.isCall } then {
receiverScope(rcvrNode.receiver).getScope(rcvrNode.nameString)
} elseif { rcvrNode.isOuter } then {
var resultScope := rcvrNode.scope.enclosingObjectScope // self's scope
repeat (rcvrNode.numberOfLevels) times {
resultScope := resultScope.enclosingObjectScope
}
resultScope
} elseif { rcvrNode.isConstant } then {
universalScope // TODO: define scopes for strings and numbers
} elseif { rcvrNode.isSequenceConstructor } then {
universalScope // TODO: define scope for Sequences
} elseif { rcvrNode.isObject } then {
rcvrNode.scope // TODO: do we need to remove the confidential attributes?
} else {
ProgrammingError.raise("unexpected receiver {rcvrNode.toGrace 0} " ++
"on line {rcvrNode.line}")
}
}
method isInSameObjectAs (enclosingScope) {
if (self == enclosingScope) then { return true }
if (self.parent.isObjectScope) then { return false }
self.parent.isInSameObjectAs(enclosingScope)
}
method isObjectScope {
if (variety == "object") then { return true }
if (variety == "module") then { return true }
if (variety == "dialect") then { return true }
if (variety == "class") then { return true }
if (variety == "built-in") then { return true }
false
}
method allowsShadowing {
if (variety == "type") then { return true }
isObjectScope
}
method isMethodScope {
variety == "method"
}
method isModuleScope {
variety == "module"
}
method isInheritableScope {
"class | object".contains(variety)
}
method resolveOuterMethod(name) fromNode (aNode) {
// replace name by a request with receiver self, or an outerNode
def outerChain = list [ ]
withSurroundingScopesDo { s->
if (s.contains(name)) then {
if (s.variety == "dialect") then {
return ast.memberNode.new(name,
ast.identifierNode.new("prelude", false)
scope(self)) scope(self).
onSelf.withGenericArgs(aNode.generics)
} elseif { s.variety == "module" } then {
return ast.memberNode.new(name, thisModule) scope(self).
onSelf.withGenericArgs(aNode.generics)
}
def rcvr = if (outerChain.isEmpty) then {
ast.identifierNode.new("self", false) scope(self).
setStart(ast.noPosition)
} else {
ast.outerNode(outerChain).setScope(self).
setStart(ast.noPosition)
}
return ast.memberNode.new(name, rcvr).setScope(self).
setPositionFrom(aNode).
onSelf.withGenericArgs(aNode.generics)
}
if (s.variety == "object") then {
def definingObjNode = s.node
if (outerChain.isEmpty.not && {outerChain.last == definingObjNode}) then {
ProgrammingError.raise "adding {definingObjNode} twice"
} else {
outerChain.addLast(s.node)
}
}
}
if (aNode.nameString == "explOde(1)") then {
ProgrammingError.raise "the compiler exploded."
}
reportUndeclaredIdentifier(aNode.asIdentifier)
}
method isSpecial(name) is confidential {
if (name.startsWith "list") then {
endsWithParenthesizedNumber(name, 5)
} elseif { name.startsWith "set" } then {
endsWithParenthesizedNumber(name, 4)
} elseif { name.startsWith "sequence" } then {
endsWithParenthesizedNumber(name, 9)
} elseif { name.startsWith "dictionary" } then {
endsWithParenthesizedNumber(name, 11)
} else {
false
}
}
method endsWithParenthesizedNumber(name, startIndex) is confidential {
def sz = name.size
if ( startIndex ≥ sz ) then { return false }
if ( name.at(startIndex) ≠ "(" ) then { return false }
var i := startIndex + 1
while { name.at(i).startsWithDigit } do {
i := i + 1
if (i > sz) then { return false }
}
( name.at(i) == ")" ) && ( i == sz )
}
method scopeReferencedBy(nd:ast.AstNode) {
// Finds the scope referenced by astNode nd.
// If nd references an object, then the returned
// scope will have bindings for the methods of that object.
// Otherwise, it will be the empty scope.
if (nd.isIdentifier) then {
def sought = nd.nameString
if (sought == "outer") then {
return parent.enclosingObjectScope
}
withSurroundingScopesDo {s->
if (s.contains(sought)) then {
return s.getScope(sought)
}
}
if (nd.nameString == "explOde(1)") then {
ProgrammingError.raise "the compiler exploded."
}
errormessages.syntaxError "no method {nd.canonicalName}."
atRange (nd.range)
} elseif {nd.kind == "outer"} then {
nd.theObjects.last.scope
} elseif {nd.kind == "op"} then {
def receiverScope = self.scopeReferencedBy(nd.left)
receiverScope.scopeReferencedBy(nd.asIdentifier)
} elseif {nd.isCall} then { // this includes "memberNodes"
def receiver = nd.receiver
if (receiver.isImplicit) then {
util.log 60 verbose "inherit from implicit.{nd.nameString} on line {nd.line}"
}
def newNd = transformCall(nd)
def receiverScope = self.scopeReferencedBy(newNd.receiver)
receiverScope.scopeReferencedBy(newNd.asIdentifier)
} else {
ProgrammingError.raise("{nd.nameString} is not a Call, Member, Identifier, Outer or Op node.\n"
++ nd.pretty(0))
}
}
method enclosingObjectScope {
// Answer the closest enclosing scope that describes an
// object, class or module. Could answer self.
withSurroundingScopesDo { s ->
if (s.isObjectScope) then { return s }
}
ProgrammingError.raise "no object scope found!"
// the outermost scope should always be a module scope,
// which is an object scope.
}
method inSameContextAs(encScope) {
// Is this scope within the same context as encScope?
// i.e. within the same method and object?
if (encScope.isObjectScope) then { return false }
withSurroundingScopesDo { s ->
if (s == encScope) then { return true }
if (s.isObjectScope) then { return false }
if (s.isMethodScope) then { return false }
}
ProgrammingError.raise "self = {self}; encScope = {encScope}"
}
method isUniversal { false }
method checkShadowing(ident) asA(newKind) {
def name = ident.nameString
def priorScope = thatDefines(name) ifNone {
return
}
def description = if (priorScope == self) then {
"this"
} else {
"an enclosing {priorScope.variety}"
}
def priorKind = priorScope.kind(name)
if (priorScope.allowsShadowing && {self.allowsShadowing}) then {
return
}
// new object attributes can shadow old, but other shadowing is illegal
var more := ""
if (priorScope.elementLines.containsKey(name)) then {
def ln = priorScope.elementLines.at(name)
if (ln > 0) then {
more := " on line {priorScope.elementLines.at(name)}"
}
}
if (newKind == k.vardec) then {
def suggs = list [ ]
def sugg = errormessages.suggestion.new
if (sugg.replaceUntil("=")with("{name} :=")
onLine(ident.line)) then {
suggs.push(sugg)
}
if (priorKind == k.vardec) then {
more := more ++ ". To assign to the existing variable, remove 'var'"
}
errormessages.syntaxError("'{ident.canonicalName}' cannot be "
++ "redeclared because it is already declared in "
++ "{description} scope{more}.")
atRange(ident.range)
withSuggestions(suggs)
} else {
errormessages.syntaxError("'{ident.canonicalName}' cannot be "
++ "redeclared in this {variety} scope because it is already declared in "
++ "{description} scope{more}. Use a different name.")
atRange(ident.range)
}
}
}
def emptyScope = newScopeKind("empty")
ast.nullNode.scope := emptyScope // TODO: eliminate!
def builtInsScope = newScopeIn(emptyScope) kind "built-in"
def preludeScope = newScopeIn(builtInsScope) kind "dialect"
def moduleScope = newScopeIn(preludeScope) kind "module"
def graceObjectScope = newScopeIn(emptyScope) kind "object"
def booleanScope = newScopeIn(builtInsScope) kind "object"
def varFieldDecls = list [] // a list of declarations of var fields
util.setPosition(0, 0)
def thisModule = ast.identifierNode.new("module()object", false)
scope(moduleScope)
// a hack to give us a way of referring to this module,
// other than by a chain of `outer`s. The name is one that
// cannot occur naturally in a program
moduleScope.addName "module()object" asA (k.defdec)
moduleScope.at "module()object" putScope(moduleScope)
def universalScope = object {
// The scope that defines every identifier,
// used when we have no information about an object
inherit newScopeIn(emptyScope) kind "universal"
method hasParent { false }
method parent { ProgrammingError.raise "universal scope has no parent" }
method addName(n) { ProgrammingError.raise "can't add to the universal scope" }
method addName(n)asA(kd) { ProgrammingError.raise "can't add to the universal scope" }
method addNode(n)asA(kd) { ProgrammingError.raise "can't add to the universal scope" }
method contains(n) { true }
method withSurroundingScopesDo(b) { b.apply(self) }
method kind(n) { "unknown" }
method at(n) putScope(scp) { }
method getScope(n) { self }
method isUniversal { true }
}
method transformIdentifier(node) ancestors(anc) {
// node is a (copy of an) ast node that represents an applied occurrence of
// an identifer id.
// This method may or may not transform node into another ast.
// There is no spec for what this method should do. The code below
// was developed by addding and removing particular cases until
// the transformed AST was sufficiecntly similar to the one emitted by the
// old identifier resolution pass for the C code generator to accept it.
// This method seems to do the following:
// - id is self => do nothing
// - id is super => do nothing
// - id is outer => transform to an outerNode
// - id is in an assignment position and a method ‹id›:=(_) is in scope => do nothing. The enclosing bind will transform it.
// - id is in the lexical scope: store binding occurrence of id in node
// - id is a method in an outer object scope: transform into member nodes or requests on outerNodes
// - id is a self-method: transform into a request on self
// - id is not declared: generate an error message
def nm = node.nameString
def nodeScope = node.scope
def nmGets = nm ++ ":=(1)"
util.setPosition(node.line, node.linePos)
if (node.isAssigned) then {
if (nodeScope.hasDefinitionInNest(nmGets)) then {
if (nodeScope.kindInNest(nmGets) == k.methdec) then {
return node // do nothing; this will be tranformed by the enclosing bind
}
}
}
def definingScope = nodeScope.thatDefines(nm) ifNone {
reportUndeclaredIdentifier(node)
}
def nodeKind = definingScope.kind(nm)
if (node.isAssigned) then {
if (nodeKind.isAssignable.not) then {
reportAssignmentTo(node) declaredInScope(definingScope)
}
}
if (nm == "outer") then {
return ast.outerNode [nodeScope.enclosingObjectScope.node].
setPositionFrom(node).setScope(nodeScope)
}
if (nm == "self") then {
return node
}
checkForAmbiguityOf (node) definedIn (definingScope) asA (nodeKind)
def v = definingScope.variety
if (v == "built-in") then { return node }
if (v == "dialect") then {
def p = ast.identifierNode.new("prelude", false) scope(nodeScope)
return ast.memberNode.new(nm, p)
scope(nodeScope).onSelf.withGenericArgs(node.generics)
}
if (nodeKind.isParameter) then { return node }
if (definingScope == moduleScope) then {
if (nodeKind == k.defdec) then { return node }
if (nodeKind == k.vardec) then { return node }
}
if (definingScope == nodeScope.enclosingObjectScope) then {
return ast.memberNode.new(nm,
ast.identifierNode.new("self", false) scope(nodeScope)
) scope(nodeScope).onSelf.withGenericArgs(node.generics)
}
if (nodeScope.isObjectScope.not
&& {nodeScope.isInSameObjectAs(definingScope)}) then {
if (nodeKind == k.methdec) then { return node } // can this ever happen?
if (nodeKind == k.defdec) then { return node }
if (nodeKind == k.vardec) then { return node }
}
if (v == "method") then { return node }
// node is defined in the closest enclosing method.
// there may be intervening blocks, but no objects or clases.
// If this identifier is in a block that is returned, then ids
// defined in the enclosing method scope have to go in a closure
// In that case, leaving the id untouched may be wrong
if (v == "block") then { return node }
return nodeScope.resolveOuterMethod(nm) fromNode(node)
}
method checkForAmbiguityOf (node) definedIn (definingScope) asA (kind) {
// The spec says:
// When resolving an implicit request, the usual rules of lexical scoping
// apply, so a definition of m in the current scope will take precedence
// over any definitions in enclosing scopes. However, if m is defined in
// the current scope by inheritance or trait use, rather than directly,
// and also defined directly in an enclosing scope, then an implicit
// request of m is ambiguous and is an error.
def currentScope = node.scope
if (kind.fromParent.not) then { return }
def name = node.nameString
def conflictingScope = definingScope.parent.thatDefines(name) ifNone {
return
}
def conflictingKind = conflictingScope.kind(name)
if (conflictingKind.fromParent) then {
return // request is ambiguous only if name is defined
// _directly_ in an enclosing scope.
}
var more := ""
if (conflictingScope.elementLines.containsKey(name)) then {
def earlierDef = conflictingScope.elementLines.at(name)
if (earlierDef != 0) then {
more := " at line {earlierDef}"
}
}
util.log 60 verbose "currentScope = {currentScope}\n defines {name} as {kind}\nconflictingScope = {conflictingScope}\n defines {name} as {conflictingKind}"
errormessages.syntaxError "{node.canonicalName} is both {kind}, and defined in an enclosing scope{more}."
atRange(node.range)
}
method checkForReservedName(node) {
def ns = node.nameString
if (reserved.contains(ns)) then {
errormessages.syntaxError "{ns} is a reserved name and cannot be re-declared."
atRange(node.range)
}
}
method suggestionsForIdentifier(node) {
def nm = node.nameString
def suggestions = set.empty
def nodeScope = node.scope
def thresh = 4 // max number of suggestions
nodeScope.withSurroundingScopesDo { s ->
s.elements.keysDo { v ->
if (errormessages.name (nm) mightBeIntendedToBe(v)) then {
def sug = errormessages.suggestion.new
sug.replaceRange(node.linePos, node.linePos +
node.value.size - 1) with (canonical(v)) onLine(node.line)
suggestions.add(sug)
if (suggestions.size ≥ thresh) then { return suggestions }
}
}
}
nodeScope.elementScopes.keysDo { s ->
if (nodeScope.elementScopes.at(s).contains(nm)) then {
def sug = errormessages.suggestion.new
sug.insert "{s}." atPosition (node.linePos) onLine(node.line)
suggestions.add(sug)
if (suggestions.size ≥ thresh) then { return suggestions }
}
}
suggestions
}
method canonical(numericName) {
def parts = numericName.split "("
var output := parts.first
for (2..parts.size) do { i ->
def part_split = parts.at(i).split ")"
def n = part_split.first.asNumber
if (n.isNaN) then {
output := output ++ part_split.first
} else {
output := output ++ "(" ++ ("_," * (n - 1)) ++ "_)"
if (part_split.size > 1) then {
output := output ++ part_split.second
}
}
}
return output
}
method reportUndeclaredIdentifier(node) {
def suggestions = suggestionsForIdentifier(node)
def cn = node.canonicalName
def varBit = if (cn.endsWith ")") then { "" } else { " variable or" }
errormessages.syntaxError("unknown{varBit} method '{cn}'; " ++
"this may be a spelling mistake, or an attempt to access a{varBit} method in another scope")
atRange (node.range) withSuggestions (suggestions)
}
method reportAssignmentTo(node) declaredInScope(scp) {
// Report a syntax error for an illegal assignment
def name = node.nameString
def kind = scp.kind(name)
var more := ""
def suggestions = list []
if (scp.elementLines.containsKey(name)) then {
more := " on line {scp.elementLines.at(name)}"
}
if (kind == k.selfDef) then {
errormessages.syntaxError("'{name}' cannot be re-bound; " ++
"it always refers to the current object.")
atRange(node.range)
} elseif { reserved.contains(name) } then {
errormessages.syntaxError("'{name}' is a reserved name and " ++
"cannot be re-bound.")
atRange(node.range)
} elseif { kind == k.defdec } then {
if (scp.elementTokens.containsKey(name)) then {
def tok = scp.elementTokens.at(name)
def sugg = errormessages.suggestion.new
if (tok.value == "def") then {
var eq := tok
while {(eq.kind != "op") || (eq.value != "=")} do {
eq := eq.next
}
sugg.replaceToken(eq)with(":=")
sugg.replaceToken(tok)with("var")
suggestions.push(sugg)
} else {
errormessages.syntaxError("'{name}' cannot be changed " ++
"because it was declared as a '{tok.value}'{more}.")
atRange(node.range)
}
}
errormessages.syntaxError("'{name}' cannot be changed "
++ "because it was declared with 'def'{more}. "
++ "To make it a variable, use 'var' in the declaration")
atRange(node.range)
withSuggestions(suggestions)
} elseif { kind == k.typedec } then {
errormessages.syntaxError("'{name}' cannot be re-bound "
++ "because it is declared as a type{more}.")
atRange(node.range)
} elseif { kind.isParameter } then {
errormessages.syntaxError("'{name}' cannot be re-bound "
++ "because it is declared as a parameter{more}.")
atRange(node.range)
} elseif { kind == k.methdec } then {
errormessages.syntaxError("'{name}' cannot be re-bound "
++ "because it is declared as a method{more}.")
atRange(node.range)
}
}
method resolveIdentifiers(topNode) {
// Recursively replace bare identifiers with their fully-qualified
// equivalents. Creates and returns a new AST; map works
// bottom-up, so by the time a node is mapped, all of its
// descendents have already been mapped.
def newModule = topNode.map { node, anc ->
if ( node.isAppliedOccurrence ) then {
transformIdentifier(node) ancestors(anc)
} elseif { node.isCall } then {
transformCall(node)
} elseif { node.isInherits } then {
transformInherits(node) ancestors(anc)
} elseif { node.isBind } then {
transformBind(node) ancestors(anc)
} elseif { node.isTypeDec } then {
node
} else {
node
}
} ancestors (ast.ancestorChain.empty)
addAssignmentMethodsToSymbolTable
newModule
}
method addAssignmentMethodsToSymbolTable {
// Adds the ‹var›(_):= methods for var fields to the symbol table, so that
// they will be inserted into the gct file. This is delayed until after
// identifiers have been resolved, so that assignments to module-level
// var fields are _not_ resolved into requests on the ‹var›(_):= method,
// but are compiled as simple assignments (which are more efficient). Note
// that module-level var fields that are not public don't get (_):= methods
varFieldDecls.do { decl ->
def dScope = decl.scope
def nameGets = decl.nameString ++ ":=(_)"
if (dScope.isModuleScope.not || decl.isPublic) then {
util.setPosition(decl.line, decl.linePos)
dScope.addName(nameGets) asA (k.methdec) // will complain if already declared
}
}
}
method processGCT(gct, importedModuleScope) {
gct.at "classes" ifAbsent {emptySequence}.do { c ->
def constrs = gct.at "constructors-of:{c}"
def classScope = newScopeIn(importedModuleScope) kind "class"
for (constrs) do { constr ->
def ns = newScopeIn(importedModuleScope) kind "object"
classScope.addName(constr)
classScope.at(constr) putScope(ns)
gct.at "methods-of:{c}.{constr}".do { mn ->
ns.addName(mn)
}
}
importedModuleScope.addName(c)
importedModuleScope.at(c) putScope(classScope)
}
gct.at "fresh-methods" ifAbsent {emptySequence}.do { c ->
def objScope = newScopeIn(importedModuleScope) kind "object"
gct.at "fresh:{c}".do { mn ->
objScope.addName(mn)
}
importedModuleScope.addName(c)
importedModuleScope.at(c) putScope(objScope)
}
}
var isInBeginningStudentDialect := false
method setupContext(moduleObject) {
// define the built-in names
util.setPosition(0, 0)
builtInsScope.addName "Type" asA(k.typedec)
builtInsScope.addName "Object" asA(k.typedec)
builtInsScope.addName "Unknown" asA(k.typedec)
builtInsScope.addName "String" asA(k.typedec)
builtInsScope.addName "Number" asA(k.typedec)
builtInsScope.addName "Boolean" asA(k.typedec)
builtInsScope.addName "Done" asA(k.typedec)
builtInsScope.addName "done" asA(k.defdec)
builtInsScope.addName "true"
builtInsScope.addName "false"
builtInsScope.addName "outer" asA(k.defdec)
builtInsScope.addName "readable"
builtInsScope.addName "writable"
builtInsScope.addName "public"
builtInsScope.addName "confidential"
builtInsScope.addName "override"
builtInsScope.addName "parent"
builtInsScope.addName "..." asA(k.defdec)
preludeScope.addName "asString"
preludeScope.addName "::(1)"
preludeScope.addName "++(1)"
preludeScope.addName "==(1)"
preludeScope.addName "≠(1)"
preludeScope.addName "hash"
preludeScope.addName "for(1)do(1)"
preludeScope.addName "while(1)do(1)"
preludeScope.addName "print(1)"
preludeScope.addName "native(1)code(1)"
preludeScope.addName "native(1)header(1)"
preludeScope.addName "Exception" asA(k.defdec)
preludeScope.addName "RuntimeError" asA(k.defdec)
preludeScope.addName "NoSuchMethod" asA(k.defdec)
preludeScope.addName "ProgrammingError" asA(k.defdec)
preludeScope.addName "TypeError" asA(k.defdec)
preludeScope.addName "ResourceException" asA(k.defdec)
preludeScope.addName "EnvironmentException" asA(k.defdec)
preludeScope.addName "π" asA(k.defdec)
preludeScope.addName "infinity" asA(k.defdec)
preludeScope.addName "minigrace"
preludeScope.addName "_methods"
preludeScope.addName "primitiveArray"
preludeScope.addName "become(1)"
preludeScope.addName "unbecome(1)"
preludeScope.addName "clone(1)"
preludeScope.addName "inBrowser"
preludeScope.addName "engine"
graceObjectScope.addName "isMe(1)" asA (k.graceObjectMethod)
graceObjectScope.addName "myIdentityHash" asA (k.graceObjectMethod)
graceObjectScope.addName "asString" asA (k.graceObjectMethod)
graceObjectScope.addName "asDebugString" asA (k.graceObjectMethod)
booleanScope.addName "prefix!"
booleanScope.addName "&&(1)"
booleanScope.addName "||(1)"
booleanScope.addName "not"
builtInsScope.addName "graceObject"
builtInsScope.at "graceObject" putScope(graceObjectScope)
builtInsScope.addName "prelude" asA(k.defdec)
builtInsScope.at "prelude" putScope(preludeScope)
builtInsScope.addName "_prelude" asA(k.defdec)
builtInsScope.at "_prelude" putScope(preludeScope)
builtInsScope.at "true" putScope(booleanScope)
builtInsScope.at "false" putScope(booleanScope)
def dialectNode = moduleObject.theDialect
def dialectName:String = dialectNode.value
if (dialectName ≠ "none") then {
xmodule.checkExternalModule(dialectNode)
def gctDict = xmodule.parseGCT(dialectName)
def typeDecls = set.withAll(gctDict.at "types" ifAbsent {sequence.empty})
gctDict.at "public" ifAbsent {emptySequence}.do { mn ->
preludeScope.addName(mn) asA (if (typeDecls.contains(mn))
then { k.typedec } else { k.methdec })
}
processGCT(gctDict, preludeScope)
}
if (dialectName == "beginningStudent") then {
isInBeginningStudentDialect := true
}
}
method checkTraitBody(traitObjNode) {
traitObjNode.value.do { node ->
if (node.isLegalInTrait.not) then {
def badThing = node.statementName
def article = articleFor (badThing)
errormessages.syntaxError("{article} {badThing} cannot appear in " ++
"a trait (defined on line {traitObjNode.line})")
atLine(node.line)
}
}
}
method articleFor(str) {
// the indefinite article to preceed str
if ("aeioAEIO".contains(str.first)) then { "an" } else { "a" }
}
method buildSymbolTableFor(topNode) ancestors(topChain) {
def symbolTableVis = object {
inherit ast.baseVisitor
method visitBind (o) up (anc) {
o.scope := anc.parent.scope
def lValue = o.dest
if (lValue.kind == "identifier") then {
lValue.isAssigned := true
}
return true
}
method visitCall (o) up (anc) {
def enclosingNode = anc.parent
def scope = enclosingNode.scope
o.scope := scope
def callee = o.receiver
if (callee.isIdentifier) then {
callee.inRequest := true
}
o.parts.do { each -> each.scope := scope }
if (enclosingNode.isMethod) then {
if (enclosingNode.body.last == o) then {
o.isTailCall := true
}
} elseif { enclosingNode.isReturn } then {
o.isTailCall := true
}
return true
}
method visitBlock (o) up (anc) {
o.scope := newScopeIn(anc.parent.scope) kind "block"
true
}
method visitDefDec (o) up (anc) {
def myParent = anc.parent
o.scope := myParent.scope
o.parentKind := myParent.kind
def declaredName = o.nameString
if (false != o.startToken) then {
myParent.scope.elementTokens.at(declaredName)put(o.startToken)
}
if (o.value.isObject) then { o.value.name := declaredName }
true
}
method visitVarDec(o) up (anc) {
def myParent = anc.parent
o.scope := myParent.scope
o.parentKind := myParent.kind
true
}
method visitIdentifier (o) up (anc) {
var scope := anc.parent.scope
o.scope := scope
if (o.isBindingOccurrence) then {
if ((o.isDeclaredByParent.not) && {o.wildcard.not}) then {
checkForReservedName(o)
def kind = o.declarationKindWithAncestors(anc)
if (scope.isObjectScope && (kind == k.vardec)) then {
varFieldDecls.add(anc.parent)
// Why not just add the :=(_) now?
// Because we want some field assignments to be compiled as
// direct assignments, and hence have to distinguish
// programmer-writen :=(_) methods from synthetic ones.
}
scope.addNode(o) asA (kind)
}
} elseif {o.wildcard} then {
errormessages.syntaxError("'_' cannot be used in an expression")
atRange(o.range)
}
true
}
method visitAlias (o) up (ac) {
o.scope := ac.parent.scope
o.newName.accept(self) from (ac.extend(o))
false // no need to visit the aliasNode's other components
}
method visitImport (o) up (anc) {
o.scope := anc.parent.scope
xmodule.checkExternalModule(o)
def gct = xmodule.parseGCT(o.path)
def otherModule = newScopeIn(anc.parent.scope) kind "module"
otherModule.node := o
processGCT(gct, otherModule)
o.scope.at(o.nameString) putScope(otherModule)
true
}
method visitInherits (o) up (anc) {
o.scope := anc.parent.scope
if (o.isUse) then {
if (anc.parent.canUse.not) then {