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