forked from gracelang/minigrace
-
Notifications
You must be signed in to change notification settings - Fork 3
/
scope.grace
1588 lines (1502 loc) · 59.1 KB
/
scope.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 "errormessages" as errormessages
import "regularExpression" as regEx
import "collections" as collections
import "basic" as basic
import "util" as util
// This module defines:
// — scope: a mapping from defined names (of methods, vars, defs, types, etc) to variables
// – variable: an object that describes a defined name, and
// – nameDictionary: a dictionary that provides special treatment for Grace's special
// control structures (if–then–elseif—else, try–catch–finally, and match–case–else)
use basic.open
def predefined is public = dictionary.empty
var typeType is writable // dependency injected from constantScope
type MinimalScope = interface {
localNames → Collection
reusedNames → Collection
defines(name) → Boolean
}
var id := 100 // for generating unique ids for scopes
class blockScope {
inherit graceScope
method variety { "block" }
}
class builtInScope {
inherit moduleScope
method variety { "builtIn" }
method areReusedNamesCompleted { true }
method isBuiltInScope { true }
method varsAreMethods { true } // we want to treat references to them as requests
}
class graceDialectScope {
inherit moduleScope
method variety { "dialect" }
method varsAreMethods { true }
method areReusedNamesCompleted {
true // because any reuse in the dialect
// happended before it became our dialect
}
method isDialectScope { true }
}
def emptyScope:MinimalScope is public = object {
// I represent the empty scope, with no definitions, and to which no definitions can be added.
use identityEquality
method <(other) { uid < other.uid }
def uid is public = "$scopeEmpty"
predefined.at(uid) put (self)
method meet (anotherScope) {
// create and return a new scope that is the mathematical meet of self
// and anotherScope; it contains those names common to both scopes.
self
}
method isTheEmptyScope { true }
method isTheUniversalScope { false }
method isFresh { false }
method isDialectScope { false }
method lookup (name) ifAbsent (aBlock) ifPresent (pBlock) {
aBlock.apply
}
method localNames { nameDictionary [] }
method reusedNames { nameDictionary [] }
method types { dictionary.empty }
method lookup (name) ifAbsent (aBlock) {
aBlock.apply
}
method attributeScopeOf(name) in (nd) {
self
}
method lookup(name) {
ProgrammingError.raise "{name} was not found in any lexical scope"
}
method lookupLocally (name) ifAbsent (aBlock) {
aBlock.apply
}
method localAndReusedNamesAndValuesDo (aBlock) {
done
}
method node {
ProgrammingError.raise "the empty scope is not associated with a node"
}
method node := (nu) {
ProgrammingError.raise "the empty scope cannot be associated with a node"
}
method asString {
"the empty scope"
}
method add (aVariable:Variable) withName (aString) {
ProgrammingError.raise("an attempt was made to add {aVariable.name} with " ++
"name {aString} to the empty scope")
}
method lookupLocallyOrReused (name) ifAbsent (aBlock) {
aBlock.apply
}
method allNamesAndValuesDo (aBlock) {
self
}
method lookupLexically (name) ifAbsent (aBlock) {
aBlock.apply
}
method currentObjectScope {
self
}
method enclosingObjectScope {
ProgrammingError.raise "the empty scope has no enclosing scopes"
}
method defines (name) {
false
}
method allNamesAndValuesDo (aBlock) filteringOut (closerDefinitions) {
done
}
method lookupLocallyOrReused (name) ifAbsent (aBlock) ifPresent (pBlock) {
aBlock.apply
}
method localNamesAndValuesDo (aBlock) {
done
}
method isObjectScope {
// I'm treated as an object scope so that every non-empty scope has
// an enclosingObjectScope
true
}
method lookupLexically (name) ifAbsent (aBlock) ifPresent (pBlock) {
aBlock.apply
}
method outerScope {
ProgrammingError.raise "the empty scope has no outerScope"
}
method outerScope := (nu) {
ProgrammingError.raise "the empty scope cannot be given an outerScope"
}
method variety { "empty" }
method clear { }
}
def universalScope:Scope is public = object {
inherit graceScope
// I represent the universal scope, which defines all names
// I'm used when no more specific scope information is available.
def universalVariable = singleton "universal variable"
method iterationError is confidential {
ProgrammingError.raise "can't iterate through the Universal Scope"
}
uidCache := "$scopeUniv"
predefined.at(uidCache) put (self)
method isTheEmptyScope { false }
method isFresh { false }
method isFresh:=(_) {
ProgrammingError.raise "can't change the freshness of the Universal Scope"
}
method isTheUniversalScope { true }
method lookup (name) ifAbsent (aBlock) ifPresent (pBlock) {
pBlock.apply
}
method lookup (name) ifAbsent (aBlock) { universalVariable }
method lookup(name) { universalVariable }
method lookupLocally (name) ifAbsent (aBlock) { universalVariable }
method localAndReusedNamesAndValuesDo (aBlock) { iterationError }
method node {
ProgrammingError.raise "the universal scope is not associated with a node"
}
method node := (nu) {
ProgrammingError.raise "the universal scope cannot be associated with a node"
}
method asString {
"the universal scope"
}
method add (aVariable:Variable) withName (aString) {
ProgrammingError.raise("an attempt was made to add {aVariable.name} with " ++
"name {aString} to the universal scope")
}
method lookupLocallyOrReused (name) ifAbsent (aBlock) { universalVariable }
method allNamesAndValuesDo (aBlock) { iterationError }
method lookupLexically (name) ifAbsent (aBlock) { universalVariable }
method currentObjectScope { self }
method enclosingObjectScope {
self.outerScope.currentObjectScope
}
method defines (name) { true }
method allNamesAndValuesDo (aBlock) filteringOut (closerDefinitions) {
iterationError
}
method lookupLocallyOrReused (name) ifAbsent (aBlock) ifPresent (pBlock) {
pBlock.apply
}
method localNamesAndValuesDo (aBlock) {
iterationError
}
method attributeScopeOf (aName) in (nd) { self }
method isObjectScope {
// I'm treated as an object scope so that every non-empty scope has
// an enclosing objectScope
true
}
method lookupLexically (name) ifAbsent (aBlock) ifPresent (pBlock) {
pBlock.apply
}
method outerScope {
ProgrammingError.raise "the universal scope has no outerScope"
}
method outerScope := (nu) {
ProgrammingError.raise "the universal scope cannot be given an outerScope"
}
method meet (anotherScope) {
// create and return a new scope that is the mathematical meet of self
// and anotherScope; it contains those names common to both scopes.
anotherScope
}
method variety { "universal" }
method clear {
ProgrammingError.raise "can't clear the universal scope"
}
method types { dictionary.empty }
}
class interfaceScope {
inherit graceScope
// I represent an iterface scope, that is, a set of methods. Thus, I also
// represent the methods in an interface type.
once method meet (anotherScope) {
// create and return a new scope that is the mathematical meet of self
// and anotherScope; it contains those names common to both scopes.
// But with what attributes? Is this too hard? Do we just give up and
// return universalScope?
def result = interfaceScope
anotherScope.localNamesAndValuesDo { nm, rightVar →
lookupLocally (nm) ifAbsent {
} ifPresent { leftVar →
result.add (leftVar.meet (rightVar)) withName (nm)
}
}
result
}
method variety { "interface" }
method allowsShadowing { true }
}
class methodScope {
inherit graceScope
alias superAdd(_)withName(_) = add(_)withName(_)
method add (aVariable:Variable) withName (aString) {
if (aVariable.isExplicitMethod) then {
structuralError "sorry, you can't declare a method immediately inside a method"
variable (aVariable)
}
superAdd (aVariable) withName (aString)
}
method variety { "methodDec" }
}
class objectScope {
// I represent an object scope in a Grace program. I support reuse via
// inheritance of objects and use of traits, and hence have an additional
// dictionary for reused names.
//
// My fields are those of graceScope, and:
// reusedNames — a dictionary containing as keys all of the names reused
// (from a trait or superobject) in my scope. This dictionary
// is polpulated on demand.
// statusOfReusedNames — one of "undiscovered", "inProgress", or "completed";
// the state of the process of collecting the reusedNames.
// methodTypes - a dictionary containing the type (aString) of each method
// defined in this object
// types - a dictionary containing the types defined in this object (as strings)
// isFresh — can objects with me as their scope be inherited or used?
inherit graceScope
alias superCopy(other) = copy(other)
alias superClear = clear
def reusedNames is public = nameDictionary []
var statusOfReusedNames := "undiscovered"
def methodTypes is public = dictionary.empty
def types is public = dictionary.empty
method isEmpty { names.isEmpty && reusedNames.isEmpty }
var isFresh is public := false // changed in currentObjectScopesVis in identifierResolution
method varsAreMethods { true } // TODO: maybe false when not fresh?
method allNames {
(names.keys ++ reusedNames.keys) >> sequence
}
method markReusedNamesAsInProgress {
statusOfReusedNames := "inProgress"
}
once method isTrait {
// Can objects with me as their scope be used as a trait?
// My declaration may or may not use the trait syntax.
node.value.do { each → // TODO: use allSatisfy on collections
if (each.isLegalInTrait.not) then { return false }
}
true
}
method currentObjectScope {
// this scope, since it is an object scope
self
}
method enclosingObjectScope {
self.outerScope.currentObjectScope
}
method addLocalAndReusedFrom (anotherScope) {
anotherScope.localAndReusedNamesAndValuesDo { nm, defn →
if (defn.isAvailableForReuse) then {
addReused (defn) withName (nm)
}
}
}
method addReused (aVariable:Variable) {
addReused (aVariable) withName (aVariable.declaredName)
}
method localAndReusedNamesAndValuesDo (aBlock) filteringOut (closerDefinitions) {
names.keysAndValuesDo { name, defn →
if (closerDefinitions.contains (name).not) then {
aBlock.apply (name, defn)
closerDefinitions.add (name)
}
}
reusedNames.keysAndValuesDo { name, defn →
if (closerDefinitions.contains (name).not) then {
aBlock.apply (name, defn)
closerDefinitions.add (name)
}
}
}
method addReused (aVariable:Variable) withName (aName) {
reusedNames.at (aName) put (aVariable)
aVariable
}
method reuses (name) {
// Is name defined by a scope that this scope reuses?
if (areReusedNamesCompleted.not) then {
GatheringError.raise ("reused names of {self} declared on " ++
"{node.range.lineRangeString} have not been gathered")
}
reusedNames.containsKey (name)
}
method lookupReused (name) ifAbsent (aBlock) {
// Return the variable corresponding to name, if it is defined in a scope that this
// scope reuses. If it is not defined, return the value of executing aBlock.
if (areReusedNamesCompleted.not) then {
GatheringError.raise ("reused names of {self} declared on " ++
"{node.range.lineRangeString} have not been gathered")
}
reusedNames.at (name) ifAbsent {
aBlock.apply
}
}
method reusedNamesAndValuesDo (aBlock) {
reusedNames.keysAndValuesDo (aBlock)
}
method areReusedNamesInProgress {
(statusOfReusedNames == "inProgress")
}
method lookupReused (name) ifAbsent (aBlock) ifPresent (pBlock) {
// If the variable corresponding to name is defined in a scope that this
// scope reuses, apply pBlock to it and return the result.
// If it is not defined, return the value of executing aBlock.
if (areReusedNamesCompleted.not) then {
GatheringError.raise ("reused names of {self} declared on " ++
"{node.range.lineRangeString} have not been gathered")
}
def variable = reusedNames.at (name) ifAbsent {
return aBlock.apply
}
pBlock.apply (variable)
}
method copy(other) {
def result = superCopy(other)
other.reusedNames.keysAndValuesDo { name, variable →
result.addReused(variable) withName (name)
}
result
}
method areReusedNamesCompleted {
statusOfReusedNames == "completed"
}
method markReusedNamesAsCompleted {
statusOfReusedNames := "completed"
self
}
method isObjectScope { true }
method variety { "object" }
method clear {
superClear
reusedNames.clear
statusOfReusedNames := "undiscovered"
self
}
once method meet (anotherScope) {
// create and return a new scope that is the mathematical meet of self
// and anotherScope; it contains those names common to both scopes.
if (self.isMe(anotherScope)) then { return self }
// disambiguating with isMe in standard dialect
if (anotherScope.isTheUniversalScope) then { return self }
def result = species
anotherScope.localAndReusedNamesAndValuesDo { nm, rightVar →
lookupLocallyOrReused (nm) ifAbsent {
} ifPresent { leftVar →
result.add (leftVar.meet (rightVar)) withName (nm)
}
}
result
}
method species is confidential { objectScope }
method allowsShadowing { true }
}
class externalScope {
// I describe a scope defined in some other module.
//
// I've been made known to the module being compiled by a gct entry;
// consequently, there is no parse node associated with me.
inherit objectScope
method varsAreMethods { true }
method node is override {
ProgrammingError.raise "an external variable has no associated node"
}
var isTrait is public := false
var isFresh is public := false
method isExternal { true }
method variety { "external" }
method areReusedNamesCompleted { true }
method species is confidential { externalScope }
}
method predefinedObjectScope(name) {
// I'm an object scope for predefined objects like String and Number.
//
// I differ from an ordinary externalScope because I don't need to be
// written to the gct. To support this, I have the same uid in every
// compilation. The dictionary `predefined` can be used to find me
def scpId = "$scope_{name}"
predefined.at(scpId) ifAbsent {
object {
inherit externalScope
uidCache := scpId
predefined.at(scpId) put (self)
method variety { "predefined" }
method species is confidential { objectScope }
}
}
}
class parameterScope {
// A parameter scope is used to declare the type parameters and the value
// parameters of a method. Type parameters of a type go in the type scope.
inherit graceScope
method variety { "parameter" }
}
class typeScope {
// I record the names introduced by a type declaration. These are the
// parameters to the type, if any.
// Nothing else goes in the type scope; the methods of an interface go in
// an interface scope.
inherit graceScope
method variety { "type" }
}
class moduleScope {
inherit objectScope
method varsAreMethods { false }
method isModuleScope { true }
method lookup (name) ifAbsent (aBlock) {
// Return the variable corresponding to name, which may or may not be
// defined in this scope, or in the surroundng dialect scope, but no further.
// If name is not defined, return the value of executing aBlock.
lookupLocallyOrReused (name) ifAbsent {
outerScope.lookupLocallyOrReused (name) ifAbsent {
aBlock.apply
}
}
}
method lookupLexically (name) ifAbsent (aBlock) {
// Return the variable corresponding to name, which may or may not be
// defined in this scope, or in the surroundng dialect scope,
// but no further. If name is not defined, return the value of executing aBlock.
// Note that this method ignores reused names; it is intended for implementing Grace's shadowing check
lookupLocally (name) ifAbsent {
outerScope.lookupLocally (name) ifAbsent {
aBlock.apply
}
}
}
method importedModules {
names.values.select { each →
each.isImport
}
}
method variety { "module" }
method species is confidential { moduleScope }
}
class graceScope {
// I'm an abstract class representing a declaration scope in a Grace program.
//
// My fields are:
// names — a dictionary containing as keys all of the names declared in my scope.
// The values are the "variable" objects that represent the declaration.
// outerScope — the scope surrounding me, or emptyScope if there is none.
// openingNode — the node that opens this scope. For example, if this is a method scope,
// then openingNode is the method node
// uidCache — a string that uniquely identifies this scope within the current compilation,
// or the empty string if the uid has yet to be requested.
use identityEquality
method <(other) { uid < other.uid }
def names = nameDictionary []
var outerScope is public := emptyScope
var openingNode := nullNode
var uidCache := ""
method isExternal { false }
method uid {
if (uidCache.isEmpty) then {
uidCache := "${id}"
id := id + 1
}
uidCache
}
method varsAreMethods { false }
method allNames { names.keys >> sequence }
method isEmpty { names.isEmpty }
method in(anotherScope) {
// sets the outerScope for this scope, and returns self
outerScope := anotherScope
self
}
method node(nu) {
// sets the node for this scope, and returns self
openingNode := nu
initialize(openingNode)
self
}
method node:=(nu) {
openingNode := nu
initialize(openingNode)
done
}
method node {
openingNode
}
method initialize(aNode) is confidential {
// a hook method
}
method lookup (name) ifAbsent (aBlock) {
// Return the variable corresponding to name, which may or may not be
// defined in this scope, or in one of the lexically surrounding scopes.
// If it is not defined, return the value of executing aBlock.
lookupLocallyOrReused (name) ifAbsent {
outerScope.lookup (name) ifAbsent {
aBlock.apply
}
}
}
method lookup (name) {
// Return the variable corresponding to name, which must be
// defined in this scope, or in one of the lexically surrounding scopes.
lookup (name) ifAbsent {
ProgrammingError.raise "name {name} not found in scope {self}"
}
}
method localAndReusedNamesAndValuesDo (aBlock)
filteringOut (closerDefinitions) is confidential {
names.keysAndValuesDo { name, defn →
if (closerDefinitions.contains (name).not) then {
aBlock.apply (name, defn)
closerDefinitions.add (name)
}
}
}
method lookupLocally (name) ifAbsent (aBlock) ifPresent (pBlock) {
// Look up variable corresponding to name, which may or may not be defined
// in this scope. If it is not defined, return the result of executing
// aBlock; otherwise, return the result of applying pBlock to the variable.
def variable = names.at (name) ifAbsent {
return aBlock.apply
}
pBlock.apply (variable)
}
method attributeScopeOf (aName) in (nd) {
lookup (aName) ifAbsent {
util.log 50 verbose "`{aName}` ({nd.range}) not found in scope search — assuming universal scope"
return universalScope
}.attributeScope
}
method asDebugString {
"{variety} scope {uid}"
}
method asString {
"{variety} scope {uid} containing " ++ (names.keys.sorted >> sequence)
}
method asStringWithParents { "{asString} ⇒ {outerScope.uid}" }
method lookupLocallyOrReused (name) ifAbsent (aBlock) {
// Return the variable corresponding to name, which may or may not be defined in this scope,
// or in one of the scopes that it reuses.
// If name is not defined, return the value of executing aBlock.
lookupLocally (name) ifAbsent {
lookupReused (name) ifAbsent {
aBlock.apply
}
}
}
method lookupLocallyOrReused (name) {
lookupLocallyOrReused (name) ifAbsent { ProgrammingError.raise "{name} not found" }
}
method copy(other) {
def result = graceScope
other.names.keysAndValuesDo { name, variable →
result.add(variable) withName (name)
}
result.outerScope := emptyScope
result
}
method areReusedNamesCompleted {
// Overriden in objectScope
true
}
method currentObjectScope {
// the enclosing object scope, since this scope is not an object scope
var s := self.outerScope
while { s.isObjectScope.not } do {
s := s.outerScope
}
s
}
method enclosingObjectScope {
// because I am not an object scope, this is the same as currentObjectScope
currentObjectScope
}
method reusedNames { dictionary.empty }
method reuses (name) {
// Is name defined by a scope that this scope reuses?
false
}
method lookup (name) ifAbsent (aBlock) ifPresent (pBlock) {
// applies pBlock to the variable corresponding to name, if it is defined
// in this scope, or in one of the lexically surrounding scopes. If it
// is not defined, return the value of executing aBlock.
lookupLocallyOrReused (name) ifAbsent {
outerScope.lookup (name) ifAbsent (aBlock) ifPresent (pBlock)
} ifPresent (pBlock)
}
method error (innerDefn) shadows (outerDefn) is confidential {
def cName = canonicalName(innerDefn.declaredName)
def v = outerDefn.definingScope.variety
errormessages.namingError ("Sorry, you can't use '{cName}' as the name " ++
"of a {innerDefn.kind}, because '{cName}' " ++
"is declared as a {outerDefn.kind} on {outerDefn.lineRangeString} " ++
"in a surrounding {v} scope; use a different name")
atRange (innerDefn.definingParseNode)
}
method lookupLexically (name) {
// Return the variable corresponding to name, which may or may not be
// defined in this scope, or in one of the lexically surrounding scopes.
// If name is not defined, return the value of executing aBlock.
// Note that this method ignores reused names; it is intended for
// implementing Grace's shadowing check
lookupLexically (name) ifAbsent {
errormessages.namingError "{name} was not found in any lexical scope"
}
}
method redeclarationError (aMessage) variable (aVariable) {
errormessages.namingError (aMessage) atRange (aVariable.definingParseNode)
}
method add (aVariable:Variable) withName (aName) {
def priorDeclaration = names.at (aName) ifAbsent {
checkForShadowing (aVariable)
names.at (aName) put (aVariable)
return aVariable
}
def kind = aVariable.kind
def cName = canonicalName(aName)
def nm1 = if ((kind == "var") && cName.endsWith ":=(_)") then {
cName.replace ":=(_)" with ""
} else {
cName
}
def pCName = priorDeclaration.canonicalName
def nm2 = if ((priorDeclaration.kind == "var") && {
pCName.endsWith ":=(_)" }) then {
pCName.replace ":=(_)" with ""
} else {
pCName
}
errormessages.namingError ("Sorry, you can't declare '{nm1}' " ++
"as a {aVariable.description}, because '{nm2}' is already declared as " ++
"a {priorDeclaration.description} on {priorDeclaration.rangeLongString}, " ++
"which is in the same scope; use a different name")
atRange (aVariable.definingParseNode)
}
method checkForShadowing (aVar) is confidential {
// is it ok to declare aVar in this scope, or will it shadow an
// enclosing definition?
def priorVar = lookupLexically (aVar.name) ifAbsent { return }
def priorScope = priorVar.definingScope
if (self.allowsShadowing && priorScope.allowsShadowing) then { return }
error (aVar) shadows (priorVar)
}
method structuralError (aMessage) variable (aVariable) {
errormessages.namingError (aMessage) atRange (aVariable.range)
}
method allNamesAndValuesDo (aBlock) {
allNamesAndValuesDo (aBlock) filteringOut (Set.new)
}
method defines (name) {
// Is name defined in this scope, or in one of the lexically surrounding scopes?
definesLocallyOrReuses (name) || { outerScope.defines (name) }
}
method allNamesAndValuesDo (aBlock) filteringOut (closerDefinitions) {
names.keysAndValuesDo { name, defn →
if (closerDefinitions.contains (name).not) then {
aBlock.apply (name, defn)
closerDefinitions.add (name)
}
}
reusedNames.keysAndValuesDo { name, defn →
if (closerDefinitions.contains (name).not) then {
aBlock.apply (name, defn)
closerDefinitions.add (name)
}
}
outerScope.allNamesAndValuesDo (aBlock) filteringOut (closerDefinitions)
}
method redefine (aVariable) withName (aName) {
// overwrites an existing defintion
names.at (aName) put (aVariable)
aVariable
}
method isTrait { false }
method isFresh { false }
method isTheEmptyScope { false }
method isTheUniversalScope { false }
method isDialectScope { false }
method isModuleScope { false }
method isBuiltInScope { false }
method reportShadowingErrors {
names.keysAndValuesDo { name, defn →
outerScope.lookup (name) ifAbsent {
} ifPresent { outerDefn →
error (defn) shadows (outerDefn)
}
}
}
method localAndReusedNamesAndValuesDo (aBlock) {
localAndReusedNamesAndValuesDo (aBlock) filteringOut (set.empty)
}
method lookupReused (name) ifAbsent (aBlock) {
// this is the default behaviour for scopes that don't allow reuse.
// This method is overriden for object scopes
aBlock.apply
}
method lookupReused (name) ifAbsent (aBlock) ifPresent (pBlock) {
// this is the default behaviour for scopes that don't allow reuse.
// This method is overriden for object scopes
aBlock.apply
}
method lookupLexically (name) ifAbsent (aBlock) {
// Return the variable corresponding to name, which may or may not be
// defined in this scope, or in one of the lexically surrounding scopes.
// If name is not defined, return the value of executing aBlock.
// Note that this method ignores reused names; it is intended for
// implementing Grace's shadowing check
lookupLocally (name) ifAbsent {
outerScope.lookupLexically (name) ifAbsent {
aBlock.apply
}
}
}
method definesLocallyOrReuses (name) {
// Is name defined in this scope, or a scope that it reuses
// (ignoring surrounding scopes)
names.containsKey (name) || { reuses (name) }
}
method dialectError (aString) {
errormessages.CompilationError.raise (aString) with (emptyRange)
}
method localNamesAndValuesDo (aBlock) {
names.keysAndValuesDo (aBlock)
}
method removeReused (aName) ifAbsent (aBlock) {
ProgrammingError.raise "a {variety} scope has no reused names"
}
method lookupLocallyOrOutwards (name) ifAbsent (aBlock) {
// Return the variable corresponding to name, which may or may not be
// defined in this scope, or in one of the lexically-enclosing scopes.
// We do NOT look in the reused names of this scope.
// If name is not defined, return the value of executing aBlock.
lookupLocally (name) ifAbsent {
outerScope.lookup (name) ifAbsent {
aBlock.apply
}
}
}
method add (aVariable:Variable) {
add (aVariable) withName (aVariable.declaredName)
}
method localNames {
names
}
method lookupLocally (name) ifAbsent (aBlock) {
// Return the variable corresponding to name, which may or may not be
// defined in this scope. If name is not defined, return the value of
// executing aBlock.
names.at (name) ifAbsent {
aBlock.apply
}
}
method reusedNamesAndValuesDo (aBlock) {
self
}
method definesLocally (name) {
// Is name defined in this scope (ignoring surrounding scopes)
names.at (name) ifAbsent {
return false
}.isConcrete
}
method doesNotDefineLocally (name) {
definesLocally (name).not
}
method lookupLocallyOrReused (name) ifAbsent (aBlock) ifPresent (pBlock) {
// applies pBlock to the variable corresponding to name, if it is defined in this scope,
// or in one of the scopes that it reuses.
// If name is not defined, return the value of executing aBlock.
lookupLocally (name) ifAbsent {
lookupReused (name) ifAbsent {
aBlock.apply
} ifPresent (pBlock)
} ifPresent (pBlock)
}
method isObjectScope {
false
}
method variety is abstract
method clear { names.clear }
method withSurroundingScopesDo (b) {
// do b in this scope and all surounding scopes.
var cur := self
while {
b.apply(cur)
cur := cur.outerScope
cur.isTheEmptyScope.not
} do { }
}
method allowsShadowing { false }
} // end of graceScope
class resolvedVariable(aVariable) {
// My instances represent the defining occurence of a name, as seen from
// the perspective of an applied occurrence of that name.
// - definition: a subinstance of abstractVariable, representing the defining occurence.
// - objectsUp: the number of levels of object nesting above me where the
// defining occurence was found. 0 means that the definiing occurence
// is in the current object, 1 in the outer object, etc.
// - isReused: true if the definition is obtained from a use of a trait, or from
// an inherited object.
def definition is public = aVariable
var objectsUp is public
var isReused is public // true if this variable is accessible by virtue of
// a reuse (inherit or use) statement
method resolutionString {
// Answers a string, suitable for printing, that describes the location of this variable.
var s := if (isReused) then {
"reused {definition.kind} in the "
} else {
"lexically-enclosing {definition.kind} in the "
}
if (objectsUp == 0) then {
s := s ++ "current"
} else {
(1 .. objectsUp).do { _ →
s := s ++ "outer"
} separatedBy {
s := s ++ "."
}
}
s ++ " " ++ definition.definingScope.variety
}
method reuseString {
// Answers a string, suitable for printing, that describes my reuse.
if (isReused) then {
"reused"
} else {
"lexically-enclosing"
}
}
method definingScope {
// the scope in which this 'variable' is defined
definition.definingParseNode.scope
}
method asString {
"{reuseString} {definition.kind} declared on {definition.rangeLongString}"
}
method moduleName {
// the name of the module in which this name was defined
definition.moduleName
}
}
class variableResolver {
// this class has no state; it encapsulates the process of finding the definitions
// of a name in a scope. The only public method is definitionsOf(_)visibleIn(_)
method definitionsOf (aName) visibleIn (aScope) {
// answers a list of resolvedVariables describing the definitions of aName that
// are visible from aScope. The collection is empty if there is no definition.
// If aName is defined locally in aScope, then we allways answer a
// singleton collection, ignoring inherited definitions and those in
// outer scopes; this gives local definitions priority over inherited and
// enclosing definitions. If aName is defined by inheritance _and_
// directly in an outer scope, then the collection will have 2 elements.
// In no case will it have more than 2 elements.
definitionsOf (aName) visibleIn (aScope) atObject 0
}
method definitionsOf (aName) visibleIn (aScope) atObject (n) → Collection is confidential {
// local version of definitionsOf(_)visibleIn(_) with additional recursion parameter
lexicalOrLocalDefinitionOf (aName) in (aScope) atObject (n) ifPresent { defn →
list.with(defn)
} ifAbsent {
def currentObjectScope = aScope.currentObjectScope // may be aScope itself
def result = reusedDefinitionOf (aName) in (currentObjectScope) atObject (n) addTo (list.empty)
if (result.isEmpty) then {
def outerScope = currentObjectScope.outerScope
if (outerScope.isTheEmptyScope) then { return result }
definitionsOf (aName) visibleIn (outerScope) atObject (n+1) // simple recursion
} else {
// we have found a reused definition, so we look for a conflicting
// _direct_ definition.
outerDefinitionOf (aName) in (currentObjectScope) atObject (n) addTo (result)
}
}
}
method outerDefinitionOf (aName) in (aScope) atObject (o) addTo (aCollection) is confidential {
// Looks for the first direct definition of aName in the scopes
// _surrounding_ aScope, and adds it to aCollection, along with its
// depth from our start point. Ignores reused definitions, and stops
// when it reaches the dialect scope
var currentScope := aScope
var objectLevel := o
while {
if (currentScope.isObjectScope) then {
objectLevel := objectLevel + 1
}
currentScope := currentScope.outerScope
currentScope.isDialectScope.not
} do {
currentScope.lookupLocally (aName) ifAbsent {
} ifPresent { defn →
return aCollection.add (definition (defn) atObject (objectLevel))
}
}
// assert currentScope.isDialectScope
aCollection
}
method reusedDefinitionOf (aName) in (aScope) atObject (o) addTo (aCollection) is confidential {
if (aScope.areReusedNamesCompleted.not) then {
return aCollection
}
def defn = aScope.lookupReused (aName) ifAbsent {
return aCollection
}
aCollection.add (reusedDefinition (defn) atObject (o))
}
method lexicalOrLocalDefinitionOf (aName) in (aScope) atObject(o)
ifPresent (pBlock) ifAbsent (aBlock) is confidential {
// Look for a definition of aName in the nest of method and block scopes including and
// surrounding aScope, but not outside the current object. Don't look at reused names.
// If aName is not found, applies aBlock; if it is found, applies pBlock to a ResolvedVariable
// containing the definition.
var currentScope := aScope
while { true } do {
currentScope.lookupLocally (aName) ifAbsent {
} ifPresent { defn →
return pBlock.apply (definition (defn) atObject(o))