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