-
Notifications
You must be signed in to change notification settings - Fork 11.6k
/
XRefs.cpp
1986 lines (1819 loc) · 74.6 KB
/
XRefs.cpp
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
//===--- XRefs.cpp -----------------------------------------------*- C++-*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "XRefs.h"
#include "AST.h"
#include "CodeCompletionStrings.h"
#include "FindSymbols.h"
#include "FindTarget.h"
#include "ParsedAST.h"
#include "Protocol.h"
#include "Quality.h"
#include "Selection.h"
#include "SourceCode.h"
#include "URI.h"
#include "index/Index.h"
#include "index/Merge.h"
#include "index/Relation.h"
#include "index/SymbolLocation.h"
#include "support/Logger.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTTypeTraits.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Attrs.inc"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/Type.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TokenKinds.h"
#include "clang/Index/IndexDataConsumer.h"
#include "clang/Index/IndexSymbol.h"
#include "clang/Index/IndexingAction.h"
#include "clang/Index/IndexingOptions.h"
#include "clang/Index/USRGeneration.h"
#include "clang/Tooling/Syntax/Tokens.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
namespace clang {
namespace clangd {
namespace {
// Returns the single definition of the entity declared by D, if visible.
// In particular:
// - for non-redeclarable kinds (e.g. local vars), return D
// - for kinds that allow multiple definitions (e.g. namespaces), return nullptr
// Kinds of nodes that always return nullptr here will not have definitions
// reported by locateSymbolAt().
const NamedDecl *getDefinition(const NamedDecl *D) {
assert(D);
// Decl has one definition that we can find.
if (const auto *TD = dyn_cast<TagDecl>(D))
return TD->getDefinition();
if (const auto *VD = dyn_cast<VarDecl>(D))
return VD->getDefinition();
if (const auto *FD = dyn_cast<FunctionDecl>(D))
return FD->getDefinition();
// Objective-C classes can have three types of declarations:
//
// - forward declaration: @class MyClass;
// - true declaration (interface definition): @interface MyClass ... @end
// - true definition (implementation): @implementation MyClass ... @end
//
// Objective-C categories are extensions are on classes:
//
// - declaration: @interface MyClass (Ext) ... @end
// - definition: @implementation MyClass (Ext) ... @end
//
// With one special case, a class extension, which is normally used to keep
// some declarations internal to a file without exposing them in a header.
//
// - class extension declaration: @interface MyClass () ... @end
// - which really links to class definition: @implementation MyClass ... @end
if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(D))
return ID->getImplementation();
if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
if (CD->IsClassExtension()) {
if (const auto *ID = CD->getClassInterface())
return ID->getImplementation();
return nullptr;
}
return CD->getImplementation();
}
// Only a single declaration is allowed.
if (isa<ValueDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
isa<TemplateTemplateParmDecl>(D)) // except cases above
return D;
// Multiple definitions are allowed.
return nullptr; // except cases above
}
void logIfOverflow(const SymbolLocation &Loc) {
if (Loc.Start.hasOverflow() || Loc.End.hasOverflow())
log("Possible overflow in symbol location: {0}", Loc);
}
// Convert a SymbolLocation to LSP's Location.
// TUPath is used to resolve the path of URI.
// FIXME: figure out a good home for it, and share the implementation with
// FindSymbols.
llvm::Optional<Location> toLSPLocation(const SymbolLocation &Loc,
llvm::StringRef TUPath) {
if (!Loc)
return None;
auto Uri = URI::parse(Loc.FileURI);
if (!Uri) {
elog("Could not parse URI {0}: {1}", Loc.FileURI, Uri.takeError());
return None;
}
auto U = URIForFile::fromURI(*Uri, TUPath);
if (!U) {
elog("Could not resolve URI {0}: {1}", Loc.FileURI, U.takeError());
return None;
}
Location LSPLoc;
LSPLoc.uri = std::move(*U);
LSPLoc.range.start.line = Loc.Start.line();
LSPLoc.range.start.character = Loc.Start.column();
LSPLoc.range.end.line = Loc.End.line();
LSPLoc.range.end.character = Loc.End.column();
logIfOverflow(Loc);
return LSPLoc;
}
SymbolLocation toIndexLocation(const Location &Loc, std::string &URIStorage) {
SymbolLocation SymLoc;
URIStorage = Loc.uri.uri();
SymLoc.FileURI = URIStorage.c_str();
SymLoc.Start.setLine(Loc.range.start.line);
SymLoc.Start.setColumn(Loc.range.start.character);
SymLoc.End.setLine(Loc.range.end.line);
SymLoc.End.setColumn(Loc.range.end.character);
return SymLoc;
}
// Returns the preferred location between an AST location and an index location.
SymbolLocation getPreferredLocation(const Location &ASTLoc,
const SymbolLocation &IdxLoc,
std::string &Scratch) {
// Also use a mock symbol for the index location so that other fields (e.g.
// definition) are not factored into the preference.
Symbol ASTSym, IdxSym;
ASTSym.ID = IdxSym.ID = SymbolID("mock_symbol_id");
ASTSym.CanonicalDeclaration = toIndexLocation(ASTLoc, Scratch);
IdxSym.CanonicalDeclaration = IdxLoc;
auto Merged = mergeSymbol(ASTSym, IdxSym);
return Merged.CanonicalDeclaration;
}
std::vector<std::pair<const NamedDecl *, DeclRelationSet>>
getDeclAtPositionWithRelations(ParsedAST &AST, SourceLocation Pos,
DeclRelationSet Relations,
ASTNodeKind *NodeKind = nullptr) {
unsigned Offset = AST.getSourceManager().getDecomposedSpellingLoc(Pos).second;
std::vector<std::pair<const NamedDecl *, DeclRelationSet>> Result;
auto ResultFromTree = [&](SelectionTree ST) {
if (const SelectionTree::Node *N = ST.commonAncestor()) {
if (NodeKind)
*NodeKind = N->ASTNode.getNodeKind();
llvm::copy_if(allTargetDecls(N->ASTNode, AST.getHeuristicResolver()),
std::back_inserter(Result),
[&](auto &Entry) { return !(Entry.second & ~Relations); });
}
return !Result.empty();
};
SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), Offset,
Offset, ResultFromTree);
return Result;
}
std::vector<const NamedDecl *>
getDeclAtPosition(ParsedAST &AST, SourceLocation Pos, DeclRelationSet Relations,
ASTNodeKind *NodeKind = nullptr) {
std::vector<const NamedDecl *> Result;
for (auto &Entry :
getDeclAtPositionWithRelations(AST, Pos, Relations, NodeKind))
Result.push_back(Entry.first);
return Result;
}
// Expects Loc to be a SpellingLocation, will bail out otherwise as it can't
// figure out a filename.
llvm::Optional<Location> makeLocation(const ASTContext &AST, SourceLocation Loc,
llvm::StringRef TUPath) {
const auto &SM = AST.getSourceManager();
const FileEntry *F = SM.getFileEntryForID(SM.getFileID(Loc));
if (!F)
return None;
auto FilePath = getCanonicalPath(F, SM);
if (!FilePath) {
log("failed to get path!");
return None;
}
Location L;
L.uri = URIForFile::canonicalize(*FilePath, TUPath);
// We call MeasureTokenLength here as TokenBuffer doesn't store spelled tokens
// outside the main file.
auto TokLen = Lexer::MeasureTokenLength(Loc, SM, AST.getLangOpts());
L.range = halfOpenToRange(
SM, CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(TokLen)));
return L;
}
// Treat #included files as symbols, to enable go-to-definition on them.
llvm::Optional<LocatedSymbol> locateFileReferent(const Position &Pos,
ParsedAST &AST,
llvm::StringRef MainFilePath) {
for (auto &Inc : AST.getIncludeStructure().MainFileIncludes) {
if (!Inc.Resolved.empty() && Inc.HashLine == Pos.line) {
LocatedSymbol File;
File.Name = std::string(llvm::sys::path::filename(Inc.Resolved));
File.PreferredDeclaration = {
URIForFile::canonicalize(Inc.Resolved, MainFilePath), Range{}};
File.Definition = File.PreferredDeclaration;
// We're not going to find any further symbols on #include lines.
return File;
}
}
return llvm::None;
}
// Macros are simple: there's no declaration/definition distinction.
// As a consequence, there's no need to look them up in the index either.
llvm::Optional<LocatedSymbol>
locateMacroReferent(const syntax::Token &TouchedIdentifier, ParsedAST &AST,
llvm::StringRef MainFilePath) {
if (auto M = locateMacroAt(TouchedIdentifier, AST.getPreprocessor())) {
if (auto Loc =
makeLocation(AST.getASTContext(), M->NameLoc, MainFilePath)) {
LocatedSymbol Macro;
Macro.Name = std::string(M->Name);
Macro.PreferredDeclaration = *Loc;
Macro.Definition = Loc;
return Macro;
}
}
return llvm::None;
}
// A wrapper around `Decl::getCanonicalDecl` to support cases where Clang's
// definition of a canonical declaration doesn't match up to what a programmer
// would expect. For example, Objective-C classes can have three types of
// declarations:
//
// - forward declaration(s): @class MyClass;
// - true declaration (interface definition): @interface MyClass ... @end
// - true definition (implementation): @implementation MyClass ... @end
//
// Clang will consider the forward declaration to be the canonical declaration
// because it is first. We actually want the class definition if it is
// available since that is what a programmer would consider the primary
// declaration to be.
const NamedDecl *getPreferredDecl(const NamedDecl *D) {
// FIXME: Canonical declarations of some symbols might refer to built-in
// decls with possibly-invalid source locations (e.g. global new operator).
// In such cases we should pick up a redecl with valid source location
// instead of failing.
D = llvm::cast<NamedDecl>(D->getCanonicalDecl());
// Prefer Objective-C class/protocol definitions over the forward declaration.
if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(D))
if (const auto *DefinitionID = ID->getDefinition())
return DefinitionID;
if (const auto *PD = dyn_cast<ObjCProtocolDecl>(D))
if (const auto *DefinitionID = PD->getDefinition())
return DefinitionID;
return D;
}
std::vector<LocatedSymbol> findImplementors(llvm::DenseSet<SymbolID> IDs,
RelationKind Predicate,
const SymbolIndex *Index,
llvm::StringRef MainFilePath) {
if (IDs.empty())
return {};
static constexpr trace::Metric FindImplementorsMetric(
"find_implementors", trace::Metric::Counter, "case");
switch (Predicate) {
case RelationKind::BaseOf:
FindImplementorsMetric.record(1, "find-base");
break;
case RelationKind::OverriddenBy:
FindImplementorsMetric.record(1, "find-override");
break;
}
RelationsRequest Req;
Req.Predicate = Predicate;
Req.Subjects = std::move(IDs);
std::vector<LocatedSymbol> Results;
Index->relations(Req, [&](const SymbolID &Subject, const Symbol &Object) {
auto DeclLoc =
indexToLSPLocation(Object.CanonicalDeclaration, MainFilePath);
if (!DeclLoc) {
elog("Find overrides: {0}", DeclLoc.takeError());
return;
}
Results.emplace_back();
Results.back().Name = Object.Name.str();
Results.back().PreferredDeclaration = *DeclLoc;
auto DefLoc = indexToLSPLocation(Object.Definition, MainFilePath);
if (!DefLoc) {
elog("Failed to convert location: {0}", DefLoc.takeError());
return;
}
Results.back().Definition = *DefLoc;
});
return Results;
}
// Decls are more complicated.
// The AST contains at least a declaration, maybe a definition.
// These are up-to-date, and so generally preferred over index results.
// We perform a single batch index lookup to find additional definitions.
std::vector<LocatedSymbol>
locateASTReferent(SourceLocation CurLoc, const syntax::Token *TouchedIdentifier,
ParsedAST &AST, llvm::StringRef MainFilePath,
const SymbolIndex *Index, ASTNodeKind *NodeKind) {
const SourceManager &SM = AST.getSourceManager();
// Results follow the order of Symbols.Decls.
std::vector<LocatedSymbol> Result;
// Keep track of SymbolID -> index mapping, to fill in index data later.
llvm::DenseMap<SymbolID, size_t> ResultIndex;
static constexpr trace::Metric LocateASTReferentMetric(
"locate_ast_referent", trace::Metric::Counter, "case");
auto AddResultDecl = [&](const NamedDecl *D) {
D = getPreferredDecl(D);
auto Loc =
makeLocation(AST.getASTContext(), nameLocation(*D, SM), MainFilePath);
if (!Loc)
return;
Result.emplace_back();
Result.back().Name = printName(AST.getASTContext(), *D);
Result.back().PreferredDeclaration = *Loc;
if (const NamedDecl *Def = getDefinition(D))
Result.back().Definition = makeLocation(
AST.getASTContext(), nameLocation(*Def, SM), MainFilePath);
// Record SymbolID for index lookup later.
if (auto ID = getSymbolID(D))
ResultIndex[ID] = Result.size() - 1;
};
// Emit all symbol locations (declaration or definition) from AST.
DeclRelationSet Relations =
DeclRelation::TemplatePattern | DeclRelation::Alias;
auto Candidates =
getDeclAtPositionWithRelations(AST, CurLoc, Relations, NodeKind);
llvm::DenseSet<SymbolID> VirtualMethods;
for (const auto &E : Candidates) {
const NamedDecl *D = E.first;
if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D)) {
// Special case: virtual void ^method() = 0: jump to all overrides.
// FIXME: extend it to ^virtual, unfortunately, virtual location is not
// saved in the AST.
if (CMD->isPure()) {
if (TouchedIdentifier && SM.getSpellingLoc(CMD->getLocation()) ==
TouchedIdentifier->location()) {
VirtualMethods.insert(getSymbolID(CMD));
LocateASTReferentMetric.record(1, "method-to-override");
}
}
// Special case: void foo() ^override: jump to the overridden method.
const InheritableAttr *Attr = D->getAttr<OverrideAttr>();
if (!Attr)
Attr = D->getAttr<FinalAttr>();
if (Attr && TouchedIdentifier &&
SM.getSpellingLoc(Attr->getLocation()) ==
TouchedIdentifier->location()) {
LocateASTReferentMetric.record(1, "method-to-base");
// We may be overridding multiple methods - offer them all.
for (const NamedDecl *ND : CMD->overridden_methods())
AddResultDecl(ND);
continue;
}
}
// Special case: the cursor is on an alias, prefer other results.
// This targets "using ns::^Foo", where the target is more interesting.
// This does not trigger on renaming aliases:
// `using Foo = ^Bar` already targets Bar via a TypeLoc
// `using ^Foo = Bar` has no other results, as Underlying is filtered.
if (E.second & DeclRelation::Alias && Candidates.size() > 1 &&
// beginLoc/endLoc are a token range, so rewind the identifier we're in.
SM.isPointWithin(TouchedIdentifier ? TouchedIdentifier->location()
: CurLoc,
D->getBeginLoc(), D->getEndLoc()))
continue;
// Special case: the point of declaration of a template specialization,
// it's more useful to navigate to the template declaration.
if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
if (TouchedIdentifier &&
D->getLocation() == TouchedIdentifier->location()) {
LocateASTReferentMetric.record(1, "template-specialization-to-primary");
AddResultDecl(CTSD->getSpecializedTemplate());
continue;
}
}
// Special case: if the class name is selected, also map Objective-C
// categories and category implementations back to their class interface.
//
// Since `TouchedIdentifier` might refer to the `ObjCCategoryImplDecl`
// instead of the `ObjCCategoryDecl` we intentionally check the contents
// of the locs when checking for class name equivalence.
if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D))
if (const auto *ID = CD->getClassInterface())
if (TouchedIdentifier &&
(CD->getLocation() == TouchedIdentifier->location() ||
ID->getName() == TouchedIdentifier->text(SM))) {
LocateASTReferentMetric.record(1, "objc-category-to-class");
AddResultDecl(ID);
}
LocateASTReferentMetric.record(1, "regular");
// Otherwise the target declaration is the right one.
AddResultDecl(D);
}
// Now query the index for all Symbol IDs we found in the AST.
if (Index && !ResultIndex.empty()) {
LookupRequest QueryRequest;
for (auto It : ResultIndex)
QueryRequest.IDs.insert(It.first);
std::string Scratch;
Index->lookup(QueryRequest, [&](const Symbol &Sym) {
auto &R = Result[ResultIndex.lookup(Sym.ID)];
if (R.Definition) { // from AST
// Special case: if the AST yielded a definition, then it may not be
// the right *declaration*. Prefer the one from the index.
if (auto Loc = toLSPLocation(Sym.CanonicalDeclaration, MainFilePath))
R.PreferredDeclaration = *Loc;
// We might still prefer the definition from the index, e.g. for
// generated symbols.
if (auto Loc = toLSPLocation(
getPreferredLocation(*R.Definition, Sym.Definition, Scratch),
MainFilePath))
R.Definition = *Loc;
} else {
R.Definition = toLSPLocation(Sym.Definition, MainFilePath);
// Use merge logic to choose AST or index declaration.
if (auto Loc = toLSPLocation(
getPreferredLocation(R.PreferredDeclaration,
Sym.CanonicalDeclaration, Scratch),
MainFilePath))
R.PreferredDeclaration = *Loc;
}
});
}
auto Overrides = findImplementors(VirtualMethods, RelationKind::OverriddenBy,
Index, MainFilePath);
Result.insert(Result.end(), Overrides.begin(), Overrides.end());
return Result;
}
std::vector<LocatedSymbol> locateSymbolForType(const ParsedAST &AST,
const QualType &Type) {
const auto &SM = AST.getSourceManager();
auto MainFilePath =
getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM);
if (!MainFilePath) {
elog("Failed to get a path for the main file, so no symbol.");
return {};
}
auto Decls = targetDecl(DynTypedNode::create(Type.getNonReferenceType()),
DeclRelation::TemplatePattern | DeclRelation::Alias,
AST.getHeuristicResolver());
if (Decls.empty())
return {};
std::vector<LocatedSymbol> Results;
const auto &ASTContext = AST.getASTContext();
for (const NamedDecl *D : Decls) {
D = getPreferredDecl(D);
auto Loc = makeLocation(ASTContext, nameLocation(*D, SM), *MainFilePath);
if (!Loc)
continue;
Results.emplace_back();
Results.back().Name = printName(ASTContext, *D);
Results.back().PreferredDeclaration = *Loc;
if (const NamedDecl *Def = getDefinition(D))
Results.back().Definition =
makeLocation(ASTContext, nameLocation(*Def, SM), *MainFilePath);
}
return Results;
}
bool tokenSpelledAt(SourceLocation SpellingLoc, const syntax::TokenBuffer &TB) {
auto ExpandedTokens = TB.expandedTokens(
TB.sourceManager().getMacroArgExpandedLocation(SpellingLoc));
return !ExpandedTokens.empty();
}
llvm::StringRef sourcePrefix(SourceLocation Loc, const SourceManager &SM) {
auto D = SM.getDecomposedLoc(Loc);
bool Invalid = false;
llvm::StringRef Buf = SM.getBufferData(D.first, &Invalid);
if (Invalid || D.second > Buf.size())
return "";
return Buf.substr(0, D.second);
}
bool isDependentName(ASTNodeKind NodeKind) {
return NodeKind.isSame(ASTNodeKind::getFromNodeKind<OverloadExpr>()) ||
NodeKind.isSame(
ASTNodeKind::getFromNodeKind<CXXDependentScopeMemberExpr>()) ||
NodeKind.isSame(
ASTNodeKind::getFromNodeKind<DependentScopeDeclRefExpr>());
}
} // namespace
std::vector<LocatedSymbol>
locateSymbolTextually(const SpelledWord &Word, ParsedAST &AST,
const SymbolIndex *Index, const std::string &MainFilePath,
ASTNodeKind NodeKind) {
// Don't use heuristics if this is a real identifier, or not an
// identifier.
// Exception: dependent names, because those may have useful textual
// matches that AST-based heuristics cannot find.
if ((Word.ExpandedToken && !isDependentName(NodeKind)) ||
!Word.LikelyIdentifier || !Index)
return {};
// We don't want to handle words in string literals. (It'd be nice to list
// *allowed* token kinds explicitly, but comment Tokens aren't retained).
if (Word.PartOfSpelledToken &&
isStringLiteral(Word.PartOfSpelledToken->kind()))
return {};
const auto &SM = AST.getSourceManager();
// Look up the selected word in the index.
FuzzyFindRequest Req;
Req.Query = Word.Text.str();
Req.ProximityPaths = {MainFilePath};
// Find the namespaces to query by lexing the file.
Req.Scopes =
visibleNamespaces(sourcePrefix(Word.Location, SM), AST.getLangOpts());
// FIXME: For extra strictness, consider AnyScope=false.
Req.AnyScope = true;
// We limit the results to 3 further below. This limit is to avoid fetching
// too much data, while still likely having enough for 3 results to remain
// after additional filtering.
Req.Limit = 10;
bool TooMany = false;
using ScoredLocatedSymbol = std::pair<float, LocatedSymbol>;
std::vector<ScoredLocatedSymbol> ScoredResults;
Index->fuzzyFind(Req, [&](const Symbol &Sym) {
// Only consider exact name matches, including case.
// This is to avoid too many false positives.
// We could relax this in the future (e.g. to allow for typos) if we make
// the query more accurate by other means.
if (Sym.Name != Word.Text)
return;
// Exclude constructor results. They have the same name as the class,
// but we don't have enough context to prefer them over the class.
if (Sym.SymInfo.Kind == index::SymbolKind::Constructor)
return;
auto MaybeDeclLoc =
indexToLSPLocation(Sym.CanonicalDeclaration, MainFilePath);
if (!MaybeDeclLoc) {
log("locateSymbolNamedTextuallyAt: {0}", MaybeDeclLoc.takeError());
return;
}
LocatedSymbol Located;
Located.PreferredDeclaration = *MaybeDeclLoc;
Located.Name = (Sym.Name + Sym.TemplateSpecializationArgs).str();
if (Sym.Definition) {
auto MaybeDefLoc = indexToLSPLocation(Sym.Definition, MainFilePath);
if (!MaybeDefLoc) {
log("locateSymbolNamedTextuallyAt: {0}", MaybeDefLoc.takeError());
return;
}
Located.PreferredDeclaration = *MaybeDefLoc;
Located.Definition = *MaybeDefLoc;
}
if (ScoredResults.size() >= 5) {
// If we have more than 5 results, don't return anything,
// as confidence is too low.
// FIXME: Alternatively, try a stricter query?
TooMany = true;
return;
}
SymbolQualitySignals Quality;
Quality.merge(Sym);
SymbolRelevanceSignals Relevance;
Relevance.Name = Sym.Name;
Relevance.Query = SymbolRelevanceSignals::Generic;
Relevance.merge(Sym);
auto Score = evaluateSymbolAndRelevance(Quality.evaluateHeuristics(),
Relevance.evaluateHeuristics());
dlog("locateSymbolNamedTextuallyAt: {0}{1} = {2}\n{3}{4}\n", Sym.Scope,
Sym.Name, Score, Quality, Relevance);
ScoredResults.push_back({Score, std::move(Located)});
});
if (TooMany) {
vlog("Heuristic index lookup for {0} returned too many candidates, ignored",
Word.Text);
return {};
}
llvm::sort(ScoredResults,
[](const ScoredLocatedSymbol &A, const ScoredLocatedSymbol &B) {
return A.first > B.first;
});
std::vector<LocatedSymbol> Results;
for (auto &Res : std::move(ScoredResults))
Results.push_back(std::move(Res.second));
if (Results.empty())
vlog("No heuristic index definition for {0}", Word.Text);
else
log("Found definition heuristically in index for {0}", Word.Text);
return Results;
}
const syntax::Token *findNearbyIdentifier(const SpelledWord &Word,
const syntax::TokenBuffer &TB) {
// Don't use heuristics if this is a real identifier.
// Unlikely identifiers are OK if they were used as identifiers nearby.
if (Word.ExpandedToken)
return nullptr;
// We don't want to handle words in string literals. (It'd be nice to list
// *allowed* token kinds explicitly, but comment Tokens aren't retained).
if (Word.PartOfSpelledToken &&
isStringLiteral(Word.PartOfSpelledToken->kind()))
return {};
const SourceManager &SM = TB.sourceManager();
// We prefer the closest possible token, line-wise. Backwards is penalized.
// Ties are implicitly broken by traversal order (first-one-wins).
auto File = SM.getFileID(Word.Location);
unsigned WordLine = SM.getSpellingLineNumber(Word.Location);
auto Cost = [&](SourceLocation Loc) -> unsigned {
assert(SM.getFileID(Loc) == File && "spelled token in wrong file?");
unsigned Line = SM.getSpellingLineNumber(Loc);
return Line >= WordLine ? Line - WordLine : 2 * (WordLine - Line);
};
const syntax::Token *BestTok = nullptr;
unsigned BestCost = -1;
// Search bounds are based on word length:
// - forward: 2^N lines
// - backward: 2^(N-1) lines.
unsigned MaxDistance =
1U << std::min<unsigned>(Word.Text.size(),
std::numeric_limits<unsigned>::digits - 1);
// Line number for SM.translateLineCol() should be one-based, also
// SM.translateLineCol() can handle line number greater than
// number of lines in the file.
// - LineMin = max(1, WordLine + 1 - 2^(N-1))
// - LineMax = WordLine + 1 + 2^N
unsigned LineMin =
WordLine + 1 <= MaxDistance / 2 ? 1 : WordLine + 1 - MaxDistance / 2;
unsigned LineMax = WordLine + 1 + MaxDistance;
SourceLocation LocMin = SM.translateLineCol(File, LineMin, 1);
assert(LocMin.isValid());
SourceLocation LocMax = SM.translateLineCol(File, LineMax, 1);
assert(LocMax.isValid());
// Updates BestTok and BestCost if Tok is a good candidate.
// May return true if the cost is too high for this token.
auto Consider = [&](const syntax::Token &Tok) {
if (Tok.location() < LocMin || Tok.location() > LocMax)
return true; // we are too far from the word, break the outer loop.
if (!(Tok.kind() == tok::identifier && Tok.text(SM) == Word.Text))
return false;
// No point guessing the same location we started with.
if (Tok.location() == Word.Location)
return false;
// We've done cheap checks, compute cost so we can break the caller's loop.
unsigned TokCost = Cost(Tok.location());
if (TokCost >= BestCost)
return true; // causes the outer loop to break.
// Allow locations that might be part of the AST, and macros (even if empty)
// but not things like disabled preprocessor sections.
if (!(tokenSpelledAt(Tok.location(), TB) || TB.expansionStartingAt(&Tok)))
return false;
// We already verified this token is an improvement.
BestCost = TokCost;
BestTok = &Tok;
return false;
};
auto SpelledTokens = TB.spelledTokens(File);
// Find where the word occurred in the token stream, to search forward & back.
auto *I = llvm::partition_point(SpelledTokens, [&](const syntax::Token &T) {
assert(SM.getFileID(T.location()) == SM.getFileID(Word.Location));
return T.location() < Word.Location; // Comparison OK: same file.
});
// Search for matches after the cursor.
for (const syntax::Token &Tok : llvm::makeArrayRef(I, SpelledTokens.end()))
if (Consider(Tok))
break; // costs of later tokens are greater...
// Search for matches before the cursor.
for (const syntax::Token &Tok :
llvm::reverse(llvm::makeArrayRef(SpelledTokens.begin(), I)))
if (Consider(Tok))
break;
if (BestTok)
vlog(
"Word {0} under cursor {1} isn't a token (after PP), trying nearby {2}",
Word.Text, Word.Location.printToString(SM),
BestTok->location().printToString(SM));
return BestTok;
}
std::vector<LocatedSymbol> locateSymbolAt(ParsedAST &AST, Position Pos,
const SymbolIndex *Index) {
const auto &SM = AST.getSourceManager();
auto MainFilePath =
getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM);
if (!MainFilePath) {
elog("Failed to get a path for the main file, so no references");
return {};
}
if (auto File = locateFileReferent(Pos, AST, *MainFilePath))
return {std::move(*File)};
auto CurLoc = sourceLocationInMainFile(SM, Pos);
if (!CurLoc) {
elog("locateSymbolAt failed to convert position to source location: {0}",
CurLoc.takeError());
return {};
}
const syntax::Token *TouchedIdentifier = nullptr;
auto TokensTouchingCursor =
syntax::spelledTokensTouching(*CurLoc, AST.getTokens());
for (const syntax::Token &Tok : TokensTouchingCursor) {
if (Tok.kind() == tok::identifier) {
if (auto Macro = locateMacroReferent(Tok, AST, *MainFilePath))
// Don't look at the AST or index if we have a macro result.
// (We'd just return declarations referenced from the macro's
// expansion.)
return {*std::move(Macro)};
TouchedIdentifier = &Tok;
break;
}
if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
// go-to-definition on auto should find the definition of the deduced
// type, if possible
if (auto Deduced = getDeducedType(AST.getASTContext(), Tok.location())) {
auto LocSym = locateSymbolForType(AST, *Deduced);
if (!LocSym.empty())
return LocSym;
}
}
}
ASTNodeKind NodeKind;
auto ASTResults = locateASTReferent(*CurLoc, TouchedIdentifier, AST,
*MainFilePath, Index, &NodeKind);
if (!ASTResults.empty())
return ASTResults;
// If the cursor can't be resolved directly, try fallback strategies.
auto Word =
SpelledWord::touching(*CurLoc, AST.getTokens(), AST.getLangOpts());
if (Word) {
// Is the same word nearby a real identifier that might refer to something?
if (const syntax::Token *NearbyIdent =
findNearbyIdentifier(*Word, AST.getTokens())) {
if (auto Macro = locateMacroReferent(*NearbyIdent, AST, *MainFilePath)) {
log("Found macro definition heuristically using nearby identifier {0}",
Word->Text);
return {*std::move(Macro)};
}
ASTResults =
locateASTReferent(NearbyIdent->location(), NearbyIdent, AST,
*MainFilePath, Index, /*NodeKind=*/nullptr);
if (!ASTResults.empty()) {
log("Found definition heuristically using nearby identifier {0}",
NearbyIdent->text(SM));
return ASTResults;
} else {
vlog("No definition found using nearby identifier {0} at {1}",
Word->Text, Word->Location.printToString(SM));
}
}
// No nearby word, or it didn't refer to anything either. Try the index.
auto TextualResults =
locateSymbolTextually(*Word, AST, Index, *MainFilePath, NodeKind);
if (!TextualResults.empty())
return TextualResults;
}
return {};
}
std::vector<DocumentLink> getDocumentLinks(ParsedAST &AST) {
const auto &SM = AST.getSourceManager();
auto MainFilePath =
getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM);
if (!MainFilePath) {
elog("Failed to get a path for the main file, so no links");
return {};
}
std::vector<DocumentLink> Result;
for (auto &Inc : AST.getIncludeStructure().MainFileIncludes) {
if (Inc.Resolved.empty())
continue;
auto HashLoc = SM.getComposedLoc(SM.getMainFileID(), Inc.HashOffset);
const auto *HashTok = AST.getTokens().spelledTokenAt(HashLoc);
assert(HashTok && "got inclusion at wrong offset");
const auto *IncludeTok = std::next(HashTok);
const auto *FileTok = std::next(IncludeTok);
// FileTok->range is not sufficient here, as raw lexing wouldn't yield
// correct tokens for angled filenames. Hence we explicitly use
// Inc.Written's length.
auto FileRange =
syntax::FileRange(SM, FileTok->location(), Inc.Written.length())
.toCharRange(SM);
Result.push_back(
DocumentLink({halfOpenToRange(SM, FileRange),
URIForFile::canonicalize(Inc.Resolved, *MainFilePath)}));
}
return Result;
}
namespace {
/// Collects references to symbols within the main file.
class ReferenceFinder : public index::IndexDataConsumer {
public:
struct Reference {
syntax::Token SpelledTok;
index::SymbolRoleSet Role;
SymbolID Target;
Range range(const SourceManager &SM) const {
return halfOpenToRange(SM, SpelledTok.range(SM).toCharRange(SM));
}
};
ReferenceFinder(const ParsedAST &AST,
const llvm::DenseSet<SymbolID> &TargetIDs, bool PerToken)
: PerToken(PerToken), AST(AST), TargetIDs(TargetIDs) {}
std::vector<Reference> take() && {
llvm::sort(References, [](const Reference &L, const Reference &R) {
auto LTok = L.SpelledTok.location();
auto RTok = R.SpelledTok.location();
return std::tie(LTok, L.Role) < std::tie(RTok, R.Role);
});
// We sometimes see duplicates when parts of the AST get traversed twice.
References.erase(std::unique(References.begin(), References.end(),
[](const Reference &L, const Reference &R) {
auto LTok = L.SpelledTok.location();
auto RTok = R.SpelledTok.location();
return std::tie(LTok, L.Role) ==
std::tie(RTok, R.Role);
}),
References.end());
return std::move(References);
}
bool
handleDeclOccurrence(const Decl *D, index::SymbolRoleSet Roles,
llvm::ArrayRef<index::SymbolRelation> Relations,
SourceLocation Loc,
index::IndexDataConsumer::ASTNodeInfo ASTNode) override {
const SourceManager &SM = AST.getSourceManager();
if (!isInsideMainFile(Loc, SM))
return true;
SymbolID ID = getSymbolID(D);
if (!TargetIDs.contains(ID))
return true;
const auto &TB = AST.getTokens();
llvm::SmallVector<SourceLocation, 1> Locs;
if (PerToken) {
// Check whether this is one of the few constructs where the reference
// can be split over several tokens.
if (auto *OME = llvm::dyn_cast_or_null<ObjCMessageExpr>(ASTNode.OrigE)) {
OME->getSelectorLocs(Locs);
} else if (auto *OMD =
llvm::dyn_cast_or_null<ObjCMethodDecl>(ASTNode.OrigD)) {
OMD->getSelectorLocs(Locs);
}
// Sanity check: we expect the *first* token to match the reported loc.
// Otherwise, maybe it was e.g. some other kind of reference to a Decl.
if (!Locs.empty() && Locs.front() != Loc)
Locs.clear(); // First token doesn't match, assume our guess was wrong.
}
if (Locs.empty())
Locs.push_back(Loc);
for (SourceLocation L : Locs) {
L = SM.getFileLoc(L);
if (const auto *Tok = TB.spelledTokenAt(L))
References.push_back({*Tok, Roles, ID});
}
return true;
}
private:
bool PerToken; // If true, report 3 references for split ObjC selector names.
std::vector<Reference> References;
const ParsedAST &AST;
const llvm::DenseSet<SymbolID> &TargetIDs;
};
std::vector<ReferenceFinder::Reference>
findRefs(const llvm::DenseSet<SymbolID> &IDs, ParsedAST &AST, bool PerToken) {
ReferenceFinder RefFinder(AST, IDs, PerToken);
index::IndexingOptions IndexOpts;
IndexOpts.SystemSymbolFilter =
index::IndexingOptions::SystemSymbolFilterKind::All;
IndexOpts.IndexFunctionLocals = true;
IndexOpts.IndexParametersInDeclarations = true;
IndexOpts.IndexTemplateParameters = true;
indexTopLevelDecls(AST.getASTContext(), AST.getPreprocessor(),
AST.getLocalTopLevelDecls(), RefFinder, IndexOpts);
return std::move(RefFinder).take();
}
const Stmt *getFunctionBody(DynTypedNode N) {
if (const auto *FD = N.get<FunctionDecl>())
return FD->getBody();
if (const auto *FD = N.get<BlockDecl>())
return FD->getBody();
if (const auto *FD = N.get<LambdaExpr>())
return FD->getBody();
if (const auto *FD = N.get<ObjCMethodDecl>())
return FD->getBody();
return nullptr;
}
const Stmt *getLoopBody(DynTypedNode N) {
if (const auto *LS = N.get<ForStmt>())
return LS->getBody();
if (const auto *LS = N.get<CXXForRangeStmt>())
return LS->getBody();
if (const auto *LS = N.get<WhileStmt>())
return LS->getBody();
if (const auto *LS = N.get<DoStmt>())
return LS->getBody();
return nullptr;
}
// AST traversal to highlight control flow statements under some root.
// Once we hit further control flow we prune the tree (or at least restrict
// what we highlight) so we capture e.g. breaks from the outer loop only.
class FindControlFlow : public RecursiveASTVisitor<FindControlFlow> {
// Types of control-flow statements we might highlight.
enum Target {
Break = 1,
Continue = 2,
Return = 4,
Case = 8,