forked from sorbet/sorbet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnamer.cc
1964 lines (1741 loc) · 84.8 KB
/
namer.cc
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
#include "namer/namer.h"
#include "ast/ArgParsing.h"
#include "ast/Helpers.h"
#include "ast/ast.h"
#include "ast/desugar/Desugar.h"
#include "ast/treemap/treemap.h"
#include "class_flatten/class_flatten.h"
#include "common/Timer.h"
#include "common/concurrency/ConcurrentQueue.h"
#include "common/concurrency/WorkerPool.h"
#include "common/sort.h"
#include "core/Context.h"
#include "core/Names.h"
#include "core/Symbols.h"
#include "core/core.h"
#include "core/errors/namer.h"
#include "core/lsp/TypecheckEpochManager.h"
using namespace std;
namespace sorbet::namer {
namespace {
class FoundDefinitions;
struct FoundClassRef;
struct FoundClass;
struct FoundStaticField;
struct FoundTypeMember;
struct FoundMethod;
enum class DefinitionKind : u1 {
Empty = 0,
Class = 1,
ClassRef = 2,
Method = 3,
StaticField = 4,
TypeMember = 5,
Symbol = 6,
};
class FoundDefinitionRef final {
DefinitionKind _kind;
u4 _id;
public:
FoundDefinitionRef(DefinitionKind kind, u4 idx) : _kind(kind), _id(idx) {}
FoundDefinitionRef() : FoundDefinitionRef(DefinitionKind::Empty, 0) {}
FoundDefinitionRef(const FoundDefinitionRef &nm) = default;
FoundDefinitionRef(FoundDefinitionRef &&nm) = default;
FoundDefinitionRef &operator=(const FoundDefinitionRef &rhs) = default;
static FoundDefinitionRef root() {
return FoundDefinitionRef(DefinitionKind::Symbol, core::SymbolRef(core::Symbols::root()).rawId());
}
DefinitionKind kind() const {
return _kind;
}
bool exists() const {
return _id > 0;
}
u4 idx() const {
return _id;
}
FoundClassRef &klassRef(FoundDefinitions &foundDefs);
const FoundClassRef &klassRef(const FoundDefinitions &foundDefs) const;
FoundClass &klass(FoundDefinitions &foundDefs);
const FoundClass &klass(const FoundDefinitions &foundDefs) const;
FoundMethod &method(FoundDefinitions &foundDefs);
const FoundMethod &method(const FoundDefinitions &foundDefs) const;
FoundStaticField &staticField(FoundDefinitions &foundDefs);
const FoundStaticField &staticField(const FoundDefinitions &foundDefs) const;
FoundTypeMember &typeMember(FoundDefinitions &foundDefs);
const FoundTypeMember &typeMember(const FoundDefinitions &foundDefs) const;
core::SymbolRef symbol() const;
};
struct FoundClassRef final {
core::NameRef name;
core::LocOffsets loc;
// If !owner.exists(), owner is determined by reference site.
FoundDefinitionRef owner;
};
struct FoundClass final {
FoundDefinitionRef owner;
FoundDefinitionRef klass;
core::LocOffsets loc;
core::LocOffsets declLoc;
ast::ClassDef::Kind classKind;
};
struct FoundStaticField final {
FoundDefinitionRef owner;
FoundDefinitionRef klass;
core::NameRef name;
core::LocOffsets asgnLoc;
core::LocOffsets lhsLoc;
bool isTypeAlias = false;
};
struct FoundTypeMember final {
FoundDefinitionRef owner;
core::NameRef name;
core::LocOffsets asgnLoc;
core::LocOffsets nameLoc;
core::LocOffsets litLoc;
core::NameRef varianceName;
bool isFixed = false;
bool isTypeTemplete = false;
};
struct FoundMethod final {
FoundDefinitionRef owner;
core::NameRef name;
core::LocOffsets loc;
core::LocOffsets declLoc;
ast::MethodDef::Flags flags;
vector<ast::ParsedArg> parsedArgs;
vector<u4> argsHash;
};
struct Modifier {
enum class Kind : u1 {
Class = 0,
Method = 1,
ClassOrStaticField = 2,
};
Kind kind;
FoundDefinitionRef owner;
core::LocOffsets loc;
// The name of the modification.
core::NameRef name;
// For methods: The name of the method being modified.
// For constants: The name of the constant being modified.
core::NameRef target;
Modifier withTarget(core::NameRef target) {
return Modifier{this->kind, this->owner, this->loc, this->name, target};
}
};
class FoundDefinitions final {
// Contains references to items in _klasses, _methods, _staticFields, and _typeMembers.
// Used to determine the order in which symbols are defined in SymbolDefiner.
vector<FoundDefinitionRef> _definitions;
// Contains references to classes in general. Separate from `FoundClass` because we sometimes need to define class
// Symbols for classes that are referenced from but not present in the given file.
vector<FoundClassRef> _klassRefs;
// Contains all classes defined in the file.
vector<FoundClass> _klasses;
// Contains all methods defined in the file.
vector<FoundMethod> _methods;
// Contains all static fields defined in the file.
vector<FoundStaticField> _staticFields;
// Contains all type members defined in the file.
vector<FoundTypeMember> _typeMembers;
// Contains all method and class modifiers (e.g. private/public/protected).
vector<Modifier> _modifiers;
FoundDefinitionRef addDefinition(FoundDefinitionRef ref) {
_definitions.emplace_back(ref);
return ref;
}
public:
FoundDefinitions() = default;
FoundDefinitions(FoundDefinitions &&names) = default;
FoundDefinitions(const FoundDefinitions &names) = delete;
~FoundDefinitions() = default;
FoundDefinitionRef addClass(FoundClass &&klass) {
const u4 idx = _klasses.size();
_klasses.emplace_back(move(klass));
return addDefinition(FoundDefinitionRef(DefinitionKind::Class, idx));
}
FoundDefinitionRef addClassRef(FoundClassRef &&klassRef) {
const u4 idx = _klassRefs.size();
_klassRefs.emplace_back(move(klassRef));
return FoundDefinitionRef(DefinitionKind::ClassRef, idx);
}
FoundDefinitionRef addMethod(FoundMethod &&method) {
const u4 idx = _methods.size();
_methods.emplace_back(move(method));
return addDefinition(FoundDefinitionRef(DefinitionKind::Method, idx));
}
FoundDefinitionRef addStaticField(FoundStaticField &&staticField) {
const u4 idx = _staticFields.size();
_staticFields.emplace_back(move(staticField));
return addDefinition(FoundDefinitionRef(DefinitionKind::StaticField, idx));
}
FoundDefinitionRef addTypeMember(FoundTypeMember &&typeMember) {
const u4 idx = _typeMembers.size();
_typeMembers.emplace_back(move(typeMember));
return addDefinition(FoundDefinitionRef(DefinitionKind::TypeMember, idx));
}
FoundDefinitionRef addSymbol(core::SymbolRef symbol) {
return FoundDefinitionRef(DefinitionKind::Symbol, symbol.rawId());
}
void addModifier(Modifier &&mod) {
_modifiers.emplace_back(move(mod));
}
const vector<FoundDefinitionRef> &definitions() const {
return _definitions;
}
const vector<FoundClass> &klasses() const {
return _klasses;
}
const vector<FoundMethod> &methods() const {
return _methods;
}
const vector<Modifier> &modifiers() const {
return _modifiers;
}
friend FoundDefinitionRef;
};
FoundClassRef &FoundDefinitionRef::klassRef(FoundDefinitions &foundDefs) {
ENFORCE(kind() == DefinitionKind::ClassRef);
ENFORCE(foundDefs._klassRefs.size() > idx());
return foundDefs._klassRefs[idx()];
}
const FoundClassRef &FoundDefinitionRef::klassRef(const FoundDefinitions &foundDefs) const {
ENFORCE(kind() == DefinitionKind::ClassRef);
ENFORCE(foundDefs._klassRefs.size() > idx());
return foundDefs._klassRefs[idx()];
}
FoundClass &FoundDefinitionRef::klass(FoundDefinitions &foundDefs) {
ENFORCE(kind() == DefinitionKind::Class);
ENFORCE(foundDefs._klasses.size() > idx());
return foundDefs._klasses[idx()];
}
const FoundClass &FoundDefinitionRef::klass(const FoundDefinitions &foundDefs) const {
ENFORCE(kind() == DefinitionKind::Class);
ENFORCE(foundDefs._klasses.size() > idx());
return foundDefs._klasses[idx()];
}
FoundMethod &FoundDefinitionRef::method(FoundDefinitions &foundDefs) {
ENFORCE(kind() == DefinitionKind::Method);
ENFORCE(foundDefs._methods.size() > idx());
return foundDefs._methods[idx()];
}
const FoundMethod &FoundDefinitionRef::method(const FoundDefinitions &foundDefs) const {
ENFORCE(kind() == DefinitionKind::Method);
ENFORCE(foundDefs._methods.size() > idx());
return foundDefs._methods[idx()];
}
FoundStaticField &FoundDefinitionRef::staticField(FoundDefinitions &foundDefs) {
ENFORCE(kind() == DefinitionKind::StaticField);
ENFORCE(foundDefs._staticFields.size() > idx());
return foundDefs._staticFields[idx()];
}
const FoundStaticField &FoundDefinitionRef::staticField(const FoundDefinitions &foundDefs) const {
ENFORCE(kind() == DefinitionKind::StaticField);
ENFORCE(foundDefs._staticFields.size() > idx());
return foundDefs._staticFields[idx()];
}
FoundTypeMember &FoundDefinitionRef::typeMember(FoundDefinitions &foundDefs) {
ENFORCE(kind() == DefinitionKind::TypeMember);
ENFORCE(foundDefs._typeMembers.size() > idx());
return foundDefs._typeMembers[idx()];
}
const FoundTypeMember &FoundDefinitionRef::typeMember(const FoundDefinitions &foundDefs) const {
ENFORCE(kind() == DefinitionKind::TypeMember);
ENFORCE(foundDefs._typeMembers.size() > idx());
return foundDefs._typeMembers[idx()];
}
core::SymbolRef FoundDefinitionRef::symbol() const {
ENFORCE(kind() == DefinitionKind::Symbol);
return core::SymbolRef::fromRaw(_id);
}
struct SymbolFinderResult {
ast::ParsedFile tree;
unique_ptr<FoundDefinitions> names;
};
core::ClassOrModuleRef methodOwner(core::Context ctx, const ast::MethodDef::Flags &flags) {
auto owner = ctx.owner.data(ctx)->enclosingClass(ctx);
if (owner == core::Symbols::root()) {
// Root methods end up going on object
owner = core::Symbols::Object();
}
if (flags.isSelfMethod) {
owner = owner.data(ctx)->lookupSingletonClass(ctx);
}
ENFORCE(owner.exists());
return owner;
}
// Returns the SymbolRef corresponding to the class `self.class`, unless the
// context is a class, in which case return it.
core::ClassOrModuleRef contextClass(const core::GlobalState &gs, core::SymbolRef ofWhat) {
core::SymbolRef owner = ofWhat;
while (true) {
ENFORCE(owner.exists(), "non-existing owner in contextClass");
const auto &data = owner.data(gs);
if (data->isClassOrModule()) {
return owner.asClassOrModuleRef();
}
if (data->name == core::Names::staticInit()) {
owner = data->owner.data(gs)->attachedClass(gs);
} else {
owner = data->owner;
}
}
}
/**
* Used with TreeMap to locate all of the class, method, static field, and type member symbols defined in the tree.
* Does not mutate GlobalState, which allows us to parallelize this process.
* Does not report any errors, which lets us cache its output.
* Produces a vector of symbols to insert, and a vector of modifiers to those symbols.
*/
class SymbolFinder {
unique_ptr<FoundDefinitions> foundDefs = make_unique<FoundDefinitions>();
// The tree doesn't have symbols yet, so `ctx.owner`, which is a SymbolRef, is meaningless.
// Instead, we track the owner manually via FoundDefinitionRefs.
vector<FoundDefinitionRef> ownerStack;
// `private` with no arguments toggles the visibility of all methods below in the class def.
// This tracks those as they appear.
vector<optional<Modifier>> methodVisiStack = {nullopt};
void findClassModifiers(core::Context ctx, FoundDefinitionRef klass, ast::ExpressionPtr &line) {
auto *send = ast::cast_tree<ast::Send>(line);
if (send == nullptr) {
return;
}
switch (send->fun.rawId()) {
case core::Names::declareFinal().rawId():
case core::Names::declareSealed().rawId():
case core::Names::declareInterface().rawId():
case core::Names::declareAbstract().rawId(): {
Modifier mod;
mod.kind = Modifier::Kind::Class;
mod.owner = klass;
mod.loc = send->loc;
mod.name = send->fun;
foundDefs->addModifier(move(mod));
break;
}
default:
break;
}
}
FoundDefinitionRef getOwner() {
if (ownerStack.empty()) {
return FoundDefinitionRef::root();
}
return ownerStack.back();
}
// Returns index to foundDefs containing the given name. Recursively inserts class refs for its owners.
FoundDefinitionRef squashNames(core::Context ctx, const ast::ExpressionPtr &node) {
if (auto *id = ast::cast_tree<ast::ConstantLit>(node)) {
// Already defined. Insert a foundname so we can reference it.
auto sym = id->symbol.data(ctx)->dealias(ctx);
ENFORCE(sym.exists());
return foundDefs->addSymbol(sym);
} else if (auto constLit = ast::cast_tree<ast::UnresolvedConstantLit>(node)) {
FoundClassRef found;
found.owner = squashNames(ctx, constLit->scope);
found.name = constLit->cnst;
found.loc = constLit->loc;
return foundDefs->addClassRef(move(found));
} else {
// `class <<self`, `::Foo`, `self::Foo`
// Return non-existent nameref as placeholder.
return FoundDefinitionRef();
}
}
public:
unique_ptr<FoundDefinitions> getAndClearFoundDefinitions() {
ownerStack.clear();
auto rv = move(foundDefs);
foundDefs = make_unique<FoundDefinitions>();
return rv;
}
ast::ExpressionPtr preTransformClassDef(core::Context ctx, ast::ExpressionPtr tree) {
auto &klass = ast::cast_tree_nonnull<ast::ClassDef>(tree);
FoundClass found;
found.owner = getOwner();
found.classKind = klass.kind;
found.loc = klass.loc;
found.declLoc = klass.declLoc;
auto *ident = ast::cast_tree<ast::UnresolvedIdent>(klass.name);
if ((ident != nullptr) && ident->name == core::Names::singleton()) {
FoundClassRef foundRef;
foundRef.name = ident->name;
foundRef.loc = ident->loc;
found.klass = foundDefs->addClassRef(move(foundRef));
} else {
if (klass.symbol == core::Symbols::todo()) {
found.klass = squashNames(ctx, klass.name);
} else {
// Desugar populates a top-level root() ClassDef.
// Nothing else should have been typeAlias by now.
ENFORCE(klass.symbol == core::Symbols::root());
found.klass = foundDefs->addSymbol(klass.symbol);
}
}
ownerStack.emplace_back(foundDefs->addClass(move(found)));
methodVisiStack.emplace_back(nullopt);
return tree;
}
ast::ExpressionPtr postTransformClassDef(core::Context ctx, ast::ExpressionPtr tree) {
auto &klass = ast::cast_tree_nonnull<ast::ClassDef>(tree);
FoundDefinitionRef klassName = ownerStack.back();
ownerStack.pop_back();
methodVisiStack.pop_back();
for (auto &exp : klass.rhs) {
findClassModifiers(ctx, klassName, exp);
}
return tree;
}
ast::ExpressionPtr preTransformBlock(core::Context ctx, ast::ExpressionPtr block) {
methodVisiStack.emplace_back(nullopt);
return block;
}
ast::ExpressionPtr postTransformBlock(core::Context ctx, ast::ExpressionPtr block) {
methodVisiStack.pop_back();
return block;
}
ast::ExpressionPtr preTransformMethodDef(core::Context ctx, ast::ExpressionPtr tree) {
auto &method = ast::cast_tree_nonnull<ast::MethodDef>(tree);
FoundMethod foundMethod;
foundMethod.owner = getOwner();
foundMethod.name = method.name;
foundMethod.loc = method.loc;
foundMethod.declLoc = method.declLoc;
foundMethod.flags = method.flags;
foundMethod.parsedArgs = ast::ArgParsing::parseArgs(method.args);
foundMethod.argsHash = ast::ArgParsing::hashArgs(ctx, foundMethod.parsedArgs);
ownerStack.emplace_back(foundDefs->addMethod(move(foundMethod)));
// After flatten, method defs have been hoisted and reordered, so instead we look for the
// keep_def / keep_self_def calls, which will still be ordered correctly relative to
// visibility modifiers.
return tree;
}
ast::ExpressionPtr postTransformMethodDef(core::Context ctx, ast::ExpressionPtr tree) {
ownerStack.pop_back();
return tree;
}
ast::ExpressionPtr postTransformSend(core::Context ctx, ast::ExpressionPtr tree) {
auto &original = ast::cast_tree_nonnull<ast::Send>(tree);
switch (original.fun.rawId()) {
case core::Names::privateClassMethod().rawId():
for (const auto &arg : original.args) {
addMethodModifier(ctx, original.fun, arg);
}
break;
case core::Names::private_().rawId():
case core::Names::protected_().rawId():
case core::Names::public_().rawId():
if (original.args.empty()) {
ENFORCE(!methodVisiStack.empty());
methodVisiStack.back() = optional<Modifier>{Modifier{
Modifier::Kind::Method,
getOwner(),
original.loc,
original.fun,
core::NameRef::noName(),
}};
} else {
for (const auto &arg : original.args) {
addMethodModifier(ctx, original.fun, arg);
}
}
break;
case core::Names::privateConstant().rawId():
for (const auto &arg : original.args) {
addConstantModifier(ctx, original.fun, arg);
}
break;
case core::Names::keepDef().rawId():
// ^ visibility toggle doesn't look at `self.*` methods, only instance methods
// (need to use `class << self` to use nullary private with singleton class methods)
if (original.args.size() != 3) {
break;
}
ENFORCE(!methodVisiStack.empty());
if (!methodVisiStack.back().has_value()) {
break;
}
auto recv = ast::cast_tree<ast::ConstantLit>(original.recv);
if (recv == nullptr || recv->symbol != core::Symbols::Sorbet_Private_Static()) {
break;
}
auto methodName = unwrapLiteralToMethodName(ctx, original.args[1]);
foundDefs->addModifier(methodVisiStack.back()->withTarget(methodName));
break;
}
return tree;
}
void addMethodModifier(core::Context ctx, core::NameRef modifierName, const ast::ExpressionPtr &arg) {
auto target = unwrapLiteralToMethodName(ctx, arg);
if (target.exists()) {
foundDefs->addModifier(Modifier{
Modifier::Kind::Method,
getOwner(),
arg.loc(),
/*name*/ modifierName,
target,
});
}
}
void addConstantModifier(core::Context ctx, core::NameRef modifierName, const ast::ExpressionPtr &arg) {
auto target = core::NameRef::noName();
if (auto sym = ast::cast_tree<ast::Literal>(arg)) {
if (sym->isSymbol(ctx)) {
target = sym->asSymbol(ctx);
} else if (sym->isString(ctx)) {
target = sym->asString(ctx);
}
}
if (target.exists()) {
foundDefs->addModifier(Modifier{
Modifier::Kind::ClassOrStaticField,
getOwner(),
arg.loc(),
/*name*/ modifierName,
target,
});
}
}
core::NameRef unwrapLiteralToMethodName(core::Context ctx, const ast::ExpressionPtr &expr) {
if (auto sym = ast::cast_tree<ast::Literal>(expr)) {
// this handles the `private :foo` case
if (!sym->isSymbol(ctx)) {
return core::NameRef::noName();
}
return sym->asSymbol(ctx);
} else if (auto send = ast::cast_tree<ast::Send>(expr)) {
if (send->fun != core::Names::keepDef() && send->fun != core::Names::keepSelfDef()) {
return core::NameRef::noName();
}
auto recv = ast::cast_tree<ast::ConstantLit>(send->recv);
if (recv == nullptr) {
return core::NameRef::noName();
}
if (recv->symbol != core::Symbols::Sorbet_Private_Static()) {
return core::NameRef::noName();
}
if (send->args.size() != 3) {
return core::NameRef::noName();
}
return unwrapLiteralToMethodName(ctx, send->args[1]);
} else {
ENFORCE(!ast::isa_tree<ast::MethodDef>(expr), "methods inside sends should be gone");
return core::NameRef::noName();
}
}
FoundDefinitionRef fillAssign(core::Context ctx, const ast::Assign &asgn) {
auto &lhs = ast::cast_tree_nonnull<ast::UnresolvedConstantLit>(asgn.lhs);
FoundStaticField found;
found.owner = getOwner();
found.klass = squashNames(ctx, lhs.scope);
found.name = lhs.cnst;
found.asgnLoc = asgn.loc;
found.lhsLoc = lhs.loc;
return foundDefs->addStaticField(move(found));
}
FoundDefinitionRef handleTypeMemberDefinition(core::Context ctx, const ast::Send *send, const ast::Assign &asgn,
const ast::UnresolvedConstantLit *typeName) {
ENFORCE(ast::cast_tree<ast::UnresolvedConstantLit>(asgn.lhs) == typeName &&
ast::cast_tree<ast::Send>(asgn.rhs) ==
send); // this method assumes that `asgn` owns `send` and `typeName`
FoundTypeMember found;
found.owner = getOwner();
found.asgnLoc = asgn.loc;
found.nameLoc = typeName->loc;
found.name = typeName->cnst;
// Store name rather than core::Variance type so that we can defer reporting an error until later.
found.varianceName = core::NameRef();
found.isTypeTemplete = send->fun == core::Names::typeTemplate();
if (send->numPosArgs > 1) {
// Too many arguments. Define a static field that we'll use for this type åmember later.
FoundStaticField staticField;
staticField.owner = found.owner;
staticField.name = found.name;
staticField.asgnLoc = found.asgnLoc;
staticField.lhsLoc = asgn.lhs.loc();
staticField.isTypeAlias = true;
return foundDefs->addStaticField(move(staticField));
}
if (!send->args.empty()) {
// If there are positional arguments, there might be a variance annotation
if (send->numPosArgs > 0) {
auto *lit = ast::cast_tree<ast::Literal>(send->args[0]);
if (lit != nullptr && lit->isSymbol(ctx)) {
found.varianceName = lit->asSymbol(ctx);
found.litLoc = lit->loc;
}
}
auto end = send->args.size();
if (send->hasKwSplat()) {
end -= 1;
}
// Walk over the keyword args to find bounds annotations
for (auto i = send->numPosArgs; i < end; i += 2) {
auto *key = ast::cast_tree<ast::Literal>(send->args[i]);
if (key != nullptr && key->isSymbol(ctx)) {
switch (key->asSymbol(ctx).rawId()) {
case core::Names::fixed().rawId():
found.isFixed = true;
break;
}
}
}
}
return foundDefs->addTypeMember(move(found));
}
FoundDefinitionRef handleAssignment(core::Context ctx, const ast::Assign &asgn) {
auto &send = ast::cast_tree_nonnull<ast::Send>(asgn.rhs);
auto foundRef = fillAssign(ctx, asgn);
ENFORCE(foundRef.kind() == DefinitionKind::StaticField);
auto &staticField = foundRef.staticField(*foundDefs);
staticField.isTypeAlias = send.fun == core::Names::typeAlias();
return foundRef;
}
ast::ExpressionPtr postTransformAssign(core::Context ctx, ast::ExpressionPtr tree) {
auto &asgn = ast::cast_tree_nonnull<ast::Assign>(tree);
auto *lhs = ast::cast_tree<ast::UnresolvedConstantLit>(asgn.lhs);
if (lhs == nullptr) {
return tree;
}
auto *send = ast::cast_tree<ast::Send>(asgn.rhs);
if (send == nullptr) {
fillAssign(ctx, asgn);
} else if (!send->recv.isSelfReference()) {
handleAssignment(ctx, asgn);
} else {
switch (send->fun.rawId()) {
case core::Names::typeTemplate().rawId():
handleTypeMemberDefinition(ctx, send, asgn, lhs);
break;
case core::Names::typeMember().rawId():
handleTypeMemberDefinition(ctx, send, asgn, lhs);
break;
default:
fillAssign(ctx, asgn);
break;
}
}
return tree;
}
};
/**
* Defines symbols for all of the definitions found via SymbolFinder. Single threaded.
*/
class SymbolDefiner {
unique_ptr<const FoundDefinitions> foundDefs;
vector<core::ClassOrModuleRef> definedClasses;
vector<core::MethodRef> definedMethods;
// Returns a symbol to the referenced name. Name must be a class or module.
// Prerequisite: Owner is a class or module.
core::SymbolRef squashNames(core::MutableContext ctx, FoundDefinitionRef ref, core::ClassOrModuleRef owner) {
switch (ref.kind()) {
case DefinitionKind::Empty:
return owner;
case DefinitionKind::Symbol: {
return ref.symbol();
}
case DefinitionKind::ClassRef: {
auto &klassRef = ref.klassRef(*foundDefs);
auto newOwner = squashNames(ctx, klassRef.owner, owner);
return getOrDefineSymbol(ctx.withOwner(newOwner), klassRef.name, klassRef.loc);
}
default:
Exception::raise("Invalid name reference");
}
}
// Get the symbol for an already-defined owner. Limited to refs that can own things (classes and methods).
core::SymbolRef getOwnerSymbol(FoundDefinitionRef ref) {
switch (ref.kind()) {
case DefinitionKind::Symbol:
return ref.symbol();
case DefinitionKind::Class:
ENFORCE(ref.idx() < definedClasses.size());
return definedClasses[ref.idx()];
case DefinitionKind::Method:
ENFORCE(ref.idx() < definedMethods.size());
return definedMethods[ref.idx()];
default:
Exception::raise("Invalid owner reference");
}
}
// Allow stub symbols created to hold intrinsics to be filled in
// with real types from code
bool isIntrinsic(const core::SymbolData &data) {
return data->intrinsic != nullptr && !data->hasSig();
}
void emitRedefinedConstantError(core::MutableContext ctx, core::Loc errorLoc, std::string constantName,
core::Loc prevDefinitionLoc) {
if (auto e = ctx.state.beginError(errorLoc, core::errors::Namer::ModuleKindRedefinition)) {
e.setHeader("Redefining constant `{}`", constantName);
e.addErrorLine(prevDefinitionLoc, "Previous definition");
}
}
void emitRedefinedConstantError(core::MutableContext ctx, core::Loc errorLoc, core::SymbolRef symbol,
core::SymbolRef renamedSymbol) {
emitRedefinedConstantError(ctx, errorLoc, symbol.data(ctx)->show(ctx), renamedSymbol.data(ctx)->loc());
}
core::ClassOrModuleRef ensureIsClass(core::MutableContext ctx, core::SymbolRef scope, core::NameRef name,
core::LocOffsets loc) {
// Common case: Everything is fine, user is trying to define a symbol on a class or module.
if (scope.isClassOrModule()) {
// Check if original symbol was mangled away. If so, complain.
auto renamedSymbol = ctx.state.findRenamedSymbol(scope.data(ctx)->owner, scope);
if (renamedSymbol.exists()) {
if (auto e = ctx.state.beginError(core::Loc(ctx.file, loc), core::errors::Namer::InvalidClassOwner)) {
auto constLitName = name.show(ctx);
auto scopeName = scope.data(ctx)->show(ctx);
e.setHeader("Can't nest `{}` under `{}` because `{}` is not a class or module", constLitName,
scopeName, scopeName);
e.addErrorLine(renamedSymbol.data(ctx)->loc(), "`{}` defined here", scopeName);
}
}
return scope.asClassOrModuleRef();
}
// Check if class was already mangled.
auto klassSymbol =
ctx.state.lookupClassSymbol(scope.data(ctx)->owner.asClassOrModuleRef(), scope.data(ctx)->name);
if (klassSymbol.exists()) {
return klassSymbol;
}
if (auto e = ctx.state.beginError(core::Loc(ctx.file, loc), core::errors::Namer::InvalidClassOwner)) {
auto constLitName = name.show(ctx);
auto newOwnerName = scope.data(ctx)->show(ctx);
e.setHeader("Can't nest `{}` under `{}` because `{}` is not a class or module", constLitName, newOwnerName,
newOwnerName);
e.addErrorLine(scope.data(ctx)->loc(), "`{}` defined here", newOwnerName);
}
// Mangle this one out of the way, and re-enter a symbol with this name as a class.
auto scopeName = scope.data(ctx)->name;
ctx.state.mangleRenameSymbol(scope, scopeName);
auto scopeKlass = ctx.state.enterClassSymbol(core::Loc(ctx.file, loc),
scope.data(ctx)->owner.asClassOrModuleRef(), scopeName);
scopeKlass.data(ctx)->singletonClass(ctx); // force singleton class into existance
return scopeKlass;
}
// Gets the symbol with the given name, or defines it as a class if it does not exist.
core::SymbolRef getOrDefineSymbol(core::MutableContext ctx, core::NameRef name, core::LocOffsets loc) {
if (name == core::Names::singleton()) {
return ctx.owner.data(ctx)->enclosingClass(ctx).data(ctx)->singletonClass(ctx);
}
auto scope = ensureIsClass(ctx, ctx.owner, name, loc);
core::SymbolRef existing = scope.data(ctx)->findMember(ctx, name);
if (!existing.exists()) {
existing = ctx.state.enterClassSymbol(core::Loc(ctx.file, loc), scope, name);
existing.data(ctx)->singletonClass(ctx); // force singleton class into existance
}
return existing;
}
void defineArg(core::MutableContext ctx, core::SymbolData &methodData, int pos, const ast::ParsedArg &parsedArg) {
if (pos < methodData->arguments().size()) {
// TODO: check that flags match;
methodData->arguments()[pos].loc = core::Loc(ctx.file, parsedArg.loc);
return;
}
core::NameRef name;
if (parsedArg.flags.isKeyword) {
name = parsedArg.local._name;
} else if (parsedArg.flags.isBlock) {
name = core::Names::blkArg();
} else {
name = ctx.state.freshNameUnique(core::UniqueNameKind::PositionalArg, core::Names::arg(), pos + 1);
}
// we know right now that pos >= arguments().size() because otherwise we would have hit the early return at the
// beginning of this method
auto &argInfo =
ctx.state.enterMethodArgumentSymbol(core::Loc(ctx.file, parsedArg.loc), ctx.owner.asMethodRef(), name);
// if enterMethodArgumentSymbol did not emplace a new argument into the list, then it means it's reusing an
// existing one, which means we've seen a repeated kwarg (as it treats identically named kwargs as
// identical). We know that we need to match the arity of the function as written, so if we don't have as many
// arguments as we expect, clone the one we got back from enterMethodArgumentSymbol in the position we expect
if (methodData->arguments().size() == pos) {
auto argCopy = argInfo.deepCopy();
argCopy.name = ctx.state.freshNameUnique(core::UniqueNameKind::MangledKeywordArg, argInfo.name, pos + 1);
methodData->arguments().emplace_back(move(argCopy));
return;
}
// at this point, we should have at least pos + 1 arguments, and arguments[pos] should be the thing we got back
// from enterMethodArgumentSymbol
ENFORCE(methodData->arguments().size() >= pos + 1);
argInfo.flags = parsedArg.flags;
}
void defineArgs(core::MutableContext ctx, const vector<ast::ParsedArg> &parsedArgs) {
auto methodData = ctx.owner.data(ctx);
bool inShadows = false;
bool intrinsic = isIntrinsic(methodData);
bool swapArgs = intrinsic && (methodData->arguments().size() == 1);
core::ArgInfo swappedArg;
if (swapArgs) {
// When we're filling in an intrinsic method, we want to overwrite the block arg that used
// to exist with the block arg that we got from desugaring the method def in the RBI files.
ENFORCE(methodData->arguments()[0].flags.isBlock);
swappedArg = move(methodData->arguments()[0]);
methodData->arguments().clear();
}
int i = -1;
for (auto &arg : parsedArgs) {
i++;
if (arg.flags.isShadow) {
inShadows = true;
} else {
ENFORCE(!inShadows, "shadow argument followed by non-shadow argument!");
if (swapArgs && arg.flags.isBlock) {
// see commnent on if (swapArgs) above
methodData->arguments().emplace_back(move(swappedArg));
}
defineArg(ctx, methodData, i, arg);
ENFORCE(i < methodData->arguments().size());
}
}
}
bool paramsMatch(core::MutableContext ctx, core::SymbolRef method, const vector<ast::ParsedArg> &parsedArgs) {
auto sym = method.data(ctx)->dealias(ctx);
if (sym.data(ctx)->arguments().size() != parsedArgs.size()) {
return false;
}
for (int i = 0; i < parsedArgs.size(); i++) {
auto &methodArg = parsedArgs[i];
auto &symArg = sym.data(ctx)->arguments()[i];
if (symArg.flags.isKeyword != methodArg.flags.isKeyword ||
symArg.flags.isBlock != methodArg.flags.isBlock ||
symArg.flags.isRepeated != methodArg.flags.isRepeated ||
(symArg.flags.isKeyword && symArg.name != methodArg.local._name)) {
return false;
}
}
return true;
}
void paramMismatchErrors(core::MutableContext ctx, core::Loc loc, const vector<ast::ParsedArg> &parsedArgs) {
auto sym = ctx.owner.data(ctx)->dealias(ctx);
if (!sym.data(ctx)->isMethod()) {
return;
}
if (sym.data(ctx)->arguments().size() != parsedArgs.size()) {
if (auto e = ctx.state.beginError(loc, core::errors::Namer::RedefinitionOfMethod)) {
if (sym != ctx.owner) {
// Subtracting 1 because of the block arg we added everywhere.
// Eventually we should be more principled about how we report this.
e.setHeader(
"Method alias `{}` redefined without matching argument count. Expected: `{}`, got: `{}`",
ctx.owner.data(ctx)->show(ctx), sym.data(ctx)->arguments().size() - 1, parsedArgs.size() - 1);
e.addErrorLine(ctx.owner.data(ctx)->loc(), "Previous alias definition");
e.addErrorLine(sym.data(ctx)->loc(), "Dealiased definition");
} else {
// Subtracting 1 because of the block arg we added everywhere.
// Eventually we should be more principled about how we report this.
e.setHeader("Method `{}` redefined without matching argument count. Expected: `{}`, got: `{}`",
sym.show(ctx), sym.data(ctx)->arguments().size() - 1, parsedArgs.size() - 1);
e.addErrorLine(sym.data(ctx)->loc(), "Previous definition");
}
}
return;
}
for (int i = 0; i < parsedArgs.size(); i++) {
auto &methodArg = parsedArgs[i];
auto &symArg = sym.data(ctx)->arguments()[i];
if (symArg.flags.isKeyword != methodArg.flags.isKeyword) {
if (auto e = ctx.state.beginError(loc, core::errors::Namer::RedefinitionOfMethod)) {
e.setHeader("Method `{}` redefined with argument `{}` as a {} argument", sym.show(ctx),
methodArg.local.toString(ctx), methodArg.flags.isKeyword ? "keyword" : "non-keyword");
e.addErrorLine(
sym.data(ctx)->loc(),
"The corresponding argument `{}` in the previous definition was {}a keyword argument",
symArg.show(ctx), symArg.flags.isKeyword ? "" : "not ");
}
return;
}
// because of how we synthesize block args, this condition should always be true. In particular: the
// last thing in our list of arguments will always be a block arg, either an explicit one or an implicit
// one, and the only situation in which a block arg will ever be seen is as the last argument in the
// list. Consequently, the only situation in which a block arg will be matched up with a non-block arg
// is when the lists are different lengths: but in that case, we'll have bailed out of this function
// already with the "without matching argument count" error above. So, as long as we have maintained the
// intended invariants around methods and arguments, we do not need to ever issue an error about
// non-matching isBlock-ness.
ENFORCE(symArg.flags.isBlock == methodArg.flags.isBlock);
if (symArg.flags.isRepeated != methodArg.flags.isRepeated) {
if (auto e = ctx.state.beginError(loc, core::errors::Namer::RedefinitionOfMethod)) {
e.setHeader("Method `{}` redefined with argument `{}` as a {} argument", sym.show(ctx),
methodArg.local.toString(ctx), methodArg.flags.isRepeated ? "splat" : "non-splat");
e.addErrorLine(sym.data(ctx)->loc(),
"The corresponding argument `{}` in the previous definition was {}a splat argument",
symArg.show(ctx), symArg.flags.isRepeated ? "" : "not ");
}
return;
}
if (symArg.flags.isKeyword && symArg.name != methodArg.local._name) {
if (auto e = ctx.state.beginError(loc, core::errors::Namer::RedefinitionOfMethod)) {
e.setHeader(
"Method `{}` redefined with mismatched keyword argument name. Expected: `{}`, got: `{}`",
sym.show(ctx), symArg.name.show(ctx), methodArg.local._name.show(ctx));
e.addErrorLine(sym.data(ctx)->loc(), "Previous definition");
}
return;
}
}
}
core::MethodRef defineMethod(core::MutableContext ctx, const FoundMethod &method) {
auto owner = methodOwner(ctx, method.flags);