forked from sorbet/sorbet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresolver.cc
4101 lines (3602 loc) · 187 KB
/
resolver.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 "core/errors/resolver.h"
#include "ast/Helpers.h"
#include "ast/Trees.h"
#include "ast/ast.h"
#include "ast/treemap/treemap.h"
#include "common/sort.h"
#include "core/Error.h"
#include "core/Names.h"
#include "core/StrictLevel.h"
#include "core/core.h"
#include "core/errors/internal.h"
#include "core/lsp/TypecheckEpochManager.h"
#include "resolver/CorrectTypeAlias.h"
#include "resolver/resolver.h"
#include "resolver/type_syntax/type_syntax.h"
#include "absl/algorithm/container.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "common/Timer.h"
#include "common/concurrency/ConcurrentQueue.h"
#include "core/Symbols.h"
#include <utility>
#include <vector>
using namespace std;
namespace sorbet::resolver {
namespace {
/*
* Note: There are multiple separate tree walks defined in this file, the main
* ones being:
*
* - ResolveConstantsWalk
* - ResolveSignaturesWalk
*
* There are also other important parts of resolver found elsewhere in the
* resolver/ package (GlobalPass, type_syntax). Below we describe
* ResolveConstantsWalk, which is particularly sophisticated.
*
* - - - - -
*
* Ruby supports resolving constants via ancestors--superclasses and mixins.
* Since superclass and mixins are themselves constant references, we thus may
* not be able to resolve certain constants until after we've resolved others.
*
* To solve this, we collect any failed resolutions in a number of TODO lists,
* and iterate over them to a fixed point (namely, either all constants
* resolve, or no new constants resolve and we stub out any that remain).
* In practice this fixed point computation terminates after 3 or fewer passes
* on most real codebases.
*
* The four TODO lists that this loop maintains are:
*
* - constants to be resolved
* - ancestors to be filled that require constants to be resolved
* - class aliases (class aliases know the symbol they alias to)
* - type aliases (type aliases know the fully parsed type of their RHS, and
* thus require their RHS to be resolved)
*
* Successful resolutions are removed from the lists, and then we loop again.
* We track all these lists separately for the dual reasons that
*
* 1. Upon successful resolution, we need to do additional work (mutating the
* symbol table to reflect the new ancestors) and
* 2. Resolving those constants potentially renders additional constants
* resolvable, and so if any resolution succeeds, we need to keep looping in
* the outer loop.
*
* We also track failure in the item, in order to distinguish a thing left in the
* list because we simply haven't succeeded yet and a thing left in the list
* because we have actively found a failure. For example, we might know that a
* given constant is unresolvable by Sorbet because it was qualified under
* not-a-constant: we mark this kind of job `resolution_failed`. The reason for
* this is unresolved constants are set to noSymbol, and once constant resolution
* has truly finished, we want to know which remaining failed jobs we need to set
* to a sensible default value. (Setting a conceptually failed job to untyped()
* before we've completed this loop can occasionally cause other jobs to
* non-deterministically half-resolve in the presence of multiple errors---c.f.
* issue #1126 on Github---so we mark jobs as failed rather than reporting an
* error and "resolving" them as untyped during the loop.)
*
* After the above passes:
*
* - ast::UnresolvedConstantLit nodes (constants that have a NameRef) are
* replaced with ast::ConstantLit nodes (constants that have a SymbolRef).
* - Every constant SymbolRef has enough to completely understand it's own
* place in the ancestor hierarchy.
* - Every type alias symbol carries with it the type it should be treated as.
*
* The resolveConstants method is the best place to start if you want to browse
* the fixed point loop at a high level.
*/
bool isT(ast::ExpressionPtr &expr) {
auto *tMod = ast::cast_tree<ast::ConstantLit>(expr);
return tMod && tMod->symbol == core::Symbols::T();
}
bool isTClassOf(ast::ExpressionPtr &expr) {
auto *send = ast::cast_tree<ast::Send>(expr);
if (send == nullptr) {
return false;
}
if (!isT(send->recv)) {
return false;
}
return send->fun == core::Names::classOf();
}
const UnorderedMap<core::NameRef, string> COMMON_TYPOS = {
{core::Names::Constants::Int(), "Integer"s},
{core::Names::Constants::Timestamp(), "Time"s},
{core::Names::Constants::Bool(), "T::Boolean"s},
{core::Names::Constants::Boolean(), "T::Boolean"s},
};
class ResolveConstantsWalk {
friend class ResolveSanityCheckWalk;
private:
struct Nesting {
const shared_ptr<Nesting> parent;
const core::SymbolRef scope;
Nesting(shared_ptr<Nesting> parent, core::SymbolRef scope) : parent(std::move(parent)), scope(scope) {}
};
shared_ptr<Nesting> nesting_;
struct ConstantResolutionItem {
shared_ptr<Nesting> scope;
ast::ConstantLit *out;
bool resolutionFailed = false;
bool possibleGenericType = false;
ConstantResolutionItem() = default;
ConstantResolutionItem(const shared_ptr<Nesting> &scope, ast::ConstantLit *lit) : scope(scope), out(lit) {}
ConstantResolutionItem(ConstantResolutionItem &&rhs) noexcept = default;
ConstantResolutionItem &operator=(ConstantResolutionItem &&rhs) noexcept = default;
ConstantResolutionItem(const ConstantResolutionItem &rhs) = delete;
const ConstantResolutionItem &operator=(const ConstantResolutionItem &rhs) = delete;
};
template <class T> struct ResolveItems {
core::FileRef file;
vector<T> items;
ResolveItems(core::FileRef file, vector<T> &&items) : file(file), items(move(items)){};
};
struct AncestorResolutionItem {
ast::ConstantLit *ancestor;
core::ClassOrModuleRef klass;
bool isSuperclass; // true if superclass, false for mixin
bool isInclude; // true if include, false if extend
std::optional<uint16_t> mixinIndex;
AncestorResolutionItem() = default;
AncestorResolutionItem(AncestorResolutionItem &&rhs) noexcept = default;
AncestorResolutionItem &operator=(AncestorResolutionItem &&rhs) noexcept = default;
AncestorResolutionItem(const AncestorResolutionItem &rhs) = delete;
const AncestorResolutionItem &operator=(const AncestorResolutionItem &rhs) = delete;
};
struct ClassAliasResolutionItem {
core::SymbolRef lhs;
ast::ConstantLit *rhs;
ClassAliasResolutionItem(core::SymbolRef lhs, ast::ConstantLit *rhs) : lhs(lhs), rhs(rhs) {}
ClassAliasResolutionItem() = default;
ClassAliasResolutionItem(ClassAliasResolutionItem &&) noexcept = default;
ClassAliasResolutionItem &operator=(ClassAliasResolutionItem &&rhs) noexcept = default;
ClassAliasResolutionItem(const ClassAliasResolutionItem &) = delete;
const ClassAliasResolutionItem &operator=(const ClassAliasResolutionItem &) = delete;
};
struct TypeAliasResolutionItem {
core::SymbolRef lhs;
core::FileRef file;
ast::ExpressionPtr *rhs;
TypeAliasResolutionItem(core::SymbolRef lhs, core::FileRef file, ast::ExpressionPtr *rhs)
: lhs(lhs), file(file), rhs(rhs) {}
TypeAliasResolutionItem(TypeAliasResolutionItem &&) noexcept = default;
TypeAliasResolutionItem &operator=(TypeAliasResolutionItem &&rhs) noexcept = default;
TypeAliasResolutionItem(const TypeAliasResolutionItem &) = delete;
const TypeAliasResolutionItem &operator=(const TypeAliasResolutionItem &) = delete;
};
struct ClassMethodsResolutionItem {
core::FileRef file;
core::SymbolRef owner;
ast::Send *send;
ClassMethodsResolutionItem(core::FileRef file, core::SymbolRef owner, ast::Send *send)
: file(file), owner(owner), send(send) {}
ClassMethodsResolutionItem(ClassMethodsResolutionItem &&) noexcept = default;
ClassMethodsResolutionItem &operator=(ClassMethodsResolutionItem &&rhs) noexcept = default;
ClassMethodsResolutionItem(const ClassMethodsResolutionItem &) = delete;
const ClassMethodsResolutionItem &operator=(const ClassMethodsResolutionItem &) = delete;
};
struct RequireAncestorResolutionItem {
core::FileRef file;
core::ClassOrModuleRef owner;
ast::Send *send;
RequireAncestorResolutionItem(core::FileRef file, core::ClassOrModuleRef owner, ast::Send *send)
: file(file), owner(owner), send(send) {}
RequireAncestorResolutionItem(RequireAncestorResolutionItem &&) noexcept = default;
RequireAncestorResolutionItem &operator=(RequireAncestorResolutionItem &&rhs) noexcept = default;
RequireAncestorResolutionItem(const RequireAncestorResolutionItem &) = delete;
const RequireAncestorResolutionItem &operator=(const RequireAncestorResolutionItem &) = delete;
};
vector<ConstantResolutionItem> todo_;
vector<AncestorResolutionItem> todoAncestors_;
vector<ClassAliasResolutionItem> todoClassAliases_;
vector<TypeAliasResolutionItem> todoTypeAliases_;
vector<ClassMethodsResolutionItem> todoClassMethods_;
vector<RequireAncestorResolutionItem> todoRequiredAncestors_;
static core::SymbolRef resolveLhs(core::Context ctx, const shared_ptr<Nesting> &nesting, core::NameRef name) {
Nesting *scope = nesting.get();
while (scope != nullptr) {
if (scope->scope.isClassOrModule()) {
// We don't want to rely on existing information in the symbol table for the
// fast path in LSP, but we do need to explicitly look through type template
// static fields to find the field on the singleton class.
auto lookup = scope->scope.asClassOrModuleRef().data(ctx)->findMemberNoDealias(ctx, name);
if (lookup.isStaticField(ctx)) {
if (lookup.asFieldRef().data(ctx)->isClassAlias()) {
auto dealiased = lookup.dealias(ctx);
if (dealiased.isTypeMember() &&
dealiased.asTypeMemberRef().data(ctx)->owner ==
lookup.owner(ctx).asClassOrModuleRef().data(ctx)->lookupSingletonClass(ctx)) {
// This static field is a shim that exists only so that `MyTypeTemplate` resolves as normal
// constant literal by looking for the thing with that name on the singleton class.
// Should never be leaked externally, so in this case we forcibly dealias.
lookup = dealiased;
}
}
}
if (lookup.exists()) {
return lookup;
}
}
scope = scope->parent.get();
}
return nesting->scope.asClassOrModuleRef().data(ctx)->findMemberTransitiveNoDealias(ctx, name);
}
static bool isAlreadyResolved(core::Context ctx, const ast::ConstantLit &original) {
auto sym = original.symbol;
if (!sym.exists()) {
return false;
}
if (sym.isTypeAlias(ctx)) {
return sym.asFieldRef().data(ctx)->resultType != nullptr;
}
return true;
}
class ResolutionChecker {
public:
bool seenUnresolved = false;
void postTransformConstantLit(core::Context ctx, ast::ExpressionPtr &tree) {
auto &original = ast::cast_tree_nonnull<ast::ConstantLit>(tree);
seenUnresolved |= !isAlreadyResolved(ctx, original);
};
};
static bool isFullyResolved(core::Context ctx, const ast::ExpressionPtr &expression) {
ResolutionChecker checker;
ast::ExpressionPtr dummy(expression.getTagged());
ast::TreeWalk::apply(ctx, checker, dummy);
ENFORCE(dummy == expression);
dummy.release();
return !checker.seenUnresolved;
}
static core::SymbolRef resolveConstant(core::Context ctx, const shared_ptr<Nesting> &nesting,
const ast::UnresolvedConstantLit &c, bool &resolutionFailed) {
if (ast::isa_tree<ast::EmptyTree>(c.scope)) {
core::SymbolRef result = resolveLhs(ctx, nesting, c.cnst);
return result;
}
if (auto *id = ast::cast_tree<ast::ConstantLit>(c.scope)) {
auto sym = id->symbol;
if (sym.exists() && sym.isTypeAlias(ctx) && !resolutionFailed) {
if (auto e = ctx.beginError(c.loc, core::errors::Resolver::ConstantInTypeAlias)) {
e.setHeader("Resolving constants through type aliases is not supported");
}
resolutionFailed = true;
return core::Symbols::noSymbol();
}
if (!sym.exists()) {
return core::Symbols::noSymbol();
}
core::SymbolRef resolved = id->symbol.dealias(ctx);
core::SymbolRef result;
if (resolved.isClassOrModule()) {
result = resolved.asClassOrModuleRef().data(ctx)->findMemberNoDealias(ctx, c.cnst);
}
// Private constants are allowed to be resolved, when there is no scope set (the scope is checked above),
// otherwise we should error out. Private constant references _are not_ enforced inside RBI files.
if (result.exists() &&
((result.isClassOrModule() && result.asClassOrModuleRef().data(ctx)->flags.isPrivate) ||
(result.isStaticField(ctx) && result.asFieldRef().data(ctx)->flags.isStaticFieldPrivate)) &&
!ctx.file.data(ctx).isRBI()) {
if (auto e = ctx.beginError(c.loc, core::errors::Resolver::PrivateConstantReferenced)) {
e.setHeader("Non-private reference to private constant `{}` referenced", result.show(ctx));
}
}
return result;
}
if (!resolutionFailed) {
if (auto e = ctx.beginError(c.loc, core::errors::Resolver::DynamicConstant)) {
e.setHeader("Dynamic constant references are unsupported");
}
}
resolutionFailed = true;
return core::Symbols::noSymbol();
}
static const int MAX_SUGGESTION_COUNT = 10;
struct PackageStub {
core::NameRef packageId;
vector<core::NameRef> fullName;
PackageStub(const core::packages::PackageInfo &info)
: packageId{info.mangledName()}, fullName{info.fullName()} {}
bool couldDefineChildNamespace(const core::GlobalState &gs, const std::vector<core::NameRef> &prefix,
const std::vector<ast::ConstantLit *> &suffix) const {
ENFORCE(!prefix.empty());
auto start = prefix.begin();
if (*start == core::Names::Constants::Test()) {
++start;
}
auto prefixSize = std::distance(start, prefix.end());
if (prefixSize == 0) {
return false;
}
// The reasoning is as follows: the prefix is derived from a nesting scope paired with the symbol being
// resolved. The nesting scopes could only define a package in the parent namespace, while this check is
// only applied to packages that are known to not occupy that part of the namespace.
if (this->fullName.size() <= prefixSize) {
return false;
}
if (!std::equal(start, prefix.end(), this->fullName.begin())) {
return false;
}
auto it = this->fullName.begin() + prefixSize;
for (auto *cnst : suffix) {
if (it == this->fullName.end()) {
return true;
}
auto &original = ast::cast_tree_nonnull<ast::UnresolvedConstantLit>(cnst->original);
if (original.cnst != *it) {
return false;
}
++it;
}
return true;
}
};
struct ParentPackageStub {
PackageStub stub;
vector<core::NameRef> exports;
// NOTE: these are the public-facing exports of the package that start with the `Test::` special prefix. They
// are not the names exported to the implicit test package via `export_for_test`.
vector<core::NameRef> testExports;
ParentPackageStub(const core::packages::PackageInfo &info) : stub{info} {
auto prefixLen = this->stub.fullName.size();
auto testPrefixLen = prefixLen + 1;
for (auto &path : info.exports()) {
// We only need the unique part of the export's name. It's safe to assume that the exports are
// populated, as the only case we allow a full re-export of the module is for leaf modules, and we
// already know this not a leaf.
if (path.front() == core::Names::Constants::Test()) {
this->testExports.emplace_back(path[testPrefixLen]);
} else {
this->exports.emplace_back(path[prefixLen]);
}
}
}
// Check that the candidate name is one of the top-level exported names from a parent package.
bool exportsSymbol(bool inTestNamespace, core::NameRef candidate) const {
auto &exportList = inTestNamespace ? this->testExports : this->exports;
return absl::c_find(exportList, candidate) != exportList.end();
}
};
struct ImportStubs {
std::vector<ParentPackageStub> parents;
std::vector<PackageStub> imports;
static ImportStubs make(core::GlobalState &gs) {
ImportStubs stubs;
auto &db = gs.packageDB();
for (auto parent : gs.singlePackageImports->parentImports) {
auto &info = db.getPackageInfo(parent);
stubs.parents.emplace_back(ParentPackageStub{info});
}
for (auto parent : gs.singlePackageImports->regularImports) {
auto &info = db.getPackageInfo(parent);
stubs.imports.emplace_back(PackageStub{info});
}
return stubs;
}
// Determine if a package with the same name as `scope` is known to export the name `cnst`.
bool packageExportsConstant(const std::vector<core::NameRef> &scope, core::NameRef cnst) const {
ENFORCE(!scope.empty());
auto start = scope.begin();
if (*start == core::Names::Constants::Test()) {
++start;
}
auto scopeSize = std::distance(start, scope.end());
ENFORCE(scopeSize > 0);
const auto parent = absl::c_find_if(this->parents, [start, scopeSize, &scope](auto &p) {
return scopeSize == p.stub.fullName.size() && std::equal(start, scope.end(), p.stub.fullName.begin());
});
bool inTestNamespace = start != scope.begin();
return parent != this->parents.end() && parent->exportsSymbol(inTestNamespace, cnst);
}
// Determine if a package is known to have a prefix that is a combination of the name defined by `scope`, and
// some prefix of the suffix vector provided.
bool fromChildNamespace(const core::GlobalState &gs, const std::vector<core::NameRef> &prefix,
const std::vector<ast::ConstantLit *> &suffix) const {
return absl::c_any_of(this->imports, [&gs, &prefix, &suffix](auto &stub) {
return stub.couldDefineChildNamespace(gs, prefix, suffix);
});
}
};
static void ensureTGenericMixin(core::GlobalState &gs, core::ClassOrModuleRef klass) {
auto &mixins = klass.data(gs)->mixins();
if (absl::c_find(mixins, core::Symbols::T_Generic()) == mixins.end()) {
mixins.emplace_back(core::Symbols::T_Generic());
}
}
static core::ClassOrModuleRef stubConstant(core::MutableContext ctx, core::ClassOrModuleRef owner,
ast::ConstantLit *out, bool possibleGenericType) {
auto symbol = ctx.state.enterClassSymbol(ctx.locAt(out->loc), owner,
ast::cast_tree<ast::UnresolvedConstantLit>(out->original)->cnst);
auto data = symbol.data(ctx);
// force a singleton into existence
auto singletonClass = data->singletonClass(ctx);
if (possibleGenericType) {
ensureTGenericMixin(ctx, singletonClass);
}
out->symbol = symbol;
return symbol;
}
static void stubConstantSuffix(core::MutableContext ctx, core::ClassOrModuleRef owner,
std::vector<ast::ConstantLit *> suffix, bool possibleGenericType) {
if (suffix.empty()) {
return;
}
auto last = suffix.end() - 1;
for (auto it = suffix.begin(); it != last; ++it) {
owner = stubConstant(ctx, owner, *it, false);
}
stubConstant(ctx, owner, *last, possibleGenericType);
}
// Turn a symbol into a vector of `NameRefs`. Returns true if a non-empty result vector was populated, and false if
// the scope was root, or one of the owning symbols in the hierarchy doesn't exist.
static bool scopeToNames(core::GlobalState &gs, core::SymbolRef sym, std::vector<core::NameRef> &res) {
res.clear();
while (sym.exists() && sym != core::Symbols::root()) {
if (!sym.isClassOrModule()) {
res.clear();
return false;
}
auto cls = sym.asClassOrModuleRef();
res.emplace_back(cls.data(gs)->name);
sym = cls.data(gs)->owner;
}
// Explicitly consider an empty top-level scope as one to skip. This arises when the symbol passed in is
// `core::Symbols::root()`, which will always be the top-most parent for the `Nesting` linked list present for
// the `ResolutionItem` being stubbed. As this doesn't correspond to a prefix of the current package's
// namespace, we return false to signal that this scope doesn't need to be considered as either of the
// parent/child package special cases.
if (res.empty()) {
return false;
}
absl::c_reverse(res);
return true;
}
// Determine if a parent package exports a constant named `base`. If it does, return the symbol that already exists
// for that nesting scope.
static core::ClassOrModuleRef parentPackageOwner(core::MutableContext ctx, const ImportStubs &importStubs,
const Nesting *scope, ast::ConstantLit *base) {
std::vector<core::NameRef> prefix;
prefix.reserve(5);
for (auto *cursor = scope; cursor != nullptr; cursor = cursor->parent.get()) {
// If this is expensive, we could cache it in stubForRbiGeneration below
if (!scopeToNames(ctx, cursor->scope, prefix)) {
continue;
}
auto &original = ast::cast_tree_nonnull<ast::UnresolvedConstantLit>(base->original);
if (importStubs.packageExportsConstant(prefix, original.cnst)) {
ENFORCE(cursor->scope.isClassOrModule());
return cursor->scope.asClassOrModuleRef();
}
}
return core::ClassOrModuleRef{};
}
// Determine if a child class shares a name in suffix, potentially rooted in any of the nesting scopes.
static core::ClassOrModuleRef childPackageOwner(core::MutableContext ctx, const ImportStubs &importStubs,
const Nesting *scope, std::vector<ast::ConstantLit *> suffix) {
std::vector<core::NameRef> prefix;
prefix.reserve(5);
for (auto *cursor = scope; cursor != nullptr; cursor = cursor->parent.get()) {
// If this is expensive, we could cache it in stubForRbiGeneration below
if (!scopeToNames(ctx, cursor->scope, prefix)) {
continue;
}
if (importStubs.fromChildNamespace(ctx, prefix, suffix)) {
ENFORCE(cursor->scope.isClassOrModule());
return cursor->scope.asClassOrModuleRef();
}
}
return core::ClassOrModuleRef{};
}
static void stubForRbiGeneration(core::MutableContext ctx, const ImportStubs &importStubs, const Nesting *scope,
ast::ConstantLit *out, bool possibleGenericType) {
std::vector<ast::ConstantLit *> suffix;
{
auto *cursor = out;
bool isRootReference = false;
while (cursor != nullptr) {
auto *original = ast::cast_tree<ast::UnresolvedConstantLit>(cursor->original);
if (original == nullptr) {
isRootReference = cursor->symbol == core::Symbols::root();
break;
}
suffix.emplace_back(cursor);
cursor = ast::cast_tree<ast::ConstantLit>(original->scope);
}
absl::c_reverse(suffix);
// If the constant looks like `::Foo::Bar`, we don't need to apply the heuristics below as it's known to be
// defined at the root.
if (isRootReference) {
stubConstantSuffix(ctx, core::Symbols::root(), suffix, possibleGenericType);
return;
}
}
// If the constant doesn't resolve to something that overlaps with this package's namespace, it will be defined
// at the root scope.
auto owner = core::Symbols::root();
// First, determine if we're already in the context of a parent package by crawling up the nesting scopes.
auto parentPackage = parentPackageOwner(ctx, importStubs, scope, suffix.front());
if (parentPackage.exists()) {
owner = parentPackage;
} else {
// If we're not in a parent package, check the name suffix to determine if we're inside of a child package.
auto childPackage = childPackageOwner(ctx, importStubs, scope, suffix);
if (childPackage.exists()) {
owner = childPackage;
}
}
stubConstantSuffix(ctx, owner, suffix, possibleGenericType);
}
// We have failed to resolve the constant. We'll need to report the error and stub it so that we can proceed
static void constantResolutionFailed(core::GlobalState &gs, core::FileRef file, ConstantResolutionItem &job,
const ImportStubs &importStubs, int &suggestionCount) {
auto &original = ast::cast_tree_nonnull<ast::UnresolvedConstantLit>(job.out->original);
core::Context ctx(gs, core::Symbols::root(), file);
bool singlePackageRbiGeneration = ctx.state.singlePackageImports.has_value();
auto resolved = resolveConstant(ctx.withOwner(job.scope->scope), job.scope, original, job.resolutionFailed);
if (resolved.exists() && resolved.isTypeAlias(ctx)) {
auto resolvedField = resolved.asFieldRef();
if (resolvedField.data(ctx)->resultType == nullptr) {
if (singlePackageRbiGeneration) {
job.out->symbol.setResultType(gs, core::make_type<core::ClassType>(core::Symbols::todo()));
} else {
// This is actually a use-site error, but we limit ourselves to emitting it once by checking
// resultType
auto loc = resolvedField.data(ctx)->loc();
if (auto e = ctx.state.beginError(loc, core::errors::Resolver::RecursiveTypeAlias)) {
e.setHeader("Unable to resolve right hand side of type alias `{}`", resolved.show(ctx));
e.addErrorLine(ctx.locAt(job.out->original.loc()), "Type alias used here");
}
resolvedField.data(gs)->resultType = core::Types::untyped(ctx, resolved);
}
}
job.out->symbol = resolved;
return;
}
if (job.resolutionFailed) {
// we only set this when a job has failed for other reasons and we've already reported an error, and
// continuining on will only redundantly report that we can't resolve the constant, so bail early here
job.out->symbol = core::Symbols::untyped();
return;
}
// When generating rbis in single-package mode, we may need to invent a symbol at this point
if (singlePackageRbiGeneration) {
core::MutableContext ctx(gs, job.scope->scope, file);
stubForRbiGeneration(ctx, importStubs, job.scope.get(), job.out, job.possibleGenericType);
return;
}
ENFORCE(!resolved.exists());
ENFORCE(!job.out->symbol.exists());
job.out->symbol = core::Symbols::StubModule();
bool alreadyReported = false;
job.out->resolutionScopes = make_unique<ast::ConstantLit::ResolutionScopes>();
if (auto *id = ast::cast_tree<ast::ConstantLit>(original.scope)) {
auto originalScope = id->symbol.dealias(ctx);
if (originalScope == core::Symbols::StubModule()) {
// If we were trying to resolve some literal like C::D but `C` itself was already stubbed,
// no need to also report that `D` is missing.
alreadyReported = true;
job.out->resolutionScopes->emplace_back(core::Symbols::noSymbol());
} else {
// We were trying to resolve a constant literal that had an explicit scope.
// Since Sorbet doesn't combine ancestor resolution and explicit scope resolution,
// we just put a single entry in the resolutionScopes list.
job.out->resolutionScopes->emplace_back(originalScope);
}
} else {
auto nesting = job.scope;
while (true) {
job.out->resolutionScopes->emplace_back(nesting->scope);
if (nesting->parent == nullptr) {
break;
}
nesting = nesting->parent;
}
}
ENFORCE(!job.out->resolutionScopes->empty());
ENFORCE(job.scope->scope != core::Symbols::StubModule());
// This name is an artifact of parser recovery--no need to leak the parser implementation to the user,
// because an error will have already been reported.
auto constantNameMissing = original.cnst == core::Names::Constants::ConstantNameMissing();
// If a package exports a name that does not exist only one error should appear at the
// export site. Ignore resolution failures in the aliases/modules created by packaging to
// avoid this resulting in duplicate errors.
if (!constantNameMissing && !alreadyReported) {
if (auto e = ctx.beginError(job.out->original.loc(), core::errors::Resolver::StubConstant)) {
e.setHeader("Unable to resolve constant `{}`", original.cnst.show(ctx));
auto foundCommonTypo = false;
if (ast::isa_tree<ast::EmptyTree>(original.scope)) {
for (const auto &[from, to] : COMMON_TYPOS) {
if (from == original.cnst) {
e.didYouMean(to, ctx.locAt(job.out->loc));
foundCommonTypo = true;
break;
}
}
}
auto suggestScope = job.out->resolutionScopes->front();
if (!foundCommonTypo && suggestionCount < MAX_SUGGESTION_COUNT && suggestScope.exists() &&
suggestScope.isClassOrModule()) {
suggestionCount++;
auto suggested =
suggestScope.asClassOrModuleRef().data(ctx)->findMemberFuzzyMatch(ctx, original.cnst);
if (suggested.size() > 3) {
suggested.resize(3);
}
for (auto suggestion : suggested) {
const auto replacement = suggestion.symbol.show(ctx);
auto replaceLoc = ctx.locAt(job.out->loc);
if (replaceLoc.source(ctx) == replacement) {
// The replacement is the same as the original.
// This can happen for a number of reasons, usually due to things
// where one of the names has an unprintable name from a rewriter.
// It's confusing to see those bad did you mean and they don't
// provide value.
continue;
}
e.didYouMean(replacement, replaceLoc);
e.addErrorLine(suggestion.symbol.loc(ctx), "`{}` defined here", replacement);
}
}
}
}
}
static bool resolveJob(core::Context ctx, ConstantResolutionItem &job) {
if (isAlreadyResolved(ctx, *job.out)) {
if (job.possibleGenericType) {
return false;
}
return true;
}
auto &original = ast::cast_tree_nonnull<ast::UnresolvedConstantLit>(job.out->original);
auto resolved = resolveConstant(ctx.withOwner(job.scope->scope), job.scope, original, job.resolutionFailed);
if (!resolved.exists()) {
return false;
}
if (resolved.isTypeAlias(ctx)) {
auto resolvedField = resolved.asFieldRef();
if (resolvedField.data(ctx)->resultType != nullptr) {
job.out->symbol = resolved;
return true;
}
return false;
}
job.out->symbol = resolved;
return true;
}
static bool resolveConstantResolutionItems(const core::GlobalState &gs,
vector<ResolveItems<ConstantResolutionItem>> &jobs,
WorkerPool &workers) {
if (jobs.empty()) {
return false;
}
auto outputq = make_shared<BlockingBoundedQueue<pair<uint32_t, vector<ResolveItems<ConstantResolutionItem>>>>>(
jobs.size());
auto inputq = make_shared<ConcurrentBoundedQueue<ResolveItems<ConstantResolutionItem>>>(jobs.size());
for (auto &job : jobs) {
inputq->push(move(job), 1);
}
jobs.clear();
workers.multiplexJob("resolveConstantsWorker", [inputq, outputq, &gs]() {
vector<ResolveItems<ConstantResolutionItem>> leftover;
ResolveItems<ConstantResolutionItem> job(core::FileRef(), {});
uint32_t processed = 0;
uint32_t retries = 0;
for (auto result = inputq->try_pop(job); !result.done(); result = inputq->try_pop(job)) {
if (result.gotItem()) {
processed++;
core::Context ictx(gs, core::Symbols::root(), job.file);
auto origSize = job.items.size();
auto fileIt =
remove_if(job.items.begin(), job.items.end(),
[&](ConstantResolutionItem &item) -> bool { return resolveJob(ictx, item); });
job.items.erase(fileIt, job.items.end());
retries += origSize - job.items.size();
if (!job.items.empty()) {
leftover.emplace_back(move(job));
}
}
}
if (processed > 0) {
auto pair = make_pair(retries, move(leftover));
outputq->push(move(pair), processed);
}
});
uint32_t retries = 0;
pair<uint32_t, vector<ResolveItems<ConstantResolutionItem>>> threadResult;
for (auto result = outputq->wait_pop_timed(threadResult, WorkerPool::BLOCK_INTERVAL(), gs.tracer());
!result.done();
result = outputq->wait_pop_timed(threadResult, WorkerPool::BLOCK_INTERVAL(), gs.tracer())) {
if (result.gotItem()) {
retries += threadResult.first;
jobs.insert(jobs.end(), make_move_iterator(threadResult.second.begin()),
make_move_iterator(threadResult.second.end()));
}
}
categoryCounterAdd("resolve.constants.nonancestor", "retry", retries);
return retries > 0;
}
static bool resolveTypeAliasJob(core::MutableContext ctx, TypeAliasResolutionItem &job) {
core::TypeMemberRef enclosingTypeMember;
core::ClassOrModuleRef enclosingClass = job.lhs.enclosingClass(ctx);
while (enclosingClass != core::Symbols::root()) {
auto typeMembers = enclosingClass.data(ctx)->typeMembers();
if (!typeMembers.empty()) {
enclosingTypeMember = typeMembers[0];
break;
}
enclosingClass = enclosingClass.data(ctx)->owner;
}
auto &rhs = *job.rhs;
if (enclosingTypeMember.exists()) {
if (auto e = ctx.beginError(rhs.loc(), core::errors::Resolver::TypeAliasInGenericClass)) {
e.setHeader("Type aliases are not allowed in generic classes");
e.addErrorLine(enclosingTypeMember.data(ctx)->loc(), "Here is enclosing generic member");
}
job.lhs.setResultType(ctx, core::Types::untyped(ctx, job.lhs));
return true;
}
if (isFullyResolved(ctx, rhs)) {
// this todo will be resolved during ResolveTypeMembersAndFieldsWalk below
job.lhs.setResultType(ctx, core::make_type<core::ClassType>(core::Symbols::todo()));
return true;
}
return false;
}
static bool resolveClassAliasJob(core::MutableContext ctx, ClassAliasResolutionItem &it) {
auto rhsSym = it.rhs->symbol;
if (!rhsSym.exists()) {
return false;
}
if (rhsSym.isTypeAlias(ctx)) {
if (auto e = ctx.beginError(it.rhs->loc, core::errors::Resolver::ReassignsTypeAlias)) {
e.setHeader("Reassigning a type alias is not allowed");
e.addErrorLine(rhsSym.loc(ctx), "Originally defined here");
auto rhsLoc = ctx.locAt(it.rhs->loc);
if (rhsLoc.exists()) {
e.replaceWith("Declare as type alias", rhsLoc, "T.type_alias {{ {} }}", rhsLoc.source(ctx).value());
}
}
it.lhs.setResultType(ctx, core::Types::untypedUntracked());
return true;
}
if (rhsSym.dealias(ctx) != it.lhs) {
it.lhs.setResultType(ctx, core::make_type<core::AliasType>(rhsSym));
} else {
if (auto e = ctx.state.beginError(it.lhs.loc(ctx), core::errors::Resolver::RecursiveClassAlias)) {
e.setHeader("Class alias aliases to itself");
}
it.lhs.setResultType(ctx, core::Types::untypedUntracked());
}
return true;
}
static void saveAncestorTypeForHashing(core::MutableContext ctx, const AncestorResolutionItem &item) {
// For LSP, create a synthetic method <unresolved-ancestors> that has a return type containing a type
// for every ancestor. When this return type changes, LSP takes the slow path (see
// Symbol::methodShapeHash()).
auto unresolvedPath = item.ancestor->fullUnresolvedPath(ctx);
if (!unresolvedPath.has_value()) {
return;
}
auto ancestorType =
core::make_type<core::UnresolvedClassType>(unresolvedPath->first, move(unresolvedPath->second));
auto uaSym = ctx.state.enterMethodSymbol(core::Loc::none(), item.klass, core::Names::unresolvedAncestors());
// Add a fake block argument so that this method symbol passes sanity checks
auto &arg = ctx.state.enterMethodArgumentSymbol(core::Loc::none(), uaSym, core::Names::blkArg());
arg.flags.isBlock = true;
core::TypePtr resultType = uaSym.data(ctx)->resultType;
if (!resultType) {
uaSym.data(ctx)->resultType = core::make_type<core::TupleType>(vector<core::TypePtr>{ancestorType});
} else if (auto tt = core::cast_type<core::TupleType>(resultType)) {
tt->elems.push_back(ancestorType);
} else {
ENFORCE(false);
}
}
static core::ClassOrModuleRef stubSymbolForAncestor(const AncestorResolutionItem &item) {
if (item.isSuperclass) {
return core::Symbols::StubSuperClass();
}
return core::Symbols::StubMixin();
}
static bool resolveAncestorJob(core::MutableContext ctx, AncestorResolutionItem &job, bool lastRun) {
auto ancestorSym = job.ancestor->symbol;
if (!ancestorSym.exists()) {
if (!lastRun && !job.isSuperclass && !job.mixinIndex.has_value()) {
// This is an include or extend. Add a placeholder to fill in later to preserve
// ordering of mixins, unless an index is already set.
job.mixinIndex = job.klass.data(ctx)->addMixinPlaceholder(ctx);
}
return false;
}
core::ClassOrModuleRef resolvedClass;
{
core::SymbolRef resolved;
if (ancestorSym.isTypeAlias(ctx)) {
if (!lastRun) {
return false;
}
if (auto e = ctx.beginError(job.ancestor->loc, core::errors::Resolver::DynamicSuperclass)) {
e.setHeader("Superclasses and mixins may not be type aliases");
}
resolved = stubSymbolForAncestor(job);
} else {
resolved = ancestorSym.dealias(ctx);
}
if (!resolved.isClassOrModule()) {
if (!lastRun) {
if (!job.isSuperclass && !job.mixinIndex.has_value()) {
// This is an include or extend. Add a placeholder to fill in later to preserve
// ordering of mixins.
job.mixinIndex = job.klass.data(ctx)->addMixinPlaceholder(ctx);
}
return false;
}
if (auto e = ctx.beginError(job.ancestor->loc, core::errors::Resolver::DynamicSuperclass)) {
e.setHeader("Superclasses and mixins may only use class aliases like `{}`", "A = Integer");
}
resolved = stubSymbolForAncestor(job);
}
resolvedClass = resolved.asClassOrModuleRef();
}
if (resolvedClass == job.klass) {
if (auto e = ctx.beginError(job.ancestor->loc, core::errors::Resolver::CircularDependency)) {
e.setHeader("Circular dependency: `{}` is a parent of itself", job.klass.show(ctx));
e.addErrorLine(resolvedClass.data(ctx)->loc(), "Class definition");
}
resolvedClass = stubSymbolForAncestor(job);
} else if (resolvedClass.data(ctx)->derivesFrom(ctx, job.klass)) {
if (auto e = ctx.beginError(job.ancestor->loc, core::errors::Resolver::CircularDependency)) {
e.setHeader("Circular dependency: `{}` and `{}` are declared as parents of each other",
job.klass.show(ctx), resolvedClass.show(ctx));
e.addErrorLine(job.klass.data(ctx)->loc(), "One definition");
e.addErrorLine(resolvedClass.data(ctx)->loc(), "Other definition");
}
resolvedClass = stubSymbolForAncestor(job);
}
bool ancestorPresent = true;
if (job.isSuperclass) {
if (resolvedClass == core::Symbols::todo()) {
// No superclass specified
ancestorPresent = false;
} else if (!job.klass.data(ctx)->superClass().exists() ||
job.klass.data(ctx)->superClass() == core::Symbols::todo() ||
job.klass.data(ctx)->superClass() == resolvedClass) {
job.klass.data(ctx)->setSuperClass(resolvedClass);
} else {