-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSCIPIndexer.cc
More file actions
1602 lines (1471 loc) · 72.9 KB
/
SCIPIndexer.cc
File metadata and controls
1602 lines (1471 loc) · 72.9 KB
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
// NOTE: Protobuf headers should go first since they use poisoned functions.
#include "proto/SCIP.pb.h"
#include <algorithm>
#include <fstream>
#include <iterator>
#include <memory>
#include <optional>
#include <string>
#include <cxxopts.hpp>
#include "absl/hash/hash.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/str_split.h"
#include "absl/synchronization/mutex.h"
#include "spdlog/fmt/fmt.h"
#include "ast/Trees.h"
#include "ast/treemap/treemap.h"
#include "cfg/CFG.h"
#include "common/EarlyReturnWithCode.h"
#include "common/common.h"
#include "common/sort/sort.h"
#include "core/Error.h"
#include "core/ErrorQueue.h"
#include "core/Loc.h"
#include "core/SymbolRef.h"
#include "core/Symbols.h"
#include "core/errors/scip_ruby.h"
#include "sorbet_version/sorbet_version.h"
#include "scip_indexer/Debug.h"
#include "scip_indexer/SCIPFieldResolve.h"
#include "scip_indexer/SCIPGemMetadata.h"
#include "scip_indexer/SCIPIndexer.h"
#include "scip_indexer/SCIPProtoExt.h"
#include "scip_indexer/SCIPSymbolRef.h"
#include "scip_indexer/SCIPUtils.h"
using namespace std;
/** 32-bit FNV-1a hash function.
Technically, these hashes are only used for local variables, so if they change
from run-to-run, that is fine from a code navigation perspective. (It would be a
problem if they were use for cross-file navigation, but that's not applicable here.)
However, having stable hashes is useful for snapshot testing. Normally, we'd use
absl::Hash but it isn't guaranteed to be stable across runs.
*/
static uint32_t fnv1a_32(const string &s) {
uint32_t h = 2166136261;
for (auto c : s) {
h ^= uint32_t(c);
h *= 16777619;
}
return h;
}
const char scip_ruby_version[] = "0.4.7";
// Last updated: https://github.com/sourcegraph/scip-ruby/pull/217
const char scip_ruby_sync_upstream_sorbet_sha[] = "0a7b175bc0bb41e2672369554f74364e83711a84";
namespace sorbet::scip_indexer {
// TODO(varun): This is an inline workaround for https://github.com/sorbet/sorbet/issues/5925
// I've not changed the main definition because I didn't bother to rerun the tests with the change.
static bool isTemporary(const core::GlobalState &gs, const core::LocalVariable &var) {
using namespace sorbet::core;
if (var.isSyntheticTemporary()) {
return true;
}
auto n = var._name;
return n == Names::blockPreCallTemp() || n == Names::blockTemp() || n == Names::blockPassTemp() ||
n == Names::blkArg() || n == Names::blockCall() || n == Names::blockBreakAssign() ||
n == Names::argPresent() || n == Names::forTemp() || n == Names::keepForCfgTemp() ||
// Insert checks because sometimes temporaries are initialized with a 0 unique value. 😬
n == Names::finalReturn() || n == NameRef::noName() || n == Names::blockCall() || n == Names::selfLocal() ||
n == Names::unconditional();
}
/// Utility type for carrying a local variable along with its owner.
struct OwnedLocal {
/// Parent method.
const core::SymbolRef owner;
/// Counter corresponding to the local's definition, unique within a method.
uint32_t counter;
/// Location for the occurrence.
core::LocOffsets offsets;
/// Display the OwnedLocal, suitable for use inside a SCIP index.
string toSCIPString(const core::GlobalState &gs, core::FileRef file) {
// 32-bits => if there are 10k methods in a single file, the chance of at least one
// colliding pair is about 1.1%, assuming even distribution. That seems OK.
return fmt::format("local {}${}", counter, ::fnv1a_32(owner.name(gs).show(gs)));
}
};
InlinedVector<int32_t, 4> fromSorbetLoc(const core::GlobalState &gs, core::Loc loc) {
ENFORCE(!loc.empty());
auto [start, end] = loc.position(gs);
ENFORCE(start.line <= INT32_MAX && start.column <= INT32_MAX);
ENFORCE(end.line <= INT32_MAX && end.column <= INT32_MAX);
InlinedVector<int32_t, 4> r;
r.push_back(start.line - 1);
r.push_back(start.column - 1);
if (start.line != end.line) {
r.push_back(end.line - 1);
} else {
ENFORCE(start.column < end.column);
}
r.push_back(end.column - 1);
return r;
}
core::Loc trimColonColonPrefix(const core::GlobalState &gs, core::Loc baseLoc) {
ENFORCE(!baseLoc.empty());
auto source = baseLoc.source(gs);
if (!source.has_value()) {
return baseLoc;
}
auto colonColonOffsetFromRangeStart = source.value().rfind("::"sv);
if (colonColonOffsetFromRangeStart == string::npos) {
return baseLoc;
}
auto occLen = source.value().length() - (colonColonOffsetFromRangeStart + 2);
ENFORCE(occLen < baseLoc.endPos());
auto newBeginLoc = baseLoc.endPos() - uint32_t(occLen);
ENFORCE(newBeginLoc > baseLoc.beginPos());
return core::Loc(baseLoc.file(), {.beginLoc = newBeginLoc, .endLoc = baseLoc.endPos()});
}
enum class Emitted {
Now,
Earlier,
};
/// Per-thread state storing information to be emitting in a SCIP index.
///
/// The states are implicitly merged at the time of emitting the index.
///
/// WARNING: A SCIPState value will in general be reused across files,
/// so caches should generally directly or indirectly include a FileRef
/// as part of key (e.g. via core::Loc).
class SCIPState {
UnorderedMap<UntypedGenericSymbolRef, string> symbolStringCache;
/// Cache of occurrences for locals that have been emitted in this function.
///
/// Note that the SymbolRole is a part of the key too, because we can
/// have a read-reference and write-reference at the same location
/// (we don't merge those for now).
///
/// There are some edge cases when different locals (i.e. different counters)
/// have the same role and the same location. For example,
/// 1. When a function uses ... for its arguments.
/// 2. Some situations around types in signatures (not exactly sure when,
/// but these were discovered on a private codebase)
///
/// That's why the value is an InlinedVector rather than a single uint32_t.
UnorderedMap<pair<core::LocOffsets, /*SymbolRole*/ int32_t>, InlinedVector<uint32_t, 1>> localOccurrenceCache;
// ^ The 'value' in the map is purely for sanity-checking. It's a bit
// cumbersome to conditionalize the type to be a set in non-debug and
// map in debug, so keeping it a map.
/// Analogous to localOccurrenceCache but for symbols.
///
/// This is mainly present to avoid emitting duplicate occurrences
/// for DSL-like constructs like prop/def_delegator.
UnorderedSet<tuple<GenericSymbolRef, core::Loc, /*SymbolRole*/ int32_t>> symbolOccurrenceCache;
/// Map to keep track of symbols which lack a direct definition,
/// and are indirectly defined by another symbol through a Relationship.
///
/// Ideally, 'UntypedGenericSymbolRef' would not be duplicated across files
/// but we keep these separate per file to avoid weirdness where logically
/// different but identically named classes exist in different files.
UnorderedMap<core::FileRef, UnorderedSet<UntypedGenericSymbolRef>> potentialRefOnlySymbols;
// ^ Naively, I would think that that shouldn't happen because we don't traverse
// rewriter-synthesized method bodies, but it does seem to happen.
//
// Also, you would think that emittedSymbols below would handle this.
// But it doesn't, for some reason... 🤔
//
// FIXME(varun): This seems redundant, get rid of it.
GemMapping gemMap;
public:
UnorderedMap<core::FileRef, vector<scip::Occurrence>> occurrenceMap;
/// Set containing symbols that have been emitted.
///
/// For every (f, s) in emittedSymbols, symbolMap[f] = SymbolInfo{s, ... other stuff}
/// and vice-versa. This is present to avoid emitting multiple SymbolInfos
/// for the same local variable if there are multiple definitions.
UnorderedSet<pair<core::FileRef, string>> emittedSymbols;
UnorderedMap<core::FileRef, vector<scip::SymbolInformation>> symbolMap;
/// Stores the relationships that apply to a field or a method.
///
/// Ideally, 'UntypedGenericSymbolRef' would not be duplicated across files
/// but we keep these separate per file to avoid weirdness where logically
/// different but identically named classes exist in different files.
UnorderedMap<core::FileRef, RelationshipsMap> relationshipsMap;
FieldResolver fieldResolver;
vector<scip::Document> documents;
vector<scip::SymbolInformation> externalSymbols;
public:
SCIPState(GemMapping gemMap)
: symbolStringCache(), localOccurrenceCache(), symbolOccurrenceCache(), potentialRefOnlySymbols(),
gemMap(gemMap), occurrenceMap(), emittedSymbols(), symbolMap(), documents(), externalSymbols() {}
~SCIPState() = default;
SCIPState(SCIPState &&) = default;
SCIPState &operator=(SCIPState &&other) = default;
// Make move-only to avoid accidental copy of large Documents/maps.
SCIPState(const SCIPState &) = delete;
SCIPState &operator=(const SCIPState &other) = delete;
void clearFunctionLocalCaches() {
this->localOccurrenceCache.clear();
}
/// If the returned value is as success, the pointer is non-null.
///
/// The argument symbol is used instead of recomputing from scratch if it is non-null.
utils::Result saveSymbolString(const core::GlobalState &gs, UntypedGenericSymbolRef symRef,
const scip::Symbol *symbol, std::string &output) {
auto pair = this->symbolStringCache.find(symRef);
if (pair != this->symbolStringCache.end()) {
// Yes, there is a "redundant" string copy here when we could "just"
// optimize it to return an interior pointer into the cache. However,
// that creates a footgun where this method cannot be safely called
// across invocations to non-const method calls on SCIPState.
output = pair->second;
return utils::Result::okValue();
}
absl::Status status;
if (symbol) {
status = utils::emitSymbolString(*symbol, output);
} else {
scip::Symbol symbol;
auto result = symRef.symbolForExpr(gs, this->gemMap, {}, symbol);
if (!result.ok()) {
return result;
}
status = utils::emitSymbolString(symbol, output);
}
if (!status.ok()) {
return utils::Result::statusValue(status);
}
symbolStringCache.insert({symRef, output});
return utils::Result::okValue();
}
private:
bool alreadyEmittedSymbolInfo(core::FileRef file, const string &symbolString) {
return this->emittedSymbols.contains({file, symbolString});
}
Emitted saveSymbolInfo(core::FileRef file, const string &symbolString, const SmallVec<string> &docs,
const SmallVec<scip::Relationship> &rels) {
if (this->alreadyEmittedSymbolInfo(file, symbolString)) {
return Emitted::Earlier;
}
scip::SymbolInformation symbolInfo;
symbolInfo.set_symbol(symbolString);
for (auto &doc : docs) {
symbolInfo.add_documentation(doc);
}
for (auto &rel : rels) {
*symbolInfo.add_relationships() = rel;
}
this->symbolMap[file].push_back(symbolInfo);
return Emitted::Now;
}
absl::Status saveDefinitionImpl(const core::GlobalState &gs, core::FileRef file, const string &symbolString,
core::Loc occLoc, const SmallVec<string> &docs,
const SmallVec<scip::Relationship> &rels) {
ENFORCE(!symbolString.empty());
occLoc = trimColonColonPrefix(gs, occLoc);
auto range = sorbet::scip_indexer::fromSorbetLoc(gs, occLoc);
if (range.size() == 4) {
// Don't emit multiline occurrences; generally this indicates a bug in the indexer.
// FIXME: This causes us to miss the definition for the initialize method
// in the struct.rb test case.
return absl::OkStatus();
}
auto emitted = this->saveSymbolInfo(file, symbolString, docs, rels);
scip::Occurrence occurrence;
occurrence.set_symbol(symbolString);
occurrence.set_symbol_roles(scip::SymbolRole::Definition);
for (auto val : range) {
occurrence.add_range(val);
}
switch (emitted) {
case Emitted::Now:
break;
case Emitted::Earlier:
for (auto &doc : docs) {
*occurrence.add_override_documentation() = doc;
}
}
this->occurrenceMap[file].push_back(occurrence);
// TODO(varun): When should we fill out the diagnostics and override_docs fields?
return absl::OkStatus();
}
void saveReferenceImpl(const core::GlobalState &gs, core::FileRef file, const string &symbolString,
const SmallVec<string> &overrideDocs, core::LocOffsets occLocOffsets, int32_t symbol_roles) {
ENFORCE(!symbolString.empty());
auto occLoc = trimColonColonPrefix(gs, core::Loc(file, occLocOffsets));
scip::Occurrence occurrence;
occurrence.set_symbol(symbolString);
occurrence.set_symbol_roles(symbol_roles);
auto range = sorbet::scip_indexer::fromSorbetLoc(gs, occLoc);
if (range.size() == 4) {
// Don't emit multiline occurrences; generally this indicates a bug in the indexer.
return;
}
for (auto val : range) {
occurrence.add_range(val);
}
for (auto &doc : overrideDocs) {
occurrence.add_override_documentation(doc);
}
this->occurrenceMap[file].push_back(occurrence);
// TODO(varun): When should we fill out the diagnostics field?
}
// Returns true if there was a cache hit.
//
// Otherwise, inserts the location into the cache and returns false.
bool cacheOccurrence(const core::GlobalState &gs, core::FileRef file, OwnedLocal occ, int32_t symbolRoles) {
// Optimization:
// Avoid emitting duplicate defs/refs for locals.
// This can happen with constructs like:
// z = if cond then expr else expr end
// When this is lowered to a CFG, we will end up with
// multiple bindings with the same LHS location.
//
// Repeated reads for the same occurrence can happen for rvalues too.
// If the compiler has proof that a scrutinee variable is not modified,
// each comparison in a case will perform a read.
// case x
// when 0 then <stuff>
// when 1 then <stuff>
// else <stuff>
// end
// The CFG for this involves two reads for x in calls to ==.
// (This wouldn't have happened if x was always stashed away into
// a temporary first, but the temporary only appears in the CFG if
// evaluating one of the cases has a chance to modify x.)
auto &counters = this->localOccurrenceCache[{occ.offsets, symbolRoles}]; // deliberate default init
// The vast majority of cases will be the empty vector or a single element
// vector, so using absl::c_find is fine here, as a longer linear search
// will be quite rare.
if (absl::c_find(counters, occ.counter) != counters.end()) {
return true;
}
counters.push_back(occ.counter);
return false;
}
bool cacheOccurrence(const core::GlobalState &gs, core::Loc loc, GenericSymbolRef sym, int32_t symbolRoles) {
// Optimization:
// Avoid emitting duplicate def/refs for symbols.
// This can happen with constructs like:
// prop :foo, String
// Without this optimization, there are 4 occurrences for String
// emitted for the same source range.
auto [_, inserted] = this->symbolOccurrenceCache.insert({sym, loc, symbolRoles});
return !inserted;
}
void saveParentRelationships(const core::GlobalState &gs, core::FileRef file, UntypedGenericSymbolRef untypedSymRef,
SmallVec<scip::Relationship> &rels) {
untypedSymRef.saveParentRelationships(gs, this->relationshipsMap[file], rels,
[this, &gs](UntypedGenericSymbolRef sym, std::string &out) {
auto status = this->saveSymbolString(gs, sym, nullptr, out);
ENFORCE(status.skip() || status.ok());
});
}
public:
absl::Status saveDefinition(const core::GlobalState &gs, core::FileRef file, OwnedLocal occ, core::TypePtr type) {
if (this->cacheOccurrence(gs, file, occ, scip::SymbolRole::Definition)) {
return absl::OkStatus();
}
SmallVec<string> docStrings;
auto loc = core::Loc(file, occ.offsets);
if (type) {
auto var = loc.source(gs);
ENFORCE(var.has_value(), "Failed to find source text for definition of local variable");
docStrings.push_back(fmt::format("```ruby\n{} ({})\n```", var.value(), type.show(gs)));
}
return this->saveDefinitionImpl(gs, file, occ.toSCIPString(gs, file), loc, docStrings, {});
}
void saveAliasRelationship(const core::GlobalState &gs, UntypedGenericSymbolRef aliasedSymbol,
SmallVec<scip::Relationship> &rels) {
scip::Relationship rel;
rel.set_is_reference(true);
this->saveSymbolString(gs, aliasedSymbol, /*symbol*/ nullptr, *rel.mutable_symbol());
rels.push_back(move(rel));
}
// Save definition when you have a sorbet Symbol.
// Meant for methods, fields etc., but not local variables.
// TODO(varun): Should we always pass in the location instead of sometimes only?
absl::Status saveDefinition(const core::GlobalState &gs, core::FileRef file, GenericSymbolRef symRef,
optional<UntypedGenericSymbolRef> aliasedSymbol,
optional<core::LocOffsets> loc = nullopt) {
// In practice, there doesn't seem to be any situation which triggers
// a duplicate definition being emitted, so skip calling cacheOccurrence here.
auto occLoc = loc.has_value() ? core::Loc(file, loc.value()) : symRef.symbolLoc(gs);
scip::Symbol symbol;
auto untypedSymRef = symRef.withoutType();
auto result = untypedSymRef.symbolForExpr(gs, this->gemMap, occLoc, symbol);
if (result.skip()) {
return absl::OkStatus();
}
if (!result.ok()) {
return result.status();
}
std::string symbolString;
result = this->saveSymbolString(gs, untypedSymRef, &symbol, symbolString);
ENFORCE(!result.skip(), "Should've skipped earlier");
if (!result.ok()) {
return result.status();
}
SmallVec<string> docs;
symRef.saveDocStrings(gs, symRef.definitionType(), occLoc, docs);
SmallVec<scip::Relationship> rels;
this->saveParentRelationships(gs, file, symRef.withoutType(), rels);
if (aliasedSymbol.has_value()) {
this->saveAliasRelationship(gs, aliasedSymbol.value(), rels);
}
return this->saveDefinitionImpl(gs, file, symbolString, occLoc, docs, rels);
}
absl::Status saveReference(const core::GlobalState &gs, core::FileRef file, OwnedLocal occ,
optional<core::TypePtr> overrideType, int32_t symbol_roles) {
if (this->cacheOccurrence(gs, file, occ, symbol_roles)) {
return absl::OkStatus();
}
SmallVec<string> overrideDocs;
auto loc = core::Loc(file, occ.offsets);
if (overrideType.has_value()) {
ENFORCE(overrideType.value(), "forgot to fold type to nullopt earlier: {}\n{}\n", file.data(gs).path(),
core::Loc(file, occ.offsets).toString(gs));
auto var = loc.source(gs);
ENFORCE(var.has_value(), "Failed to find source text for definition of local variable");
overrideDocs.push_back(fmt::format("```ruby\n{} ({})\n```", var.value(), overrideType->show(gs)));
}
this->saveReferenceImpl(gs, file, occ.toSCIPString(gs, file), overrideDocs, occ.offsets, symbol_roles);
return absl::OkStatus();
}
absl::Status saveQualifierReferences(const core::GlobalState &gs, core::FileRef file,
ast::ExpressionPtr &constantLitExpr) {
auto *expr = &constantLitExpr;
while (auto *constantLit = ast::cast_tree<ast::ConstantLit>(*expr)) {
if (constantLit->symbol.exists() && constantLit->symbol.isClassOrModule() && constantLit->symbol.asClassOrModuleRef().exists()) {
core::Context ctx(gs, constantLit->symbol, file);
auto status = this->saveReference(ctx, GenericSymbolRef::classOrModule(constantLit->symbol),
/*overrideType*/ std::nullopt, constantLit->loc, 0);
if (!status.ok()) {
return status;
}
}
if (auto *unresolved = ast::cast_tree<ast::UnresolvedConstantLit>(constantLit->original)) {
expr = &unresolved->scope;
continue;
}
break;
}
return absl::OkStatus();
}
absl::Status saveReference(const core::Context &ctx, GenericSymbolRef symRef, optional<core::TypePtr> overrideType,
core::LocOffsets occLoc, int32_t symbol_roles) {
// HACK: Reduce noise due to <static-init> in snapshots.
if (ctx.owner.name(ctx) == core::Names::staticInit()) {
if (symRef.isSorbetInternalClassOrMethod(ctx)) {
return absl::OkStatus();
}
}
auto loc = core::Loc(ctx.file, occLoc);
if (this->cacheOccurrence(ctx, loc, symRef, symbol_roles)) {
return absl::OkStatus();
}
auto &gs = ctx.state;
auto file = ctx.file;
std::string symbolString;
auto result = this->saveSymbolString(gs, symRef.withoutType(), nullptr, symbolString);
if (result.skip()) {
return absl::OkStatus();
}
if (!result.ok()) {
return result.status();
}
SmallVec<string> overrideDocs{};
using Kind = GenericSymbolRef::Kind;
switch (symRef.kind()) {
case Kind::ClassOrModule:
case Kind::Method:
break;
case Kind::Field:
if (overrideType.has_value()) {
symRef.saveDocStrings(gs, overrideType.value(), loc, overrideDocs);
}
}
// If we haven't emitted a SymbolInfo yet, record that we may want to emit
// a SymbolInfo in the future, if it isn't emitted later in this file.
if (!this->emittedSymbols.contains({file, symbolString})) {
auto &rels = this->relationshipsMap[file];
if (rels.contains(symRef.withoutType())) {
this->potentialRefOnlySymbols[file].insert(symRef.withoutType());
}
}
this->saveReferenceImpl(gs, file, symbolString, overrideDocs, occLoc, symbol_roles);
return absl::OkStatus();
}
void finalizeRefOnlySymbolInfos(const core::GlobalState &gs, core::FileRef file) {
auto &potentialSyms = this->potentialRefOnlySymbols[file];
std::string symbolString;
for (auto symRef : potentialSyms) {
if (!this->saveSymbolString(gs, symRef, nullptr, symbolString).ok()) {
continue;
}
// Avoid calling saveRelationships if we already emitted this.
// saveSymbolInfo does this check too, so it isn't strictly needed.
if (this->alreadyEmittedSymbolInfo(file, symbolString)) {
continue;
}
SmallVec<scip::Relationship> rels;
this->saveParentRelationships(gs, file, symRef, rels);
// For ref-only symbols, since we're lacking a direct definition,
// there's no way to determine if the actual definition has an alias or not.
// So don't call saveAliasRelationship.
this->saveSymbolInfo(file, symbolString, {}, rels);
}
}
void saveDocument(const core::GlobalState &gs, const core::FileRef file) {
scip::Document document;
// TODO(varun): Double-check the path code and maybe document it,
// to make sure its guarantees match what SCIP expects.
ENFORCE(file.exists());
auto path = file.data(gs).path();
ENFORCE(!path.empty());
if (path.front() == '/') {
document.set_relative_path(filesystem::path(path).lexically_relative(filesystem::current_path()));
} else {
document.set_relative_path(string(path));
}
auto occurrences = this->occurrenceMap.find(file);
if (occurrences != this->occurrenceMap.end()) {
for (auto &occurrence : occurrences->second) {
*document.add_occurrences() = move(occurrence);
}
fast_sort(*document.mutable_occurrences(),
[](const auto &o1, const auto &o2) -> bool { return scip::compareOccurrence(o1, o2) < 0; });
this->occurrenceMap.erase(file);
}
auto symbols = this->symbolMap.find(file);
if (symbols != this->symbolMap.end()) {
for (auto &symbol : symbols->second) {
*document.add_symbols() = move(symbol);
}
fast_sort(*document.mutable_symbols(), [](const auto &s1, const auto &s2) -> bool {
return scip::compareSymbolInformation(s1, s2) < 0;
});
this->symbolMap.erase(file);
}
this->documents.push_back(move(document));
}
};
string format_ancestry(const core::GlobalState &gs, core::SymbolRef sym) {
UnorderedSet<core::SymbolRef> visited;
auto i = 0;
std::ostringstream out;
while (sym.exists() && !visited.contains(sym)) {
out << fmt::format("#{}{}{}\n", string(i * 2, ' '), i == 0 ? "" : "<- ", sym.name(gs).toString(gs));
visited.insert(sym);
sym = sym.owner(gs);
i++;
}
return out.str();
}
// Loosely inspired by AliasesAndKeywords in IREmitterContext.cc
class AliasMap final {
public:
using Impl = UnorderedMap<cfg::LocalRef, tuple<GenericSymbolRef, core::LocOffsets, /*emitted*/ bool>>;
private:
Impl map;
AliasMap(const AliasMap &) = delete;
AliasMap &operator=(const AliasMap &) = delete;
public:
AliasMap() = default;
void populate(const core::Context &ctx, const cfg::CFG &cfg, FieldResolver &fieldResolver,
RelationshipsMap &relMap) {
this->map = {};
auto &gs = ctx.state;
auto method = ctx.owner;
const auto klass = method.owner(gs);
// Make sure that the offsets we store here match the offsets we use
// in saveDefinition/saveReference.
auto trim = [&](core::LocOffsets loc) -> core::LocOffsets {
return trimColonColonPrefix(gs, core::Loc(ctx.file, loc)).offsets();
};
for (auto &bb : cfg.basicBlocks) {
for (auto &bind : bb->exprs) {
auto *instr = cfg::cast_instruction<cfg::Alias>(bind.value);
if (!instr) {
continue;
}
ENFORCE(this->map.find(bind.bind.variable) == this->map.end(),
"Overwriting an entry in the aliases map");
auto sym = instr->what;
if (!sym.exists() || sym == core::Symbols::Magic()) {
continue;
}
if (sym == core::Symbols::Magic_undeclaredFieldStub()) {
ENFORCE(!bind.loc.empty());
ENFORCE(klass.isClassOrModule());
auto fieldName = instr->name.shortName(gs);
if (!fieldName.empty() && fieldName[0] == '$') {
auto klass = core::Symbols::rootSingleton();
this->map.insert( // no trim(...) because globals can't have a :: prefix
{bind.bind.variable,
{GenericSymbolRef::field(klass, instr->name, bind.bind.type), bind.loc, false}});
continue;
}
// There are 4 possibilities here.
// 1. This is an undeclared field logically defined by `klass`.
// 2. This is declared in one of the modules transitively included by `klass`.
// 3. This is an undeclared field logically defined by one of `klass`'s ancestor classes.
// 4. This is an undeclared field logically defined by one of the modules transitively included by
// `klass`.
auto normalizedKlass = FieldResolver::normalizeParentForClassVar(gs, klass.asClassOrModuleRef(),
instr->name.shortName(gs));
auto namedSymRef = GenericSymbolRef::field(normalizedKlass, instr->name, bind.bind.type);
if (!relMap.contains(namedSymRef.withoutType())) {
auto result = fieldResolver.findUnresolvedFieldTransitive(
ctx, {ctx.file, klass.asClassOrModuleRef(), instr->name}, ctx.locAt(bind.loc));
ENFORCE(result.inherited.exists(),
"Returned non-existent class from findUnresolvedFieldTransitive with start={}, "
"field={}, file={}, loc={}",
klass.exists() ? klass.toStringFullName(gs) : "<non-existent>",
instr->name.exists() ? instr->name.toString(gs) : "<non-existent>",
ctx.file.data(gs).path(), ctx.locAt(bind.loc).showRawLineColumn(gs))
relMap.insert({namedSymRef.withoutType(), result});
}
// no trim(...) because undeclared fields shouldn't have ::
ENFORCE(trim(bind.loc) == bind.loc);
this->map.insert({bind.bind.variable, {namedSymRef, bind.loc, false}});
continue;
}
if (sym.isFieldOrStaticField()) {
// There are 3 possibilities here.
// 1. This is a reference to a non-instance non-class variable.
// 2. This is a reference to an instance or class variable declared by `klass`.
// 3. This is a reference to an instance or class variable declared by one of `klass`'s ancestor
// classes.
//
// For case 3, we want to emit a scip::Symbol that uses `klass`, not the ancestor.
ENFORCE(!bind.loc.empty());
auto name = instr->what.name(gs);
std::string_view nameText = name.shortName(gs);
auto symRef = GenericSymbolRef::field(instr->what.owner(gs), name, bind.bind.type);
if (!nameText.empty() && nameText[0] == '@') {
auto normalizedKlass =
FieldResolver::normalizeParentForClassVar(gs, klass.asClassOrModuleRef(), nameText);
symRef = GenericSymbolRef::field(normalizedKlass, name, bind.bind.type);
// Mimic the logic from the Magic_undeclaredFieldStub branch so that we don't
// miss out on relationships for declared symbols.
if (!relMap.contains(symRef.withoutType())) {
auto result = fieldResolver.findUnresolvedFieldTransitive(
ctx, {ctx.file, klass.asClassOrModuleRef(), name}, ctx.locAt(bind.loc));
result.inherited =
FieldResolver::normalizeParentForClassVar(gs, result.inherited, nameText);
relMap.insert({symRef.withoutType(), result});
}
}
this->map.insert({bind.bind.variable, {symRef, trim(bind.loc), false}});
continue;
}
// Outside of definition contexts for classes & modules,
// we emit a reference directly at the alias instruction
// instead of relying on usages. The reason for this is that
// in some cases, there may not be any usages.
//
// For example, if you have access to M::K, there will be no usage
// for the alias to M. I'm not 100% sure if this is a Sorbet bug
// where it is missing a keep_for_ide call (which we can rely on
// in definition contexts) of if this is deliberate.
if (sym.isClassOrModule()) {
auto loc = bind.loc;
if (!loc.exists() || loc.empty() || sym == core::Symbols::root() ||
sym == core::Symbols::T_Sig_WithoutRuntime()) {
// TODO(varun): Should we go through the list of all symbols and filter out
// all the 'internal' stuff here?
continue;
}
this->map.insert({bind.bind.variable, {GenericSymbolRef::classOrModule(sym), trim(loc), false}});
}
}
}
}
optional<pair<GenericSymbolRef, core::LocOffsets>> try_consume(cfg::LocalRef localRef) {
auto it = this->map.find(localRef);
if (it == this->map.end()) {
return nullopt;
}
auto &[namedSym, loc, emitted] = it->second;
emitted = true;
return {{namedSym, loc}};
}
optional<GenericSymbolRef> try_get(cfg::LocalRef localRef) {
auto it = this->map.find(localRef);
if (it == this->map.end()) {
return nullopt;
}
auto &[namedSym, loc, emitted] = it->second;
return namedSym;
}
string showRaw(const core::GlobalState &gs, core::FileRef file, const cfg::CFG &cfg) const {
return showMap(this->map, [&](const cfg::LocalRef &local, const auto &data) -> string {
auto symRef = get<0>(data);
auto offsets = get<1>(data);
auto emitted = get<2>(data);
return fmt::format("(local: {}) -> (symRef: {}, emitted: {}, loc: {})", local.toString(gs, cfg),
symRef.showRaw(gs), emitted ? "true" : "false", core::Loc(file, offsets).showRaw(gs));
});
}
void extract(Impl &out) {
out = std::move(this->map);
}
};
optional<core::TypePtr> computeOverrideType(core::TypePtr definitionType, core::TypePtr newType) {
if (!newType ||
// newType can be empty if an assignment is unreachable.
// Normally, someone would not commit unreachable code (because Sorbet would
// flag it as a hard error in CI), but it is better to be more permissive here.
definitionType == newType
// For definitions, this can happen if a variable is initialized to different
// types along different code paths. For references, this can happen through
// type-changing assignment.
) {
return nullopt;
}
return {newType};
}
core::ClassOrModuleRef computeReceiver(const core::GlobalState &gs, const cfg::Send &send) {
auto recvType = send.recv.type;
// TODO(varun): When is the isTemporary check going to succeed?
if (!recvType || !send.fun.exists() || !send.funLoc.exists() || send.funLoc.empty() ||
isTemporary(gs, core::LocalVariable(send.fun, 1))) {
return core::ClassOrModuleRef();
}
// NOTE(varun): Based on core::Types::getRepresentedClass. Trying to use it directly
// didn't quite work properly, but we might want to consolidate the implementation. I
// didn't quite understand the bit about attachedClass.
if (core::isa_type<core::ClassType>(recvType)) {
return core::cast_type_nonnull<core::ClassType>(recvType).symbol;
}
if (core::isa_type<core::AppliedType>(recvType)) {
// Triggered for a module nested inside a class
// as well as for class method calls. E.g.
// XYZ::MyKlass.myKlassMethod
auto recv = core::cast_type_nonnull<core::AppliedType>(recvType).klass;
if (recv.exists() && send.fun == core::Names::call()) {
// Special case to mimic code navigation from rewriter/Command.cc
// See associated test call.rb for details as well as GRAPH-895.
auto recvAttached = recv.data(gs)->attachedClass(gs);
if (recvAttached.exists()) {
auto super = recvAttached.data(gs)->superClass();
if (super.exists()) {
auto superData = super.data(gs);
if (superData->name == core::Names::Constants::Command() && superData->owner.exists() &&
superData->owner.data(gs)->name == core::Names::Constants::Opus()) {
return recvAttached;
}
}
}
}
return recv;
}
return core::ClassOrModuleRef();
}
/// Convenience type to handle CFG traversal and recording info in SCIPState.
///
/// Any caches that are not specific to a traversal should be added to SCIPState.
class CFGTraversal final {
// A map from each basic block to the locals in it.
//
// The locals may be coming from the parents, or they may be defined in the
// block. Locals coming from the parents may be in the form of basic block
// arguments or they may be "directly referenced."
//
// For example, if you have code like:
//
// def f(x):
// y = 0
// if cond:
// y = x + $z
//
// Then x and $z will be passed as arguments to the basic block for the
// true branch, whereas 'y' won't be. However, 'y' is still technically
// coming from the parent basic block, otherwise we'd end up marking the
// assignment as a definition instead of a (write) reference.
//
// At the start of the traversal of a basic block, the entry for a basic
// block is populated with the locals coming from the parents. Then,
// we traverse each instruction and populate it with the locals defined
// in the block.
UnorderedMap<const cfg::BasicBlock *, UnorderedSet<cfg::LocalRef>> blockLocals;
UnorderedMap<cfg::LocalRef, uint32_t> functionLocals;
// Map for storing the type at the original site of definition for a local variable.
//
// Performs the role of definitionType on GenericSymbolRef but for locals.
//
// NOTE: Subsequent references may have different types.
UnorderedMap<uint32_t, core::TypePtr> localDefinitionType;
AliasMap aliasMap;
// Local variable counter that is reset for every function.
uint32_t counter = 0;
SCIPState &scipState;
core::Context ctx;
public:
CFGTraversal(SCIPState &scipState, core::Context ctx)
: blockLocals(), functionLocals(), aliasMap(), scipState(scipState), ctx(ctx) {}
private:
uint32_t addLocal(const cfg::BasicBlock *bb, cfg::LocalRef localRef) {
this->counter++;
this->blockLocals[bb].insert(localRef);
this->functionLocals[localRef] = this->counter;
return this->counter;
}
static core::LocOffsets lhsLocIfPresent(const cfg::Binding &binding) {
auto lhsLoc = binding.bind.loc;
// FIXME(varun): Right now, the locations aren't being propagated for arguments correctly,
// so fallback instead of crashing.
return lhsLoc.exists() ? lhsLoc : binding.loc;
}
enum class ValueCategory : bool {
LValue,
RValue,
};
struct DefRefData {
ValueCategory valueCategory;
// Only applicable for lvalues.
optional<cfg::LocalRef> aliasRHS;
static const DefRefData RValue() {
return DefRefData{ValueCategory::RValue, /*aliasRHS*/ nullopt};
}
};
// Emit an occurrence for a local variable if applicable.
//
// Returns true if an occurrence was emitted.
//
// The type should be provided if we have an lvalue.
bool emitLocalOccurrence(const cfg::CFG &cfg, const cfg::BasicBlock *bb, cfg::LocalOccurrence local,
DefRefData defRefData, core::TypePtr type) {
auto loc = local.loc;
if (!loc.exists() || loc.empty()) {
// Safeguard against incorrect merges from upstream Sorbet, where
// some changes cause empty source locations to propagate down here.
//
// FIXME: Investigate which code patterns trigger this; normally
// locals should carry non-empty locations, but this was
// triggered on some private code.
return false;
}
auto localRef = local.variable;
auto localVar = localRef.data(cfg);
auto symRef = this->aliasMap.try_consume(localRef);
if (!symRef.has_value() && isTemporary(ctx.state, localVar)) {
return false;
}
scip::SymbolRole referenceRole;
bool isDefinition = false;
switch (defRefData.valueCategory) {
case ValueCategory::LValue: {
referenceRole = scip::SymbolRole::WriteAccess;
if (!this->functionLocals.contains(localRef)) {
// If we're seeing this for the first time in topological order,
// The current block must have a definition for the variable.
isDefinition = true;
auto id = this->addLocal(bb, localRef);
this->localDefinitionType[id] = type;
} else if (!this->blockLocals[bb].contains(localRef)) {
// The variable wasn't passed in as an argument, and hasn't already been recorded
// as a local in the block. So this must be a definition line.
isDefinition = true;
this->blockLocals[bb].insert(localRef);
}
break;
}
case ValueCategory::RValue: {
referenceRole = scip::SymbolRole::ReadAccess;
// Ill-formed code where we're trying to access a variable
// without setting it first. Emit a local as a best-effort.
// TODO(varun): Will Sorbet error out before we get here?
if (!this->functionLocals.contains(localRef)) {
this->addLocal(bb, localRef);
} else if (!this->blockLocals[bb].contains(localRef)) {
this->blockLocals[bb].insert(localRef);
}
break;
}
}
ENFORCE(this->functionLocals.contains(localRef), "should've added local earlier if it was missing");
absl::Status status;
auto &gs = this->ctx.state;
auto file = this->ctx.file;
if (symRef.has_value()) {
auto [namedSym, _] = symRef.value();
if (isDefinition) {
optional<UntypedGenericSymbolRef> aliasedSymbol = nullopt;
if (defRefData.aliasRHS.has_value()) {
if (auto symRef = this->aliasMap.try_get(defRefData.aliasRHS.value())) {
aliasedSymbol = symRef.value().withoutType();
} else {
spdlog::warn("Alias not found for {} in file: {}, code navigation across constant aliases may "
"not work correctly",
defRefData.aliasRHS->toString(gs, cfg), file.data(gs).path());
}
}
status = this->scipState.saveDefinition(gs, file, namedSym, aliasedSymbol, loc);
} else {
auto overrideType = computeOverrideType(namedSym.definitionType(), type);
status = this->scipState.saveReference(ctx, namedSym, overrideType, loc, referenceRole);
}
} else {
uint32_t localId = this->functionLocals[localRef];
auto it = this->localDefinitionType.find(localId);
optional<core::TypePtr> overrideType = nullopt;
if (it != this->localDefinitionType.end()) {
overrideType = computeOverrideType(it->second, type);
} else {
// TODO: It's unclear when exactly this case is triggered. Work around
// that by going for a best-effort solution.
if (type) {
overrideType = type;
}
}
if (isDefinition) {
status = this->scipState.saveDefinition(gs, file, OwnedLocal{this->ctx.owner, localId, loc}, type);
} else {
status = this->scipState.saveReference(gs, file, OwnedLocal{this->ctx.owner, localId, loc},