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