clang-tools  10.0.0svn
SymbolCollector.cpp
Go to the documentation of this file.
1 //===--- SymbolCollector.cpp -------------------------------------*- C++-*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "SymbolCollector.h"
10 #include "AST.h"
11 #include "CanonicalIncludes.h"
12 #include "CodeComplete.h"
13 #include "CodeCompletionStrings.h"
14 #include "ExpectedTypes.h"
15 #include "Logger.h"
16 #include "SourceCode.h"
17 #include "SymbolLocation.h"
18 #include "URI.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/Basic/SourceLocation.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/Specifiers.h"
26 #include "clang/Index/IndexSymbol.h"
27 #include "clang/Index/IndexingAction.h"
28 #include "clang/Index/USRGeneration.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/Path.h"
34 
35 namespace clang {
36 namespace clangd {
37 namespace {
38 
39 /// If \p ND is a template specialization, returns the described template.
40 /// Otherwise, returns \p ND.
41 const NamedDecl &getTemplateOrThis(const NamedDecl &ND) {
42  if (auto T = ND.getDescribedTemplate())
43  return *T;
44  return ND;
45 }
46 
47 // Returns a URI of \p Path. Firstly, this makes the \p Path absolute using the
48 // current working directory of the given SourceManager if the Path is not an
49 // absolute path. If failed, this resolves relative paths against \p FallbackDir
50 // to get an absolute path. Then, this tries creating an URI for the absolute
51 // path with schemes specified in \p Opts. This returns an URI with the first
52 // working scheme, if there is any; otherwise, this returns None.
53 //
54 // The Path can be a path relative to the build directory, or retrieved from
55 // the SourceManager.
56 std::string toURI(const SourceManager &SM, llvm::StringRef Path,
57  const SymbolCollector::Options &Opts) {
58  llvm::SmallString<128> AbsolutePath(Path);
59  if (auto File = SM.getFileManager().getFile(Path)) {
60  if (auto CanonPath = getCanonicalPath(*File, SM)) {
61  AbsolutePath = *CanonPath;
62  }
63  }
64  // We don't perform is_absolute check in an else branch because makeAbsolute
65  // might return a relative path on some InMemoryFileSystems.
66  if (!llvm::sys::path::is_absolute(AbsolutePath) && !Opts.FallbackDir.empty())
67  llvm::sys::fs::make_absolute(Opts.FallbackDir, AbsolutePath);
68  llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
69  return URI::create(AbsolutePath).toString();
70 }
71 
72 // All proto generated headers should start with this line.
73 static const char *PROTO_HEADER_COMMENT =
74  "// Generated by the protocol buffer compiler. DO NOT EDIT!";
75 
76 // Checks whether the decl is a private symbol in a header generated by
77 // protobuf compiler.
78 // To identify whether a proto header is actually generated by proto compiler,
79 // we check whether it starts with PROTO_HEADER_COMMENT.
80 // FIXME: make filtering extensible when there are more use cases for symbol
81 // filters.
82 bool isPrivateProtoDecl(const NamedDecl &ND) {
83  const auto &SM = ND.getASTContext().getSourceManager();
84  auto Loc = spellingLocIfSpelled(findName(&ND), SM);
85  auto FileName = SM.getFilename(Loc);
86  if (!FileName.endswith(".proto.h") && !FileName.endswith(".pb.h"))
87  return false;
88  auto FID = SM.getFileID(Loc);
89  // Double check that this is an actual protobuf header.
90  if (!SM.getBufferData(FID).startswith(PROTO_HEADER_COMMENT))
91  return false;
92 
93  // ND without identifier can be operators.
94  if (ND.getIdentifier() == nullptr)
95  return false;
96  auto Name = ND.getIdentifier()->getName();
97  if (!Name.contains('_'))
98  return false;
99  // Nested proto entities (e.g. Message::Nested) have top-level decls
100  // that shouldn't be used (Message_Nested). Ignore them completely.
101  // The nested entities are dangling type aliases, we may want to reconsider
102  // including them in the future.
103  // For enum constants, SOME_ENUM_CONSTANT is not private and should be
104  // indexed. Outer_INNER is private. This heuristic relies on naming style, it
105  // will include OUTER_INNER and exclude some_enum_constant.
106  // FIXME: the heuristic relies on naming style (i.e. no underscore in
107  // user-defined names) and can be improved.
108  return (ND.getKind() != Decl::EnumConstant) || llvm::any_of(Name, islower);
109 }
110 
111 // We only collect #include paths for symbols that are suitable for global code
112 // completion, except for namespaces since #include path for a namespace is hard
113 // to define.
114 bool shouldCollectIncludePath(index::SymbolKind Kind) {
115  using SK = index::SymbolKind;
116  switch (Kind) {
117  case SK::Macro:
118  case SK::Enum:
119  case SK::Struct:
120  case SK::Class:
121  case SK::Union:
122  case SK::TypeAlias:
123  case SK::Using:
124  case SK::Function:
125  case SK::Variable:
126  case SK::EnumConstant:
127  return true;
128  default:
129  return false;
130  }
131 }
132 
133 // Return the symbol range of the token at \p TokLoc.
134 std::pair<SymbolLocation::Position, SymbolLocation::Position>
135 getTokenRange(SourceLocation TokLoc, const SourceManager &SM,
136  const LangOptions &LangOpts) {
137  auto CreatePosition = [&SM](SourceLocation Loc) {
138  auto LSPLoc = sourceLocToPosition(SM, Loc);
139  SymbolLocation::Position Pos;
140  Pos.setLine(LSPLoc.line);
141  Pos.setColumn(LSPLoc.character);
142  return Pos;
143  };
144 
145  auto TokenLength = clang::Lexer::MeasureTokenLength(TokLoc, SM, LangOpts);
146  return {CreatePosition(TokLoc),
147  CreatePosition(TokLoc.getLocWithOffset(TokenLength))};
148 }
149 
150 // Return the symbol location of the token at \p TokLoc.
151 llvm::Optional<SymbolLocation>
152 getTokenLocation(SourceLocation TokLoc, const SourceManager &SM,
153  const SymbolCollector::Options &Opts,
154  const clang::LangOptions &LangOpts,
155  std::string &FileURIStorage) {
156  auto Path = SM.getFilename(TokLoc);
157  if (Path.empty())
158  return None;
159  FileURIStorage = toURI(SM, Path, Opts);
160  SymbolLocation Result;
161  Result.FileURI = FileURIStorage.c_str();
162  auto Range = getTokenRange(TokLoc, SM, LangOpts);
163  Result.Start = Range.first;
164  Result.End = Range.second;
165 
166  return Result;
167 }
168 
169 // Checks whether \p ND is a definition of a TagDecl (class/struct/enum/union)
170 // in a header file, in which case clangd would prefer to use ND as a canonical
171 // declaration.
172 // FIXME: handle symbol types that are not TagDecl (e.g. functions), if using
173 // the first seen declaration as canonical declaration is not a good enough
174 // heuristic.
175 bool isPreferredDeclaration(const NamedDecl &ND, index::SymbolRoleSet Roles) {
176  const auto &SM = ND.getASTContext().getSourceManager();
177  return (Roles & static_cast<unsigned>(index::SymbolRole::Definition)) &&
178  isa<TagDecl>(&ND) && !isInsideMainFile(ND.getLocation(), SM);
179 }
180 
181 RefKind toRefKind(index::SymbolRoleSet Roles) {
182  return static_cast<RefKind>(static_cast<unsigned>(RefKind::All) & Roles);
183 }
184 
185 bool shouldIndexRelation(const index::SymbolRelation &R) {
186  // We currently only index BaseOf relations, for type hierarchy subtypes.
187  return R.Roles & static_cast<unsigned>(index::SymbolRole::RelationBaseOf);
188 }
189 
190 } // namespace
191 
192 SymbolCollector::SymbolCollector(Options Opts) : Opts(std::move(Opts)) {}
193 
194 void SymbolCollector::initialize(ASTContext &Ctx) {
195  ASTCtx = &Ctx;
196  CompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
197  CompletionTUInfo =
198  std::make_unique<CodeCompletionTUInfo>(CompletionAllocator);
199 }
200 
201 bool SymbolCollector::shouldCollectSymbol(const NamedDecl &ND,
202  const ASTContext &ASTCtx,
203  const Options &Opts,
204  bool IsMainFileOnly) {
205  // Skip anonymous declarations, e.g (anonymous enum/class/struct).
206  if (ND.getDeclName().isEmpty())
207  return false;
208 
209  // Skip main-file symbols if we are not collecting them.
210  if (IsMainFileOnly && !Opts.CollectMainFileSymbols)
211  return false;
212 
213  // Skip symbols in anonymous namespaces in header files.
214  if (!IsMainFileOnly && ND.isInAnonymousNamespace())
215  return false;
216 
217  // We want most things but not "local" symbols such as symbols inside
218  // FunctionDecl, BlockDecl, ObjCMethodDecl and OMPDeclareReductionDecl.
219  // FIXME: Need a matcher for ExportDecl in order to include symbols declared
220  // within an export.
221  const auto *DeclCtx = ND.getDeclContext();
222  switch (DeclCtx->getDeclKind()) {
223  case Decl::TranslationUnit:
224  case Decl::Namespace:
225  case Decl::LinkageSpec:
226  case Decl::Enum:
227  case Decl::ObjCProtocol:
228  case Decl::ObjCInterface:
229  case Decl::ObjCCategory:
230  case Decl::ObjCCategoryImpl:
231  case Decl::ObjCImplementation:
232  break;
233  default:
234  // Record has a few derivations (e.g. CXXRecord, Class specialization), it's
235  // easier to cast.
236  if (!isa<RecordDecl>(DeclCtx))
237  return false;
238  }
239 
240  // Avoid indexing internal symbols in protobuf generated headers.
241  if (isPrivateProtoDecl(ND))
242  return false;
243  return true;
244 }
245 
246 // Always return true to continue indexing.
248  const Decl *D, index::SymbolRoleSet Roles,
249  llvm::ArrayRef<index::SymbolRelation> Relations, SourceLocation Loc,
250  index::IndexDataConsumer::ASTNodeInfo ASTNode) {
251  assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
252  assert(CompletionAllocator && CompletionTUInfo);
253  assert(ASTNode.OrigD);
254  // Indexing API puts cannonical decl into D, which might not have a valid
255  // source location for implicit/built-in decls. Fallback to original decl in
256  // such cases.
257  if (D->getLocation().isInvalid())
258  D = ASTNode.OrigD;
259  // If OrigD is an declaration associated with a friend declaration and it's
260  // not a definition, skip it. Note that OrigD is the occurrence that the
261  // collector is currently visiting.
262  if ((ASTNode.OrigD->getFriendObjectKind() !=
263  Decl::FriendObjectKind::FOK_None) &&
264  !(Roles & static_cast<unsigned>(index::SymbolRole::Definition)))
265  return true;
266  // Skip non-semantic references, we should start processing these when we
267  // decide to implement renaming with index support.
268  if ((Roles & static_cast<unsigned>(index::SymbolRole::NameReference)))
269  return true;
270  // A declaration created for a friend declaration should not be used as the
271  // canonical declaration in the index. Use OrigD instead, unless we've already
272  // picked a replacement for D
273  if (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None)
274  D = CanonicalDecls.try_emplace(D, ASTNode.OrigD).first->second;
275  const NamedDecl *ND = dyn_cast<NamedDecl>(D);
276  if (!ND)
277  return true;
278 
279  // Mark D as referenced if this is a reference coming from the main file.
280  // D may not be an interesting symbol, but it's cheaper to check at the end.
281  auto &SM = ASTCtx->getSourceManager();
282  auto SpellingLoc = SM.getSpellingLoc(Loc);
283  if (Opts.CountReferences &&
284  (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) &&
285  SM.getFileID(SpellingLoc) == SM.getMainFileID())
286  ReferencedDecls.insert(ND);
287 
288  auto ID = getSymbolID(ND);
289  if (!ID)
290  return true;
291 
292  // Note: we need to process relations for all decl occurrences, including
293  // refs, because the indexing code only populates relations for specific
294  // occurrences. For example, RelationBaseOf is only populated for the
295  // occurrence inside the base-specifier.
296  processRelations(*ND, *ID, Relations);
297 
298  bool CollectRef = static_cast<unsigned>(Opts.RefFilter) & Roles;
299  bool IsOnlyRef =
300  !(Roles & (static_cast<unsigned>(index::SymbolRole::Declaration) |
301  static_cast<unsigned>(index::SymbolRole::Definition)));
302 
303  if (IsOnlyRef && !CollectRef)
304  return true;
305 
306  // ND is the canonical (i.e. first) declaration. If it's in the main file
307  // (which is not a header), then no public declaration was visible, so assume
308  // it's main-file only.
309  bool IsMainFileOnly =
310  SM.isWrittenInMainFile(SM.getExpansionLoc(ND->getBeginLoc())) &&
311  !ASTCtx->getLangOpts().IsHeaderFile;
312  // In C, printf is a redecl of an implicit builtin! So check OrigD instead.
313  if (ASTNode.OrigD->isImplicit() ||
314  !shouldCollectSymbol(*ND, *ASTCtx, Opts, IsMainFileOnly))
315  return true;
316  // Do not store references to main-file symbols.
317  if (CollectRef && !IsMainFileOnly && !isa<NamespaceDecl>(ND) &&
318  (Opts.RefsInHeaders || SM.getFileID(SpellingLoc) == SM.getMainFileID()))
319  DeclRefs[ND].emplace_back(SpellingLoc, Roles);
320  // Don't continue indexing if this is a mere reference.
321  if (IsOnlyRef)
322  return true;
323 
324  // FIXME: ObjCPropertyDecl are not properly indexed here:
325  // - ObjCPropertyDecl may have an OrigD of ObjCPropertyImplDecl, which is
326  // not a NamedDecl.
327  auto *OriginalDecl = dyn_cast<NamedDecl>(ASTNode.OrigD);
328  if (!OriginalDecl)
329  return true;
330 
331  const Symbol *BasicSymbol = Symbols.find(*ID);
332  if (!BasicSymbol) // Regardless of role, ND is the canonical declaration.
333  BasicSymbol = addDeclaration(*ND, std::move(*ID), IsMainFileOnly);
334  else if (isPreferredDeclaration(*OriginalDecl, Roles))
335  // If OriginalDecl is preferred, replace the existing canonical
336  // declaration (e.g. a class forward declaration). There should be at most
337  // one duplicate as we expect to see only one preferred declaration per
338  // TU, because in practice they are definitions.
339  BasicSymbol = addDeclaration(*OriginalDecl, std::move(*ID), IsMainFileOnly);
340 
341  if (Roles & static_cast<unsigned>(index::SymbolRole::Definition))
342  addDefinition(*OriginalDecl, *BasicSymbol);
343 
344  return true;
345 }
346 
347 bool SymbolCollector::handleMacroOccurence(const IdentifierInfo *Name,
348  const MacroInfo *MI,
349  index::SymbolRoleSet Roles,
350  SourceLocation Loc) {
351  if (!Opts.CollectMacro)
352  return true;
353  assert(PP.get());
354 
355  const auto &SM = PP->getSourceManager();
356  auto DefLoc = MI->getDefinitionLoc();
357 
358  // Builtin macros don't have useful locations and aren't needed in completion.
359  if (MI->isBuiltinMacro())
360  return true;
361 
362  // Skip main-file symbols if we are not collecting them.
363  bool IsMainFileSymbol = SM.isInMainFile(SM.getExpansionLoc(DefLoc));
364  if (IsMainFileSymbol && !Opts.CollectMainFileSymbols)
365  return false;
366 
367  // Also avoid storing predefined macros like __DBL_MIN__.
368  if (SM.isWrittenInBuiltinFile(DefLoc))
369  return true;
370 
371  // Mark the macro as referenced if this is a reference coming from the main
372  // file. The macro may not be an interesting symbol, but it's cheaper to check
373  // at the end.
374  if (Opts.CountReferences &&
375  (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) &&
376  SM.getFileID(SM.getSpellingLoc(Loc)) == SM.getMainFileID())
377  ReferencedMacros.insert(Name);
378  // Don't continue indexing if this is a mere reference.
379  // FIXME: remove macro with ID if it is undefined.
380  if (!(Roles & static_cast<unsigned>(index::SymbolRole::Declaration) ||
381  Roles & static_cast<unsigned>(index::SymbolRole::Definition)))
382  return true;
383 
384  auto ID = getSymbolID(*Name, MI, SM);
385  if (!ID)
386  return true;
387 
388  // Only collect one instance in case there are multiple.
389  if (Symbols.find(*ID) != nullptr)
390  return true;
391 
392  Symbol S;
393  S.ID = std::move(*ID);
394  S.Name = Name->getName();
395  if (!IsMainFileSymbol) {
398  }
399  S.SymInfo = index::getSymbolInfoForMacro(*MI);
400  std::string FileURI;
401  // FIXME: use the result to filter out symbols.
402  shouldIndexFile(SM.getFileID(Loc));
403  if (auto DeclLoc =
404  getTokenLocation(DefLoc, SM, Opts, PP->getLangOpts(), FileURI))
405  S.CanonicalDeclaration = *DeclLoc;
406 
407  CodeCompletionResult SymbolCompletion(Name);
408  const auto *CCS = SymbolCompletion.CreateCodeCompletionStringForMacro(
409  *PP, *CompletionAllocator, *CompletionTUInfo);
410  std::string Signature;
411  std::string SnippetSuffix;
412  getSignature(*CCS, &Signature, &SnippetSuffix);
413  S.Signature = Signature;
415 
416  IndexedMacros.insert(Name);
417  setIncludeLocation(S, DefLoc);
418  Symbols.insert(S);
419  return true;
420 }
421 
422 void SymbolCollector::processRelations(
423  const NamedDecl &ND, const SymbolID &ID,
424  ArrayRef<index::SymbolRelation> Relations) {
425  // Store subtype relations.
426  if (!dyn_cast<TagDecl>(&ND))
427  return;
428 
429  for (const auto &R : Relations) {
430  if (!shouldIndexRelation(R))
431  continue;
432 
433  const Decl *Object = R.RelatedSymbol;
434 
435  auto ObjectID = getSymbolID(Object);
436  if (!ObjectID)
437  continue;
438 
439  // Record the relation.
440  // TODO: There may be cases where the object decl is not indexed for some
441  // reason. Those cases should probably be removed in due course, but for
442  // now there are two possible ways to handle it:
443  // (A) Avoid storing the relation in such cases.
444  // (B) Store it anyways. Clients will likely lookup() the SymbolID
445  // in the index and find nothing, but that's a situation they
446  // probably need to handle for other reasons anyways.
447  // We currently do (B) because it's simpler.
448  this->Relations.insert(Relation{ID, RelationKind::BaseOf, *ObjectID});
449  }
450 }
451 
452 void SymbolCollector::setIncludeLocation(const Symbol &S, SourceLocation Loc) {
453  if (Opts.CollectIncludePath)
454  if (shouldCollectIncludePath(S.SymInfo.Kind))
455  // Use the expansion location to get the #include header since this is
456  // where the symbol is exposed.
457  IncludeFiles[S.ID] =
458  PP->getSourceManager().getDecomposedExpansionLoc(Loc).first;
459 }
460 
462  // At the end of the TU, add 1 to the refcount of all referenced symbols.
463  auto IncRef = [this](const SymbolID &ID) {
464  if (const auto *S = Symbols.find(ID)) {
465  Symbol Inc = *S;
466  ++Inc.References;
467  Symbols.insert(Inc);
468  }
469  };
470  for (const NamedDecl *ND : ReferencedDecls) {
471  if (auto ID = getSymbolID(ND)) {
472  IncRef(*ID);
473  }
474  }
475  if (Opts.CollectMacro) {
476  assert(PP);
477  // First, drop header guards. We can't identify these until EOF.
478  for (const IdentifierInfo *II : IndexedMacros) {
479  if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
480  if (auto ID = getSymbolID(*II, MI, PP->getSourceManager()))
481  if (MI->isUsedForHeaderGuard())
482  Symbols.erase(*ID);
483  }
484  // Now increment refcounts.
485  for (const IdentifierInfo *II : ReferencedMacros) {
486  if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
487  if (auto ID = getSymbolID(*II, MI, PP->getSourceManager()))
488  IncRef(*ID);
489  }
490  }
491 
492  // Fill in IncludeHeaders.
493  // We delay this until end of TU so header guards are all resolved.
494  // Symbols in slabs aren' mutable, so insert() has to walk all the strings :-(
495  llvm::SmallString<256> QName;
496  for (const auto &Entry : IncludeFiles)
497  if (const Symbol *S = Symbols.find(Entry.first)) {
498  QName = S->Scope;
499  QName.append(S->Name);
500  if (auto Header = getIncludeHeader(QName, Entry.second)) {
501  Symbol NewSym = *S;
502  NewSym.IncludeHeaders.push_back({*Header, 1});
503  Symbols.insert(NewSym);
504  }
505  }
506 
507  const auto &SM = ASTCtx->getSourceManager();
508  llvm::DenseMap<FileID, std::string> URICache;
509  auto GetURI = [&](FileID FID) -> llvm::Optional<std::string> {
510  auto Found = URICache.find(FID);
511  if (Found == URICache.end()) {
512  if (auto *FileEntry = SM.getFileEntryForID(FID)) {
513  auto FileURI = toURI(SM, FileEntry->getName(), Opts);
514  Found = URICache.insert({FID, FileURI}).first;
515  } else {
516  // Ignore cases where we can not find a corresponding file entry
517  // for the loc, thoses are not interesting, e.g. symbols formed
518  // via macro concatenation.
519  return None;
520  }
521  }
522  return Found->second;
523  };
524  // Populate Refs slab from DeclRefs.
525  if (auto MainFileURI = GetURI(SM.getMainFileID())) {
526  for (const auto &It : DeclRefs) {
527  if (auto ID = getSymbolID(It.first)) {
528  for (const auto &LocAndRole : It.second) {
529  auto FileID = SM.getFileID(LocAndRole.first);
530  // FIXME: use the result to filter out references.
531  shouldIndexFile(FileID);
532  if (auto FileURI = GetURI(FileID)) {
533  auto Range =
534  getTokenRange(LocAndRole.first, SM, ASTCtx->getLangOpts());
535  Ref R;
536  R.Location.Start = Range.first;
537  R.Location.End = Range.second;
538  R.Location.FileURI = FileURI->c_str();
539  R.Kind = toRefKind(LocAndRole.second);
540  Refs.insert(*ID, R);
541  }
542  }
543  }
544  }
545  }
546 
547  ReferencedDecls.clear();
548  ReferencedMacros.clear();
549  DeclRefs.clear();
550  FilesToIndexCache.clear();
551  HeaderIsSelfContainedCache.clear();
552  IncludeFiles.clear();
553 }
554 
555 const Symbol *SymbolCollector::addDeclaration(const NamedDecl &ND, SymbolID ID,
556  bool IsMainFileOnly) {
557  auto &Ctx = ND.getASTContext();
558  auto &SM = Ctx.getSourceManager();
559 
560  Symbol S;
561  S.ID = std::move(ID);
562  std::string QName = printQualifiedName(ND);
563  // FIXME: this returns foo:bar: for objective-C methods, we prefer only foo:
564  // for consistency with CodeCompletionString and a clean name/signature split.
565  std::tie(S.Scope, S.Name) = splitQualifiedName(QName);
566  std::string TemplateSpecializationArgs = printTemplateSpecializationArgs(ND);
567  S.TemplateSpecializationArgs = TemplateSpecializationArgs;
568 
569  // We collect main-file symbols, but do not use them for code completion.
570  if (!IsMainFileOnly && isIndexedForCodeCompletion(ND, Ctx))
572  if (isImplementationDetail(&ND))
574  if (!IsMainFileOnly)
576  S.SymInfo = index::getSymbolInfo(&ND);
577  std::string FileURI;
578  auto Loc = spellingLocIfSpelled(findName(&ND), SM);
579  assert(Loc.isValid() && "Invalid source location for NamedDecl");
580  // FIXME: use the result to filter out symbols.
581  shouldIndexFile(SM.getFileID(Loc));
582  if (auto DeclLoc =
583  getTokenLocation(Loc, SM, Opts, ASTCtx->getLangOpts(), FileURI))
584  S.CanonicalDeclaration = *DeclLoc;
585 
586  S.Origin = Opts.Origin;
587  if (ND.getAvailability() == AR_Deprecated)
589 
590  // Add completion info.
591  // FIXME: we may want to choose a different redecl, or combine from several.
592  assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
593  // We use the primary template, as clang does during code completion.
594  CodeCompletionResult SymbolCompletion(&getTemplateOrThis(ND), 0);
595  const auto *CCS = SymbolCompletion.CreateCodeCompletionString(
596  *ASTCtx, *PP, CodeCompletionContext::CCC_Symbol, *CompletionAllocator,
597  *CompletionTUInfo,
598  /*IncludeBriefComments*/ false);
599  std::string Documentation =
600  formatDocumentation(*CCS, getDocComment(Ctx, SymbolCompletion,
601  /*CommentsFromHeaders=*/true));
603  if (Opts.StoreAllDocumentation)
604  S.Documentation = Documentation;
605  Symbols.insert(S);
606  return Symbols.find(S.ID);
607  }
608  S.Documentation = Documentation;
609  std::string Signature;
610  std::string SnippetSuffix;
611  getSignature(*CCS, &Signature, &SnippetSuffix);
612  S.Signature = Signature;
614  std::string ReturnType = getReturnType(*CCS);
616 
617  llvm::Optional<OpaqueType> TypeStorage;
619  TypeStorage = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion);
620  if (TypeStorage)
621  S.Type = TypeStorage->raw();
622  }
623 
624  Symbols.insert(S);
625  setIncludeLocation(S, ND.getLocation());
626  return Symbols.find(S.ID);
627 }
628 
629 void SymbolCollector::addDefinition(const NamedDecl &ND,
630  const Symbol &DeclSym) {
631  if (DeclSym.Definition)
632  return;
633  // If we saw some forward declaration, we end up copying the symbol.
634  // This is not ideal, but avoids duplicating the "is this a definition" check
635  // in clang::index. We should only see one definition.
636  Symbol S = DeclSym;
637  std::string FileURI;
638  const auto &SM = ND.getASTContext().getSourceManager();
639  auto Loc = spellingLocIfSpelled(findName(&ND), SM);
640  // FIXME: use the result to filter out symbols.
641  shouldIndexFile(SM.getFileID(Loc));
642  if (auto DefLoc =
643  getTokenLocation(Loc, SM, Opts, ASTCtx->getLangOpts(), FileURI))
644  S.Definition = *DefLoc;
645  Symbols.insert(S);
646 }
647 
648 /// Gets a canonical include (URI of the header or <header> or "header") for
649 /// header of \p FID (which should usually be the *expansion* file).
650 /// Returns None if includes should not be inserted for this file.
651 llvm::Optional<std::string>
652 SymbolCollector::getIncludeHeader(llvm::StringRef QName, FileID FID) {
653  const SourceManager &SM = ASTCtx->getSourceManager();
654  const FileEntry *FE = SM.getFileEntryForID(FID);
655  if (!FE || FE->getName().empty())
656  return llvm::None;
657  llvm::StringRef Filename = FE->getName();
658  // If a file is mapped by canonical headers, use that mapping, regardless
659  // of whether it's an otherwise-good header (header guards etc).
660  if (Opts.Includes) {
661  llvm::StringRef Canonical = Opts.Includes->mapHeader(Filename, QName);
662  // If we had a mapping, always use it.
663  if (Canonical.startswith("<") || Canonical.startswith("\""))
664  return Canonical.str();
665  if (Canonical != Filename)
666  return toURI(SM, Canonical, Opts);
667  }
668  if (!isSelfContainedHeader(FID)) {
669  // A .inc or .def file is often included into a real header to define
670  // symbols (e.g. LLVM tablegen files).
671  if (Filename.endswith(".inc") || Filename.endswith(".def"))
672  return getIncludeHeader(QName, SM.getFileID(SM.getIncludeLoc(FID)));
673  // Conservatively refuse to insert #includes to files without guards.
674  return llvm::None;
675  }
676  // Standard case: just insert the file itself.
677  return toURI(SM, Filename, Opts);
678 }
679 
680 bool SymbolCollector::isSelfContainedHeader(FileID FID) {
681  // The real computation (which will be memoized).
682  auto Compute = [&] {
683  const SourceManager &SM = ASTCtx->getSourceManager();
684  const FileEntry *FE = SM.getFileEntryForID(FID);
685  if (!FE)
686  return false;
687  if (!PP->getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE))
688  return false;
689  // This pattern indicates that a header can't be used without
690  // particular preprocessor state, usually set up by another header.
691  if (isDontIncludeMeHeader(SM.getBufferData(FID)))
692  return false;
693  return true;
694  };
695 
696  auto R = HeaderIsSelfContainedCache.try_emplace(FID, false);
697  if (R.second)
698  R.first->second = Compute();
699  return R.first->second;
700 }
701 
702 // Is Line an #if or #ifdef directive?
703 static bool isIf(llvm::StringRef Line) {
704  Line = Line.ltrim();
705  if (!Line.consume_front("#"))
706  return false;
707  Line = Line.ltrim();
708  return Line.startswith("if");
709 }
710 // Is Line an #error directive mentioning includes?
711 static bool isErrorAboutInclude(llvm::StringRef Line) {
712  Line = Line.ltrim();
713  if (!Line.consume_front("#"))
714  return false;
715  Line = Line.ltrim();
716  if (!Line.startswith("error"))
717  return false;
718  return Line.contains_lower("includ"); // Matches "include" or "including".
719 }
720 
721 bool SymbolCollector::isDontIncludeMeHeader(llvm::StringRef Content) {
722  llvm::StringRef Line;
723  // Only sniff up to 100 lines or 10KB.
724  Content = Content.take_front(100 * 100);
725  for (unsigned I = 0; I < 100 && !Content.empty(); ++I) {
726  std::tie(Line, Content) = Content.split('\n');
727  if (isIf(Line) && isErrorAboutInclude(Content.split('\n').first))
728  return true;
729  }
730  return false;
731 }
732 
734  if (!Opts.FileFilter)
735  return true;
736  auto I = FilesToIndexCache.try_emplace(FID);
737  if (I.second)
738  I.first->second = Opts.FileFilter(ASTCtx->getSourceManager(), FID);
739  return I.first->second;
740 }
741 
742 } // namespace clangd
743 } // namespace clang
SourceLocation Loc
&#39;#&#39; location in the include directive
bool handleMacroOccurence(const IdentifierInfo *Name, const MacroInfo *MI, index::SymbolRoleSet Roles, SourceLocation Loc) override
SourceLocation findName(const clang::Decl *D)
Find the identifier source location of the given D.
Definition: AST.cpp:83
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
Definition: AST.cpp:87
Represents a relation between two symbols.
Definition: Relation.h:29
llvm::Optional< SymbolID > getSymbolID(const Decl *D)
Gets the symbol ID for a declaration, if possible.
Definition: AST.cpp:199
const Symbol * find(const SymbolID &ID)
Returns the symbol with an ID, if it exists. Valid until insert/remove.
Definition: Symbol.h:211
clang::find_all_symbols::SymbolInfo::SymbolKind SymbolKind
Definition: SymbolInfo.cpp:21
std::pair< StringRef, StringRef > splitQualifiedName(StringRef QName)
Definition: SourceCode.cpp:602
bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM)
Returns true iff Loc is inside the main file.
Definition: SourceCode.cpp:537
Represents a symbol occurrence in the source file.
Definition: Ref.h:52
Symbol is visible to other files (not e.g. a static helper function).
Definition: Symbol.h:125
void insert(const Symbol &S)
Adds a symbol, overwriting any existing one with the same ID.
Definition: Symbol.cpp:50
def make_absolute(f, directory)
llvm::StringRef Scope
The containing namespace. e.g. "" (global), "ns::" (top-level namespace).
Definition: Symbol.h:44
std::string getDocComment(const ASTContext &Ctx, const CodeCompletionResult &Result, bool CommentsFromHeaders)
Gets a minimally formatted documentation comment of Result, with comment markers stripped.
Documents should not be synced at all.
std::string printTemplateSpecializationArgs(const NamedDecl &ND)
Prints template arguments of a decl as written in the source code, including enclosing &#39;<&#39; and &#39;>&#39;...
Definition: AST.cpp:162
void erase(const SymbolID &ID)
Removes the symbol with an ID, if it exists.
Definition: Symbol.h:208
void initialize(ASTContext &Ctx) override
unsigned References
The number of translation units that reference this symbol from their main file.
Definition: Symbol.h:59
SymbolID ID
The ID of the symbol.
Definition: Symbol.h:38
index::SymbolInfo SymInfo
The symbol information, like symbol kind.
Definition: Symbol.h:40
std::string getReturnType(const CodeCompletionString &CCS)
Gets detail to be used as the detail field in an LSP completion item.
BindArgumentKind Kind
Symbol is an implementation detail.
Definition: Symbol.h:123
SymbolLocation Definition
The location of the symbol&#39;s definition, if one was found.
Definition: Symbol.h:47
Context Ctx
std::vector< SymbolDetails > getSymbolInfo(ParsedAST &AST, Position Pos)
Get info about symbols at Pos.
Definition: XRefs.cpp:983
std::string QName
std::string Filename
Filename as a string.
Whether or not this symbol is meant to be used for the code completion.
Definition: Symbol.h:119
bool handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles, ArrayRef< index::SymbolRelation > Relations, SourceLocation Loc, index::IndexDataConsumer::ASTNodeInfo ASTNode) override
bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx)
llvm::SmallVector< IncludeHeaderWithReferences, 1 > IncludeHeaders
One Symbol can potentially be incuded via different headers.
Definition: Symbol.h:111
SymbolFlag Flags
Definition: Symbol.h:128
static bool isErrorAboutInclude(llvm::StringRef Line)
llvm::StringRef Signature
A brief description of the symbol that can be appended in the completion candidate list...
Definition: Symbol.h:65
SymbolLocation Location
The source location where the symbol is named.
Definition: Ref.h:54
std::string Signature
llvm::StringRef Documentation
Documentation including comment for the symbol declaration.
Definition: Symbol.h:76
std::string Path
A typedef to represent a file path.
Definition: Path.h:20
static constexpr llvm::StringLiteral Name
SymbolLocation CanonicalDeclaration
The location of the preferred declaration of the symbol.
Definition: Symbol.h:56
const Decl * D
Definition: XRefs.cpp:849
RefKind
Describes the kind of a cross-reference.
Definition: Ref.h:28
PathRef FileName
std::string formatDocumentation(const CodeCompletionString &CCS, llvm::StringRef DocComment)
Assembles formatted documentation for a completion result.
llvm::Optional< Range > getTokenRange(const SourceManager &SM, const LangOptions &LangOpts, SourceLocation TokLoc)
Returns the taken range at TokLoc.
Definition: SourceCode.cpp:229
std::string ReturnType
bool shouldIndexFile(FileID FID)
Returns true if we are interested in references and declarations from FID.
std::string SnippetSuffix
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
Definition: SourceCode.cpp:194
bool CollectMainFileSymbols
Collect symbols local to main-files, such as static functions and symbols inside an anonymous namespa...
static bool shouldCollectSymbol(const NamedDecl &ND, const ASTContext &ASTCtx, const Options &Opts, bool IsMainFileSymbol)
Returns true is ND should be collected.
static llvm::Expected< URI > create(llvm::StringRef AbsolutePath, llvm::StringRef Scheme)
Creates a URI for a file in the given scheme.
Definition: URI.cpp:197
The class presents a C++ symbol, e.g.
Definition: Symbol.h:36
Position Start
The symbol range, using half-open range [Start, End).
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
llvm::StringRef Name
The unqualified name of the symbol, e.g. "bar" (for ns::bar).
Definition: Symbol.h:42
CharSourceRange Range
SourceRange for the file name.
SourceLocation spellingLocIfSpelled(SourceLocation Loc, const SourceManager &SM)
Returns the spelling location of the token at Loc if isSpelledInSource, otherwise its expansion locat...
Definition: SourceCode.cpp:221
llvm::Optional< std::string > getCanonicalPath(const FileEntry *F, const SourceManager &SourceMgr)
Get the canonical path of F.
Definition: SourceCode.cpp:625
void getSignature(const CodeCompletionString &CCS, std::string *Signature, std::string *Snippet, std::string *RequiredQualifiers, bool CompletingPattern)
Formats the signature for an item, as a display string and snippet.
void insert(const SymbolID &ID, const Ref &S)
Adds a ref to the slab. Deep copy: Strings will be owned by the slab.
Definition: Ref.cpp:35
bool isImplementationDetail(const Decl *D)
Returns true if the declaration is considered implementation detail based on heuristics.
Definition: AST.cpp:78
llvm::StringRef CompletionSnippetSuffix
What to insert when completing this symbol, after the symbol name.
Definition: Symbol.h:74
Indicates if the symbol is deprecated.
Definition: Symbol.h:121
static bool isIf(llvm::StringRef Line)
llvm::StringRef Type
Raw representation of the OpaqueType of the symbol, used for scoring purposes.
Definition: Symbol.h:85
SymbolOrigin Origin
Where this symbol came from. Usually an index provides a constant value.
Definition: Symbol.h:61
llvm::StringRef TemplateSpecializationArgs
Argument list in human-readable format, will be displayed to help disambiguate between different spec...
Definition: Symbol.h:69
llvm::StringRef ReturnType
Type when this symbol is used in an expression.
Definition: Symbol.h:80
static llvm::Optional< OpaqueType > fromCompletionResult(ASTContext &Ctx, const CodeCompletionResult &R)
Create a type from a code completion result.