forked from sorbet/sorbet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresolver.cc
2167 lines (1921 loc) · 96.9 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 "resolver/CorrectTypeAlias.h"
#include "resolver/resolver.h"
#include "resolver/type_syntax.h"
#include "absl/strings/str_cat.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.
*/
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 ResolutionItem {
shared_ptr<Nesting> scope;
ast::ConstantLit *out;
bool resolutionFailed = false;
ResolutionItem() = default;
ResolutionItem(ResolutionItem &&rhs) noexcept = default;
ResolutionItem &operator=(ResolutionItem &&rhs) noexcept = default;
ResolutionItem(const ResolutionItem &rhs) = delete;
const ResolutionItem &operator=(const ResolutionItem &rhs) = delete;
};
struct AncestorResolutionItem {
ast::ConstantLit *ancestor;
core::SymbolRef klass;
bool isSuperclass; // true if superclass, false for mixin
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() = 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;
ast::Expression *rhs;
TypeAliasResolutionItem(core::SymbolRef lhs, ast::Expression *rhs) : lhs(lhs), rhs(rhs) {}
TypeAliasResolutionItem(TypeAliasResolutionItem &&) noexcept = default;
TypeAliasResolutionItem &operator=(TypeAliasResolutionItem &&rhs) noexcept = default;
TypeAliasResolutionItem(const TypeAliasResolutionItem &) = delete;
const TypeAliasResolutionItem &operator=(const TypeAliasResolutionItem &) = delete;
};
vector<ResolutionItem> todo_;
vector<AncestorResolutionItem> todoAncestors_;
vector<ClassAliasResolutionItem> todoClassAliases_;
vector<TypeAliasResolutionItem> todoTypeAliases_;
static core::SymbolRef resolveLhs(core::Context ctx, shared_ptr<Nesting> nesting, core::NameRef name) {
Nesting *scope = nesting.get();
while (scope != nullptr) {
auto lookup = scope->scope.data(ctx)->findMember(ctx, name);
if (lookup.exists()) {
return lookup;
}
scope = scope->parent.get();
}
return nesting->scope.data(ctx)->findMemberTransitive(ctx, name);
}
static bool isAlreadyResolved(core::Context ctx, const ast::ConstantLit &original) {
auto sym = original.symbol;
if (!sym.exists()) {
return false;
}
auto data = sym.data(ctx);
if (data->isTypeAlias()) {
return data->resultType != nullptr;
} else {
return true;
}
}
class ResolutionChecker {
public:
bool seenUnresolved = false;
unique_ptr<ast::ConstantLit> postTransformConstantLit(core::Context ctx,
unique_ptr<ast::ConstantLit> original) {
seenUnresolved |= !isAlreadyResolved(ctx, *original);
return original;
};
};
static bool isFullyResolved(core::Context ctx, const ast::Expression *expression) {
ResolutionChecker checker;
unique_ptr<ast::Expression> dummy(const_cast<ast::Expression *>(expression));
dummy = ast::TreeMap::apply(ctx, checker, std::move(dummy));
ENFORCE(dummy.get() == expression);
dummy.release();
return !checker.seenUnresolved;
}
static core::SymbolRef resolveConstant(core::Context ctx, shared_ptr<Nesting> nesting,
const unique_ptr<ast::UnresolvedConstantLit> &c, bool &resolutionFailed) {
if (ast::isa_tree<ast::EmptyTree>(c->scope.get())) {
core::SymbolRef result = resolveLhs(ctx, nesting, c->cnst);
return result;
}
ast::Expression *resolvedScope = c->scope.get();
if (auto *id = ast::cast_tree<ast::ConstantLit>(resolvedScope)) {
auto sym = id->symbol;
if (sym.exists() && sym.data(ctx)->isTypeAlias() && !resolutionFailed) {
if (auto e = ctx.state.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.data(ctx)->dealias(ctx);
core::SymbolRef result = resolved.data(ctx)->findMember(ctx, c->cnst);
return result;
} else {
if (!resolutionFailed) {
if (auto e = ctx.state.beginError(c->loc, core::errors::Resolver::DynamicConstant)) {
e.setHeader("Dynamic constant references are unsupported");
}
}
resolutionFailed = true;
return core::Symbols::noSymbol();
}
}
// 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::MutableContext ctx, ResolutionItem &job, bool suggestDidYouMean) {
auto resolved =
resolveConstant(ctx.withOwner(job.scope->scope), job.scope, job.out->original, job.resolutionFailed);
if (resolved.exists() && resolved.data(ctx)->isTypeAlias()) {
if (resolved.data(ctx)->resultType == nullptr) {
// This is actually a use-site error, but we limit ourselves to emitting it once by checking resultType
auto loc = resolved.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.data(ctx)->show(ctx));
e.addErrorLine(job.out->original->loc, "Type alias used here");
}
resolved.data(ctx)->resultType =
core::Types::untyped(ctx, resolved); // <<-- This is the reason this takes a MutableContext
}
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;
}
ENFORCE(!resolved.exists());
core::SymbolRef scope;
if (job.out->symbol.exists()) {
scope = job.out->symbol.data(ctx)->dealias(ctx);
} else if (auto *id = ast::cast_tree<ast::ConstantLit>(job.out->original->scope.get())) {
scope = id->symbol.data(ctx)->dealias(ctx);
} else {
scope = job.scope->scope;
}
auto customAutogenError = job.out->original->cnst == core::Symbols::Subclasses().data(ctx)->name;
if (scope != core::Symbols::StubModule() || customAutogenError) {
if (auto e = ctx.state.beginError(job.out->original->loc, core::errors::Resolver::StubConstant)) {
e.setHeader("Unable to resolve constant `{}`", job.out->original->cnst.show(ctx));
if (customAutogenError) {
e.addErrorSection(
core::ErrorSection("If this constant is generated by Autogen, you "
"may need to re-generate the .rbi. Try running:\n"
" scripts/bin/remote-script sorbet/shim_generation/autogen.rb"));
} else if (suggestDidYouMean && scope.data(ctx)->isClassOrModule()) {
auto suggested = scope.data(ctx)->findMemberFuzzyMatch(ctx, job.out->original->cnst);
if (suggested.size() > 3) {
suggested.resize(3);
}
if (!suggested.empty()) {
vector<core::ErrorLine> lines;
for (auto suggestion : suggested) {
const auto replacement = suggestion.symbol.show(ctx);
lines.emplace_back(core::ErrorLine::from(suggestion.symbol.data(ctx)->loc(),
"Did you mean: `{}`?", replacement));
e.replaceWith(fmt::format("Replace with `{}`", replacement), job.out->loc, "{}",
replacement);
}
e.addErrorSection(core::ErrorSection(lines));
}
}
}
}
if (scope == core::Symbols::StubModule()) {
scope = core::Symbols::noSymbol();
}
job.out->symbol = core::Symbols::StubModule();
job.out->resolutionScope = scope;
}
static bool resolveJob(core::Context ctx, ResolutionItem &job) {
if (isAlreadyResolved(ctx, *job.out)) {
return true;
}
auto resolved =
resolveConstant(ctx.withOwner(job.scope->scope), job.scope, job.out->original, job.resolutionFailed);
if (!resolved.exists()) {
return false;
}
if (resolved.data(ctx)->isTypeAlias()) {
if (resolved.data(ctx)->resultType != nullptr) {
job.out->symbol = resolved;
return true;
}
return false;
}
job.out->symbol = resolved;
return true;
}
static bool resolveTypeAliasJob(core::MutableContext ctx, TypeAliasResolutionItem &job) {
core::SymbolRef enclosingTypeMember;
core::SymbolRef enclosingClass = job.lhs.data(ctx)->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.data(ctx)->enclosingClass(ctx);
}
if (enclosingTypeMember.exists()) {
if (auto e = ctx.state.beginError(job.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.data(ctx)->resultType = core::Types::untyped(ctx, job.lhs);
return true;
}
if (isFullyResolved(ctx, job.rhs)) {
// this todo will be resolved during ResolveTypeParamsWalk below
job.lhs.data(ctx)->resultType = 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;
}
auto rhsData = rhsSym.data(ctx);
if (rhsData->isTypeAlias()) {
if (auto e = ctx.state.beginError(it.rhs->loc, core::errors::Resolver::ReassignsTypeAlias)) {
e.setHeader("Reassigning a type alias is not allowed");
e.addErrorLine(rhsData->loc(), "Originally defined here");
e.replaceWith("Declare as type alias", it.rhs->loc, "T.type_alias {{{}}}", it.rhs->loc.source(ctx));
}
it.lhs.data(ctx)->resultType = core::Types::untypedUntracked();
return true;
} else {
if (rhsData->dealias(ctx) != it.lhs) {
it.lhs.data(ctx)->resultType = core::make_type<core::AliasType>(rhsSym);
} else {
if (auto e =
ctx.state.beginError(it.lhs.data(ctx)->loc(), core::errors::Resolver::RecursiveClassAlias)) {
e.setHeader("Class alias aliases to itself");
}
it.lhs.data(ctx)->resultType = 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));
core::SymbolRef uaSym =
ctx.state.enterMethodSymbol(core::Loc::none(), item.klass, core::Names::unresolvedAncestors());
core::TypePtr resultType = uaSym.data(ctx)->resultType;
if (!resultType) {
uaSym.data(ctx)->resultType = core::TupleType::build(ctx, {ancestorType});
} else if (auto tt = core::cast_type<core::TupleType>(resultType.get())) {
tt->elems.push_back(ancestorType);
} else {
ENFORCE(false);
}
}
static core::SymbolRef stubSymbolForAncestor(const AncestorResolutionItem &item) {
if (item.isSuperclass) {
return core::Symbols::StubSuperClass();
} else {
return core::Symbols::StubMixin();
}
}
static bool resolveAncestorJob(core::MutableContext ctx, AncestorResolutionItem &job, bool lastRun) {
auto ancestorSym = job.ancestor->symbol;
if (!ancestorSym.exists()) {
return false;
}
core::SymbolRef resolved;
if (ancestorSym.data(ctx)->isTypeAlias()) {
if (!lastRun) {
return false;
}
if (auto e = ctx.state.beginError(job.ancestor->loc, core::errors::Resolver::DynamicSuperclass)) {
e.setHeader("Superclasses and mixins may not be type aliases");
}
resolved = stubSymbolForAncestor(job);
} else {
resolved = ancestorSym.data(ctx)->dealias(ctx);
}
if (!resolved.data(ctx)->isClassOrModule()) {
if (!lastRun) {
return false;
}
if (auto e = ctx.state.beginError(job.ancestor->loc, core::errors::Resolver::DynamicSuperclass)) {
e.setHeader("Superclasses and mixins may only use class aliases like `{}`", "A = Integer");
}
resolved = stubSymbolForAncestor(job);
}
if (resolved == job.klass) {
if (auto e = ctx.state.beginError(job.ancestor->loc, core::errors::Resolver::CircularDependency)) {
e.setHeader("Circular dependency: `{}` is a parent of itself", job.klass.data(ctx)->show(ctx));
e.addErrorLine(resolved.data(ctx)->loc(), "Class definition");
}
resolved = stubSymbolForAncestor(job);
} else if (resolved.data(ctx)->derivesFrom(ctx, job.klass)) {
if (auto e = ctx.state.beginError(job.ancestor->loc, core::errors::Resolver::CircularDependency)) {
e.setHeader("Circular dependency: `{}` and `{}` are declared as parents of each other",
job.klass.data(ctx)->show(ctx), resolved.data(ctx)->show(ctx));
e.addErrorLine(job.klass.data(ctx)->loc(), "One definition");
e.addErrorLine(resolved.data(ctx)->loc(), "Other definition");
}
resolved = stubSymbolForAncestor(job);
}
bool ancestorPresent = true;
if (job.isSuperclass) {
if (resolved == 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() == resolved) {
job.klass.data(ctx)->setSuperClass(resolved);
} else {
if (auto e = ctx.state.beginError(job.ancestor->loc, core::errors::Resolver::RedefinitionOfParents)) {
e.setHeader("Parent of class `{}` redefined from `{}` to `{}`", job.klass.data(ctx)->show(ctx),
job.klass.data(ctx)->superClass().show(ctx), resolved.show(ctx));
}
}
} else {
ENFORCE(resolved.data(ctx)->isClassOrModule());
job.klass.data(ctx)->addMixin(resolved);
}
if (ancestorPresent) {
saveAncestorTypeForHashing(ctx, job);
}
return true;
}
static void tryRegisterSealedSubclass(core::MutableContext ctx, AncestorResolutionItem &job) {
ENFORCE(job.ancestor->symbol.exists(), "Ancestor must exist, or we can't check whether it's sealed.");
auto ancestorSym = job.ancestor->symbol.data(ctx)->dealias(ctx);
if (!ancestorSym.data(ctx)->isClassOrModuleSealed()) {
return;
}
Timer timeit(ctx.state.tracer(), "resolver.registerSealedSubclass");
ancestorSym.data(ctx)->recordSealedSubclass(ctx, job.klass);
}
void transformAncestor(core::Context ctx, core::SymbolRef klass, unique_ptr<ast::Expression> &ancestor,
bool isSuperclass = false) {
if (auto *constScope = ast::cast_tree<ast::UnresolvedConstantLit>(ancestor.get())) {
unique_ptr<ast::UnresolvedConstantLit> inner(constScope);
ancestor.release();
auto scopeTmp = nesting_;
if (isSuperclass) {
nesting_ = nesting_->parent;
}
ancestor = postTransformUnresolvedConstantLit(ctx, std::move(inner));
nesting_ = scopeTmp;
}
AncestorResolutionItem job;
job.klass = klass;
job.isSuperclass = isSuperclass;
if (auto *cnst = ast::cast_tree<ast::ConstantLit>(ancestor.get())) {
auto sym = cnst->symbol;
if (sym.exists() && sym.data(ctx)->isTypeAlias()) {
if (auto e = ctx.state.beginError(cnst->loc, core::errors::Resolver::DynamicSuperclass)) {
e.setHeader("Superclasses and mixins may not be type aliases");
}
return;
}
ENFORCE(sym.exists() || ast::isa_tree<ast::ConstantLit>(cnst->original->scope.get()) ||
ast::isa_tree<ast::EmptyTree>(cnst->original->scope.get()));
if (isSuperclass && sym == core::Symbols::todo()) {
return;
}
job.ancestor = cnst;
} else if (ancestor->isSelfReference()) {
auto loc = ancestor->loc;
auto enclosingClass = ctx.owner.data(ctx)->enclosingClass(ctx);
auto nw = ast::MK::UnresolvedConstant(loc, std::move(ancestor), enclosingClass.data(ctx)->name);
auto out = make_unique<ast::ConstantLit>(loc, enclosingClass, std::move(nw));
job.ancestor = out.get();
ancestor = std::move(out);
} else if (ast::isa_tree<ast::EmptyTree>(ancestor.get())) {
return;
} else {
ENFORCE(false, "Namer should have not allowed this");
}
todoAncestors_.emplace_back(std::move(job));
}
public:
ResolveConstantsWalk(core::Context ctx) : nesting_(make_unique<Nesting>(nullptr, core::Symbols::root())) {}
unique_ptr<ast::ClassDef> preTransformClassDef(core::Context ctx, unique_ptr<ast::ClassDef> original) {
nesting_ = make_unique<Nesting>(std::move(nesting_), original->symbol);
return original;
}
unique_ptr<ast::Expression> postTransformUnresolvedConstantLit(core::Context ctx,
unique_ptr<ast::UnresolvedConstantLit> c) {
if (auto *constScope = ast::cast_tree<ast::UnresolvedConstantLit>(c->scope.get())) {
unique_ptr<ast::UnresolvedConstantLit> inner(constScope);
c->scope.release();
c->scope = postTransformUnresolvedConstantLit(ctx, std::move(inner));
}
auto loc = c->loc;
auto out = make_unique<ast::ConstantLit>(loc, core::Symbols::noSymbol(), std::move(c));
ResolutionItem job{nesting_, out.get()};
if (resolveJob(ctx, job)) {
categoryCounterInc("resolve.constants.nonancestor", "firstpass");
} else {
todo_.emplace_back(std::move(job));
}
return out;
}
unique_ptr<ast::Expression> postTransformClassDef(core::Context ctx, unique_ptr<ast::ClassDef> original) {
core::SymbolRef klass = original->symbol;
for (auto &ancst : original->ancestors) {
bool isSuperclass = (original->kind == ast::Class && &ancst == &original->ancestors.front() &&
!klass.data(ctx)->isSingletonClass(ctx));
transformAncestor(isSuperclass ? ctx : ctx.withOwner(klass), klass, ancst, isSuperclass);
}
auto singleton = klass.data(ctx)->lookupSingletonClass(ctx);
for (auto &ancst : original->singletonAncestors) {
ENFORCE(singleton.exists());
transformAncestor(ctx.withOwner(klass), singleton, ancst);
}
nesting_ = nesting_->parent;
return original;
}
unique_ptr<ast::Expression> postTransformAssign(core::Context ctx, unique_ptr<ast::Assign> asgn) {
auto *id = ast::cast_tree<ast::ConstantLit>(asgn->lhs.get());
if (id == nullptr || !id->symbol.dataAllowingNone(ctx)->isStaticField()) {
return asgn;
}
auto *send = ast::cast_tree<ast::Send>(asgn->rhs.get());
if (send != nullptr && send->fun == core::Names::typeAlias()) {
if (!send->block) {
// if we have an invalid (i.e. nullary) call to TypeAlias, then we'll treat it as a type alias for
// Untyped and report an error here: otherwise, we end up in a state at the end of constant resolution
// that won't match our expected invariants (and in fact will fail our sanity checks)
// auto temporaryUntyped = ast::MK::Untyped(asgn->lhs.get()->loc);
auto temporaryUntyped = ast::MK::Block0(asgn->lhs.get()->loc, ast::MK::Untyped(asgn->lhs.get()->loc));
send->block = std::move(temporaryUntyped);
// because we're synthesizing a fake "untyped" here and actually adding it to the AST, we won't report
// an arity mismatch for `T.untyped` in the future, so report the arity mismatch now
if (auto e = ctx.state.beginError(send->loc, core::errors::Resolver::InvalidTypeAlias)) {
e.setHeader("No block given to `{}`", "T.type_alias");
CorrectTypeAlias::eagerToLazy(ctx, e, send);
}
}
auto typeAliasItem = TypeAliasResolutionItem{id->symbol, send->block->body.get()};
this->todoTypeAliases_.emplace_back(std::move(typeAliasItem));
// We also enter a ResolutionItem for the lhs of a type alias so even if the type alias isn't used,
// we'll still emit a warning when the rhs of a type alias doesn't resolve.
auto item = ResolutionItem{nesting_, id};
this->todo_.emplace_back(std::move(item));
return asgn;
}
auto *rhs = ast::cast_tree<ast::ConstantLit>(asgn->rhs.get());
if (rhs == nullptr) {
return asgn;
}
auto item = ClassAliasResolutionItem{id->symbol, rhs};
// TODO(perf) currently, by construction the last item in resolve todo list is the one this alias depends on
// We may be able to get some perf by using this
this->todoClassAliases_.emplace_back(std::move(item));
return asgn;
}
static bool compareLocs(core::Context ctx, core::Loc lhs, core::Loc rhs) {
core::StrictLevel left = core::StrictLevel::Strong;
core::StrictLevel right = core::StrictLevel::Strong;
if (lhs.file().exists()) {
left = lhs.file().data(ctx).strictLevel;
}
if (rhs.file().exists()) {
right = rhs.file().data(ctx).strictLevel;
}
if (left != right) {
return right < left;
}
if (lhs.file() != rhs.file()) {
return lhs.file() < rhs.file();
}
if (lhs.beginPos() != rhs.beginPos()) {
return lhs.beginPos() < rhs.beginPos();
}
return lhs.endPos() < rhs.endPos();
}
static int constantDepth(ast::ConstantLit *exp) {
int depth = 0;
ast::ConstantLit *scope = exp;
while (scope->original && (scope = ast::cast_tree<ast::ConstantLit>(scope->original->scope.get()))) {
depth += 1;
}
return depth;
}
struct ResolveWalkResult {
vector<ResolutionItem> todo_;
vector<AncestorResolutionItem> todoAncestors_;
vector<ClassAliasResolutionItem> todoClassAliases_;
vector<TypeAliasResolutionItem> todoTypeAliases_;
vector<ast::ParsedFile> trees;
};
static bool locCompare(core::Loc lhs, core::Loc rhs) {
if (lhs.file() < rhs.file()) {
return true;
}
if (lhs.file() > rhs.file()) {
return false;
}
if (lhs.beginPos() < rhs.beginPos()) {
return true;
}
if (lhs.beginPos() > rhs.beginPos()) {
return false;
}
return lhs.endPos() < rhs.endPos();
}
static vector<ast::ParsedFile> resolveConstants(core::MutableContext ctx, vector<ast::ParsedFile> trees,
WorkerPool &workers) {
Timer timeit(ctx.state.tracer(), "resolver.resolve_constants");
core::Context ictx = ctx;
auto resultq = make_shared<BlockingBoundedQueue<ResolveWalkResult>>(trees.size());
auto fileq = make_shared<ConcurrentBoundedQueue<ast::ParsedFile>>(trees.size());
for (auto &tree : trees) {
fileq->push(move(tree), 1);
}
workers.multiplexJob("resolveConstantsWalk", [ictx, fileq, resultq]() {
Timer timeit(ictx.state.tracer(), "ResolveConstantsWorker");
ResolveConstantsWalk constants(ictx);
vector<ast::ParsedFile> partiallyResolvedTrees;
ast::ParsedFile job;
for (auto result = fileq->try_pop(job); !result.done(); result = fileq->try_pop(job)) {
if (result.gotItem()) {
job.tree = ast::TreeMap::apply(ictx, constants, std::move(job.tree));
partiallyResolvedTrees.emplace_back(move(job));
}
}
if (!partiallyResolvedTrees.empty()) {
ResolveWalkResult result{move(constants.todo_), move(constants.todoAncestors_),
move(constants.todoClassAliases_), move(constants.todoTypeAliases_),
move(partiallyResolvedTrees)};
auto computedTreesCount = result.trees.size();
resultq->push(move(result), computedTreesCount);
}
});
trees.clear();
vector<ResolutionItem> todo;
vector<AncestorResolutionItem> todoAncestors;
vector<ClassAliasResolutionItem> todoClassAliases;
vector<TypeAliasResolutionItem> todoTypeAliases;
{
ResolveWalkResult threadResult;
for (auto result = resultq->wait_pop_timed(threadResult, WorkerPool::BLOCK_INTERVAL(), ctx.state.tracer());
!result.done();
result = resultq->wait_pop_timed(threadResult, WorkerPool::BLOCK_INTERVAL(), ctx.state.tracer())) {
if (result.gotItem()) {
todo.insert(todo.end(), make_move_iterator(threadResult.todo_.begin()),
make_move_iterator(threadResult.todo_.end()));
todoAncestors.insert(todoAncestors.end(), make_move_iterator(threadResult.todoAncestors_.begin()),
make_move_iterator(threadResult.todoAncestors_.end()));
todoClassAliases.insert(todoClassAliases.end(),
make_move_iterator(threadResult.todoClassAliases_.begin()),
make_move_iterator(threadResult.todoClassAliases_.end()));
todoTypeAliases.insert(todoTypeAliases.end(),
make_move_iterator(threadResult.todoTypeAliases_.begin()),
make_move_iterator(threadResult.todoTypeAliases_.end()));
trees.insert(trees.end(), make_move_iterator(threadResult.trees.begin()),
make_move_iterator(threadResult.trees.end()));
}
}
}
fast_sort(todo,
[](const auto &lhs, const auto &rhs) -> bool { return locCompare(lhs.out->loc, rhs.out->loc); });
fast_sort(todoAncestors, [](const auto &lhs, const auto &rhs) -> bool {
return locCompare(lhs.ancestor->loc, rhs.ancestor->loc);
});
fast_sort(todoClassAliases,
[](const auto &lhs, const auto &rhs) -> bool { return locCompare(lhs.rhs->loc, rhs.rhs->loc); });
fast_sort(todoTypeAliases,
[](const auto &lhs, const auto &rhs) -> bool { return locCompare(lhs.rhs->loc, rhs.rhs->loc); });
fast_sort(trees,
[](const auto &lhs, const auto &rhs) -> bool { return locCompare(lhs.tree->loc, rhs.tree->loc); });
Timer timeit1(ctx.state.tracer(), "resolver.resolve_constants.fixed_point");
bool progress = true;
bool first = true; // we need to run at least once to force class aliases and type aliases
while (progress && (first || !todo.empty() || !todoAncestors.empty())) {
first = false;
counterInc("resolve.constants.retries");
{
Timer timeit(ctx.state.tracer(), "resolver.resolve_constants.fixed_point.ancestors");
// This is an optimization. The order should not matter semantically
// We try to resolve most ancestors second because this makes us much more likely to resolve everything
// else.
int origSize = todoAncestors.size();
auto it =
remove_if(todoAncestors.begin(), todoAncestors.end(), [ctx](AncestorResolutionItem &job) -> bool {
auto resolved = resolveAncestorJob(ctx, job, false);
if (resolved) {
tryRegisterSealedSubclass(ctx, job);
}
return resolved;
});
todoAncestors.erase(it, todoAncestors.end());
progress = (origSize != todoAncestors.size());
categoryCounterAdd("resolve.constants.ancestor", "retry", origSize - todoAncestors.size());
}
{
Timer timeit(ctx.state.tracer(), "resolver.resolve_constants.fixed_point.constants");
int origSize = todo.size();
auto it = remove_if(todo.begin(), todo.end(),
[ctx](ResolutionItem &job) -> bool { return resolveJob(ctx, job); });
todo.erase(it, todo.end());
progress = progress || (origSize != todo.size());
categoryCounterAdd("resolve.constants.nonancestor", "retry", origSize - todo.size());
}
{
Timer timeit(ctx.state.tracer(), "resolver.resolve_constants.fixed_point.class_aliases");
// This is an optimization. The order should not matter semantically
// This is done as a "pre-step" because the first iteration of this effectively ran in TreeMap.
// every item in todoClassAliases implicitly depends on an item in item in todo
// there would be no point in running the todoClassAliases step before todo
int origSize = todoClassAliases.size();
auto it =
remove_if(todoClassAliases.begin(), todoClassAliases.end(),
[ctx](ClassAliasResolutionItem &it) -> bool { return resolveClassAliasJob(ctx, it); });
todoClassAliases.erase(it, todoClassAliases.end());
progress = progress || (origSize != todoClassAliases.size());
categoryCounterAdd("resolve.constants.aliases", "retry", origSize - todoClassAliases.size());
}
{
Timer timeit(ctx.state.tracer(), "resolver.resolve_constants.fixed_point.type_aliases");
int origSize = todoTypeAliases.size();
auto it =
remove_if(todoTypeAliases.begin(), todoTypeAliases.end(),
[ctx](TypeAliasResolutionItem &it) -> bool { return resolveTypeAliasJob(ctx, it); });
todoTypeAliases.erase(it, todoTypeAliases.end());
progress = progress || (origSize != todoTypeAliases.size());
categoryCounterAdd("resolve.constants.typealiases", "retry", origSize - todoTypeAliases.size());
}
}
// We can no longer resolve new constants. All the code below reports errors
categoryCounterAdd("resolve.constants.nonancestor", "failure", todo.size());
categoryCounterAdd("resolve.constants.ancestor", "failure", todoAncestors.size());
/*
* Sort errors so we choose a deterministic error to report for each
* missing constant:
*
* - Visit the strictest files first. If we were to report an error in
* an untyped file it would get suppressed, even if the same error
* also appeared in a typed file.
*
* - Break ties within strictness levels by file ID. We populate file
* IDs in the order we are given files on the command-line, so this
* means users see the error on the first file they provided.
*
* - Within a file, report the first occurrence.
*/
fast_sort(todo, [ctx](const auto &lhs, const auto &rhs) -> bool {
if (lhs.out->loc == rhs.out->loc) {
return constantDepth(lhs.out) < constantDepth(rhs.out);
}
return compareLocs(ctx, lhs.out->loc, rhs.out->loc);
});
fast_sort(todoAncestors, [ctx](const auto &lhs, const auto &rhs) -> bool {
if (lhs.ancestor->loc == rhs.ancestor->loc) {
return constantDepth(lhs.ancestor) < constantDepth(rhs.ancestor);
}
return compareLocs(ctx, lhs.ancestor->loc, rhs.ancestor->loc);
});
// Note that this is missing alias stubbing, thus resolveJob needs to be able to handle missing aliases.
{
Timer timeit(ctx.state.tracer(), "resolver.resolve_constants.errors");
int i = -1;
for (auto &job : todo) {
i++;
// Only give suggestions for the first 10, because fuzzy suggestions are expensive.
auto suggestDidYouMean = i < 10;
constantResolutionFailed(ctx, job, suggestDidYouMean);
}
for (auto &job : todoAncestors) {
auto resolved = resolveAncestorJob(ctx, job, true);
if (!resolved) {
resolved = resolveAncestorJob(ctx, job, true);
ENFORCE(resolved);
}
}
}
return trees;
}
};
class ResolveTypeParamsWalk {
// A type_member, type_template, or T.type_alias that needs to have types
// resolved.
struct ResolveAssignItem {
// The owner at the time the assignment was encountered.
core::SymbolRef owner;
// The symbol being populated, either a type alias or an individual
// type_member.
core::SymbolRef lhs;
// The type_member, type_template, or type_alias of the RHS.
ast::Send *rhs;
// The symbols that this alias depends on that have type members.
vector<core::SymbolRef> dependencies;
};
vector<ResolveAssignItem> todoAssigns_;
// State for tracking type usage inside of a type alias or type member
// definition
bool trackDependencies_ = false;
vector<bool> classOfDepth_;
vector<core::SymbolRef> dependencies_;
void extendClassOfDepth(unique_ptr<ast::Send> &send) {
if (trackDependencies_) {
classOfDepth_.emplace_back(isT(send->recv) && send->fun == core::Names::classOf());
}
}
static bool isT(unique_ptr<ast::Expression> &expr) {
auto *tMod = ast::cast_tree<ast::ConstantLit>(expr.get());
return tMod && tMod->symbol == core::Symbols::T();
}
static bool isTodo(core::TypePtr type) {
auto *todo = core::cast_type<core::ClassType>(type.get());
return todo != nullptr && todo->symbol == core::Symbols::todo();
}
static bool isLHSResolved(core::MutableContext ctx, core::SymbolRef sym) {
if (sym.data(ctx)->isTypeMember()) {
auto *lambdaParam = core::cast_type<core::LambdaParam>(sym.data(ctx)->resultType.get());
ENFORCE(lambdaParam != nullptr);
// both bounds are set to todo in the namer, so it's sufficient to
// just check one here.
return !isTodo(lambdaParam->lowerBound);
} else {
return !isTodo(sym.data(ctx)->resultType);
}
}
static bool isGenericResolved(core::MutableContext ctx, core::SymbolRef sym) {
if (sym.data(ctx)->isClassOrModule()) {
return absl::c_all_of(sym.data(ctx)->typeMembers(),
[&](core::SymbolRef tm) { return isLHSResolved(ctx, tm); });
} else {
return isLHSResolved(ctx, sym);
}
}
static void resolveTypeMember(core::MutableContext ctx, core::SymbolRef lhs, ast::Send *rhs) {
auto data = lhs.data(ctx);
auto owner = data->owner;
core::LambdaParam *parentType = nullptr;
auto parentMember = owner.data(ctx)->superClass().data(ctx)->findMember(ctx, data->name);
if (parentMember.exists()) {
if (parentMember.data(ctx)->isTypeMember()) {
parentType = core::cast_type<core::LambdaParam>(parentMember.data(ctx)->resultType.get());
ENFORCE(parentType != nullptr);
} else if (auto e = ctx.state.beginError(rhs->loc, core::errors::Resolver::ParentTypeBoundsMismatch)) {
const auto parentShow = parentMember.data(ctx)->show(ctx);
e.setHeader("`{}` is a type member but `{}` is not a type member", data->show(ctx), parentShow);
e.addErrorLine(parentMember.data(ctx)->loc(), "`{}` definition", parentShow);
}
}
// Initialize the resultType to a LambdaParam with default bounds
auto lambdaParam = core::make_type<core::LambdaParam>(lhs, core::Types::bottom(), core::Types::top());
data->resultType = lambdaParam;
auto *memberType = core::cast_type<core::LambdaParam>(lambdaParam.get());
// When no args are supplied, this implies that the upper and lower
// bounds of the type parameter are top and bottom.
ast::Hash *hash = nullptr;
if (rhs->args.size() == 1) {
hash = ast::cast_tree<ast::Hash>(rhs->args[0].get());
} else if (rhs->args.size() == 2) {
hash = ast::cast_tree<ast::Hash>(rhs->args[1].get());
}
if (hash) {
int i = -1;
for (auto &keyExpr : hash->keys) {
i++;
auto lit = ast::cast_tree<ast::Literal>(keyExpr.get());
if (lit && lit->isSymbol(ctx)) {
ParsedSig emptySig;
auto allowSelfType = true;
auto allowRebind = false;
auto allowTypeMember = false;
core::TypePtr resTy =
TypeSyntax::getResultType(ctx, *(hash->values[i]), emptySig,
TypeSyntaxArgs{allowSelfType, allowRebind, allowTypeMember, lhs});
switch (lit->asSymbol(ctx)._id) {
case core::Names::fixed()._id:
memberType->lowerBound = resTy;
memberType->upperBound = resTy;
break;
case core::Names::lower()._id:
memberType->lowerBound = resTy;