| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 1 | //===--- SymbolCollector.cpp -------------------------------------*- C++-*-===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | #include "SymbolCollector.h" |
| Eric Liu | f768868 | 2018-09-07 09:40:36 +0000 | [diff] [blame] | 11 | #include "AST.h" |
| Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 12 | #include "CanonicalIncludes.h" |
| Eric Liu | f768868 | 2018-09-07 09:40:36 +0000 | [diff] [blame] | 13 | #include "CodeComplete.h" |
| 14 | #include "CodeCompletionStrings.h" |
| 15 | #include "Logger.h" |
| 16 | #include "SourceCode.h" |
| 17 | #include "URI.h" |
| Eric Liu | a57afd0 | 2018-09-17 07:43:49 +0000 | [diff] [blame^] | 18 | #include "clang/AST/Decl.h" |
| 19 | #include "clang/AST/DeclBase.h" |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 20 | #include "clang/AST/DeclCXX.h" |
| Ilya Biryukov | cf124bd | 2018-04-13 11:03:07 +0000 | [diff] [blame] | 21 | #include "clang/AST/DeclTemplate.h" |
| Eric Liu | 9af958f | 2018-01-10 14:57:58 +0000 | [diff] [blame] | 22 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 23 | #include "clang/Basic/SourceManager.h" |
| Eric Liu | a57afd0 | 2018-09-17 07:43:49 +0000 | [diff] [blame^] | 24 | #include "clang/Basic/Specifiers.h" |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 25 | #include "clang/Index/IndexSymbol.h" |
| 26 | #include "clang/Index/USRGeneration.h" |
| Eric Liu | a57afd0 | 2018-09-17 07:43:49 +0000 | [diff] [blame^] | 27 | #include "llvm/Support/Casting.h" |
| Eric Liu | 278e2d1 | 2018-01-29 15:13:29 +0000 | [diff] [blame] | 28 | #include "llvm/Support/FileSystem.h" |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 29 | #include "llvm/Support/MemoryBuffer.h" |
| 30 | #include "llvm/Support/Path.h" |
| 31 | |
| 32 | namespace clang { |
| 33 | namespace clangd { |
| 34 | |
| 35 | namespace { |
| Ilya Biryukov | f118d51 | 2018-04-14 16:27:35 +0000 | [diff] [blame] | 36 | /// If \p ND is a template specialization, returns the described template. |
| Ilya Biryukov | cf124bd | 2018-04-13 11:03:07 +0000 | [diff] [blame] | 37 | /// Otherwise, returns \p ND. |
| 38 | const NamedDecl &getTemplateOrThis(const NamedDecl &ND) { |
| Ilya Biryukov | f118d51 | 2018-04-14 16:27:35 +0000 | [diff] [blame] | 39 | if (auto T = ND.getDescribedTemplate()) |
| 40 | return *T; |
| Ilya Biryukov | cf124bd | 2018-04-13 11:03:07 +0000 | [diff] [blame] | 41 | return ND; |
| 42 | } |
| 43 | |
| Eric Liu | 7f24765 | 2018-02-06 16:10:35 +0000 | [diff] [blame] | 44 | // Returns a URI of \p Path. Firstly, this makes the \p Path absolute using the |
| 45 | // current working directory of the given SourceManager if the Path is not an |
| 46 | // absolute path. If failed, this resolves relative paths against \p FallbackDir |
| 47 | // to get an absolute path. Then, this tries creating an URI for the absolute |
| 48 | // path with schemes specified in \p Opts. This returns an URI with the first |
| 49 | // working scheme, if there is any; otherwise, this returns None. |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 50 | // |
| 51 | // The Path can be a path relative to the build directory, or retrieved from |
| 52 | // the SourceManager. |
| Eric Liu | 7f24765 | 2018-02-06 16:10:35 +0000 | [diff] [blame] | 53 | llvm::Optional<std::string> toURI(const SourceManager &SM, StringRef Path, |
| 54 | const SymbolCollector::Options &Opts) { |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 55 | llvm::SmallString<128> AbsolutePath(Path); |
| 56 | if (std::error_code EC = |
| 57 | SM.getFileManager().getVirtualFileSystem()->makeAbsolute( |
| 58 | AbsolutePath)) |
| Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 59 | log("Warning: could not make absolute file: {0}", EC.message()); |
| Eric Liu | 278e2d1 | 2018-01-29 15:13:29 +0000 | [diff] [blame] | 60 | if (llvm::sys::path::is_absolute(AbsolutePath)) { |
| 61 | // Handle the symbolic link path case where the current working directory |
| 62 | // (getCurrentWorkingDirectory) is a symlink./ We always want to the real |
| 63 | // file path (instead of the symlink path) for the C++ symbols. |
| 64 | // |
| 65 | // Consider the following example: |
| 66 | // |
| 67 | // src dir: /project/src/foo.h |
| 68 | // current working directory (symlink): /tmp/build -> /project/src/ |
| 69 | // |
| 70 | // The file path of Symbol is "/project/src/foo.h" instead of |
| 71 | // "/tmp/build/foo.h" |
| 72 | if (const DirectoryEntry *Dir = SM.getFileManager().getDirectory( |
| 73 | llvm::sys::path::parent_path(AbsolutePath.str()))) { |
| 74 | StringRef DirName = SM.getFileManager().getCanonicalName(Dir); |
| 75 | SmallString<128> AbsoluteFilename; |
| 76 | llvm::sys::path::append(AbsoluteFilename, DirName, |
| 77 | llvm::sys::path::filename(AbsolutePath.str())); |
| 78 | AbsolutePath = AbsoluteFilename; |
| 79 | } |
| Eric Liu | 7f24765 | 2018-02-06 16:10:35 +0000 | [diff] [blame] | 80 | } else if (!Opts.FallbackDir.empty()) { |
| 81 | llvm::sys::fs::make_absolute(Opts.FallbackDir, AbsolutePath); |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 82 | } |
| Eric Liu | 7f24765 | 2018-02-06 16:10:35 +0000 | [diff] [blame] | 83 | |
| Eric Liu | a095770 | 2018-06-25 11:50:11 +0000 | [diff] [blame] | 84 | llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true); |
| 85 | |
| Eric Liu | 7f24765 | 2018-02-06 16:10:35 +0000 | [diff] [blame] | 86 | std::string ErrMsg; |
| 87 | for (const auto &Scheme : Opts.URISchemes) { |
| 88 | auto U = URI::create(AbsolutePath, Scheme); |
| 89 | if (U) |
| 90 | return U->toString(); |
| 91 | ErrMsg += llvm::toString(U.takeError()) + "\n"; |
| 92 | } |
| Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 93 | log("Failed to create an URI for file {0}: {1}", AbsolutePath, ErrMsg); |
| Eric Liu | 7f24765 | 2018-02-06 16:10:35 +0000 | [diff] [blame] | 94 | return llvm::None; |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 95 | } |
| Eric Liu | 4feda80 | 2017-12-19 11:37:40 +0000 | [diff] [blame] | 96 | |
| Eric Liu | d67ec24 | 2018-05-16 12:12:30 +0000 | [diff] [blame] | 97 | // All proto generated headers should start with this line. |
| 98 | static const char *PROTO_HEADER_COMMENT = |
| 99 | "// Generated by the protocol buffer compiler. DO NOT EDIT!"; |
| 100 | |
| 101 | // Checks whether the decl is a private symbol in a header generated by |
| 102 | // protobuf compiler. |
| 103 | // To identify whether a proto header is actually generated by proto compiler, |
| 104 | // we check whether it starts with PROTO_HEADER_COMMENT. |
| 105 | // FIXME: make filtering extensible when there are more use cases for symbol |
| 106 | // filters. |
| 107 | bool isPrivateProtoDecl(const NamedDecl &ND) { |
| 108 | const auto &SM = ND.getASTContext().getSourceManager(); |
| 109 | auto Loc = findNameLoc(&ND); |
| 110 | auto FileName = SM.getFilename(Loc); |
| 111 | if (!FileName.endswith(".proto.h") && !FileName.endswith(".pb.h")) |
| 112 | return false; |
| 113 | auto FID = SM.getFileID(Loc); |
| 114 | // Double check that this is an actual protobuf header. |
| 115 | if (!SM.getBufferData(FID).startswith(PROTO_HEADER_COMMENT)) |
| 116 | return false; |
| 117 | |
| 118 | // ND without identifier can be operators. |
| 119 | if (ND.getIdentifier() == nullptr) |
| 120 | return false; |
| 121 | auto Name = ND.getIdentifier()->getName(); |
| 122 | if (!Name.contains('_')) |
| 123 | return false; |
| 124 | // Nested proto entities (e.g. Message::Nested) have top-level decls |
| 125 | // that shouldn't be used (Message_Nested). Ignore them completely. |
| 126 | // The nested entities are dangling type aliases, we may want to reconsider |
| 127 | // including them in the future. |
| 128 | // For enum constants, SOME_ENUM_CONSTANT is not private and should be |
| 129 | // indexed. Outer_INNER is private. This heuristic relies on naming style, it |
| 130 | // will include OUTER_INNER and exclude some_enum_constant. |
| 131 | // FIXME: the heuristic relies on naming style (i.e. no underscore in |
| 132 | // user-defined names) and can be improved. |
| 133 | return (ND.getKind() != Decl::EnumConstant) || |
| 134 | std::any_of(Name.begin(), Name.end(), islower); |
| 135 | } |
| 136 | |
| Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 137 | // We only collect #include paths for symbols that are suitable for global code |
| 138 | // completion, except for namespaces since #include path for a namespace is hard |
| 139 | // to define. |
| 140 | bool shouldCollectIncludePath(index::SymbolKind Kind) { |
| 141 | using SK = index::SymbolKind; |
| 142 | switch (Kind) { |
| 143 | case SK::Macro: |
| 144 | case SK::Enum: |
| 145 | case SK::Struct: |
| 146 | case SK::Class: |
| 147 | case SK::Union: |
| 148 | case SK::TypeAlias: |
| 149 | case SK::Using: |
| 150 | case SK::Function: |
| 151 | case SK::Variable: |
| 152 | case SK::EnumConstant: |
| 153 | return true; |
| 154 | default: |
| 155 | return false; |
| 156 | } |
| 157 | } |
| 158 | |
| Eric Liu | 02ce01f | 2018-02-22 10:14:05 +0000 | [diff] [blame] | 159 | /// Gets a canonical include (URI of the header or <header> or "header") for |
| 160 | /// header of \p Loc. |
| 161 | /// Returns None if fails to get include header for \p Loc. |
| Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 162 | llvm::Optional<std::string> |
| Eric Liu | b96363d | 2018-03-01 18:06:40 +0000 | [diff] [blame] | 163 | getIncludeHeader(llvm::StringRef QName, const SourceManager &SM, |
| 164 | SourceLocation Loc, const SymbolCollector::Options &Opts) { |
| Eric Liu | 3cee95e | 2018-05-24 14:40:24 +0000 | [diff] [blame] | 165 | std::vector<std::string> Headers; |
| 166 | // Collect the #include stack. |
| 167 | while (true) { |
| 168 | if (!Loc.isValid()) |
| 169 | break; |
| 170 | auto FilePath = SM.getFilename(Loc); |
| 171 | if (FilePath.empty()) |
| 172 | break; |
| 173 | Headers.push_back(FilePath); |
| 174 | if (SM.isInMainFile(Loc)) |
| 175 | break; |
| 176 | Loc = SM.getIncludeLoc(SM.getFileID(Loc)); |
| Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 177 | } |
| Eric Liu | 3cee95e | 2018-05-24 14:40:24 +0000 | [diff] [blame] | 178 | if (Headers.empty()) |
| 179 | return llvm::None; |
| 180 | llvm::StringRef Header = Headers[0]; |
| 181 | if (Opts.Includes) { |
| 182 | Header = Opts.Includes->mapHeader(Headers, QName); |
| 183 | if (Header.startswith("<") || Header.startswith("\"")) |
| 184 | return Header.str(); |
| 185 | } |
| 186 | return toURI(SM, Header, Opts); |
| Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 187 | } |
| 188 | |
| Haojian Wu | d81e314 | 2018-08-31 12:54:13 +0000 | [diff] [blame] | 189 | // Return the symbol range of the token at \p TokLoc. |
| 190 | std::pair<SymbolLocation::Position, SymbolLocation::Position> |
| 191 | getTokenRange(SourceLocation TokLoc, const SourceManager &SM, |
| 192 | const LangOptions &LangOpts) { |
| 193 | auto CreatePosition = [&SM](SourceLocation Loc) { |
| 194 | auto LSPLoc = sourceLocToPosition(SM, Loc); |
| 195 | SymbolLocation::Position Pos; |
| 196 | Pos.Line = LSPLoc.line; |
| 197 | Pos.Column = LSPLoc.character; |
| 198 | return Pos; |
| 199 | }; |
| 200 | |
| 201 | auto TokenLength = clang::Lexer::MeasureTokenLength(TokLoc, SM, LangOpts); |
| 202 | return {CreatePosition(TokLoc), |
| 203 | CreatePosition(TokLoc.getLocWithOffset(TokenLength))}; |
| 204 | } |
| 205 | |
| 206 | // Return the symbol location of the token at \p TokLoc. |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 207 | llvm::Optional<SymbolLocation> |
| 208 | getTokenLocation(SourceLocation TokLoc, const SourceManager &SM, |
| 209 | const SymbolCollector::Options &Opts, |
| 210 | const clang::LangOptions &LangOpts, |
| 211 | std::string &FileURIStorage) { |
| 212 | auto U = toURI(SM, SM.getFilename(TokLoc), Opts); |
| Eric Liu | 7f24765 | 2018-02-06 16:10:35 +0000 | [diff] [blame] | 213 | if (!U) |
| 214 | return llvm::None; |
| 215 | FileURIStorage = std::move(*U); |
| Sam McCall | 6003951 | 2018-02-09 14:42:01 +0000 | [diff] [blame] | 216 | SymbolLocation Result; |
| 217 | Result.FileURI = FileURIStorage; |
| Haojian Wu | d81e314 | 2018-08-31 12:54:13 +0000 | [diff] [blame] | 218 | auto Range = getTokenRange(TokLoc, SM, LangOpts); |
| 219 | Result.Start = Range.first; |
| 220 | Result.End = Range.second; |
| Haojian Wu | 545c02a | 2018-04-13 08:30:39 +0000 | [diff] [blame] | 221 | |
| Sam McCall | 6003951 | 2018-02-09 14:42:01 +0000 | [diff] [blame] | 222 | return std::move(Result); |
| Haojian Wu | b018906 | 2018-01-31 12:56:51 +0000 | [diff] [blame] | 223 | } |
| 224 | |
| Eric Liu | cf8601b | 2018-02-28 09:33:15 +0000 | [diff] [blame] | 225 | // Checks whether \p ND is a definition of a TagDecl (class/struct/enum/union) |
| 226 | // in a header file, in which case clangd would prefer to use ND as a canonical |
| 227 | // declaration. |
| 228 | // FIXME: handle symbol types that are not TagDecl (e.g. functions), if using |
| Fangrui Song | 943e12e | 2018-03-29 20:03:16 +0000 | [diff] [blame] | 229 | // the first seen declaration as canonical declaration is not a good enough |
| Eric Liu | cf8601b | 2018-02-28 09:33:15 +0000 | [diff] [blame] | 230 | // heuristic. |
| 231 | bool isPreferredDeclaration(const NamedDecl &ND, index::SymbolRoleSet Roles) { |
| 232 | using namespace clang::ast_matchers; |
| 233 | return (Roles & static_cast<unsigned>(index::SymbolRole::Definition)) && |
| 234 | llvm::isa<TagDecl>(&ND) && |
| 235 | match(decl(isExpansionInMainFile()), ND, ND.getASTContext()).empty(); |
| 236 | } |
| 237 | |
| Sam McCall | b013831 | 2018-09-04 14:39:56 +0000 | [diff] [blame] | 238 | RefKind toRefKind(index::SymbolRoleSet Roles) { |
| 239 | return static_cast<RefKind>(static_cast<unsigned>(RefKind::All) & Roles); |
| Haojian Wu | d81e314 | 2018-08-31 12:54:13 +0000 | [diff] [blame] | 240 | } |
| 241 | |
| Eric Liu | a57afd0 | 2018-09-17 07:43:49 +0000 | [diff] [blame^] | 242 | template <class T> bool explicitTemplateSpecialization(const NamedDecl &ND) { |
| 243 | if (const auto *TD = llvm::dyn_cast<T>(&ND)) |
| 244 | if (TD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) |
| 245 | return true; |
| 246 | return false; |
| 247 | } |
| 248 | |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 249 | } // namespace |
| 250 | |
| Eric Liu | 9af958f | 2018-01-10 14:57:58 +0000 | [diff] [blame] | 251 | SymbolCollector::SymbolCollector(Options Opts) : Opts(std::move(Opts)) {} |
| 252 | |
| Eric Liu | 76f6b44 | 2018-01-09 17:32:00 +0000 | [diff] [blame] | 253 | void SymbolCollector::initialize(ASTContext &Ctx) { |
| 254 | ASTCtx = &Ctx; |
| 255 | CompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>(); |
| 256 | CompletionTUInfo = |
| 257 | llvm::make_unique<CodeCompletionTUInfo>(CompletionAllocator); |
| 258 | } |
| 259 | |
| Eric Liu | 8763e48 | 2018-06-21 12:12:26 +0000 | [diff] [blame] | 260 | bool SymbolCollector::shouldCollectSymbol(const NamedDecl &ND, |
| 261 | ASTContext &ASTCtx, |
| 262 | const Options &Opts) { |
| 263 | using namespace clang::ast_matchers; |
| 264 | if (ND.isImplicit()) |
| 265 | return false; |
| 266 | // Skip anonymous declarations, e.g (anonymous enum/class/struct). |
| 267 | if (ND.getDeclName().isEmpty()) |
| 268 | return false; |
| 269 | |
| 270 | // FIXME: figure out a way to handle internal linkage symbols (e.g. static |
| 271 | // variables, function) defined in the .cc files. Also we skip the symbols |
| 272 | // in anonymous namespace as the qualifier names of these symbols are like |
| 273 | // `foo::<anonymous>::bar`, which need a special handling. |
| 274 | // In real world projects, we have a relatively large set of header files |
| 275 | // that define static variables (like "static const int A = 1;"), we still |
| 276 | // want to collect these symbols, although they cause potential ODR |
| 277 | // violations. |
| 278 | if (ND.isInAnonymousNamespace()) |
| 279 | return false; |
| 280 | |
| 281 | // We want most things but not "local" symbols such as symbols inside |
| 282 | // FunctionDecl, BlockDecl, ObjCMethodDecl and OMPDeclareReductionDecl. |
| 283 | // FIXME: Need a matcher for ExportDecl in order to include symbols declared |
| 284 | // within an export. |
| Eric Liu | a57afd0 | 2018-09-17 07:43:49 +0000 | [diff] [blame^] | 285 | const auto *DeclCtx = ND.getDeclContext(); |
| 286 | switch (DeclCtx->getDeclKind()) { |
| 287 | case Decl::TranslationUnit: |
| 288 | case Decl::Namespace: |
| 289 | case Decl::LinkageSpec: |
| 290 | case Decl::Enum: |
| 291 | case Decl::ObjCProtocol: |
| 292 | case Decl::ObjCInterface: |
| 293 | case Decl::ObjCCategory: |
| 294 | case Decl::ObjCCategoryImpl: |
| 295 | case Decl::ObjCImplementation: |
| 296 | break; |
| 297 | default: |
| 298 | // Record has a few derivations (e.g. CXXRecord, Class specialization), it's |
| 299 | // easier to cast. |
| 300 | if (!llvm::isa<RecordDecl>(DeclCtx)) |
| 301 | return false; |
| 302 | } |
| 303 | if (explicitTemplateSpecialization<FunctionDecl>(ND) || |
| 304 | explicitTemplateSpecialization<CXXRecordDecl>(ND) || |
| 305 | explicitTemplateSpecialization<VarDecl>(ND)) |
| Eric Liu | 8763e48 | 2018-06-21 12:12:26 +0000 | [diff] [blame] | 306 | return false; |
| 307 | |
| Eric Liu | a57afd0 | 2018-09-17 07:43:49 +0000 | [diff] [blame^] | 308 | const auto &SM = ASTCtx.getSourceManager(); |
| 309 | // Skip decls in the main file. |
| 310 | if (SM.isInMainFile(SM.getExpansionLoc(ND.getBeginLoc()))) |
| 311 | return false; |
| Eric Liu | 8763e48 | 2018-06-21 12:12:26 +0000 | [diff] [blame] | 312 | // Avoid indexing internal symbols in protobuf generated headers. |
| 313 | if (isPrivateProtoDecl(ND)) |
| 314 | return false; |
| 315 | return true; |
| 316 | } |
| 317 | |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 318 | // Always return true to continue indexing. |
| 319 | bool SymbolCollector::handleDeclOccurence( |
| 320 | const Decl *D, index::SymbolRoleSet Roles, |
| Sam McCall | b9d5711 | 2018-04-09 14:28:52 +0000 | [diff] [blame] | 321 | ArrayRef<index::SymbolRelation> Relations, SourceLocation Loc, |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 322 | index::IndexDataConsumer::ASTNodeInfo ASTNode) { |
| Eric Liu | 9af958f | 2018-01-10 14:57:58 +0000 | [diff] [blame] | 323 | assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set."); |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 324 | assert(CompletionAllocator && CompletionTUInfo); |
| Eric Liu | 77d1811 | 2018-06-04 11:31:55 +0000 | [diff] [blame] | 325 | assert(ASTNode.OrigD); |
| 326 | // If OrigD is an declaration associated with a friend declaration and it's |
| 327 | // not a definition, skip it. Note that OrigD is the occurrence that the |
| 328 | // collector is currently visiting. |
| 329 | if ((ASTNode.OrigD->getFriendObjectKind() != |
| 330 | Decl::FriendObjectKind::FOK_None) && |
| 331 | !(Roles & static_cast<unsigned>(index::SymbolRole::Definition))) |
| 332 | return true; |
| 333 | // A declaration created for a friend declaration should not be used as the |
| 334 | // canonical declaration in the index. Use OrigD instead, unless we've already |
| 335 | // picked a replacement for D |
| 336 | if (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None) |
| 337 | D = CanonicalDecls.try_emplace(D, ASTNode.OrigD).first->second; |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 338 | const NamedDecl *ND = llvm::dyn_cast<NamedDecl>(D); |
| 339 | if (!ND) |
| 340 | return true; |
| Eric Liu | 9af958f | 2018-01-10 14:57:58 +0000 | [diff] [blame] | 341 | |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 342 | // Mark D as referenced if this is a reference coming from the main file. |
| 343 | // D may not be an interesting symbol, but it's cheaper to check at the end. |
| Sam McCall | b9d5711 | 2018-04-09 14:28:52 +0000 | [diff] [blame] | 344 | auto &SM = ASTCtx->getSourceManager(); |
| Haojian Wu | d81e314 | 2018-08-31 12:54:13 +0000 | [diff] [blame] | 345 | auto SpellingLoc = SM.getSpellingLoc(Loc); |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 346 | if (Opts.CountReferences && |
| 347 | (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) && |
| Haojian Wu | d81e314 | 2018-08-31 12:54:13 +0000 | [diff] [blame] | 348 | SM.getFileID(SpellingLoc) == SM.getMainFileID()) |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 349 | ReferencedDecls.insert(ND); |
| 350 | |
| Sam McCall | b013831 | 2018-09-04 14:39:56 +0000 | [diff] [blame] | 351 | if ((static_cast<unsigned>(Opts.RefFilter) & Roles) && |
| Haojian Wu | d81e314 | 2018-08-31 12:54:13 +0000 | [diff] [blame] | 352 | SM.getFileID(SpellingLoc) == SM.getMainFileID()) |
| Sam McCall | b013831 | 2018-09-04 14:39:56 +0000 | [diff] [blame] | 353 | DeclRefs[ND].emplace_back(SpellingLoc, Roles); |
| Haojian Wu | d81e314 | 2018-08-31 12:54:13 +0000 | [diff] [blame] | 354 | |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 355 | // Don't continue indexing if this is a mere reference. |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 356 | if (!(Roles & static_cast<unsigned>(index::SymbolRole::Declaration) || |
| 357 | Roles & static_cast<unsigned>(index::SymbolRole::Definition))) |
| 358 | return true; |
| Eric Liu | 8763e48 | 2018-06-21 12:12:26 +0000 | [diff] [blame] | 359 | if (!shouldCollectSymbol(*ND, *ASTCtx, Opts)) |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 360 | return true; |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 361 | |
| Haojian Wu | c6ddb46 | 2018-08-07 08:57:52 +0000 | [diff] [blame] | 362 | auto ID = getSymbolID(ND); |
| 363 | if (!ID) |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 364 | return true; |
| Eric Liu | 76f6b44 | 2018-01-09 17:32:00 +0000 | [diff] [blame] | 365 | |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 366 | const NamedDecl &OriginalDecl = *cast<NamedDecl>(ASTNode.OrigD); |
| Haojian Wu | c6ddb46 | 2018-08-07 08:57:52 +0000 | [diff] [blame] | 367 | const Symbol *BasicSymbol = Symbols.find(*ID); |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 368 | if (!BasicSymbol) // Regardless of role, ND is the canonical declaration. |
| Haojian Wu | c6ddb46 | 2018-08-07 08:57:52 +0000 | [diff] [blame] | 369 | BasicSymbol = addDeclaration(*ND, std::move(*ID)); |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 370 | else if (isPreferredDeclaration(OriginalDecl, Roles)) |
| 371 | // If OriginalDecl is preferred, replace the existing canonical |
| 372 | // declaration (e.g. a class forward declaration). There should be at most |
| 373 | // one duplicate as we expect to see only one preferred declaration per |
| 374 | // TU, because in practice they are definitions. |
| Haojian Wu | c6ddb46 | 2018-08-07 08:57:52 +0000 | [diff] [blame] | 375 | BasicSymbol = addDeclaration(OriginalDecl, std::move(*ID)); |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 376 | |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 377 | if (Roles & static_cast<unsigned>(index::SymbolRole::Definition)) |
| 378 | addDefinition(OriginalDecl, *BasicSymbol); |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 379 | return true; |
| 380 | } |
| 381 | |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 382 | bool SymbolCollector::handleMacroOccurence(const IdentifierInfo *Name, |
| 383 | const MacroInfo *MI, |
| 384 | index::SymbolRoleSet Roles, |
| 385 | SourceLocation Loc) { |
| 386 | if (!Opts.CollectMacro) |
| 387 | return true; |
| 388 | assert(PP.get()); |
| 389 | |
| 390 | const auto &SM = PP->getSourceManager(); |
| 391 | if (SM.isInMainFile(SM.getExpansionLoc(MI->getDefinitionLoc()))) |
| 392 | return true; |
| 393 | // Header guards are not interesting in index. Builtin macros don't have |
| 394 | // useful locations and are not needed for code completions. |
| 395 | if (MI->isUsedForHeaderGuard() || MI->isBuiltinMacro()) |
| 396 | return true; |
| 397 | |
| 398 | // Mark the macro as referenced if this is a reference coming from the main |
| 399 | // file. The macro may not be an interesting symbol, but it's cheaper to check |
| 400 | // at the end. |
| 401 | if (Opts.CountReferences && |
| 402 | (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) && |
| 403 | SM.getFileID(SM.getSpellingLoc(Loc)) == SM.getMainFileID()) |
| 404 | ReferencedMacros.insert(Name); |
| 405 | // Don't continue indexing if this is a mere reference. |
| 406 | // FIXME: remove macro with ID if it is undefined. |
| 407 | if (!(Roles & static_cast<unsigned>(index::SymbolRole::Declaration) || |
| 408 | Roles & static_cast<unsigned>(index::SymbolRole::Definition))) |
| 409 | return true; |
| 410 | |
| Eric Liu | d25f121 | 2018-09-06 09:59:37 +0000 | [diff] [blame] | 411 | auto ID = getSymbolID(*Name, MI, SM); |
| 412 | if (!ID) |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 413 | return true; |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 414 | |
| 415 | // Only collect one instance in case there are multiple. |
| Eric Liu | d25f121 | 2018-09-06 09:59:37 +0000 | [diff] [blame] | 416 | if (Symbols.find(*ID) != nullptr) |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 417 | return true; |
| 418 | |
| 419 | Symbol S; |
| Eric Liu | d25f121 | 2018-09-06 09:59:37 +0000 | [diff] [blame] | 420 | S.ID = std::move(*ID); |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 421 | S.Name = Name->getName(); |
| Eric Liu | 6df6600 | 2018-09-06 18:52:26 +0000 | [diff] [blame] | 422 | S.Flags |= Symbol::IndexedForCodeCompletion; |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 423 | S.SymInfo = index::getSymbolInfoForMacro(*MI); |
| 424 | std::string FileURI; |
| 425 | if (auto DeclLoc = getTokenLocation(MI->getDefinitionLoc(), SM, Opts, |
| 426 | PP->getLangOpts(), FileURI)) |
| 427 | S.CanonicalDeclaration = *DeclLoc; |
| 428 | |
| 429 | CodeCompletionResult SymbolCompletion(Name); |
| 430 | const auto *CCS = SymbolCompletion.CreateCodeCompletionStringForMacro( |
| 431 | *PP, *CompletionAllocator, *CompletionTUInfo); |
| 432 | std::string Signature; |
| 433 | std::string SnippetSuffix; |
| 434 | getSignature(*CCS, &Signature, &SnippetSuffix); |
| 435 | |
| 436 | std::string Include; |
| 437 | if (Opts.CollectIncludePath && shouldCollectIncludePath(S.SymInfo.Kind)) { |
| 438 | if (auto Header = |
| 439 | getIncludeHeader(Name->getName(), SM, |
| 440 | SM.getExpansionLoc(MI->getDefinitionLoc()), Opts)) |
| 441 | Include = std::move(*Header); |
| 442 | } |
| 443 | S.Signature = Signature; |
| 444 | S.CompletionSnippetSuffix = SnippetSuffix; |
| Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 445 | if (!Include.empty()) |
| 446 | S.IncludeHeaders.emplace_back(Include, 1); |
| 447 | |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 448 | Symbols.insert(S); |
| 449 | return true; |
| 450 | } |
| 451 | |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 452 | void SymbolCollector::finish() { |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 453 | // At the end of the TU, add 1 to the refcount of all referenced symbols. |
| 454 | auto IncRef = [this](const SymbolID &ID) { |
| 455 | if (const auto *S = Symbols.find(ID)) { |
| 456 | Symbol Inc = *S; |
| 457 | ++Inc.References; |
| 458 | Symbols.insert(Inc); |
| 459 | } |
| 460 | }; |
| 461 | for (const NamedDecl *ND : ReferencedDecls) { |
| Haojian Wu | c6ddb46 | 2018-08-07 08:57:52 +0000 | [diff] [blame] | 462 | if (auto ID = getSymbolID(ND)) { |
| 463 | IncRef(*ID); |
| 464 | } |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 465 | } |
| 466 | if (Opts.CollectMacro) { |
| 467 | assert(PP); |
| 468 | for (const IdentifierInfo *II : ReferencedMacros) { |
| Eric Liu | a62c9d6 | 2018-07-09 18:54:51 +0000 | [diff] [blame] | 469 | if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo()) |
| Eric Liu | d25f121 | 2018-09-06 09:59:37 +0000 | [diff] [blame] | 470 | if (auto ID = getSymbolID(*II, MI, PP->getSourceManager())) |
| 471 | IncRef(*ID); |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 472 | } |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 473 | } |
| Haojian Wu | d81e314 | 2018-08-31 12:54:13 +0000 | [diff] [blame] | 474 | |
| 475 | const auto &SM = ASTCtx->getSourceManager(); |
| 476 | auto* MainFileEntry = SM.getFileEntryForID(SM.getMainFileID()); |
| 477 | |
| 478 | if (auto MainFileURI = toURI(SM, MainFileEntry->getName(), Opts)) { |
| 479 | std::string MainURI = *MainFileURI; |
| Sam McCall | b013831 | 2018-09-04 14:39:56 +0000 | [diff] [blame] | 480 | for (const auto &It : DeclRefs) { |
| Haojian Wu | d81e314 | 2018-08-31 12:54:13 +0000 | [diff] [blame] | 481 | if (auto ID = getSymbolID(It.first)) { |
| 482 | if (Symbols.find(*ID)) { |
| 483 | for (const auto &LocAndRole : It.second) { |
| Sam McCall | b013831 | 2018-09-04 14:39:56 +0000 | [diff] [blame] | 484 | Ref R; |
| Haojian Wu | d81e314 | 2018-08-31 12:54:13 +0000 | [diff] [blame] | 485 | auto Range = |
| 486 | getTokenRange(LocAndRole.first, SM, ASTCtx->getLangOpts()); |
| Sam McCall | b013831 | 2018-09-04 14:39:56 +0000 | [diff] [blame] | 487 | R.Location.Start = Range.first; |
| 488 | R.Location.End = Range.second; |
| 489 | R.Location.FileURI = MainURI; |
| 490 | R.Kind = toRefKind(LocAndRole.second); |
| 491 | Refs.insert(*ID, R); |
| Haojian Wu | d81e314 | 2018-08-31 12:54:13 +0000 | [diff] [blame] | 492 | } |
| 493 | } |
| 494 | } |
| 495 | } |
| 496 | } else { |
| 497 | log("Failed to create URI for main file: {0}", MainFileEntry->getName()); |
| 498 | } |
| 499 | |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 500 | ReferencedDecls.clear(); |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 501 | ReferencedMacros.clear(); |
| Sam McCall | b013831 | 2018-09-04 14:39:56 +0000 | [diff] [blame] | 502 | DeclRefs.clear(); |
| Sam McCall | 93f99bf | 2018-03-12 14:49:09 +0000 | [diff] [blame] | 503 | } |
| 504 | |
| Sam McCall | 6003951 | 2018-02-09 14:42:01 +0000 | [diff] [blame] | 505 | const Symbol *SymbolCollector::addDeclaration(const NamedDecl &ND, |
| 506 | SymbolID ID) { |
| Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 507 | auto &Ctx = ND.getASTContext(); |
| 508 | auto &SM = Ctx.getSourceManager(); |
| Sam McCall | 6003951 | 2018-02-09 14:42:01 +0000 | [diff] [blame] | 509 | |
| Sam McCall | 6003951 | 2018-02-09 14:42:01 +0000 | [diff] [blame] | 510 | Symbol S; |
| 511 | S.ID = std::move(ID); |
| Eric Liu | 7ad1696 | 2018-06-22 10:46:59 +0000 | [diff] [blame] | 512 | std::string QName = printQualifiedName(ND); |
| Sam McCall | 6003951 | 2018-02-09 14:42:01 +0000 | [diff] [blame] | 513 | std::tie(S.Scope, S.Name) = splitQualifiedName(QName); |
| Sam McCall | 032db94 | 2018-06-22 06:41:43 +0000 | [diff] [blame] | 514 | // FIXME: this returns foo:bar: for objective-C methods, we prefer only foo: |
| 515 | // for consistency with CodeCompletionString and a clean name/signature split. |
| Marc-Andre Laperle | 945b5a3 | 2018-06-05 14:01:40 +0000 | [diff] [blame] | 516 | |
| Eric Liu | 6df6600 | 2018-09-06 18:52:26 +0000 | [diff] [blame] | 517 | if (isIndexedForCodeCompletion(ND, Ctx)) |
| 518 | S.Flags |= Symbol::IndexedForCodeCompletion; |
| Sam McCall | 6003951 | 2018-02-09 14:42:01 +0000 | [diff] [blame] | 519 | S.SymInfo = index::getSymbolInfo(&ND); |
| 520 | std::string FileURI; |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 521 | if (auto DeclLoc = getTokenLocation(findNameLoc(&ND), SM, Opts, |
| 522 | ASTCtx->getLangOpts(), FileURI)) |
| Sam McCall | 6003951 | 2018-02-09 14:42:01 +0000 | [diff] [blame] | 523 | S.CanonicalDeclaration = *DeclLoc; |
| 524 | |
| 525 | // Add completion info. |
| 526 | // FIXME: we may want to choose a different redecl, or combine from several. |
| 527 | assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set."); |
| Ilya Biryukov | cf124bd | 2018-04-13 11:03:07 +0000 | [diff] [blame] | 528 | // We use the primary template, as clang does during code completion. |
| 529 | CodeCompletionResult SymbolCompletion(&getTemplateOrThis(ND), 0); |
| Sam McCall | 6003951 | 2018-02-09 14:42:01 +0000 | [diff] [blame] | 530 | const auto *CCS = SymbolCompletion.CreateCodeCompletionString( |
| 531 | *ASTCtx, *PP, CodeCompletionContext::CCC_Name, *CompletionAllocator, |
| 532 | *CompletionTUInfo, |
| Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 533 | /*IncludeBriefComments*/ false); |
| Sam McCall | a68951e | 2018-06-22 16:11:35 +0000 | [diff] [blame] | 534 | std::string Signature; |
| 535 | std::string SnippetSuffix; |
| 536 | getSignature(*CCS, &Signature, &SnippetSuffix); |
| Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 537 | std::string Documentation = |
| Ilya Biryukov | be0eb8f | 2018-05-24 14:49:23 +0000 | [diff] [blame] | 538 | formatDocumentation(*CCS, getDocComment(Ctx, SymbolCompletion, |
| 539 | /*CommentsFromHeaders=*/true)); |
| Sam McCall | a68951e | 2018-06-22 16:11:35 +0000 | [diff] [blame] | 540 | std::string ReturnType = getReturnType(*CCS); |
| Sam McCall | 6003951 | 2018-02-09 14:42:01 +0000 | [diff] [blame] | 541 | |
| Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 542 | std::string Include; |
| 543 | if (Opts.CollectIncludePath && shouldCollectIncludePath(S.SymInfo.Kind)) { |
| 544 | // Use the expansion location to get the #include header since this is |
| 545 | // where the symbol is exposed. |
| Eric Liu | b96363d | 2018-03-01 18:06:40 +0000 | [diff] [blame] | 546 | if (auto Header = getIncludeHeader( |
| 547 | QName, SM, SM.getExpansionLoc(ND.getLocation()), Opts)) |
| Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 548 | Include = std::move(*Header); |
| 549 | } |
| Sam McCall | a68951e | 2018-06-22 16:11:35 +0000 | [diff] [blame] | 550 | S.Signature = Signature; |
| 551 | S.CompletionSnippetSuffix = SnippetSuffix; |
| Sam McCall | 2e5700f | 2018-08-31 13:55:01 +0000 | [diff] [blame] | 552 | S.Documentation = Documentation; |
| 553 | S.ReturnType = ReturnType; |
| Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 554 | if (!Include.empty()) |
| 555 | S.IncludeHeaders.emplace_back(Include, 1); |
| Sam McCall | 6003951 | 2018-02-09 14:42:01 +0000 | [diff] [blame] | 556 | |
| Sam McCall | 2161ec7 | 2018-07-05 06:20:41 +0000 | [diff] [blame] | 557 | S.Origin = Opts.Origin; |
| Eric Liu | 6df6600 | 2018-09-06 18:52:26 +0000 | [diff] [blame] | 558 | if (ND.getAvailability() == AR_Deprecated) |
| 559 | S.Flags |= Symbol::Deprecated; |
| Sam McCall | 6003951 | 2018-02-09 14:42:01 +0000 | [diff] [blame] | 560 | Symbols.insert(S); |
| 561 | return Symbols.find(S.ID); |
| 562 | } |
| 563 | |
| 564 | void SymbolCollector::addDefinition(const NamedDecl &ND, |
| 565 | const Symbol &DeclSym) { |
| 566 | if (DeclSym.Definition) |
| 567 | return; |
| 568 | // If we saw some forward declaration, we end up copying the symbol. |
| 569 | // This is not ideal, but avoids duplicating the "is this a definition" check |
| 570 | // in clang::index. We should only see one definition. |
| 571 | Symbol S = DeclSym; |
| 572 | std::string FileURI; |
| Eric Liu | 48db19e | 2018-07-09 15:31:07 +0000 | [diff] [blame] | 573 | if (auto DefLoc = getTokenLocation(findNameLoc(&ND), |
| 574 | ND.getASTContext().getSourceManager(), |
| 575 | Opts, ASTCtx->getLangOpts(), FileURI)) |
| Sam McCall | 6003951 | 2018-02-09 14:42:01 +0000 | [diff] [blame] | 576 | S.Definition = *DefLoc; |
| 577 | Symbols.insert(S); |
| 578 | } |
| 579 | |
| Haojian Wu | 4c1394d | 2017-12-12 15:42:10 +0000 | [diff] [blame] | 580 | } // namespace clangd |
| 581 | } // namespace clang |