Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1 | //===--- CodeComplete.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 | // AST-based completions are provided using the completion hooks in Sema. |
| 11 | // |
| 12 | // Signature help works in a similar way as code completion, but it is simpler |
| 13 | // as there are typically fewer candidates. |
| 14 | // |
| 15 | //===---------------------------------------------------------------------===// |
| 16 | |
| 17 | #include "CodeComplete.h" |
Eric Liu | 63696e1 | 2017-12-20 17:24:31 +0000 | [diff] [blame] | 18 | #include "CodeCompletionStrings.h" |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 19 | #include "Compiler.h" |
Sam McCall | 84652cc | 2018-01-12 16:16:09 +0000 | [diff] [blame] | 20 | #include "FuzzyMatch.h" |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 21 | #include "Headers.h" |
Eric Liu | 6f648df | 2017-12-19 16:50:37 +0000 | [diff] [blame] | 22 | #include "Logger.h" |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 23 | #include "Quality.h" |
Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 24 | #include "SourceCode.h" |
Sam McCall | 2b78016 | 2018-01-30 17:20:54 +0000 | [diff] [blame] | 25 | #include "Trace.h" |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 26 | #include "URI.h" |
Eric Liu | 6f648df | 2017-12-19 16:50:37 +0000 | [diff] [blame] | 27 | #include "index/Index.h" |
Marc-Andre Laperle | 945b5a3 | 2018-06-05 14:01:40 +0000 | [diff] [blame] | 28 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
Ilya Biryukov | c22d344 | 2018-05-16 12:32:49 +0000 | [diff] [blame] | 29 | #include "clang/Basic/LangOptions.h" |
Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 30 | #include "clang/Format/Format.h" |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 31 | #include "clang/Frontend/CompilerInstance.h" |
| 32 | #include "clang/Frontend/FrontendActions.h" |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 33 | #include "clang/Index/USRGeneration.h" |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 34 | #include "clang/Sema/CodeCompleteConsumer.h" |
| 35 | #include "clang/Sema/Sema.h" |
Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 36 | #include "clang/Tooling/Core/Replacement.h" |
Haojian Wu | ba28e9a | 2018-01-10 14:44:34 +0000 | [diff] [blame] | 37 | #include "llvm/Support/Format.h" |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 38 | #include <queue> |
| 39 | |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 40 | // We log detailed candidate here if you run with -debug-only=codecomplete. |
| 41 | #define DEBUG_TYPE "codecomplete" |
| 42 | |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 43 | namespace clang { |
| 44 | namespace clangd { |
| 45 | namespace { |
| 46 | |
Eric Liu | 6f648df | 2017-12-19 16:50:37 +0000 | [diff] [blame] | 47 | CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) { |
| 48 | using SK = index::SymbolKind; |
| 49 | switch (Kind) { |
| 50 | case SK::Unknown: |
| 51 | return CompletionItemKind::Missing; |
| 52 | case SK::Module: |
| 53 | case SK::Namespace: |
| 54 | case SK::NamespaceAlias: |
| 55 | return CompletionItemKind::Module; |
| 56 | case SK::Macro: |
| 57 | return CompletionItemKind::Text; |
| 58 | case SK::Enum: |
| 59 | return CompletionItemKind::Enum; |
| 60 | // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the |
| 61 | // protocol. |
| 62 | case SK::Struct: |
| 63 | case SK::Class: |
| 64 | case SK::Protocol: |
| 65 | case SK::Extension: |
| 66 | case SK::Union: |
| 67 | return CompletionItemKind::Class; |
| 68 | // FIXME(ioeric): figure out whether reference is the right type for aliases. |
| 69 | case SK::TypeAlias: |
| 70 | case SK::Using: |
| 71 | return CompletionItemKind::Reference; |
| 72 | case SK::Function: |
| 73 | // FIXME(ioeric): this should probably be an operator. This should be fixed |
| 74 | // when `Operator` is support type in the protocol. |
| 75 | case SK::ConversionFunction: |
| 76 | return CompletionItemKind::Function; |
| 77 | case SK::Variable: |
| 78 | case SK::Parameter: |
| 79 | return CompletionItemKind::Variable; |
| 80 | case SK::Field: |
| 81 | return CompletionItemKind::Field; |
| 82 | // FIXME(ioeric): use LSP enum constant when it is supported in the protocol. |
| 83 | case SK::EnumConstant: |
| 84 | return CompletionItemKind::Value; |
| 85 | case SK::InstanceMethod: |
| 86 | case SK::ClassMethod: |
| 87 | case SK::StaticMethod: |
| 88 | case SK::Destructor: |
| 89 | return CompletionItemKind::Method; |
| 90 | case SK::InstanceProperty: |
| 91 | case SK::ClassProperty: |
| 92 | case SK::StaticProperty: |
| 93 | return CompletionItemKind::Property; |
| 94 | case SK::Constructor: |
| 95 | return CompletionItemKind::Constructor; |
| 96 | } |
| 97 | llvm_unreachable("Unhandled clang::index::SymbolKind."); |
| 98 | } |
| 99 | |
Sam McCall | 8330589 | 2018-06-08 21:17:19 +0000 | [diff] [blame] | 100 | CompletionItemKind |
| 101 | toCompletionItemKind(CodeCompletionResult::ResultKind ResKind, |
| 102 | const NamedDecl *Decl) { |
| 103 | if (Decl) |
| 104 | return toCompletionItemKind(index::getSymbolInfo(Decl).Kind); |
| 105 | switch (ResKind) { |
| 106 | case CodeCompletionResult::RK_Declaration: |
| 107 | llvm_unreachable("RK_Declaration without Decl"); |
| 108 | case CodeCompletionResult::RK_Keyword: |
| 109 | return CompletionItemKind::Keyword; |
| 110 | case CodeCompletionResult::RK_Macro: |
| 111 | return CompletionItemKind::Text; // unfortunately, there's no 'Macro' |
| 112 | // completion items in LSP. |
| 113 | case CodeCompletionResult::RK_Pattern: |
| 114 | return CompletionItemKind::Snippet; |
| 115 | } |
| 116 | llvm_unreachable("Unhandled CodeCompletionResult::ResultKind."); |
| 117 | } |
| 118 | |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 119 | /// Get the optional chunk as a string. This function is possibly recursive. |
| 120 | /// |
| 121 | /// The parameter info for each parameter is appended to the Parameters. |
| 122 | std::string |
| 123 | getOptionalParameters(const CodeCompletionString &CCS, |
| 124 | std::vector<ParameterInformation> &Parameters) { |
| 125 | std::string Result; |
| 126 | for (const auto &Chunk : CCS) { |
| 127 | switch (Chunk.Kind) { |
| 128 | case CodeCompletionString::CK_Optional: |
| 129 | assert(Chunk.Optional && |
| 130 | "Expected the optional code completion string to be non-null."); |
| 131 | Result += getOptionalParameters(*Chunk.Optional, Parameters); |
| 132 | break; |
| 133 | case CodeCompletionString::CK_VerticalSpace: |
| 134 | break; |
| 135 | case CodeCompletionString::CK_Placeholder: |
| 136 | // A string that acts as a placeholder for, e.g., a function call |
| 137 | // argument. |
| 138 | // Intentional fallthrough here. |
| 139 | case CodeCompletionString::CK_CurrentParameter: { |
| 140 | // A piece of text that describes the parameter that corresponds to |
| 141 | // the code-completion location within a function call, message send, |
| 142 | // macro invocation, etc. |
| 143 | Result += Chunk.Text; |
| 144 | ParameterInformation Info; |
| 145 | Info.label = Chunk.Text; |
| 146 | Parameters.push_back(std::move(Info)); |
| 147 | break; |
| 148 | } |
| 149 | default: |
| 150 | Result += Chunk.Text; |
| 151 | break; |
| 152 | } |
| 153 | } |
| 154 | return Result; |
| 155 | } |
| 156 | |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 157 | /// Creates a `HeaderFile` from \p Header which can be either a URI or a literal |
| 158 | /// include. |
| 159 | static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header, |
| 160 | llvm::StringRef HintPath) { |
| 161 | if (isLiteralInclude(Header)) |
| 162 | return HeaderFile{Header.str(), /*Verbatim=*/true}; |
| 163 | auto U = URI::parse(Header); |
| 164 | if (!U) |
| 165 | return U.takeError(); |
| 166 | |
| 167 | auto IncludePath = URI::includeSpelling(*U); |
| 168 | if (!IncludePath) |
| 169 | return IncludePath.takeError(); |
| 170 | if (!IncludePath->empty()) |
| 171 | return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true}; |
| 172 | |
| 173 | auto Resolved = URI::resolve(*U, HintPath); |
| 174 | if (!Resolved) |
| 175 | return Resolved.takeError(); |
| 176 | return HeaderFile{std::move(*Resolved), /*Verbatim=*/false}; |
| 177 | } |
| 178 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 179 | /// A code completion result, in clang-native form. |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 180 | /// It may be promoted to a CompletionItem if it's among the top-ranked results. |
| 181 | struct CompletionCandidate { |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 182 | llvm::StringRef Name; // Used for filtering and sorting. |
| 183 | // We may have a result from Sema, from the index, or both. |
| 184 | const CodeCompletionResult *SemaResult = nullptr; |
| 185 | const Symbol *IndexResult = nullptr; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 186 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 187 | // Builds an LSP completion item. |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 188 | CompletionItem build(StringRef FileName, const CompletionItemScores &Scores, |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 189 | const CodeCompleteOptions &Opts, |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 190 | CodeCompletionString *SemaCCS, |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 191 | const IncludeInserter *Includes, |
| 192 | llvm::StringRef SemaDocComment) const { |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 193 | assert(bool(SemaResult) == bool(SemaCCS)); |
| 194 | CompletionItem I; |
Eric Liu | 9b3cba7 | 2018-05-30 09:03:39 +0000 | [diff] [blame] | 195 | bool ShouldInsertInclude = true; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 196 | if (SemaResult) { |
Sam McCall | 8330589 | 2018-06-08 21:17:19 +0000 | [diff] [blame] | 197 | I.kind = toCompletionItemKind(SemaResult->Kind, SemaResult->Declaration); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 198 | getLabelAndInsertText(*SemaCCS, &I.label, &I.insertText, |
| 199 | Opts.EnableSnippets); |
| 200 | I.filterText = getFilterText(*SemaCCS); |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 201 | I.documentation = formatDocumentation(*SemaCCS, SemaDocComment); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 202 | I.detail = getDetail(*SemaCCS); |
Eric Liu | 9b3cba7 | 2018-05-30 09:03:39 +0000 | [diff] [blame] | 203 | // Avoid inserting new #include if the declaration is found in the current |
| 204 | // file e.g. the symbol is forward declared. |
| 205 | if (SemaResult->Kind == CodeCompletionResult::RK_Declaration) { |
| 206 | if (const auto *D = SemaResult->getDeclaration()) { |
| 207 | const auto &SM = D->getASTContext().getSourceManager(); |
| 208 | ShouldInsertInclude = |
| 209 | ShouldInsertInclude && |
| 210 | std::none_of(D->redecls_begin(), D->redecls_end(), |
| 211 | [&SM](const Decl *RD) { |
| 212 | return SM.isInMainFile( |
| 213 | SM.getExpansionLoc(RD->getLocStart())); |
| 214 | }); |
| 215 | } |
| 216 | } |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 217 | } |
| 218 | if (IndexResult) { |
| 219 | if (I.kind == CompletionItemKind::Missing) |
| 220 | I.kind = toCompletionItemKind(IndexResult->SymInfo.Kind); |
| 221 | // FIXME: reintroduce a way to show the index source for debugging. |
| 222 | if (I.label.empty()) |
| 223 | I.label = IndexResult->CompletionLabel; |
| 224 | if (I.filterText.empty()) |
| 225 | I.filterText = IndexResult->Name; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 226 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 227 | // FIXME(ioeric): support inserting/replacing scope qualifiers. |
| 228 | if (I.insertText.empty()) |
| 229 | I.insertText = Opts.EnableSnippets |
| 230 | ? IndexResult->CompletionSnippetInsertText |
| 231 | : IndexResult->CompletionPlainInsertText; |
| 232 | |
| 233 | if (auto *D = IndexResult->Detail) { |
| 234 | if (I.documentation.empty()) |
| 235 | I.documentation = D->Documentation; |
| 236 | if (I.detail.empty()) |
| 237 | I.detail = D->CompletionDetail; |
Eric Liu | 9b3cba7 | 2018-05-30 09:03:39 +0000 | [diff] [blame] | 238 | if (ShouldInsertInclude && Includes && !D->IncludeHeader.empty()) { |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 239 | auto Edit = [&]() -> Expected<Optional<TextEdit>> { |
| 240 | auto ResolvedDeclaring = toHeaderFile( |
| 241 | IndexResult->CanonicalDeclaration.FileURI, FileName); |
| 242 | if (!ResolvedDeclaring) |
| 243 | return ResolvedDeclaring.takeError(); |
| 244 | auto ResolvedInserted = toHeaderFile(D->IncludeHeader, FileName); |
| 245 | if (!ResolvedInserted) |
| 246 | return ResolvedInserted.takeError(); |
| 247 | return Includes->insert(*ResolvedDeclaring, *ResolvedInserted); |
| 248 | }(); |
| 249 | if (!Edit) { |
| 250 | std::string ErrMsg = |
| 251 | ("Failed to generate include insertion edits for adding header " |
| 252 | "(FileURI=\"" + |
| 253 | IndexResult->CanonicalDeclaration.FileURI + |
| 254 | "\", IncludeHeader=\"" + D->IncludeHeader + "\") into " + |
| 255 | FileName) |
| 256 | .str(); |
| 257 | log(ErrMsg + ":" + llvm::toString(Edit.takeError())); |
| 258 | } else if (*Edit) { |
| 259 | I.additionalTextEdits = {std::move(**Edit)}; |
| 260 | } |
| 261 | } |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 262 | } |
| 263 | } |
| 264 | I.scoreInfo = Scores; |
| 265 | I.sortText = sortText(Scores.finalScore, Name); |
| 266 | I.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet |
| 267 | : InsertTextFormat::PlainText; |
| 268 | return I; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 269 | } |
| 270 | }; |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 271 | using ScoredCandidate = std::pair<CompletionCandidate, CompletionItemScores>; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 272 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 273 | // Determine the symbol ID for a Sema code completion result, if possible. |
| 274 | llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) { |
| 275 | switch (R.Kind) { |
| 276 | case CodeCompletionResult::RK_Declaration: |
| 277 | case CodeCompletionResult::RK_Pattern: { |
| 278 | llvm::SmallString<128> USR; |
| 279 | if (/*Ignore=*/clang::index::generateUSRForDecl(R.Declaration, USR)) |
| 280 | return None; |
| 281 | return SymbolID(USR); |
| 282 | } |
| 283 | case CodeCompletionResult::RK_Macro: |
| 284 | // FIXME: Macros do have USRs, but the CCR doesn't contain enough info. |
| 285 | case CodeCompletionResult::RK_Keyword: |
| 286 | return None; |
| 287 | } |
| 288 | llvm_unreachable("unknown CodeCompletionResult kind"); |
| 289 | } |
| 290 | |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 291 | // Scopes of the paritial identifier we're trying to complete. |
| 292 | // It is used when we query the index for more completion results. |
Eric Liu | 6f648df | 2017-12-19 16:50:37 +0000 | [diff] [blame] | 293 | struct SpecifiedScope { |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 294 | // The scopes we should look in, determined by Sema. |
| 295 | // |
| 296 | // If the qualifier was fully resolved, we look for completions in these |
| 297 | // scopes; if there is an unresolved part of the qualifier, it should be |
| 298 | // resolved within these scopes. |
| 299 | // |
| 300 | // Examples of qualified completion: |
| 301 | // |
| 302 | // "::vec" => {""} |
| 303 | // "using namespace std; ::vec^" => {"", "std::"} |
| 304 | // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"} |
| 305 | // "std::vec^" => {""} // "std" unresolved |
| 306 | // |
| 307 | // Examples of unqualified completion: |
| 308 | // |
| 309 | // "vec^" => {""} |
| 310 | // "using namespace std; vec^" => {"", "std::"} |
| 311 | // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""} |
| 312 | // |
| 313 | // "" for global namespace, "ns::" for normal namespace. |
| 314 | std::vector<std::string> AccessibleScopes; |
| 315 | // The full scope qualifier as typed by the user (without the leading "::"). |
| 316 | // Set if the qualifier is not fully resolved by Sema. |
| 317 | llvm::Optional<std::string> UnresolvedQualifier; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 318 | |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 319 | // Construct scopes being queried in indexes. |
| 320 | // This method format the scopes to match the index request representation. |
| 321 | std::vector<std::string> scopesForIndexQuery() { |
| 322 | std::vector<std::string> Results; |
| 323 | for (llvm::StringRef AS : AccessibleScopes) { |
| 324 | Results.push_back(AS); |
| 325 | if (UnresolvedQualifier) |
| 326 | Results.back() += *UnresolvedQualifier; |
| 327 | } |
| 328 | return Results; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 329 | } |
Eric Liu | 6f648df | 2017-12-19 16:50:37 +0000 | [diff] [blame] | 330 | }; |
| 331 | |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 332 | // Get all scopes that will be queried in indexes. |
| 333 | std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext, |
Kirill Bobyrev | 5a267ed | 2018-05-29 11:50:51 +0000 | [diff] [blame] | 334 | const SourceManager &SM) { |
| 335 | auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) { |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 336 | SpecifiedScope Info; |
Kirill Bobyrev | 5a267ed | 2018-05-29 11:50:51 +0000 | [diff] [blame] | 337 | for (auto *Context : CCContext.getVisitedContexts()) { |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 338 | if (isa<TranslationUnitDecl>(Context)) |
| 339 | Info.AccessibleScopes.push_back(""); // global namespace |
Kirill Bobyrev | 5a267ed | 2018-05-29 11:50:51 +0000 | [diff] [blame] | 340 | else if (const auto *NS = dyn_cast<NamespaceDecl>(Context)) |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 341 | Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::"); |
| 342 | } |
| 343 | return Info; |
| 344 | }; |
| 345 | |
| 346 | auto SS = CCContext.getCXXScopeSpecifier(); |
| 347 | |
| 348 | // Unqualified completion (e.g. "vec^"). |
| 349 | if (!SS) { |
| 350 | // FIXME: Once we can insert namespace qualifiers and use the in-scope |
| 351 | // namespaces for scoring, search in all namespaces. |
| 352 | // FIXME: Capture scopes and use for scoring, for example, |
| 353 | // "using namespace std; namespace foo {v^}" => |
| 354 | // foo::value > std::vector > boost::variant |
| 355 | return GetAllAccessibleScopes(CCContext).scopesForIndexQuery(); |
| 356 | } |
| 357 | |
| 358 | // Qualified completion ("std::vec^"), we have two cases depending on whether |
| 359 | // the qualifier can be resolved by Sema. |
| 360 | if ((*SS)->isValid()) { // Resolved qualifier. |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 361 | return GetAllAccessibleScopes(CCContext).scopesForIndexQuery(); |
| 362 | } |
| 363 | |
| 364 | // Unresolved qualifier. |
| 365 | // FIXME: When Sema can resolve part of a scope chain (e.g. |
| 366 | // "known::unknown::id"), we should expand the known part ("known::") rather |
| 367 | // than treating the whole thing as unknown. |
| 368 | SpecifiedScope Info; |
| 369 | Info.AccessibleScopes.push_back(""); // global namespace |
| 370 | |
| 371 | Info.UnresolvedQualifier = |
Kirill Bobyrev | 5a267ed | 2018-05-29 11:50:51 +0000 | [diff] [blame] | 372 | Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), SM, |
| 373 | clang::LangOptions()) |
| 374 | .ltrim("::"); |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 375 | // Sema excludes the trailing "::". |
| 376 | if (!Info.UnresolvedQualifier->empty()) |
| 377 | *Info.UnresolvedQualifier += "::"; |
| 378 | |
| 379 | return Info.scopesForIndexQuery(); |
| 380 | } |
| 381 | |
Eric Liu | 42abe41 | 2018-05-24 11:20:19 +0000 | [diff] [blame] | 382 | // Should we perform index-based completion in a context of the specified kind? |
| 383 | // FIXME: consider allowing completion, but restricting the result types. |
| 384 | bool contextAllowsIndex(enum CodeCompletionContext::Kind K) { |
| 385 | switch (K) { |
| 386 | case CodeCompletionContext::CCC_TopLevel: |
| 387 | case CodeCompletionContext::CCC_ObjCInterface: |
| 388 | case CodeCompletionContext::CCC_ObjCImplementation: |
| 389 | case CodeCompletionContext::CCC_ObjCIvarList: |
| 390 | case CodeCompletionContext::CCC_ClassStructUnion: |
| 391 | case CodeCompletionContext::CCC_Statement: |
| 392 | case CodeCompletionContext::CCC_Expression: |
| 393 | case CodeCompletionContext::CCC_ObjCMessageReceiver: |
| 394 | case CodeCompletionContext::CCC_EnumTag: |
| 395 | case CodeCompletionContext::CCC_UnionTag: |
| 396 | case CodeCompletionContext::CCC_ClassOrStructTag: |
| 397 | case CodeCompletionContext::CCC_ObjCProtocolName: |
| 398 | case CodeCompletionContext::CCC_Namespace: |
| 399 | case CodeCompletionContext::CCC_Type: |
| 400 | case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this? |
| 401 | case CodeCompletionContext::CCC_PotentiallyQualifiedName: |
| 402 | case CodeCompletionContext::CCC_ParenthesizedExpression: |
| 403 | case CodeCompletionContext::CCC_ObjCInterfaceName: |
| 404 | case CodeCompletionContext::CCC_ObjCCategoryName: |
| 405 | return true; |
| 406 | case CodeCompletionContext::CCC_Other: // Be conservative. |
| 407 | case CodeCompletionContext::CCC_OtherWithMacros: |
| 408 | case CodeCompletionContext::CCC_DotMemberAccess: |
| 409 | case CodeCompletionContext::CCC_ArrowMemberAccess: |
| 410 | case CodeCompletionContext::CCC_ObjCPropertyAccess: |
| 411 | case CodeCompletionContext::CCC_MacroName: |
| 412 | case CodeCompletionContext::CCC_MacroNameUse: |
| 413 | case CodeCompletionContext::CCC_PreprocessorExpression: |
| 414 | case CodeCompletionContext::CCC_PreprocessorDirective: |
| 415 | case CodeCompletionContext::CCC_NaturalLanguage: |
| 416 | case CodeCompletionContext::CCC_SelectorName: |
| 417 | case CodeCompletionContext::CCC_TypeQualifiers: |
| 418 | case CodeCompletionContext::CCC_ObjCInstanceMessage: |
| 419 | case CodeCompletionContext::CCC_ObjCClassMessage: |
| 420 | case CodeCompletionContext::CCC_Recovery: |
| 421 | return false; |
| 422 | } |
| 423 | llvm_unreachable("unknown code completion context"); |
| 424 | } |
| 425 | |
Sam McCall | 4caa851 | 2018-06-07 12:49:17 +0000 | [diff] [blame] | 426 | // Some member calls are blacklisted because they're so rarely useful. |
| 427 | static bool isBlacklistedMember(const NamedDecl &D) { |
| 428 | // Destructor completion is rarely useful, and works inconsistently. |
| 429 | // (s.^ completes ~string, but s.~st^ is an error). |
| 430 | if (D.getKind() == Decl::CXXDestructor) |
| 431 | return true; |
| 432 | // Injected name may be useful for A::foo(), but who writes A::A::foo()? |
| 433 | if (auto *R = dyn_cast_or_null<RecordDecl>(&D)) |
| 434 | if (R->isInjectedClassName()) |
| 435 | return true; |
| 436 | // Explicit calls to operators are also rare. |
| 437 | auto NameKind = D.getDeclName().getNameKind(); |
| 438 | if (NameKind == DeclarationName::CXXOperatorName || |
| 439 | NameKind == DeclarationName::CXXLiteralOperatorName || |
| 440 | NameKind == DeclarationName::CXXConversionFunctionName) |
| 441 | return true; |
| 442 | return false; |
| 443 | } |
| 444 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 445 | // The CompletionRecorder captures Sema code-complete output, including context. |
| 446 | // It filters out ignored results (but doesn't apply fuzzy-filtering yet). |
| 447 | // It doesn't do scoring or conversion to CompletionItem yet, as we want to |
| 448 | // merge with index results first. |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 449 | // Generally the fields and methods of this object should only be used from |
| 450 | // within the callback. |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 451 | struct CompletionRecorder : public CodeCompleteConsumer { |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 452 | CompletionRecorder(const CodeCompleteOptions &Opts, |
| 453 | UniqueFunction<void()> ResultsCallback) |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 454 | : CodeCompleteConsumer(Opts.getClangCompleteOpts(), |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 455 | /*OutputIsBinary=*/false), |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 456 | CCContext(CodeCompletionContext::CCC_Other), Opts(Opts), |
| 457 | CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()), |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 458 | CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) { |
| 459 | assert(this->ResultsCallback); |
| 460 | } |
| 461 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 462 | std::vector<CodeCompletionResult> Results; |
| 463 | CodeCompletionContext CCContext; |
| 464 | Sema *CCSema = nullptr; // Sema that created the results. |
| 465 | // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead? |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 466 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 467 | void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context, |
| 468 | CodeCompletionResult *InResults, |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 469 | unsigned NumResults) override final { |
Eric Liu | 42abe41 | 2018-05-24 11:20:19 +0000 | [diff] [blame] | 470 | // If a callback is called without any sema result and the context does not |
| 471 | // support index-based completion, we simply skip it to give way to |
| 472 | // potential future callbacks with results. |
| 473 | if (NumResults == 0 && !contextAllowsIndex(Context.getKind())) |
| 474 | return; |
Ilya Biryukov | 94da7bd | 2018-03-16 15:23:44 +0000 | [diff] [blame] | 475 | if (CCSema) { |
| 476 | log(llvm::formatv( |
| 477 | "Multiple code complete callbacks (parser backtracked?). " |
| 478 | "Dropping results from context {0}, keeping results from {1}.", |
Eric Liu | 42abe41 | 2018-05-24 11:20:19 +0000 | [diff] [blame] | 479 | getCompletionKindString(Context.getKind()), |
| 480 | getCompletionKindString(this->CCContext.getKind()))); |
Ilya Biryukov | 94da7bd | 2018-03-16 15:23:44 +0000 | [diff] [blame] | 481 | return; |
| 482 | } |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 483 | // Record the completion context. |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 484 | CCSema = &S; |
| 485 | CCContext = Context; |
Eric Liu | 6f648df | 2017-12-19 16:50:37 +0000 | [diff] [blame] | 486 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 487 | // Retain the results we might want. |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 488 | for (unsigned I = 0; I < NumResults; ++I) { |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 489 | auto &Result = InResults[I]; |
| 490 | // Drop hidden items which cannot be found by lookup after completion. |
| 491 | // Exception: some items can be named by using a qualifier. |
Ilya Biryukov | f60bf34 | 2018-01-10 13:51:09 +0000 | [diff] [blame] | 492 | if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative)) |
| 493 | continue; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 494 | if (!Opts.IncludeIneligibleResults && |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 495 | (Result.Availability == CXAvailability_NotAvailable || |
| 496 | Result.Availability == CXAvailability_NotAccessible)) |
| 497 | continue; |
Sam McCall | 4caa851 | 2018-06-07 12:49:17 +0000 | [diff] [blame] | 498 | if (Result.Declaration && |
| 499 | !Context.getBaseType().isNull() // is this a member-access context? |
| 500 | && isBlacklistedMember(*Result.Declaration)) |
Sam McCall | d2a9592 | 2018-01-22 21:05:00 +0000 | [diff] [blame] | 501 | continue; |
Ilya Biryukov | 53d6d93 | 2018-03-06 16:45:21 +0000 | [diff] [blame] | 502 | // We choose to never append '::' to completion results in clangd. |
| 503 | Result.StartsNestedNameSpecifier = false; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 504 | Results.push_back(Result); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 505 | } |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 506 | ResultsCallback(); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 507 | } |
| 508 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 509 | CodeCompletionAllocator &getAllocator() override { return *CCAllocator; } |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 510 | CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } |
| 511 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 512 | // Returns the filtering/sorting name for Result, which must be from Results. |
| 513 | // Returned string is owned by this recorder (or the AST). |
| 514 | llvm::StringRef getName(const CodeCompletionResult &Result) { |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 515 | switch (Result.Kind) { |
| 516 | case CodeCompletionResult::RK_Declaration: |
| 517 | if (auto *ID = Result.Declaration->getIdentifier()) |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 518 | return ID->getName(); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 519 | break; |
| 520 | case CodeCompletionResult::RK_Keyword: |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 521 | return Result.Keyword; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 522 | case CodeCompletionResult::RK_Macro: |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 523 | return Result.Macro->getName(); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 524 | case CodeCompletionResult::RK_Pattern: |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 525 | return Result.Pattern->getTypedText(); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 526 | } |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 527 | auto *CCS = codeCompletionString(Result); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 528 | return CCS->getTypedText(); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 529 | } |
| 530 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 531 | // Build a CodeCompletion string for R, which must be from Results. |
| 532 | // The CCS will be owned by this recorder. |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 533 | CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) { |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 534 | // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway. |
| 535 | return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString( |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 536 | *CCSema, CCContext, *CCAllocator, CCTUInfo, |
| 537 | /*IncludeBriefComments=*/false); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 538 | } |
| 539 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 540 | private: |
| 541 | CodeCompleteOptions Opts; |
| 542 | std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 543 | CodeCompletionTUInfo CCTUInfo; |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 544 | UniqueFunction<void()> ResultsCallback; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 545 | }; |
| 546 | |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 547 | struct ScoredCandidateGreater { |
| 548 | bool operator()(const ScoredCandidate &L, const ScoredCandidate &R) { |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 549 | if (L.second.finalScore != R.second.finalScore) |
| 550 | return L.second.finalScore > R.second.finalScore; |
| 551 | return L.first.Name < R.first.Name; // Earlier name is better. |
| 552 | } |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 553 | }; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 554 | |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 555 | class SignatureHelpCollector final : public CodeCompleteConsumer { |
| 556 | |
| 557 | public: |
| 558 | SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts, |
| 559 | SignatureHelp &SigHelp) |
| 560 | : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false), |
| 561 | SigHelp(SigHelp), |
| 562 | Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()), |
| 563 | CCTUInfo(Allocator) {} |
| 564 | |
| 565 | void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, |
| 566 | OverloadCandidate *Candidates, |
| 567 | unsigned NumCandidates) override { |
| 568 | SigHelp.signatures.reserve(NumCandidates); |
| 569 | // FIXME(rwols): How can we determine the "active overload candidate"? |
| 570 | // Right now the overloaded candidates seem to be provided in a "best fit" |
| 571 | // order, so I'm not too worried about this. |
| 572 | SigHelp.activeSignature = 0; |
| 573 | assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() && |
| 574 | "too many arguments"); |
| 575 | SigHelp.activeParameter = static_cast<int>(CurrentArg); |
| 576 | for (unsigned I = 0; I < NumCandidates; ++I) { |
| 577 | const auto &Candidate = Candidates[I]; |
| 578 | const auto *CCS = Candidate.CreateSignatureString( |
| 579 | CurrentArg, S, *Allocator, CCTUInfo, true); |
| 580 | assert(CCS && "Expected the CodeCompletionString to be non-null"); |
Ilya Biryukov | be0eb8f | 2018-05-24 14:49:23 +0000 | [diff] [blame] | 581 | // FIXME: for headers, we need to get a comment from the index. |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 582 | SigHelp.signatures.push_back(ProcessOverloadCandidate( |
| 583 | Candidate, *CCS, |
Ilya Biryukov | be0eb8f | 2018-05-24 14:49:23 +0000 | [diff] [blame] | 584 | getParameterDocComment(S.getASTContext(), Candidate, CurrentArg, |
Kirill Bobyrev | 5a267ed | 2018-05-29 11:50:51 +0000 | [diff] [blame] | 585 | /*CommentsFromHeaders=*/false))); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 586 | } |
| 587 | } |
| 588 | |
| 589 | GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; } |
| 590 | |
| 591 | CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } |
| 592 | |
| 593 | private: |
Eric Liu | 63696e1 | 2017-12-20 17:24:31 +0000 | [diff] [blame] | 594 | // FIXME(ioeric): consider moving CodeCompletionString logic here to |
| 595 | // CompletionString.h. |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 596 | SignatureInformation |
| 597 | ProcessOverloadCandidate(const OverloadCandidate &Candidate, |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 598 | const CodeCompletionString &CCS, |
| 599 | llvm::StringRef DocComment) const { |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 600 | SignatureInformation Result; |
| 601 | const char *ReturnType = nullptr; |
| 602 | |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 603 | Result.documentation = formatDocumentation(CCS, DocComment); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 604 | |
| 605 | for (const auto &Chunk : CCS) { |
| 606 | switch (Chunk.Kind) { |
| 607 | case CodeCompletionString::CK_ResultType: |
| 608 | // A piece of text that describes the type of an entity or, |
| 609 | // for functions and methods, the return type. |
| 610 | assert(!ReturnType && "Unexpected CK_ResultType"); |
| 611 | ReturnType = Chunk.Text; |
| 612 | break; |
| 613 | case CodeCompletionString::CK_Placeholder: |
| 614 | // A string that acts as a placeholder for, e.g., a function call |
| 615 | // argument. |
| 616 | // Intentional fallthrough here. |
| 617 | case CodeCompletionString::CK_CurrentParameter: { |
| 618 | // A piece of text that describes the parameter that corresponds to |
| 619 | // the code-completion location within a function call, message send, |
| 620 | // macro invocation, etc. |
| 621 | Result.label += Chunk.Text; |
| 622 | ParameterInformation Info; |
| 623 | Info.label = Chunk.Text; |
| 624 | Result.parameters.push_back(std::move(Info)); |
| 625 | break; |
| 626 | } |
| 627 | case CodeCompletionString::CK_Optional: { |
| 628 | // The rest of the parameters are defaulted/optional. |
| 629 | assert(Chunk.Optional && |
| 630 | "Expected the optional code completion string to be non-null."); |
| 631 | Result.label += |
| 632 | getOptionalParameters(*Chunk.Optional, Result.parameters); |
| 633 | break; |
| 634 | } |
| 635 | case CodeCompletionString::CK_VerticalSpace: |
| 636 | break; |
| 637 | default: |
| 638 | Result.label += Chunk.Text; |
| 639 | break; |
| 640 | } |
| 641 | } |
| 642 | if (ReturnType) { |
| 643 | Result.label += " -> "; |
| 644 | Result.label += ReturnType; |
| 645 | } |
| 646 | return Result; |
| 647 | } |
| 648 | |
| 649 | SignatureHelp &SigHelp; |
| 650 | std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator; |
| 651 | CodeCompletionTUInfo CCTUInfo; |
| 652 | |
| 653 | }; // SignatureHelpCollector |
| 654 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 655 | struct SemaCompleteInput { |
| 656 | PathRef FileName; |
| 657 | const tooling::CompileCommand &Command; |
| 658 | PrecompiledPreamble const *Preamble; |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 659 | const std::vector<Inclusion> &PreambleInclusions; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 660 | StringRef Contents; |
| 661 | Position Pos; |
| 662 | IntrusiveRefCntPtr<vfs::FileSystem> VFS; |
| 663 | std::shared_ptr<PCHContainerOperations> PCHs; |
| 664 | }; |
| 665 | |
| 666 | // Invokes Sema code completion on a file. |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 667 | // If \p Includes is set, it will be initialized after a compiler instance has |
| 668 | // been set up. |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 669 | bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer, |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 670 | const clang::CodeCompleteOptions &Options, |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 671 | const SemaCompleteInput &Input, |
| 672 | std::unique_ptr<IncludeInserter> *Includes = nullptr) { |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 673 | trace::Span Tracer("Sema completion"); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 674 | std::vector<const char *> ArgStrs; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 675 | for (const auto &S : Input.Command.CommandLine) |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 676 | ArgStrs.push_back(S.c_str()); |
| 677 | |
Ilya Biryukov | a9cf311 | 2018-02-13 17:15:06 +0000 | [diff] [blame] | 678 | if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) { |
| 679 | log("Couldn't set working directory"); |
| 680 | // We run parsing anyway, our lit-tests rely on results for non-existing |
| 681 | // working dirs. |
| 682 | } |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 683 | |
| 684 | IgnoreDiagnostics DummyDiagsConsumer; |
| 685 | auto CI = createInvocationFromCommandLine( |
| 686 | ArgStrs, |
| 687 | CompilerInstance::createDiagnostics(new DiagnosticOptions, |
| 688 | &DummyDiagsConsumer, false), |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 689 | Input.VFS); |
Ilya Biryukov | b6ad25c | 2018-02-09 13:51:57 +0000 | [diff] [blame] | 690 | if (!CI) { |
Kirill Bobyrev | 5a267ed | 2018-05-29 11:50:51 +0000 | [diff] [blame] | 691 | log("Couldn't create CompilerInvocation"); |
Ilya Biryukov | b6ad25c | 2018-02-09 13:51:57 +0000 | [diff] [blame] | 692 | return false; |
| 693 | } |
Ilya Biryukov | 981a35d | 2018-05-28 12:11:37 +0000 | [diff] [blame] | 694 | auto &FrontendOpts = CI->getFrontendOpts(); |
| 695 | FrontendOpts.DisableFree = false; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 696 | FrontendOpts.SkipFunctionBodies = true; |
Ilya Biryukov | 981a35d | 2018-05-28 12:11:37 +0000 | [diff] [blame] | 697 | CI->getLangOpts()->CommentOpts.ParseAllComments = true; |
| 698 | // Disable typo correction in Sema. |
| 699 | CI->getLangOpts()->SpellChecking = false; |
| 700 | // Setup code completion. |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 701 | FrontendOpts.CodeCompleteOpts = Options; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 702 | FrontendOpts.CodeCompletionAt.FileName = Input.FileName; |
Sam McCall | a4962cc | 2018-04-27 11:59:28 +0000 | [diff] [blame] | 703 | auto Offset = positionToOffset(Input.Contents, Input.Pos); |
| 704 | if (!Offset) { |
| 705 | log("Code completion position was invalid " + |
| 706 | llvm::toString(Offset.takeError())); |
| 707 | return false; |
| 708 | } |
| 709 | std::tie(FrontendOpts.CodeCompletionAt.Line, |
| 710 | FrontendOpts.CodeCompletionAt.Column) = |
| 711 | offsetToClangLineColumn(Input.Contents, *Offset); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 712 | |
Ilya Biryukov | 981a35d | 2018-05-28 12:11:37 +0000 | [diff] [blame] | 713 | std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer = |
| 714 | llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName); |
| 715 | // The diagnostic options must be set before creating a CompilerInstance. |
| 716 | CI->getDiagnosticOpts().IgnoreWarnings = true; |
| 717 | // We reuse the preamble whether it's valid or not. This is a |
| 718 | // correctness/performance tradeoff: building without a preamble is slow, and |
| 719 | // completion is latency-sensitive. |
| 720 | // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise |
| 721 | // the remapped buffers do not get freed. |
| 722 | auto Clang = prepareCompilerInstance( |
| 723 | std::move(CI), Input.Preamble, std::move(ContentsBuffer), |
| 724 | std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 725 | Clang->setCodeCompletionConsumer(Consumer.release()); |
| 726 | |
| 727 | SyntaxOnlyAction Action; |
| 728 | if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) { |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 729 | log("BeginSourceFile() failed when running codeComplete for " + |
| 730 | Input.FileName); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 731 | return false; |
| 732 | } |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 733 | if (Includes) { |
| 734 | // Initialize Includes if provided. |
| 735 | |
| 736 | // FIXME(ioeric): needs more consistent style support in clangd server. |
| 737 | auto Style = format::getStyle("file", Input.FileName, "LLVM", |
| 738 | Input.Contents, Input.VFS.get()); |
| 739 | if (!Style) { |
| 740 | log("Failed to get FormatStyle for file" + Input.FileName + |
| 741 | ". Fall back to use LLVM style. Error: " + |
| 742 | llvm::toString(Style.takeError())); |
| 743 | Style = format::getLLVMStyle(); |
| 744 | } |
| 745 | *Includes = llvm::make_unique<IncludeInserter>( |
| 746 | Input.FileName, Input.Contents, *Style, Input.Command.Directory, |
| 747 | Clang->getPreprocessor().getHeaderSearchInfo()); |
| 748 | for (const auto &Inc : Input.PreambleInclusions) |
| 749 | Includes->get()->addExisting(Inc); |
| 750 | Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback( |
| 751 | Clang->getSourceManager(), [Includes](Inclusion Inc) { |
| 752 | Includes->get()->addExisting(std::move(Inc)); |
| 753 | })); |
| 754 | } |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 755 | if (!Action.Execute()) { |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 756 | log("Execute() failed when running codeComplete for " + Input.FileName); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 757 | return false; |
| 758 | } |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 759 | Action.EndSourceFile(); |
| 760 | |
| 761 | return true; |
| 762 | } |
| 763 | |
Ilya Biryukov | a907ba4 | 2018-05-14 10:50:04 +0000 | [diff] [blame] | 764 | // Should we allow index completions in the specified context? |
| 765 | bool allowIndex(CodeCompletionContext &CC) { |
| 766 | if (!contextAllowsIndex(CC.getKind())) |
| 767 | return false; |
| 768 | // We also avoid ClassName::bar (but allow namespace::bar). |
| 769 | auto Scope = CC.getCXXScopeSpecifier(); |
| 770 | if (!Scope) |
| 771 | return true; |
| 772 | NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep(); |
| 773 | if (!NameSpec) |
| 774 | return true; |
| 775 | // We only query the index when qualifier is a namespace. |
| 776 | // If it's a class, we rely solely on sema completions. |
| 777 | switch (NameSpec->getKind()) { |
| 778 | case NestedNameSpecifier::Global: |
| 779 | case NestedNameSpecifier::Namespace: |
| 780 | case NestedNameSpecifier::NamespaceAlias: |
| 781 | return true; |
| 782 | case NestedNameSpecifier::Super: |
| 783 | case NestedNameSpecifier::TypeSpec: |
| 784 | case NestedNameSpecifier::TypeSpecWithTemplate: |
| 785 | // Unresolved inside a template. |
| 786 | case NestedNameSpecifier::Identifier: |
| 787 | return false; |
| 788 | } |
Ilya Biryukov | a6556e2 | 2018-05-14 11:47:30 +0000 | [diff] [blame] | 789 | llvm_unreachable("invalid NestedNameSpecifier kind"); |
Ilya Biryukov | a907ba4 | 2018-05-14 10:50:04 +0000 | [diff] [blame] | 790 | } |
| 791 | |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 792 | } // namespace |
| 793 | |
| 794 | clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const { |
| 795 | clang::CodeCompleteOptions Result; |
| 796 | Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns; |
| 797 | Result.IncludeMacros = IncludeMacros; |
Sam McCall | d8169a8 | 2018-01-18 15:31:30 +0000 | [diff] [blame] | 798 | Result.IncludeGlobals = true; |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 799 | // We choose to include full comments and not do doxygen parsing in |
| 800 | // completion. |
| 801 | // FIXME: ideally, we should support doxygen in some form, e.g. do markdown |
| 802 | // formatting of the comments. |
| 803 | Result.IncludeBriefComments = false; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 804 | |
Sam McCall | 3d139c5 | 2018-01-12 18:30:08 +0000 | [diff] [blame] | 805 | // When an is used, Sema is responsible for completing the main file, |
| 806 | // the index can provide results from the preamble. |
| 807 | // Tell Sema not to deserialize the preamble to look for results. |
| 808 | Result.LoadExternal = !Index; |
Eric Liu | 6f648df | 2017-12-19 16:50:37 +0000 | [diff] [blame] | 809 | |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 810 | return Result; |
| 811 | } |
| 812 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 813 | // Runs Sema-based (AST) and Index-based completion, returns merged results. |
| 814 | // |
| 815 | // There are a few tricky considerations: |
| 816 | // - the AST provides information needed for the index query (e.g. which |
| 817 | // namespaces to search in). So Sema must start first. |
| 818 | // - we only want to return the top results (Opts.Limit). |
| 819 | // Building CompletionItems for everything else is wasteful, so we want to |
| 820 | // preserve the "native" format until we're done with scoring. |
| 821 | // - the data underlying Sema completion items is owned by the AST and various |
| 822 | // other arenas, which must stay alive for us to build CompletionItems. |
| 823 | // - we may get duplicate results from Sema and the Index, we need to merge. |
| 824 | // |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 825 | // So we start Sema completion first, and do all our work in its callback. |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 826 | // We use the Sema context information to query the index. |
| 827 | // Then we merge the two result sets, producing items that are Sema/Index/Both. |
| 828 | // These items are scored, and the top N are synthesized into the LSP response. |
| 829 | // Finally, we can clean up the data structures created by Sema completion. |
| 830 | // |
| 831 | // Main collaborators are: |
| 832 | // - semaCodeComplete sets up the compiler machinery to run code completion. |
| 833 | // - CompletionRecorder captures Sema completion results, including context. |
| 834 | // - SymbolIndex (Opts.Index) provides index completion results as Symbols |
| 835 | // - CompletionCandidates are the result of merging Sema and Index results. |
| 836 | // Each candidate points to an underlying CodeCompletionResult (Sema), a |
| 837 | // Symbol (Index), or both. It computes the result quality score. |
| 838 | // CompletionCandidate also does conversion to CompletionItem (at the end). |
| 839 | // - FuzzyMatcher scores how the candidate matches the partial identifier. |
| 840 | // This score is combined with the result quality score for the final score. |
| 841 | // - TopN determines the results with the best score. |
| 842 | class CodeCompleteFlow { |
Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 843 | PathRef FileName; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 844 | const CodeCompleteOptions &Opts; |
| 845 | // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup. |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 846 | CompletionRecorder *Recorder = nullptr; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 847 | int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging. |
| 848 | bool Incomplete = false; // Would more be available with a higher limit? |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 849 | llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs. |
| 850 | std::unique_ptr<IncludeInserter> Includes; // Initialized once compiler runs. |
Eric Liu | 09c3c37 | 2018-06-15 08:58:12 +0000 | [diff] [blame] | 851 | FileProximityMatcher FileProximityMatch; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 852 | |
| 853 | public: |
| 854 | // A CodeCompleteFlow object is only useful for calling run() exactly once. |
Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 855 | CodeCompleteFlow(PathRef FileName, const CodeCompleteOptions &Opts) |
Eric Liu | 09c3c37 | 2018-06-15 08:58:12 +0000 | [diff] [blame] | 856 | : FileName(FileName), Opts(Opts), |
| 857 | // FIXME: also use path of the main header corresponding to FileName to |
| 858 | // calculate the file proximity, which would capture include/ and src/ |
| 859 | // project setup where headers and implementations are not in the same |
| 860 | // directory. |
Haojian Wu | 7943d4f | 2018-06-15 09:32:36 +0000 | [diff] [blame^] | 861 | FileProximityMatch(ArrayRef<StringRef>({FileName})) {} |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 862 | |
| 863 | CompletionList run(const SemaCompleteInput &SemaCCInput) && { |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 864 | trace::Span Tracer("CodeCompleteFlow"); |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 865 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 866 | // We run Sema code completion first. It builds an AST and calculates: |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 867 | // - completion results based on the AST. |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 868 | // - partial identifier and context. We need these for the index query. |
| 869 | CompletionList Output; |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 870 | auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() { |
| 871 | assert(Recorder && "Recorder is not set"); |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 872 | assert(Includes && "Includes is not set"); |
| 873 | // If preprocessor was run, inclusions from preprocessor callback should |
| 874 | // already be added to Inclusions. |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 875 | Output = runWithSema(); |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 876 | Includes.reset(); // Make sure this doesn't out-live Clang. |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 877 | SPAN_ATTACH(Tracer, "sema_completion_kind", |
| 878 | getCompletionKindString(Recorder->CCContext.getKind())); |
| 879 | }); |
| 880 | |
| 881 | Recorder = RecorderOwner.get(); |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 882 | semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(), |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 883 | SemaCCInput, &Includes); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 884 | |
Sam McCall | 2b78016 | 2018-01-30 17:20:54 +0000 | [diff] [blame] | 885 | SPAN_ATTACH(Tracer, "sema_results", NSema); |
| 886 | SPAN_ATTACH(Tracer, "index_results", NIndex); |
| 887 | SPAN_ATTACH(Tracer, "merged_results", NBoth); |
| 888 | SPAN_ATTACH(Tracer, "returned_results", Output.items.size()); |
| 889 | SPAN_ATTACH(Tracer, "incomplete", Output.isIncomplete); |
Sam McCall | 0f8df3e | 2018-06-13 11:31:20 +0000 | [diff] [blame] | 890 | log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, " |
| 891 | "{2} matched, {3} returned{4}.", |
| 892 | NSema, NIndex, NBoth, Output.items.size(), |
| 893 | Output.isIncomplete ? " (incomplete)" : "")); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 894 | assert(!Opts.Limit || Output.items.size() <= Opts.Limit); |
| 895 | // We don't assert that isIncomplete means we hit a limit. |
| 896 | // Indexes may choose to impose their own limits even if we don't have one. |
| 897 | return Output; |
| 898 | } |
| 899 | |
| 900 | private: |
| 901 | // This is called by run() once Sema code completion is done, but before the |
| 902 | // Sema data structures are torn down. It does all the real work. |
| 903 | CompletionList runWithSema() { |
| 904 | Filter = FuzzyMatcher( |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 905 | Recorder->CCSema->getPreprocessor().getCodeCompletionFilter()); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 906 | // Sema provides the needed context to query the index. |
| 907 | // FIXME: in addition to querying for extra/overlapping symbols, we should |
| 908 | // explicitly request symbols corresponding to Sema results. |
| 909 | // We can use their signals even if the index can't suggest them. |
| 910 | // We must copy index results to preserve them, but there are at most Limit. |
| 911 | auto IndexResults = queryIndex(); |
| 912 | // Merge Sema and Index results, score them, and pick the winners. |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 913 | auto Top = mergeResults(Recorder->Results, IndexResults); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 914 | // Convert the results to the desired LSP structs. |
| 915 | CompletionList Output; |
| 916 | for (auto &C : Top) |
| 917 | Output.items.push_back(toCompletionItem(C.first, C.second)); |
| 918 | Output.isIncomplete = Incomplete; |
| 919 | return Output; |
| 920 | } |
| 921 | |
| 922 | SymbolSlab queryIndex() { |
Ilya Biryukov | a907ba4 | 2018-05-14 10:50:04 +0000 | [diff] [blame] | 923 | if (!Opts.Index || !allowIndex(Recorder->CCContext)) |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 924 | return SymbolSlab(); |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 925 | trace::Span Tracer("Query index"); |
Sam McCall | 2b78016 | 2018-01-30 17:20:54 +0000 | [diff] [blame] | 926 | SPAN_ATTACH(Tracer, "limit", Opts.Limit); |
| 927 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 928 | SymbolSlab::Builder ResultsBuilder; |
| 929 | // Build the query. |
| 930 | FuzzyFindRequest Req; |
Haojian Wu | 48b4865 | 2018-01-25 09:20:09 +0000 | [diff] [blame] | 931 | if (Opts.Limit) |
| 932 | Req.MaxCandidateCount = Opts.Limit; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 933 | Req.Query = Filter->pattern(); |
Marc-Andre Laperle | 945b5a3 | 2018-06-05 14:01:40 +0000 | [diff] [blame] | 934 | Req.RestrictForCodeCompletion = true; |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 935 | Req.Scopes = getQueryScopes(Recorder->CCContext, |
| 936 | Recorder->CCSema->getSourceManager()); |
Eric Liu | 6de95ec | 2018-06-12 08:48:20 +0000 | [diff] [blame] | 937 | Req.ProximityPaths.push_back(FileName); |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 938 | log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])", |
Sam McCall | 2b78016 | 2018-01-30 17:20:54 +0000 | [diff] [blame] | 939 | Req.Query, |
| 940 | llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ","))); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 941 | // Run the query against the index. |
Sam McCall | ab8e393 | 2018-02-19 13:04:41 +0000 | [diff] [blame] | 942 | if (Opts.Index->fuzzyFind( |
| 943 | Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); })) |
| 944 | Incomplete = true; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 945 | return std::move(ResultsBuilder).build(); |
| 946 | } |
| 947 | |
| 948 | // Merges the Sema and Index results where possible, scores them, and |
| 949 | // returns the top results from best to worst. |
| 950 | std::vector<std::pair<CompletionCandidate, CompletionItemScores>> |
| 951 | mergeResults(const std::vector<CodeCompletionResult> &SemaResults, |
| 952 | const SymbolSlab &IndexResults) { |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 953 | trace::Span Tracer("Merge and score results"); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 954 | // We only keep the best N results at any time, in "native" format. |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 955 | TopN<ScoredCandidate, ScoredCandidateGreater> Top( |
| 956 | Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 957 | llvm::DenseSet<const Symbol *> UsedIndexResults; |
| 958 | auto CorrespondingIndexResult = |
| 959 | [&](const CodeCompletionResult &SemaResult) -> const Symbol * { |
| 960 | if (auto SymID = getSymbolID(SemaResult)) { |
| 961 | auto I = IndexResults.find(*SymID); |
| 962 | if (I != IndexResults.end()) { |
| 963 | UsedIndexResults.insert(&*I); |
| 964 | return &*I; |
| 965 | } |
| 966 | } |
| 967 | return nullptr; |
| 968 | }; |
| 969 | // Emit all Sema results, merging them with Index results if possible. |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 970 | for (auto &SemaResult : Recorder->Results) |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 971 | addCandidate(Top, &SemaResult, CorrespondingIndexResult(SemaResult)); |
| 972 | // Now emit any Index-only results. |
| 973 | for (const auto &IndexResult : IndexResults) { |
| 974 | if (UsedIndexResults.count(&IndexResult)) |
| 975 | continue; |
| 976 | addCandidate(Top, /*SemaResult=*/nullptr, &IndexResult); |
| 977 | } |
| 978 | return std::move(Top).items(); |
| 979 | } |
| 980 | |
Sam McCall | 80ad707 | 2018-06-08 13:32:25 +0000 | [diff] [blame] | 981 | Optional<float> fuzzyScore(const CompletionCandidate &C) { |
| 982 | // Macros can be very spammy, so we only support prefix completion. |
| 983 | // We won't end up with underfull index results, as macros are sema-only. |
| 984 | if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro && |
| 985 | !C.Name.startswith_lower(Filter->pattern())) |
| 986 | return None; |
| 987 | return Filter->match(C.Name); |
| 988 | } |
| 989 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 990 | // Scores a candidate and adds it to the TopN structure. |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 991 | void addCandidate(TopN<ScoredCandidate, ScoredCandidateGreater> &Candidates, |
| 992 | const CodeCompletionResult *SemaResult, |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 993 | const Symbol *IndexResult) { |
| 994 | CompletionCandidate C; |
| 995 | C.SemaResult = SemaResult; |
| 996 | C.IndexResult = IndexResult; |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 997 | C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 998 | |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 999 | SymbolQualitySignals Quality; |
| 1000 | SymbolRelevanceSignals Relevance; |
Sam McCall | d9b54f0 | 2018-06-05 16:30:25 +0000 | [diff] [blame] | 1001 | Relevance.Query = SymbolRelevanceSignals::CodeComplete; |
Eric Liu | 09c3c37 | 2018-06-15 08:58:12 +0000 | [diff] [blame] | 1002 | Relevance.FileProximityMatch = &FileProximityMatch; |
Sam McCall | 80ad707 | 2018-06-08 13:32:25 +0000 | [diff] [blame] | 1003 | if (auto FuzzyScore = fuzzyScore(C)) |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 1004 | Relevance.NameMatch = *FuzzyScore; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1005 | else |
| 1006 | return; |
Sam McCall | d9b54f0 | 2018-06-05 16:30:25 +0000 | [diff] [blame] | 1007 | if (IndexResult) { |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 1008 | Quality.merge(*IndexResult); |
Sam McCall | d9b54f0 | 2018-06-05 16:30:25 +0000 | [diff] [blame] | 1009 | Relevance.merge(*IndexResult); |
| 1010 | } |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 1011 | if (SemaResult) { |
| 1012 | Quality.merge(*SemaResult); |
| 1013 | Relevance.merge(*SemaResult); |
| 1014 | } |
| 1015 | |
| 1016 | float QualScore = Quality.evaluate(), RelScore = Relevance.evaluate(); |
| 1017 | CompletionItemScores Scores; |
| 1018 | Scores.finalScore = evaluateSymbolAndRelevance(QualScore, RelScore); |
| 1019 | // The purpose of exporting component scores is to allow NameMatch to be |
| 1020 | // replaced on the client-side. So we export (NameMatch, final/NameMatch) |
| 1021 | // rather than (RelScore, QualScore). |
| 1022 | Scores.filterScore = Relevance.NameMatch; |
| 1023 | Scores.symbolScore = |
| 1024 | Scores.filterScore ? Scores.finalScore / Scores.filterScore : QualScore; |
| 1025 | |
Nicola Zaghen | c9fed13 | 2018-05-23 13:57:48 +0000 | [diff] [blame] | 1026 | LLVM_DEBUG(llvm::dbgs() |
| 1027 | << "CodeComplete: " << C.Name << (IndexResult ? " (index)" : "") |
| 1028 | << (SemaResult ? " (sema)" : "") << " = " << Scores.finalScore |
Kirill Bobyrev | 5a267ed | 2018-05-29 11:50:51 +0000 | [diff] [blame] | 1029 | << "\n" |
Nicola Zaghen | c9fed13 | 2018-05-23 13:57:48 +0000 | [diff] [blame] | 1030 | << Quality << Relevance << "\n"); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1031 | |
| 1032 | NSema += bool(SemaResult); |
| 1033 | NIndex += bool(IndexResult); |
| 1034 | NBoth += SemaResult && IndexResult; |
Sam McCall | ab8e393 | 2018-02-19 13:04:41 +0000 | [diff] [blame] | 1035 | if (Candidates.push({C, Scores})) |
| 1036 | Incomplete = true; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1037 | } |
| 1038 | |
| 1039 | CompletionItem toCompletionItem(const CompletionCandidate &Candidate, |
| 1040 | const CompletionItemScores &Scores) { |
| 1041 | CodeCompletionString *SemaCCS = nullptr; |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 1042 | std::string DocComment; |
| 1043 | if (auto *SR = Candidate.SemaResult) { |
| 1044 | SemaCCS = Recorder->codeCompletionString(*SR); |
| 1045 | if (Opts.IncludeComments) { |
| 1046 | assert(Recorder->CCSema); |
Ilya Biryukov | be0eb8f | 2018-05-24 14:49:23 +0000 | [diff] [blame] | 1047 | DocComment = getDocComment(Recorder->CCSema->getASTContext(), *SR, |
| 1048 | /*CommentsFromHeader=*/false); |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 1049 | } |
| 1050 | } |
Kirill Bobyrev | 5a267ed | 2018-05-29 11:50:51 +0000 | [diff] [blame] | 1051 | return Candidate.build(FileName, Scores, Opts, SemaCCS, Includes.get(), |
| 1052 | DocComment); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1053 | } |
| 1054 | }; |
| 1055 | |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 1056 | CompletionList codeComplete(PathRef FileName, |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1057 | const tooling::CompileCommand &Command, |
| 1058 | PrecompiledPreamble const *Preamble, |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 1059 | const std::vector<Inclusion> &PreambleInclusions, |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1060 | StringRef Contents, Position Pos, |
| 1061 | IntrusiveRefCntPtr<vfs::FileSystem> VFS, |
| 1062 | std::shared_ptr<PCHContainerOperations> PCHs, |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 1063 | CodeCompleteOptions Opts) { |
Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 1064 | return CodeCompleteFlow(FileName, Opts) |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 1065 | .run({FileName, Command, Preamble, PreambleInclusions, Contents, Pos, VFS, |
| 1066 | PCHs}); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1067 | } |
| 1068 | |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 1069 | SignatureHelp signatureHelp(PathRef FileName, |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 1070 | const tooling::CompileCommand &Command, |
| 1071 | PrecompiledPreamble const *Preamble, |
| 1072 | StringRef Contents, Position Pos, |
| 1073 | IntrusiveRefCntPtr<vfs::FileSystem> VFS, |
| 1074 | std::shared_ptr<PCHContainerOperations> PCHs) { |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1075 | SignatureHelp Result; |
| 1076 | clang::CodeCompleteOptions Options; |
| 1077 | Options.IncludeGlobals = false; |
| 1078 | Options.IncludeMacros = false; |
| 1079 | Options.IncludeCodePatterns = false; |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 1080 | Options.IncludeBriefComments = false; |
Eric Liu | 4c0a27b | 2018-05-16 20:31:38 +0000 | [diff] [blame] | 1081 | std::vector<Inclusion> PreambleInclusions = {}; // Unused for signatureHelp |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 1082 | semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result), |
| 1083 | Options, |
Eric Liu | 4c0a27b | 2018-05-16 20:31:38 +0000 | [diff] [blame] | 1084 | {FileName, Command, Preamble, PreambleInclusions, Contents, |
| 1085 | Pos, std::move(VFS), std::move(PCHs)}); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1086 | return Result; |
| 1087 | } |
| 1088 | |
Marc-Andre Laperle | 945b5a3 | 2018-06-05 14:01:40 +0000 | [diff] [blame] | 1089 | bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) { |
| 1090 | using namespace clang::ast_matchers; |
| 1091 | auto InTopLevelScope = hasDeclContext( |
| 1092 | anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl())); |
| 1093 | return !match(decl(anyOf(InTopLevelScope, |
| 1094 | hasDeclContext( |
| 1095 | enumDecl(InTopLevelScope, unless(isScoped()))))), |
| 1096 | ND, ASTCtx) |
| 1097 | .empty(); |
| 1098 | } |
| 1099 | |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1100 | } // namespace clangd |
| 1101 | } // namespace clang |