| 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 "CodeComplete.h" |
| 12 |
#include "CodeCompletionStrings.h" |
| 13 |
#include "ExpectedTypes.h" |
| 14 |
#include "SourceCode.h" |
| 15 |
#include "URI.h" |
| 16 |
#include "clang-include-cleaner/Analysis.h" |
| 17 |
#include "clang-include-cleaner/IncludeSpeller.h" |
| 18 |
#include "clang-include-cleaner/Record.h" |
| 19 |
#include "clang-include-cleaner/Types.h" |
| 20 |
#include "index/CanonicalIncludes.h" |
| 21 |
#include "index/Ref.h" |
| 22 |
#include "index/Relation.h" |
| 23 |
#include "index/Symbol.h" |
| 24 |
#include "index/SymbolID.h" |
| 25 |
#include "index/SymbolLocation.h" |
| 26 |
#include "clang/AST/Decl.h" |
| 27 |
#include "clang/AST/DeclBase.h" |
| 28 |
#include "clang/AST/DeclCXX.h" |
| 29 |
#include "clang/AST/DeclObjC.h" |
| 30 |
#include "clang/AST/DeclTemplate.h" |
| 31 |
#include "clang/AST/DeclarationName.h" |
| 32 |
#include "clang/AST/Expr.h" |
| 33 |
#include "clang/Basic/FileEntry.h" |
| 34 |
#include "clang/Basic/LangOptions.h" |
| 35 |
#include "clang/Basic/SourceLocation.h" |
| 36 |
#include "clang/Basic/SourceManager.h" |
| 37 |
#include "clang/Index/IndexSymbol.h" |
| 38 |
#include "clang/Lex/Preprocessor.h" |
| 39 |
#include "clang/Lex/Token.h" |
| 40 |
#include "clang/Tooling/Inclusions/HeaderAnalysis.h" |
| 41 |
#include "clang/Tooling/Inclusions/StandardLibrary.h" |
| 42 |
#include "llvm/ADT/ArrayRef.h" |
| 43 |
#include "llvm/ADT/DenseMap.h" |
| 44 |
#include "llvm/ADT/SmallVector.h" |
| 45 |
#include "llvm/ADT/StringRef.h" |
| 46 |
#include "llvm/Support/Casting.h" |
| 47 |
#include "llvm/Support/ErrorHandling.h" |
| 48 |
#include "llvm/Support/Path.h" |
| 49 |
#include <cassert> |
| 50 |
#include <memory> |
| 51 |
#include <optional> |
| 52 |
#include <string> |
| 53 |
#include <utility> |
| 54 |
|
| 55 |
namespace clang { |
| 56 |
namespace clangd { |
| 57 |
namespace { |
| 58 |
|
| 59 |
/// If \p ND is a template specialization, returns the described template. |
| 60 |
/// Otherwise, returns \p ND. |
| 61 |
const NamedDecl &getTemplateOrThis(const NamedDecl &ND) { |
| 62 |
if (auto *T = ND.getDescribedTemplate()) |
| 63 |
return *T; |
| 64 |
return ND; |
| 65 |
} |
| 66 |
|
| 67 |
// Checks whether the decl is a private symbol in a header generated by |
| 68 |
// protobuf compiler. |
| 69 |
// FIXME: make filtering extensible when there are more use cases for symbol |
| 70 |
// filters. |
| 71 |
bool isPrivateProtoDecl(const NamedDecl &ND) { |
| 72 |
const auto &SM = ND.getASTContext().getSourceManager(); |
| 73 |
if (!isProtoFile(nameLocation(ND, SM), SM)) |
| 74 |
return false; |
| 75 |
|
| 76 |
// ND without identifier can be operators. |
| 77 |
if (ND.getIdentifier() == nullptr) |
| 78 |
return false; |
| 79 |
auto Name = ND.getIdentifier()->getName(); |
| 80 |
// There are some internal helpers like _internal_set_foo(); |
| 81 |
if (Name.contains("_internal_")) |
| 82 |
return true; |
| 83 |
|
| 84 |
// https://protobuf.dev/reference/cpp/cpp-generated/#nested-types |
| 85 |
// Nested entities (messages/enums) has two names, one at the top-level scope, |
| 86 |
// with a mangled name created by prepending all the outer types. These names |
| 87 |
// are almost never preferred by the developers, so exclude them from index. |
| 88 |
// e.g. |
| 89 |
// message Foo { |
| 90 |
// message Bar {} |
| 91 |
// enum E { A } |
| 92 |
// } |
| 93 |
// |
| 94 |
// yields: |
| 95 |
// class Foo_Bar {}; |
| 96 |
// enum Foo_E { Foo_E_A }; |
| 97 |
// class Foo { |
| 98 |
// using Bar = Foo_Bar; |
| 99 |
// static constexpr Foo_E A = Foo_E_A; |
| 100 |
// }; |
| 101 |
|
| 102 |
// We get rid of Foo_Bar and Foo_E by discarding any top-level entries with |
| 103 |
// `_` in the name. This relies on original message/enum not having `_` in the |
| 104 |
// name. Hence might go wrong in certain cases. |
| 105 |
if (ND.getDeclContext()->isNamespace()) { |
| 106 |
// Strip off some known public suffix helpers for enums, rest of the helpers |
| 107 |
// are generated inside record decls so we don't care. |
| 108 |
// https://protobuf.dev/reference/cpp/cpp-generated/#enum |
| 109 |
Name.consume_back("_descriptor"); |
| 110 |
Name.consume_back("_IsValid"); |
| 111 |
Name.consume_back("_Name"); |
| 112 |
Name.consume_back("_Parse"); |
| 113 |
Name.consume_back("_MIN"); |
| 114 |
Name.consume_back("_MAX"); |
| 115 |
Name.consume_back("_ARRAYSIZE"); |
| 116 |
return Name.contains('_'); |
| 117 |
} |
| 118 |
|
| 119 |
// EnumConstantDecls need some special attention, despite being nested in a |
| 120 |
// TagDecl, they might still have mangled names. We filter those by checking |
| 121 |
// if it has parent's name as a prefix. |
| 122 |
// This might go wrong if a nested entity has a name that starts with parent's |
| 123 |
// name, e.g: enum Foo { Foo_X }. |
| 124 |
if (llvm::isa<EnumConstantDecl>(&ND)) { |
| 125 |
auto *DC = llvm::cast<EnumDecl>(ND.getDeclContext()); |
| 126 |
if (!DC || !DC->getIdentifier()) |
| 127 |
return false; |
| 128 |
auto CtxName = DC->getIdentifier()->getName(); |
| 129 |
return !CtxName.empty() && Name.consume_front(CtxName) && |
| 130 |
Name.consume_front("_"); |
| 131 |
} |
| 132 |
|
| 133 |
// Now we're only left with fields/methods without an `_internal_` in the |
| 134 |
// name, they're intended for public use. |
| 135 |
return false; |
| 136 |
} |
| 137 |
|
| 138 |
// We only collect #include paths for symbols that are suitable for global code |
| 139 |
// completion, except for namespaces since #include path for a namespace is hard |
| 140 |
// to define. |
| 141 |
Symbol::IncludeDirective shouldCollectIncludePath(index::SymbolKind Kind) { |
| 142 |
using SK = index::SymbolKind; |
| 143 |
switch (Kind) { |
| 144 |
case SK::Macro: |
| 145 |
case SK::Enum: |
| 146 |
case SK::Struct: |
| 147 |
case SK::Class: |
| 148 |
case SK::Union: |
| 149 |
case SK::TypeAlias: |
| 150 |
case SK::Using: |
| 151 |
case SK::Function: |
| 152 |
case SK::Variable: |
| 153 |
case SK::EnumConstant: |
| 154 |
case SK::Concept: |
| 155 |
return Symbol::Include | Symbol::Import; |
| 156 |
case SK::Protocol: |
| 157 |
return Symbol::Import; |
| 158 |
default: |
| 159 |
return Symbol::Invalid; |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
// Return the symbol range of the token at \p TokLoc. |
| 164 |
std::pair<SymbolLocation::Position, SymbolLocation::Position> |
| 165 |
getTokenRange(SourceLocation TokLoc, const SourceManager &SM, |
| 166 |
const LangOptions &LangOpts) { |
| 167 |
auto CreatePosition = [&SM](SourceLocation Loc) { |
| 168 |
auto LSPLoc = sourceLocToPosition(SM, Loc); |
| 169 |
SymbolLocation::Position Pos; |
| 170 |
Pos.setLine(LSPLoc.line); |
| 171 |
Pos.setColumn(LSPLoc.character); |
| 172 |
return Pos; |
| 173 |
}; |
| 174 |
|
| 175 |
auto TokenLength = clang::Lexer::MeasureTokenLength(TokLoc, SM, LangOpts); |
| 176 |
return {CreatePosition(TokLoc), |
| 177 |
CreatePosition(TokLoc.getLocWithOffset(TokenLength))}; |
| 178 |
} |
| 179 |
|
| 180 |
// Checks whether \p ND is a good candidate to be the *canonical* declaration of |
| 181 |
// its symbol (e.g. a go-to-declaration target). This overrides the default of |
| 182 |
// using Clang's canonical declaration, which is the first in the TU. |
| 183 |
// |
| 184 |
// Example: preferring a class declaration over its forward declaration. |
| 185 |
bool isPreferredDeclaration(const NamedDecl &ND, index::SymbolRoleSet Roles) { |
| 186 |
const auto &SM = ND.getASTContext().getSourceManager(); |
| 187 |
if (isa<TagDecl>(ND)) |
| 188 |
return (Roles & static_cast<unsigned>(index::SymbolRole::Definition)) && |
| 189 |
!isInsideMainFile(ND.getLocation(), SM); |
| 190 |
if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(&ND)) |
| 191 |
return ID->isThisDeclarationADefinition(); |
| 192 |
if (const auto *PD = dyn_cast<ObjCProtocolDecl>(&ND)) |
| 193 |
return PD->isThisDeclarationADefinition(); |
| 194 |
return false; |
| 195 |
} |
| 196 |
|
| 197 |
RefKind toRefKind(index::SymbolRoleSet Roles, bool Spelled = false) { |
| 198 |
RefKind Result = RefKind::Unknown; |
| 199 |
if (Roles & static_cast<unsigned>(index::SymbolRole::Declaration)) |
| 200 |
Result |= RefKind::Declaration; |
| 201 |
if (Roles & static_cast<unsigned>(index::SymbolRole::Definition)) |
| 202 |
Result |= RefKind::Definition; |
| 203 |
if (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) |
| 204 |
Result |= RefKind::Reference; |
| 205 |
if (Spelled) |
| 206 |
Result |= RefKind::Spelled; |
| 207 |
return Result; |
| 208 |
} |
| 209 |
|
| 210 |
std::optional<RelationKind> indexableRelation(const index::SymbolRelation &R) { |
| 211 |
if (R.Roles & static_cast<unsigned>(index::SymbolRole::RelationBaseOf)) |
| 212 |
return RelationKind::BaseOf; |
| 213 |
if (R.Roles & static_cast<unsigned>(index::SymbolRole::RelationOverrideOf)) |
| 214 |
return RelationKind::OverriddenBy; |
| 215 |
return std::nullopt; |
| 216 |
} |
| 217 |
|
| 218 |
// Check if there is an exact spelling of \p ND at \p Loc. |
| 219 |
bool isSpelled(SourceLocation Loc, const NamedDecl &ND) { |
| 220 |
auto Name = ND.getDeclName(); |
| 221 |
const auto NameKind = Name.getNameKind(); |
| 222 |
if (NameKind != DeclarationName::Identifier && |
| 223 |
NameKind != DeclarationName::CXXConstructorName && |
| 224 |
NameKind != DeclarationName::ObjCZeroArgSelector && |
| 225 |
NameKind != DeclarationName::ObjCOneArgSelector && |
| 226 |
NameKind != DeclarationName::ObjCMultiArgSelector) |
| 227 |
return false; |
| 228 |
const auto &AST = ND.getASTContext(); |
| 229 |
const auto &SM = AST.getSourceManager(); |
| 230 |
const auto &LO = AST.getLangOpts(); |
| 231 |
clang::Token Tok; |
| 232 |
if (clang::Lexer::getRawToken(Loc, Tok, SM, LO)) |
| 233 |
return false; |
| 234 |
auto TokSpelling = clang::Lexer::getSpelling(Tok, SM, LO); |
| 235 |
if (const auto *MD = dyn_cast<ObjCMethodDecl>(&ND)) |
| 236 |
return TokSpelling == MD->getSelector().getNameForSlot(0); |
| 237 |
return TokSpelling == Name.getAsString(); |
| 238 |
} |
| 239 |
} // namespace |
| 240 |
|
| 241 |
// Encapsulates decisions about how to record header paths in the index, |
| 242 |
// including filename normalization, URI conversion etc. |
| 243 |
// Expensive checks are cached internally. |
| 244 |
class SymbolCollector::HeaderFileURICache { |
| 245 |
struct FrameworkUmbrellaSpelling { |
| 246 |
// Spelling for the public umbrella header, e.g. <Foundation/Foundation.h> |
| 247 |
std::optional<std::string> PublicHeader; |
| 248 |
// Spelling for the private umbrella header, e.g. |
| 249 |
// <Foundation/Foundation_Private.h> |
| 250 |
std::optional<std::string> PrivateHeader; |
| 251 |
}; |
| 252 |
// Weird double-indirect access to PP, which might not be ready yet when |
| 253 |
// HeaderFiles is created but will be by the time it's used. |
| 254 |
// (IndexDataConsumer::setPreprocessor can happen before or after initialize) |
| 255 |
Preprocessor *&PP; |
| 256 |
const SourceManager &SM; |
| 257 |
const include_cleaner::PragmaIncludes *PI; |
| 258 |
llvm::StringRef FallbackDir; |
| 259 |
llvm::DenseMap<const FileEntry *, const std::string *> CacheFEToURI; |
| 260 |
llvm::StringMap<std::string> CachePathToURI; |
| 261 |
llvm::DenseMap<FileID, llvm::StringRef> CacheFIDToInclude; |
| 262 |
llvm::StringMap<std::string> CachePathToFrameworkSpelling; |
| 263 |
llvm::StringMap<FrameworkUmbrellaSpelling> |
| 264 |
CacheFrameworkToUmbrellaHeaderSpelling; |
| 265 |
|
| 266 |
public: |
| 267 |
HeaderFileURICache(Preprocessor *&PP, const SourceManager &SM, |
| 268 |
const SymbolCollector::Options &Opts) |
| 269 |
: PP(PP), SM(SM), PI(Opts.PragmaIncludes), FallbackDir(Opts.FallbackDir) { |
| 270 |
} |
| 271 |
|
| 272 |
// Returns a canonical URI for the file \p FE. |
| 273 |
// We attempt to make the path absolute first. |
| 274 |
const std::string &toURI(const FileEntryRef FE) { |
| 275 |
auto R = CacheFEToURI.try_emplace(FE); |
| 276 |
if (R.second) { |
| 277 |
auto CanonPath = getCanonicalPath(FE, SM.getFileManager()); |
| 278 |
R.first->second = &toURIInternal(CanonPath ? *CanonPath : FE.getName()); |
| 279 |
} |
| 280 |
return *R.first->second; |
| 281 |
} |
| 282 |
|
| 283 |
// Returns a canonical URI for \p Path. |
| 284 |
// If the file is in the FileManager, use that to canonicalize the path. |
| 285 |
// We attempt to make the path absolute in any case. |
| 286 |
const std::string &toURI(llvm::StringRef Path) { |
| 287 |
if (auto File = SM.getFileManager().getFileRef(Path)) |
| 288 |
return toURI(*File); |
| 289 |
return toURIInternal(Path); |
| 290 |
} |
| 291 |
|
| 292 |
// Gets a canonical include (URI of the header or <header> or "header") for |
| 293 |
// header of \p FID (which should usually be the *expansion* file). |
| 294 |
// This does not account for any per-symbol overrides! |
| 295 |
// Returns "" if includes should not be inserted for this file. |
| 296 |
llvm::StringRef getIncludeHeader(FileID FID) { |
| 297 |
auto R = CacheFIDToInclude.try_emplace(FID); |
| 298 |
if (R.second) |
| 299 |
R.first->second = getIncludeHeaderUncached(FID); |
| 300 |
return R.first->second; |
| 301 |
} |
| 302 |
|
| 303 |
// If a file is mapped by canonical headers, use that mapping, regardless |
| 304 |
// of whether it's an otherwise-good header (header guards etc). |
| 305 |
llvm::StringRef mapCanonical(llvm::StringRef HeaderPath) { |
| 306 |
if (!PP) |
| 307 |
return ""; |
| 308 |
// Populate the system header mapping as late as possible to |
| 309 |
// ensure the preprocessor has been set already. |
| 310 |
CanonicalIncludes SysHeaderMapping; |
| 311 |
SysHeaderMapping.addSystemHeadersMapping(PP->getLangOpts()); |
| 312 |
auto Canonical = SysHeaderMapping.mapHeader(HeaderPath); |
| 313 |
if (Canonical.empty()) |
| 314 |
return ""; |
| 315 |
// If we had a mapping, always use it. |
| 316 |
assert(Canonical.starts_with("<") || Canonical.starts_with("\"")); |
| 317 |
return Canonical; |
| 318 |
} |
| 319 |
|
| 320 |
private: |
| 321 |
// This takes care of making paths absolute and path->URI caching, but no |
| 322 |
// FileManager-based canonicalization. |
| 323 |
const std::string &toURIInternal(llvm::StringRef Path) { |
| 324 |
auto R = CachePathToURI.try_emplace(Path); |
| 325 |
if (R.second) { |
| 326 |
llvm::SmallString<256> AbsPath = Path; |
| 327 |
if (!llvm::sys::path::is_absolute(AbsPath) && !FallbackDir.empty()) |
| 328 |
llvm::sys::path::make_absolute(FallbackDir, AbsPath); |
| 329 |
assert(llvm::sys::path::is_absolute(AbsPath) && |
| 330 |
"If the VFS can't make paths absolute, a FallbackDir must be " |
| 331 |
"provided"); |
| 332 |
llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true); |
| 333 |
R.first->second = URI::create(AbsPath).toString(); |
| 334 |
} |
| 335 |
return R.first->second; |
| 336 |
} |
| 337 |
|
| 338 |
struct FrameworkHeaderPath { |
| 339 |
// Path to the frameworks directory containing the .framework directory. |
| 340 |
llvm::StringRef FrameworkParentDir; |
| 341 |
// Name of the framework. |
| 342 |
llvm::StringRef FrameworkName; |
| 343 |
// Subpath relative to the Headers or PrivateHeaders dir, e.g. NSObject.h |
| 344 |
// Note: This is NOT relative to the `HeadersParentDir`. |
| 345 |
llvm::StringRef HeaderSubpath; |
| 346 |
// Whether this header is under the PrivateHeaders dir |
| 347 |
bool IsPrivateHeader; |
| 348 |
}; |
| 349 |
|
| 350 |
std::optional<FrameworkHeaderPath> |
| 351 |
splitFrameworkHeaderPath(llvm::StringRef Path) { |
| 352 |
using namespace llvm::sys; |
| 353 |
path::reverse_iterator I = path::rbegin(Path); |
| 354 |
path::reverse_iterator Prev = I; |
| 355 |
path::reverse_iterator E = path::rend(Path); |
| 356 |
FrameworkHeaderPath HeaderPath; |
| 357 |
while (I != E) { |
| 358 |
if (*I == "Headers" || *I == "PrivateHeaders") { |
| 359 |
HeaderPath.HeaderSubpath = Path.substr(Prev - E); |
| 360 |
HeaderPath.IsPrivateHeader = *I == "PrivateHeaders"; |
| 361 |
if (++I == E) |
| 362 |
break; |
| 363 |
HeaderPath.FrameworkName = *I; |
| 364 |
if (!HeaderPath.FrameworkName.consume_back(".framework")) |
| 365 |
break; |
| 366 |
HeaderPath.FrameworkParentDir = Path.substr(0, I - E); |
| 367 |
return HeaderPath; |
| 368 |
} |
| 369 |
Prev = I; |
| 370 |
++I; |
| 371 |
} |
| 372 |
// Unexpected, must not be a framework header. |
| 373 |
return std::nullopt; |
| 374 |
} |
| 375 |
|
| 376 |
// Frameworks typically have an umbrella header of the same name, e.g. |
| 377 |
// <Foundation/Foundation.h> instead of <Foundation/NSObject.h> or |
| 378 |
// <Foundation/Foundation_Private.h> instead of |
| 379 |
// <Foundation/NSObject_Private.h> which should be used instead of directly |
| 380 |
// importing the header. |
| 381 |
std::optional<std::string> |
| 382 |
getFrameworkUmbrellaSpelling(const HeaderSearch &HS, |
| 383 |
FrameworkHeaderPath &HeaderPath) { |
| 384 |
StringRef Framework = HeaderPath.FrameworkName; |
| 385 |
auto Res = CacheFrameworkToUmbrellaHeaderSpelling.try_emplace(Framework); |
| 386 |
auto *CachedSpelling = &Res.first->second; |
| 387 |
if (!Res.second) { |
| 388 |
return HeaderPath.IsPrivateHeader ? CachedSpelling->PrivateHeader |
| 389 |
: CachedSpelling->PublicHeader; |
| 390 |
} |
| 391 |
SmallString<256> UmbrellaPath(HeaderPath.FrameworkParentDir); |
| 392 |
llvm::sys::path::append(UmbrellaPath, Framework + ".framework", "Headers", |
| 393 |
Framework + ".h"); |
| 394 |
|
| 395 |
llvm::vfs::Status Status; |
| 396 |
auto StatErr = HS.getFileMgr().getNoncachedStatValue(UmbrellaPath, Status); |
| 397 |
if (!StatErr) |
| 398 |
CachedSpelling->PublicHeader = llvm::formatv("<{0}/{0}.h>", Framework); |
| 399 |
|
| 400 |
UmbrellaPath = HeaderPath.FrameworkParentDir; |
| 401 |
llvm::sys::path::append(UmbrellaPath, Framework + ".framework", |
| 402 |
"PrivateHeaders", Framework + "_Private.h"); |
| 403 |
|
| 404 |
StatErr = HS.getFileMgr().getNoncachedStatValue(UmbrellaPath, Status); |
| 405 |
if (!StatErr) |
| 406 |
CachedSpelling->PrivateHeader = |
| 407 |
llvm::formatv("<{0}/{0}_Private.h>", Framework); |
| 408 |
|
| 409 |
return HeaderPath.IsPrivateHeader ? CachedSpelling->PrivateHeader |
| 410 |
: CachedSpelling->PublicHeader; |
| 411 |
} |
| 412 |
|
| 413 |
// Compute the framework include spelling for `FE` which is in a framework |
| 414 |
// named `Framework`, e.g. `NSObject.h` in framework `Foundation` would |
| 415 |
// give <Foundation/Foundation.h> if the umbrella header exists, otherwise |
| 416 |
// <Foundation/NSObject.h>. |
| 417 |
std::optional<llvm::StringRef> |
| 418 |
getFrameworkHeaderIncludeSpelling(FileEntryRef FE, HeaderSearch &HS) { |
| 419 |
auto Res = CachePathToFrameworkSpelling.try_emplace(FE.getName()); |
| 420 |
auto *CachedHeaderSpelling = &Res.first->second; |
| 421 |
if (!Res.second) |
| 422 |
return llvm::StringRef(*CachedHeaderSpelling); |
| 423 |
|
| 424 |
auto HeaderPath = splitFrameworkHeaderPath(FE.getName()); |
| 425 |
if (!HeaderPath) { |
| 426 |
// Unexpected: must not be a proper framework header, don't cache the |
| 427 |
// failure. |
| 428 |
CachePathToFrameworkSpelling.erase(Res.first); |
| 429 |
return std::nullopt; |
| 430 |
} |
| 431 |
if (auto UmbrellaSpelling = |
| 432 |
getFrameworkUmbrellaSpelling(HS, *HeaderPath)) { |
| 433 |
*CachedHeaderSpelling = *UmbrellaSpelling; |
| 434 |
return llvm::StringRef(*CachedHeaderSpelling); |
| 435 |
} |
| 436 |
|
| 437 |
*CachedHeaderSpelling = |
| 438 |
llvm::formatv("<{0}/{1}>", HeaderPath->FrameworkName, |
| 439 |
HeaderPath->HeaderSubpath) |
| 440 |
.str(); |
| 441 |
return llvm::StringRef(*CachedHeaderSpelling); |
| 442 |
} |
| 443 |
|
| 444 |
llvm::StringRef getIncludeHeaderUncached(FileID FID) { |
| 445 |
const auto FE = SM.getFileEntryRefForID(FID); |
| 446 |
if (!FE || FE->getName().empty()) |
| 447 |
return ""; |
| 448 |
|
| 449 |
if (auto Verbatim = PI->getPublic(*FE); !Verbatim.empty()) |
| 450 |
return Verbatim; |
| 451 |
|
| 452 |
llvm::StringRef Filename = FE->getName(); |
| 453 |
if (auto Canonical = mapCanonical(Filename); !Canonical.empty()) |
| 454 |
return Canonical; |
| 455 |
|
| 456 |
// Framework headers are spelled as <FrameworkName/Foo.h>, not |
| 457 |
// "path/FrameworkName.framework/Headers/Foo.h". |
| 458 |
auto &HS = PP->getHeaderSearchInfo(); |
| 459 |
if (auto Spelling = getFrameworkHeaderIncludeSpelling(*FE, HS)) |
| 460 |
return *Spelling; |
| 461 |
|
| 462 |
if (!tooling::isSelfContainedHeader(*FE, PP->getSourceManager(), |
| 463 |
PP->getHeaderSearchInfo())) { |
| 464 |
// A .inc or .def file is often included into a real header to define |
| 465 |
// symbols (e.g. LLVM tablegen files). |
| 466 |
if (Filename.ends_with(".inc") || Filename.ends_with(".def")) |
| 467 |
// Don't use cache reentrantly due to iterator invalidation. |
| 468 |
return getIncludeHeaderUncached(SM.getFileID(SM.getIncludeLoc(FID))); |
| 469 |
// Conservatively refuse to insert #includes to files without guards. |
| 470 |
return ""; |
| 471 |
} |
| 472 |
// Standard case: just insert the file itself. |
| 473 |
return toURI(*FE); |
| 474 |
} |
| 475 |
}; |
| 476 |
|
| 477 |
// Return the symbol location of the token at \p TokLoc. |
| 478 |
std::optional<SymbolLocation> |
| 479 |
SymbolCollector::getTokenLocation(SourceLocation TokLoc) { |
| 480 |
const auto &SM = ASTCtx->getSourceManager(); |
| 481 |
const auto FE = SM.getFileEntryRefForID(SM.getFileID(TokLoc)); |
| 482 |
if (!FE) |
| 483 |
return std::nullopt; |
| 484 |
|
| 485 |
SymbolLocation Result; |
| 486 |
Result.FileURI = HeaderFileURIs->toURI(*FE).c_str(); |
| 487 |
auto Range = getTokenRange(TokLoc, SM, ASTCtx->getLangOpts()); |
| 488 |
Result.Start = Range.first; |
| 489 |
Result.End = Range.second; |
| 490 |
|
| 491 |
return Result; |
| 492 |
} |
| 493 |
|
| 494 |
SymbolCollector::SymbolCollector(Options Opts) : Opts(std::move(Opts)) {} |
| 495 |
SymbolCollector::~SymbolCollector() = default; |
| 496 |
|
| 497 |
void SymbolCollector::initialize(ASTContext &Ctx) { |
| 498 |
ASTCtx = &Ctx; |
| 499 |
HeaderFileURIs = std::make_unique<HeaderFileURICache>( |
| 500 |
this->PP, ASTCtx->getSourceManager(), Opts); |
| 501 |
CompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>(); |
| 502 |
CompletionTUInfo = |
| 503 |
std::make_unique<CodeCompletionTUInfo>(CompletionAllocator); |
| 504 |
} |
| 505 |
|
| 506 |
bool SymbolCollector::shouldCollectSymbol(const NamedDecl &ND, |
| 507 |
const ASTContext &ASTCtx, |
| 508 |
const Options &Opts, |
| 509 |
bool IsMainFileOnly) { |
| 510 |
// Skip anonymous declarations, e.g (anonymous enum/class/struct). |
| 511 |
if (ND.getDeclName().isEmpty()) |
| 512 |
return false; |
| 513 |
|
| 514 |
// Skip main-file symbols if we are not collecting them. |
| 515 |
if (IsMainFileOnly && !Opts.CollectMainFileSymbols) |
| 516 |
return false; |
| 517 |
|
| 518 |
// Skip symbols in anonymous namespaces in header files. |
| 519 |
if (!IsMainFileOnly && ND.isInAnonymousNamespace()) |
| 520 |
return false; |
| 521 |
|
| 522 |
// For function local symbols, index only classes and its member functions. |
| 523 |
if (index::isFunctionLocalSymbol(&ND)) |
| 524 |
return isa<RecordDecl>(ND) || |
| 525 |
(ND.isCXXInstanceMember() && ND.isFunctionOrFunctionTemplate()); |
| 526 |
|
| 527 |
// We want most things but not "local" symbols such as symbols inside |
| 528 |
// FunctionDecl, BlockDecl, ObjCMethodDecl and OMPDeclareReductionDecl. |
| 529 |
// FIXME: Need a matcher for ExportDecl in order to include symbols declared |
| 530 |
// within an export. |
| 531 |
const auto *DeclCtx = ND.getDeclContext(); |
| 532 |
switch (DeclCtx->getDeclKind()) { |
| 533 |
case Decl::TranslationUnit: |
| 534 |
case Decl::Namespace: |
| 535 |
case Decl::LinkageSpec: |
| 536 |
case Decl::Enum: |
| 537 |
case Decl::ObjCProtocol: |
| 538 |
case Decl::ObjCInterface: |
| 539 |
case Decl::ObjCCategory: |
| 540 |
case Decl::ObjCCategoryImpl: |
| 541 |
case Decl::ObjCImplementation: |
| 542 |
break; |
| 543 |
default: |
| 544 |
// Record has a few derivations (e.g. CXXRecord, Class specialization), it's |
| 545 |
// easier to cast. |
| 546 |
if (!isa<RecordDecl>(DeclCtx)) |
| 547 |
return false; |
| 548 |
} |
| 549 |
|
| 550 |
// Avoid indexing internal symbols in protobuf generated headers. |
| 551 |
if (isPrivateProtoDecl(ND)) |
| 552 |
return false; |
| 553 |
|
| 554 |
// System headers that end with `intrin.h` likely contain useful symbols. |
| 555 |
if (!Opts.CollectReserved && |
| 556 |
(hasReservedName(ND) || hasReservedScope(*ND.getDeclContext())) && |
| 557 |
ASTCtx.getSourceManager().isInSystemHeader(ND.getLocation()) && |
| 558 |
!ASTCtx.getSourceManager() |
| 559 |
.getFilename(ND.getLocation()) |
| 560 |
.ends_with("intrin.h")) |
| 561 |
return false; |
| 562 |
|
| 563 |
return true; |
| 564 |
} |
| 565 |
|
| 566 |
const Decl * |
| 567 |
SymbolCollector::getRefContainer(const Decl *Enclosing, |
| 568 |
const SymbolCollector::Options &Opts) { |
| 569 |
while (Enclosing) { |
| 570 |
const auto *ND = dyn_cast<NamedDecl>(Enclosing); |
| 571 |
if (ND && shouldCollectSymbol(*ND, ND->getASTContext(), Opts, true)) { |
| 572 |
break; |
| 573 |
} |
| 574 |
Enclosing = dyn_cast_or_null<Decl>(Enclosing->getDeclContext()); |
| 575 |
} |
| 576 |
return Enclosing; |
| 577 |
} |
| 578 |
|
| 579 |
SmallVector<const CXXConstructorDecl *, 1> |
| 580 |
SymbolCollector::findIndirectConstructors(const Decl *D) { |
| 581 |
auto *FD = llvm::dyn_cast<clang::FunctionDecl>(D); |
| 582 |
if (FD == nullptr || !FD->isTemplateInstantiation()) |
| 583 |
return {}; |
| 584 |
if (auto Entry = ForwardingToConstructorCache.find(FD); |
| 585 |
Entry != ForwardingToConstructorCache.end()) |
| 586 |
return Entry->getSecond(); |
| 587 |
if (auto *PT = FD->getPrimaryTemplate(); |
| 588 |
PT == nullptr || !isLikelyForwardingFunction(PT)) |
| 589 |
return {}; |
| 590 |
|
| 591 |
SmallVector<const CXXConstructorDecl *, 1> FoundConstructors = |
| 592 |
searchConstructorsInForwardingFunction(FD); |
| 593 |
auto Iter = ForwardingToConstructorCache.try_emplace( |
| 594 |
FD, std::move(FoundConstructors)); |
| 595 |
return Iter.first->getSecond(); |
| 596 |
} |
| 597 |
|
| 598 |
// Always return true to continue indexing. |
| 599 |
bool SymbolCollector::handleDeclOccurrence( |
| 600 |
const Decl *D, index::SymbolRoleSet Roles, |
| 601 |
llvm::ArrayRef<index::SymbolRelation> Relations, SourceLocation Loc, |
| 602 |
index::IndexDataConsumer::ASTNodeInfo ASTNode) { |
| 603 |
assert(ASTCtx && PP && HeaderFileURIs); |
| 604 |
assert(CompletionAllocator && CompletionTUInfo); |
| 605 |
assert(ASTNode.OrigD); |
| 606 |
// Indexing API puts canonical decl into D, which might not have a valid |
| 607 |
// source location for implicit/built-in decls. Fallback to original decl in |
| 608 |
// such cases. |
| 609 |
if (D->getLocation().isInvalid()) |
| 610 |
D = ASTNode.OrigD; |
| 611 |
// If OrigD is an declaration associated with a friend declaration and it's |
| 612 |
// not a definition, skip it. Note that OrigD is the occurrence that the |
| 613 |
// collector is currently visiting. |
| 614 |
if ((ASTNode.OrigD->getFriendObjectKind() != |
| 615 |
Decl::FriendObjectKind::FOK_None) && |
| 616 |
!(Roles & static_cast<unsigned>(index::SymbolRole::Definition))) |
| 617 |
return true; |
| 618 |
// A declaration created for a friend declaration should not be used as the |
| 619 |
// canonical declaration in the index. Use OrigD instead, unless we've already |
| 620 |
// picked a replacement for D |
| 621 |
if (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None) |
| 622 |
D = CanonicalDecls.try_emplace(D, ASTNode.OrigD).first->second; |
| 623 |
// Flag to mark that D should be considered canonical meaning its declaration |
| 624 |
// will override any previous declaration for the Symbol. |
| 625 |
bool DeclIsCanonical = false; |
| 626 |
// Avoid treating ObjCImplementationDecl as a canonical declaration if it has |
| 627 |
// a corresponding non-implicit and non-forward declared ObjcInterfaceDecl. |
| 628 |
if (const auto *IID = dyn_cast<ObjCImplementationDecl>(D)) { |
| 629 |
DeclIsCanonical = true; |
| 630 |
if (const auto *CID = IID->getClassInterface()) |
| 631 |
if (const auto *DD = CID->getDefinition()) |
| 632 |
if (!DD->isImplicitInterfaceDecl()) |
| 633 |
D = DD; |
| 634 |
} |
| 635 |
// Avoid treating ObjCCategoryImplDecl as a canonical declaration in favor of |
| 636 |
// its ObjCCategoryDecl if it has one. |
| 637 |
if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(D)) { |
| 638 |
DeclIsCanonical = true; |
| 639 |
if (const auto *CD = CID->getCategoryDecl()) |
| 640 |
D = CD; |
| 641 |
} |
| 642 |
const NamedDecl *ND = dyn_cast<NamedDecl>(D); |
| 643 |
if (!ND) |
| 644 |
return true; |
| 645 |
|
| 646 |
auto ID = getSymbolIDCached(ND); |
| 647 |
if (!ID) |
| 648 |
return true; |
| 649 |
|
| 650 |
// Mark D as referenced if this is a reference coming from the main file. |
| 651 |
// D may not be an interesting symbol, but it's cheaper to check at the end. |
| 652 |
auto &SM = ASTCtx->getSourceManager(); |
| 653 |
if (Opts.CountReferences && |
| 654 |
(Roles & static_cast<unsigned>(index::SymbolRole::Reference)) && |
| 655 |
SM.getFileID(SM.getSpellingLoc(Loc)) == SM.getMainFileID()) |
| 656 |
ReferencedSymbols.insert(ID); |
| 657 |
|
| 658 |
// ND is the canonical (i.e. first) declaration. If it's in the main file |
| 659 |
// (which is not a header), then no public declaration was visible, so assume |
| 660 |
// it's main-file only. |
| 661 |
auto CheckIsMainFileOnly = [&](const NamedDecl *Decl) { |
| 662 |
return SM.isWrittenInMainFile(SM.getExpansionLoc(Decl->getBeginLoc())) && |
| 663 |
!isHeaderFile(SM.getFileEntryRefForID(SM.getMainFileID())->getName(), |
| 664 |
ASTCtx->getLangOpts()); |
| 665 |
}; |
| 666 |
bool IsMainFileOnly = CheckIsMainFileOnly(ND); |
| 667 |
// In C, printf is a redecl of an implicit builtin! So check OrigD instead. |
| 668 |
if (ASTNode.OrigD->isImplicit() || |
| 669 |
!shouldCollectSymbol(*ND, *ASTCtx, Opts, IsMainFileOnly)) |
| 670 |
return true; |
| 671 |
|
| 672 |
// Note: we need to process relations for all decl occurrences, including |
| 673 |
// refs, because the indexing code only populates relations for specific |
| 674 |
// occurrences. For example, RelationBaseOf is only populated for the |
| 675 |
// occurrence inside the base-specifier. |
| 676 |
processRelations(*ND, ID, Relations); |
| 677 |
|
| 678 |
bool CollectRef = static_cast<bool>(Opts.RefFilter & toRefKind(Roles)); |
| 679 |
// Unlike other fields, e.g. Symbols (which use spelling locations), we use |
| 680 |
// file locations for references (as it aligns the behavior of clangd's |
| 681 |
// AST-based xref). |
| 682 |
// FIXME: we should try to use the file locations for other fields. |
| 683 |
if (CollectRef && |
| 684 |
(!IsMainFileOnly || Opts.CollectMainFileRefs || |
| 685 |
ND->isExternallyVisible()) && |
| 686 |
!isa<NamespaceDecl>(ND)) { |
| 687 |
auto FileLoc = SM.getFileLoc(Loc); |
| 688 |
auto FID = SM.getFileID(FileLoc); |
| 689 |
if (Opts.RefsInHeaders || FID == SM.getMainFileID()) { |
| 690 |
auto *Container = getRefContainer(ASTNode.Parent, Opts); |
| 691 |
addRef(ID, SymbolRef{FileLoc, FID, Roles, index::getSymbolInfo(ND).Kind, |
| 692 |
Container, isSpelled(FileLoc, *ND)}); |
| 693 |
// Also collect indirect constructor calls like `make_unique` |
| 694 |
for (auto *Constructor : findIndirectConstructors(ASTNode.OrigD)) { |
| 695 |
if (!shouldCollectSymbol(*Constructor, *ASTCtx, Opts, |
| 696 |
CheckIsMainFileOnly(Constructor))) |
| 697 |
continue; |
| 698 |
if (auto ConstructorID = getSymbolIDCached(Constructor)) |
| 699 |
addRef(ConstructorID, |
| 700 |
SymbolRef{FileLoc, FID, Roles, |
| 701 |
index::getSymbolInfo(Constructor).Kind, Container, |
| 702 |
false}); |
| 703 |
} |
| 704 |
} |
| 705 |
} |
| 706 |
// Don't continue indexing if this is a mere reference. |
| 707 |
if (!(Roles & (static_cast<unsigned>(index::SymbolRole::Declaration) | |
| 708 |
static_cast<unsigned>(index::SymbolRole::Definition)))) |
| 709 |
return true; |
| 710 |
|
| 711 |
// FIXME: ObjCPropertyDecl are not properly indexed here: |
| 712 |
// - ObjCPropertyDecl may have an OrigD of ObjCPropertyImplDecl, which is |
| 713 |
// not a NamedDecl. |
| 714 |
auto *OriginalDecl = dyn_cast<NamedDecl>(ASTNode.OrigD); |
| 715 |
if (!OriginalDecl) |
| 716 |
return true; |
| 717 |
|
| 718 |
const Symbol *BasicSymbol = Symbols.find(ID); |
| 719 |
bool SkipDocCheckInDef = false; |
| 720 |
if (isPreferredDeclaration(*OriginalDecl, Roles)) { |
| 721 |
// If OriginalDecl is preferred, replace/create the existing canonical |
| 722 |
// declaration (e.g. a class forward declaration). There should be at most |
| 723 |
// one duplicate as we expect to see only one preferred declaration per |
| 724 |
// TU, because in practice they are definitions. |
| 725 |
BasicSymbol = addDeclaration(*OriginalDecl, std::move(ID), IsMainFileOnly); |
| 726 |
SkipDocCheckInDef = true; |
| 727 |
} else if (!BasicSymbol || DeclIsCanonical) { |
| 728 |
BasicSymbol = addDeclaration(*ND, std::move(ID), IsMainFileOnly); |
| 729 |
SkipDocCheckInDef = true; |
| 730 |
} |
| 731 |
|
| 732 |
if (Roles & static_cast<unsigned>(index::SymbolRole::Definition)) |
| 733 |
addDefinition(*OriginalDecl, *BasicSymbol, SkipDocCheckInDef); |
| 734 |
|
| 735 |
return true; |
| 736 |
} |
| 737 |
|
| 738 |
void SymbolCollector::handleMacros(const MainFileMacros &MacroRefsToIndex) { |
| 739 |
assert(HeaderFileURIs && PP); |
| 740 |
const auto &SM = PP->getSourceManager(); |
| 741 |
const auto MainFileEntryRef = SM.getFileEntryRefForID(SM.getMainFileID()); |
| 742 |
assert(MainFileEntryRef); |
| 743 |
|
| 744 |
const std::string &MainFileURI = HeaderFileURIs->toURI(*MainFileEntryRef); |
| 745 |
// Add macro references. |
| 746 |
for (const auto &IDToRefs : MacroRefsToIndex.MacroRefs) { |
| 747 |
for (const auto &MacroRef : IDToRefs.second) { |
| 748 |
const auto &SR = MacroRef.toSourceRange(SM); |
| 749 |
auto Range = halfOpenToRange(SM, SR); |
| 750 |
bool IsDefinition = MacroRef.IsDefinition; |
| 751 |
Ref R; |
| 752 |
R.Location.Start.setLine(Range.start.line); |
| 753 |
R.Location.Start.setColumn(Range.start.character); |
| 754 |
R.Location.End.setLine(Range.end.line); |
| 755 |
R.Location.End.setColumn(Range.end.character); |
| 756 |
R.Location.FileURI = MainFileURI.c_str(); |
| 757 |
R.Kind = IsDefinition ? RefKind::Definition : RefKind::Reference; |
| 758 |
Refs.insert(IDToRefs.first, R); |
| 759 |
if (IsDefinition) { |
| 760 |
Symbol S; |
| 761 |
S.ID = IDToRefs.first; |
| 762 |
S.Name = toSourceCode(SM, SR.getAsRange()); |
| 763 |
S.SymInfo.Kind = index::SymbolKind::Macro; |
| 764 |
S.SymInfo.SubKind = index::SymbolSubKind::None; |
| 765 |
S.SymInfo.Properties = index::SymbolPropertySet(); |
| 766 |
S.SymInfo.Lang = index::SymbolLanguage::C; |
| 767 |
S.Origin = Opts.Origin; |
| 768 |
S.CanonicalDeclaration = R.Location; |
| 769 |
// Make the macro visible for code completion if main file is an |
| 770 |
// include-able header. |
| 771 |
if (!HeaderFileURIs->getIncludeHeader(SM.getMainFileID()).empty()) { |
| 772 |
S.Flags |= Symbol::IndexedForCodeCompletion; |
| 773 |
S.Flags |= Symbol::VisibleOutsideFile; |
| 774 |
} |
| 775 |
Symbols.insert(S); |
| 776 |
} |
| 777 |
} |
| 778 |
} |
| 779 |
} |
| 780 |
|
| 781 |
bool SymbolCollector::handleMacroOccurrence(const IdentifierInfo *Name, |
| 782 |
const MacroInfo *MI, |
| 783 |
index::SymbolRoleSet Roles, |
| 784 |
SourceLocation Loc) { |
| 785 |
assert(PP); |
| 786 |
// Builtin macros don't have useful locations and aren't needed in completion. |
| 787 |
if (MI->isBuiltinMacro()) |
| 788 |
return true; |
| 789 |
|
| 790 |
const auto &SM = PP->getSourceManager(); |
| 791 |
auto DefLoc = MI->getDefinitionLoc(); |
| 792 |
// Also avoid storing macros that aren't defined in any file, i.e. predefined |
| 793 |
// macros like __DBL_MIN__ and those defined on the command line. |
| 794 |
if (SM.isWrittenInBuiltinFile(DefLoc) || |
| 795 |
SM.isWrittenInCommandLineFile(DefLoc) || |
| 796 |
Name->getName() == "__GCC_HAVE_DWARF2_CFI_ASM") |
| 797 |
return true; |
| 798 |
|
| 799 |
auto ID = getSymbolIDCached(Name->getName(), MI, SM); |
| 800 |
if (!ID) |
| 801 |
return true; |
| 802 |
|
| 803 |
auto SpellingLoc = SM.getSpellingLoc(Loc); |
| 804 |
bool IsMainFileOnly = |
| 805 |
SM.isInMainFile(SM.getExpansionLoc(DefLoc)) && |
| 806 |
!isHeaderFile(SM.getFileEntryRefForID(SM.getMainFileID())->getName(), |
| 807 |
ASTCtx->getLangOpts()); |
| 808 |
// Do not store references to main-file macros. |
| 809 |
if ((static_cast<unsigned>(Opts.RefFilter) & Roles) && !IsMainFileOnly && |
| 810 |
(Opts.RefsInHeaders || SM.getFileID(SpellingLoc) == SM.getMainFileID())) { |
| 811 |
// FIXME: Populate container information for macro references. |
| 812 |
// FIXME: All MacroRefs are marked as Spelled now, but this should be |
| 813 |
// checked. |
| 814 |
addRef(ID, |
| 815 |
SymbolRef{Loc, SM.getFileID(Loc), Roles, index::SymbolKind::Macro, |
| 816 |
/*Container=*/nullptr, |
| 817 |
/*Spelled=*/true}); |
| 818 |
} |
| 819 |
|
| 820 |
// Collect symbols. |
| 821 |
if (!Opts.CollectMacro) |
| 822 |
return true; |
| 823 |
|
| 824 |
// Skip main-file macros if we are not collecting them. |
| 825 |
if (IsMainFileOnly && !Opts.CollectMainFileSymbols) |
| 826 |
return false; |
| 827 |
|
| 828 |
// Mark the macro as referenced if this is a reference coming from the main |
| 829 |
// file. The macro may not be an interesting symbol, but it's cheaper to check |
| 830 |
// at the end. |
| 831 |
if (Opts.CountReferences && |
| 832 |
(Roles & static_cast<unsigned>(index::SymbolRole::Reference)) && |
| 833 |
SM.getFileID(SpellingLoc) == SM.getMainFileID()) |
| 834 |
ReferencedSymbols.insert(ID); |
| 835 |
|
| 836 |
// Don't continue indexing if this is a mere reference. |
| 837 |
// FIXME: remove macro with ID if it is undefined. |
| 838 |
if (!(Roles & static_cast<unsigned>(index::SymbolRole::Declaration) || |
| 839 |
Roles & static_cast<unsigned>(index::SymbolRole::Definition))) |
| 840 |
return true; |
| 841 |
|
| 842 |
// Only collect one instance in case there are multiple. |
| 843 |
if (Symbols.find(ID) != nullptr) |
| 844 |
return true; |
| 845 |
|
| 846 |
Symbol S; |
| 847 |
S.ID = std::move(ID); |
| 848 |
S.Name = Name->getName(); |
| 849 |
if (!IsMainFileOnly) { |
| 850 |
S.Flags |= Symbol::IndexedForCodeCompletion; |
| 851 |
S.Flags |= Symbol::VisibleOutsideFile; |
| 852 |
} |
| 853 |
S.SymInfo = index::getSymbolInfoForMacro(*MI); |
| 854 |
S.Origin = Opts.Origin; |
| 855 |
// FIXME: use the result to filter out symbols. |
| 856 |
shouldIndexFile(SM.getFileID(Loc)); |
| 857 |
if (auto DeclLoc = getTokenLocation(DefLoc)) |
| 858 |
S.CanonicalDeclaration = *DeclLoc; |
| 859 |
|
| 860 |
CodeCompletionResult SymbolCompletion(Name); |
| 861 |
const auto *CCS = SymbolCompletion.CreateCodeCompletionStringForMacro( |
| 862 |
*PP, *CompletionAllocator, *CompletionTUInfo); |
| 863 |
std::string Signature; |
| 864 |
std::string SnippetSuffix; |
| 865 |
getSignature(*CCS, &Signature, &SnippetSuffix, SymbolCompletion.Kind, |
| 866 |
SymbolCompletion.CursorKind); |
| 867 |
S.Signature = Signature; |
| 868 |
S.CompletionSnippetSuffix = SnippetSuffix; |
| 869 |
|
| 870 |
IndexedMacros.insert(Name); |
| 871 |
|
| 872 |
setIncludeLocation(S, DefLoc, include_cleaner::Macro{Name, DefLoc}); |
| 873 |
Symbols.insert(S); |
| 874 |
return true; |
| 875 |
} |
| 876 |
|
| 877 |
void SymbolCollector::processRelations( |
| 878 |
const NamedDecl &ND, const SymbolID &ID, |
| 879 |
ArrayRef<index::SymbolRelation> Relations) { |
| 880 |
for (const auto &R : Relations) { |
| 881 |
auto RKind = indexableRelation(R); |
| 882 |
if (!RKind) |
| 883 |
continue; |
| 884 |
const Decl *Object = R.RelatedSymbol; |
| 885 |
|
| 886 |
auto ObjectID = getSymbolIDCached(Object); |
| 887 |
if (!ObjectID) |
| 888 |
continue; |
| 889 |
|
| 890 |
// Record the relation. |
| 891 |
// TODO: There may be cases where the object decl is not indexed for some |
| 892 |
// reason. Those cases should probably be removed in due course, but for |
| 893 |
// now there are two possible ways to handle it: |
| 894 |
// (A) Avoid storing the relation in such cases. |
| 895 |
// (B) Store it anyways. Clients will likely lookup() the SymbolID |
| 896 |
// in the index and find nothing, but that's a situation they |
| 897 |
// probably need to handle for other reasons anyways. |
| 898 |
// We currently do (B) because it's simpler. |
| 899 |
if (*RKind == RelationKind::BaseOf) |
| 900 |
this->Relations.insert({ID, *RKind, ObjectID}); |
| 901 |
else if (*RKind == RelationKind::OverriddenBy) |
| 902 |
this->Relations.insert({ObjectID, *RKind, ID}); |
| 903 |
} |
| 904 |
} |
| 905 |
|
| 906 |
void SymbolCollector::setIncludeLocation(const Symbol &S, SourceLocation DefLoc, |
| 907 |
const include_cleaner::Symbol &Sym) { |
| 908 |
const auto &SM = PP->getSourceManager(); |
| 909 |
if (!Opts.CollectIncludePath || |
| 910 |
shouldCollectIncludePath(S.SymInfo.Kind) == Symbol::Invalid) |
| 911 |
return; |
| 912 |
|
| 913 |
// Use the expansion location to get the #include header since this is |
| 914 |
// where the symbol is exposed. |
| 915 |
if (FileID FID = SM.getDecomposedExpansionLoc(DefLoc).first; FID.isValid()) |
| 916 |
IncludeFiles[S.ID] = FID; |
| 917 |
|
| 918 |
// We update providers for a symbol with each occurence, as SymbolCollector |
| 919 |
// might run while parsing, rather than at the end of a translation unit. |
| 920 |
// Hence we see more and more redecls over time. |
| 921 |
SymbolProviders[S.ID] = |
| 922 |
include_cleaner::headersForSymbol(Sym, *PP, Opts.PragmaIncludes); |
| 923 |
} |
| 924 |
|
| 925 |
llvm::StringRef getStdHeader(const Symbol *S, const LangOptions &LangOpts) { |
| 926 |
tooling::stdlib::Lang Lang = tooling::stdlib::Lang::CXX; |
| 927 |
if (LangOpts.C11) |
| 928 |
Lang = tooling::stdlib::Lang::C; |
| 929 |
else if(!LangOpts.CPlusPlus) |
| 930 |
return ""; |
| 931 |
|
| 932 |
if (S->Scope == "std::" && S->Name == "move") { |
| 933 |
if (!S->Signature.contains(',')) |
| 934 |
return "<utility>"; |
| 935 |
return "<algorithm>"; |
| 936 |
} |
| 937 |
|
| 938 |
if (auto StdSym = tooling::stdlib::Symbol::named(S->Scope, S->Name, Lang)) |
| 939 |
if (auto Header = StdSym->header()) |
| 940 |
return Header->name(); |
| 941 |
return ""; |
| 942 |
} |
| 943 |
|
| 944 |
void SymbolCollector::finish() { |
| 945 |
// At the end of the TU, add 1 to the refcount of all referenced symbols. |
| 946 |
for (const auto &ID : ReferencedSymbols) { |
| 947 |
if (const auto *S = Symbols.find(ID)) { |
| 948 |
// SymbolSlab::Builder returns const symbols because strings are interned |
| 949 |
// and modifying returned symbols without inserting again wouldn't go |
| 950 |
// well. const_cast is safe here as we're modifying a data owned by the |
| 951 |
// Symbol. This reduces time spent in SymbolCollector by ~1%. |
| 952 |
++const_cast<Symbol *>(S)->References; |
| 953 |
} |
| 954 |
} |
| 955 |
if (Opts.CollectMacro) { |
| 956 |
assert(PP); |
| 957 |
// First, drop header guards. We can't identify these until EOF. |
| 958 |
for (const IdentifierInfo *II : IndexedMacros) { |
| 959 |
if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo()) |
| 960 |
if (auto ID = |
| 961 |
getSymbolIDCached(II->getName(), MI, PP->getSourceManager())) |
| 962 |
if (MI->isUsedForHeaderGuard()) |
| 963 |
Symbols.erase(ID); |
| 964 |
} |
| 965 |
} |
| 966 |
llvm::DenseMap<FileID, bool> FileToContainsImportsOrObjC; |
| 967 |
llvm::DenseMap<include_cleaner::Header, std::string> HeaderSpelling; |
| 968 |
// Fill in IncludeHeaders. |
| 969 |
// We delay this until end of TU so header guards are all resolved. |
| 970 |
for (const auto &[SID, Providers] : SymbolProviders) { |
| 971 |
const Symbol *S = Symbols.find(SID); |
| 972 |
if (!S) |
| 973 |
continue; |
| 974 |
|
| 975 |
FileID FID = IncludeFiles.lookup(SID); |
| 976 |
// Determine if the FID is #include'd or #import'ed. |
| 977 |
Symbol::IncludeDirective Directives = Symbol::Invalid; |
| 978 |
auto CollectDirectives = shouldCollectIncludePath(S->SymInfo.Kind); |
| 979 |
if ((CollectDirectives & Symbol::Include) != 0) |
| 980 |
Directives |= Symbol::Include; |
| 981 |
// Only allow #import for symbols from ObjC-like files. |
| 982 |
if ((CollectDirectives & Symbol::Import) != 0 && FID.isValid()) { |
| 983 |
auto [It, Inserted] = FileToContainsImportsOrObjC.try_emplace(FID); |
| 984 |
if (Inserted) |
| 985 |
It->second = FilesWithObjCConstructs.contains(FID) || |
| 986 |
tooling::codeContainsImports( |
| 987 |
ASTCtx->getSourceManager().getBufferData(FID)); |
| 988 |
if (It->second) |
| 989 |
Directives |= Symbol::Import; |
| 990 |
} |
| 991 |
|
| 992 |
if (Directives == Symbol::Invalid) |
| 993 |
continue; |
| 994 |
|
| 995 |
// Use the include location-based logic for Objective-C symbols. |
| 996 |
if (Directives & Symbol::Import) { |
| 997 |
llvm::StringRef IncludeHeader = getStdHeader(S, ASTCtx->getLangOpts()); |
| 998 |
if (IncludeHeader.empty()) |
| 999 |
IncludeHeader = HeaderFileURIs->getIncludeHeader(FID); |
| 1000 |
|
| 1001 |
if (!IncludeHeader.empty()) { |
| 1002 |
auto NewSym = *S; |
| 1003 |
NewSym.IncludeHeaders.push_back({IncludeHeader, 1, Directives}); |
| 1004 |
Symbols.insert(NewSym); |
| 1005 |
} |
| 1006 |
// FIXME: use providers from include-cleaner library once it's polished |
| 1007 |
// for Objective-C. |
| 1008 |
continue; |
| 1009 |
} |
| 1010 |
|
| 1011 |
// For #include's, use the providers computed by the include-cleaner |
| 1012 |
// library. |
| 1013 |
assert(Directives == Symbol::Include); |
| 1014 |
// Ignore providers that are not self-contained, this is especially |
| 1015 |
// important for symbols defined in the main-file. We want to prefer the |
| 1016 |
// header, if possible. |
| 1017 |
// TODO: Limit this to specifically ignore main file, when we're indexing a |
| 1018 |
// non-header file? |
| 1019 |
auto SelfContainedProvider = |
| 1020 |
[this](llvm::ArrayRef<include_cleaner::Header> Providers) |
| 1021 |
-> std::optional<include_cleaner::Header> { |
| 1022 |
for (const auto &H : Providers) { |
| 1023 |
if (H.kind() != include_cleaner::Header::Physical) |
| 1024 |
return H; |
| 1025 |
if (tooling::isSelfContainedHeader(H.physical(), PP->getSourceManager(), |
| 1026 |
PP->getHeaderSearchInfo())) |
| 1027 |
return H; |
| 1028 |
} |
| 1029 |
return std::nullopt; |
| 1030 |
}; |
| 1031 |
const auto OptionalProvider = SelfContainedProvider(Providers); |
| 1032 |
if (!OptionalProvider) |
| 1033 |
continue; |
| 1034 |
const auto &H = *OptionalProvider; |
| 1035 |
const auto [SpellingIt, Inserted] = HeaderSpelling.try_emplace(H); |
| 1036 |
if (Inserted) { |
| 1037 |
auto &SM = ASTCtx->getSourceManager(); |
| 1038 |
if (H.kind() == include_cleaner::Header::Kind::Physical) { |
| 1039 |
// FIXME: Get rid of this once include-cleaner has support for system |
| 1040 |
// headers. |
| 1041 |
if (auto Canonical = |
| 1042 |
HeaderFileURIs->mapCanonical(H.physical().getName()); |
| 1043 |
!Canonical.empty()) |
| 1044 |
SpellingIt->second = Canonical; |
| 1045 |
// For physical files, prefer URIs as spellings might change |
| 1046 |
// depending on the translation unit. |
| 1047 |
else if (tooling::isSelfContainedHeader(H.physical(), SM, |
| 1048 |
PP->getHeaderSearchInfo())) |
| 1049 |
SpellingIt->second = |
| 1050 |
HeaderFileURIs->toURI(H.physical()); |
| 1051 |
} else { |
| 1052 |
SpellingIt->second = include_cleaner::spellHeader( |
| 1053 |
{H, PP->getHeaderSearchInfo(), |
| 1054 |
SM.getFileEntryForID(SM.getMainFileID())}); |
| 1055 |
} |
| 1056 |
} |
| 1057 |
|
| 1058 |
if (!SpellingIt->second.empty()) { |
| 1059 |
auto NewSym = *S; |
| 1060 |
NewSym.IncludeHeaders.push_back({SpellingIt->second, 1, Directives}); |
| 1061 |
Symbols.insert(NewSym); |
| 1062 |
} |
| 1063 |
} |
| 1064 |
|
| 1065 |
ReferencedSymbols.clear(); |
| 1066 |
IncludeFiles.clear(); |
| 1067 |
SymbolProviders.clear(); |
| 1068 |
FilesWithObjCConstructs.clear(); |
| 1069 |
} |
| 1070 |
|
| 1071 |
const Symbol *SymbolCollector::addDeclaration(const NamedDecl &ND, SymbolID ID, |
| 1072 |
bool IsMainFileOnly) { |
| 1073 |
auto &Ctx = ND.getASTContext(); |
| 1074 |
auto &SM = Ctx.getSourceManager(); |
| 1075 |
|
| 1076 |
Symbol S; |
| 1077 |
S.ID = std::move(ID); |
| 1078 |
std::string QName = printQualifiedName(ND); |
| 1079 |
// FIXME: this returns foo:bar: for objective-C methods, we prefer only foo: |
| 1080 |
// for consistency with CodeCompletionString and a clean name/signature split. |
| 1081 |
std::tie(S.Scope, S.Name) = splitQualifiedName(QName); |
| 1082 |
std::string TemplateSpecializationArgs = printTemplateSpecializationArgs(ND); |
| 1083 |
S.TemplateSpecializationArgs = TemplateSpecializationArgs; |
| 1084 |
|
| 1085 |
// We collect main-file symbols, but do not use them for code completion. |
| 1086 |
if (!IsMainFileOnly && isIndexedForCodeCompletion(ND, Ctx)) |
| 1087 |
S.Flags |= Symbol::IndexedForCodeCompletion; |
| 1088 |
if (isImplementationDetail(&ND)) |
| 1089 |
S.Flags |= Symbol::ImplementationDetail; |
| 1090 |
if (!IsMainFileOnly) |
| 1091 |
S.Flags |= Symbol::VisibleOutsideFile; |
| 1092 |
S.SymInfo = index::getSymbolInfo(&ND); |
| 1093 |
auto Loc = nameLocation(ND, SM); |
| 1094 |
assert(Loc.isValid() && "Invalid source location for NamedDecl"); |
| 1095 |
// FIXME: use the result to filter out symbols. |
| 1096 |
auto FID = SM.getFileID(Loc); |
| 1097 |
shouldIndexFile(FID); |
| 1098 |
if (auto DeclLoc = getTokenLocation(Loc)) |
| 1099 |
S.CanonicalDeclaration = *DeclLoc; |
| 1100 |
|
| 1101 |
S.Origin = Opts.Origin; |
| 1102 |
if (ND.getAvailability() == AR_Deprecated) |
| 1103 |
S.Flags |= Symbol::Deprecated; |
| 1104 |
|
| 1105 |
// Add completion info. |
| 1106 |
// FIXME: we may want to choose a different redecl, or combine from several. |
| 1107 |
assert(ASTCtx && PP && "ASTContext and Preprocessor must be set."); |
| 1108 |
// We use the primary template, as clang does during code completion. |
| 1109 |
CodeCompletionResult SymbolCompletion(&getTemplateOrThis(ND), 0); |
| 1110 |
const auto *CCS = SymbolCompletion.CreateCodeCompletionString( |
| 1111 |
*ASTCtx, *PP, CodeCompletionContext::CCC_Symbol, *CompletionAllocator, |
| 1112 |
*CompletionTUInfo, |
| 1113 |
/*IncludeBriefComments*/ false); |
| 1114 |
std::string DocComment; |
| 1115 |
std::string Documentation; |
| 1116 |
bool AlreadyHasDoc = S.Flags & Symbol::HasDocComment; |
| 1117 |
if (!AlreadyHasDoc) { |
| 1118 |
DocComment = getDocComment(Ctx, SymbolCompletion, |
| 1119 |
/*CommentsFromHeaders=*/true); |
| 1120 |
Documentation = formatDocumentation(*CCS, DocComment); |
| 1121 |
} |
| 1122 |
const auto UpdateDoc = [&] { |
| 1123 |
if (!AlreadyHasDoc) { |
| 1124 |
if (!DocComment.empty()) |
| 1125 |
S.Flags |= Symbol::HasDocComment; |
| 1126 |
S.Documentation = Documentation; |
| 1127 |
} |
| 1128 |
}; |
| 1129 |
if (!(S.Flags & Symbol::IndexedForCodeCompletion)) { |
| 1130 |
if (Opts.StoreAllDocumentation) |
| 1131 |
UpdateDoc(); |
| 1132 |
Symbols.insert(S); |
| 1133 |
return Symbols.find(S.ID); |
| 1134 |
} |
| 1135 |
UpdateDoc(); |
| 1136 |
std::string Signature; |
| 1137 |
std::string SnippetSuffix; |
| 1138 |
getSignature(*CCS, &Signature, &SnippetSuffix, SymbolCompletion.Kind, |
| 1139 |
SymbolCompletion.CursorKind); |
| 1140 |
S.Signature = Signature; |
| 1141 |
S.CompletionSnippetSuffix = SnippetSuffix; |
| 1142 |
std::string ReturnType = getReturnType(*CCS); |
| 1143 |
S.ReturnType = ReturnType; |
| 1144 |
|
| 1145 |
std::optional<OpaqueType> TypeStorage; |
| 1146 |
if (S.Flags & Symbol::IndexedForCodeCompletion) { |
| 1147 |
TypeStorage = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion); |
| 1148 |
if (TypeStorage) |
| 1149 |
S.Type = TypeStorage->raw(); |
| 1150 |
} |
| 1151 |
|
| 1152 |
Symbols.insert(S); |
| 1153 |
setIncludeLocation(S, ND.getLocation(), include_cleaner::Symbol{ND}); |
| 1154 |
if (S.SymInfo.Lang == index::SymbolLanguage::ObjC) |
| 1155 |
FilesWithObjCConstructs.insert(FID); |
| 1156 |
return Symbols.find(S.ID); |
| 1157 |
} |
| 1158 |
|
| 1159 |
void SymbolCollector::addDefinition(const NamedDecl &ND, const Symbol &DeclSym, |
| 1160 |
bool SkipDocCheck) { |
| 1161 |
if (DeclSym.Definition) |
| 1162 |
return; |
| 1163 |
const auto &SM = ND.getASTContext().getSourceManager(); |
| 1164 |
auto Loc = nameLocation(ND, SM); |
| 1165 |
shouldIndexFile(SM.getFileID(Loc)); |
| 1166 |
auto DefLoc = getTokenLocation(Loc); |
| 1167 |
// If we saw some forward declaration, we end up copying the symbol. |
| 1168 |
// This is not ideal, but avoids duplicating the "is this a definition" check |
| 1169 |
// in clang::index. We should only see one definition. |
| 1170 |
if (!DefLoc) |
| 1171 |
return; |
| 1172 |
Symbol S = DeclSym; |
| 1173 |
// FIXME: use the result to filter out symbols. |
| 1174 |
S.Definition = *DefLoc; |
| 1175 |
|
| 1176 |
std::string DocComment; |
| 1177 |
std::string Documentation; |
| 1178 |
if (!SkipDocCheck && !(S.Flags & Symbol::HasDocComment) && |
| 1179 |
(llvm::isa<FunctionDecl>(ND) || llvm::isa<CXXMethodDecl>(ND))) { |
| 1180 |
CodeCompletionResult SymbolCompletion(&getTemplateOrThis(ND), 0); |
| 1181 |
const auto *CCS = SymbolCompletion.CreateCodeCompletionString( |
| 1182 |
*ASTCtx, *PP, CodeCompletionContext::CCC_Symbol, *CompletionAllocator, |
| 1183 |
*CompletionTUInfo, |
| 1184 |
/*IncludeBriefComments*/ false); |
| 1185 |
DocComment = getDocComment(ND.getASTContext(), SymbolCompletion, |
| 1186 |
/*CommentsFromHeaders=*/true); |
| 1187 |
if (!S.Documentation.empty()) |
| 1188 |
Documentation = S.Documentation.str() + '\n' + DocComment; |
| 1189 |
else |
| 1190 |
Documentation = formatDocumentation(*CCS, DocComment); |
| 1191 |
if (!DocComment.empty()) |
| 1192 |
S.Flags |= Symbol::HasDocComment; |
| 1193 |
S.Documentation = Documentation; |
| 1194 |
} |
| 1195 |
|
| 1196 |
Symbols.insert(S); |
| 1197 |
} |
| 1198 |
|
| 1199 |
bool SymbolCollector::shouldIndexFile(FileID FID) { |
| 1200 |
if (!Opts.FileFilter) |
| 1201 |
return true; |
| 1202 |
auto I = FilesToIndexCache.try_emplace(FID); |
| 1203 |
if (I.second) |
| 1204 |
I.first->second = Opts.FileFilter(ASTCtx->getSourceManager(), FID); |
| 1205 |
return I.first->second; |
| 1206 |
} |
| 1207 |
|
| 1208 |
static bool refIsCall(index::SymbolKind Kind) { |
| 1209 |
using SK = index::SymbolKind; |
| 1210 |
return Kind == SK::Function || Kind == SK::InstanceMethod || |
| 1211 |
Kind == SK::ClassMethod || Kind == SK::StaticMethod || |
| 1212 |
Kind == SK::Constructor || Kind == SK::Destructor || |
| 1213 |
Kind == SK::ConversionFunction; |
| 1214 |
} |
| 1215 |
|
| 1216 |
void SymbolCollector::addRef(SymbolID ID, const SymbolRef &SR) { |
| 1217 |
const auto &SM = ASTCtx->getSourceManager(); |
| 1218 |
// FIXME: use the result to filter out references. |
| 1219 |
shouldIndexFile(SR.FID); |
| 1220 |
if (const auto FE = SM.getFileEntryRefForID(SR.FID)) { |
| 1221 |
auto Range = getTokenRange(SR.Loc, SM, ASTCtx->getLangOpts()); |
| 1222 |
Ref R; |
| 1223 |
R.Location.Start = Range.first; |
| 1224 |
R.Location.End = Range.second; |
| 1225 |
R.Location.FileURI = HeaderFileURIs->toURI(*FE).c_str(); |
| 1226 |
R.Kind = toRefKind(SR.Roles, SR.Spelled); |
| 1227 |
if (refIsCall(SR.Kind)) { |
| 1228 |
R.Kind |= RefKind::Call; |
| 1229 |
} |
| 1230 |
R.Container = getSymbolIDCached(SR.Container); |
| 1231 |
Refs.insert(ID, R); |
| 1232 |
} |
| 1233 |
} |
| 1234 |
|
| 1235 |
SymbolID SymbolCollector::getSymbolIDCached(const Decl *D) { |
| 1236 |
auto It = DeclToIDCache.try_emplace(D); |
| 1237 |
if (It.second) |
| 1238 |
It.first->second = getSymbolID(D); |
| 1239 |
return It.first->second; |
| 1240 |
} |
| 1241 |
|
| 1242 |
SymbolID SymbolCollector::getSymbolIDCached(const llvm::StringRef MacroName, |
| 1243 |
const MacroInfo *MI, |
| 1244 |
const SourceManager &SM) { |
| 1245 |
auto It = MacroToIDCache.try_emplace(MI); |
| 1246 |
if (It.second) |
| 1247 |
It.first->second = getSymbolID(MacroName, MI, SM); |
| 1248 |
return It.first->second; |
| 1249 |
} |
| 1250 |
} // namespace clangd |
| 1251 |
} // namespace clang |