Kirill Bobyrev | 8e35f1e | 2018-08-14 16:03:32 +0000 | [diff] [blame] | 1 | //===--- CodeComplete.cpp ----------------------------------------*- C++-*-===// |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 6 | // |
Kirill Bobyrev | 8e35f1e | 2018-08-14 16:03:32 +0000 | [diff] [blame] | 7 | //===----------------------------------------------------------------------===// |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 8 | // |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 9 | // Code completion has several moving parts: |
| 10 | // - AST-based completions are provided using the completion hooks in Sema. |
| 11 | // - external completions are retrieved from the index (using hints from Sema) |
| 12 | // - the two sources overlap, and must be merged and overloads bundled |
| 13 | // - results must be scored and ranked (see Quality.h) before rendering |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 14 | // |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 15 | // Signature help works in a similar way as code completion, but it is simpler: |
| 16 | // it's purely AST-based, and there are few candidates. |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 17 | // |
Kirill Bobyrev | 8e35f1e | 2018-08-14 16:03:32 +0000 | [diff] [blame] | 18 | //===----------------------------------------------------------------------===// |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 19 | |
| 20 | #include "CodeComplete.h" |
Eric Liu | 7ad1696 | 2018-06-22 10:46:59 +0000 | [diff] [blame] | 21 | #include "AST.h" |
Eric Liu | b1d7542 | 2018-10-02 10:43:55 +0000 | [diff] [blame] | 22 | #include "ClangdUnit.h" |
Eric Liu | 63696e1 | 2017-12-20 17:24:31 +0000 | [diff] [blame] | 23 | #include "CodeCompletionStrings.h" |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 24 | #include "Compiler.h" |
Kadir Cetinkaya | 2f84d91 | 2018-08-08 08:59:29 +0000 | [diff] [blame] | 25 | #include "Diagnostics.h" |
Ilya Biryukov | 647da3e | 2018-11-26 15:38:01 +0000 | [diff] [blame] | 26 | #include "ExpectedTypes.h" |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 27 | #include "FileDistance.h" |
Sam McCall | 84652cc | 2018-01-12 16:16:09 +0000 | [diff] [blame] | 28 | #include "FuzzyMatch.h" |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 29 | #include "Headers.h" |
Eric Liu | 6f648df | 2017-12-19 16:50:37 +0000 | [diff] [blame] | 30 | #include "Logger.h" |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 31 | #include "Quality.h" |
Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 32 | #include "SourceCode.h" |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 33 | #include "TUScheduler.h" |
Sam McCall | 2b78016 | 2018-01-30 17:20:54 +0000 | [diff] [blame] | 34 | #include "Trace.h" |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 35 | #include "URI.h" |
Eric Liu | 6f648df | 2017-12-19 16:50:37 +0000 | [diff] [blame] | 36 | #include "index/Index.h" |
Eric Liu | 3fac4ef | 2018-10-17 11:19:02 +0000 | [diff] [blame] | 37 | #include "clang/AST/Decl.h" |
| 38 | #include "clang/AST/DeclBase.h" |
Ilya Biryukov | c22d344 | 2018-05-16 12:32:49 +0000 | [diff] [blame] | 39 | #include "clang/Basic/LangOptions.h" |
Kadir Cetinkaya | a9c9d00 | 2018-08-13 08:23:01 +0000 | [diff] [blame] | 40 | #include "clang/Basic/SourceLocation.h" |
Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 41 | #include "clang/Format/Format.h" |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 42 | #include "clang/Frontend/CompilerInstance.h" |
| 43 | #include "clang/Frontend/FrontendActions.h" |
Sam McCall | ebef812 | 2018-09-14 12:36:06 +0000 | [diff] [blame] | 44 | #include "clang/Lex/PreprocessorOptions.h" |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 45 | #include "clang/Sema/CodeCompleteConsumer.h" |
| 46 | #include "clang/Sema/Sema.h" |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 47 | #include "llvm/ADT/ArrayRef.h" |
Eric Liu | 3fac4ef | 2018-10-17 11:19:02 +0000 | [diff] [blame] | 48 | #include "llvm/ADT/None.h" |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 49 | #include "llvm/ADT/Optional.h" |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 50 | #include "llvm/ADT/SmallVector.h" |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 51 | #include "llvm/Support/Error.h" |
Haojian Wu | ba28e9a | 2018-01-10 14:44:34 +0000 | [diff] [blame] | 52 | #include "llvm/Support/Format.h" |
Eric Liu | bc25ef7 | 2018-07-05 08:29:33 +0000 | [diff] [blame] | 53 | #include "llvm/Support/FormatVariadic.h" |
Sam McCall | 2161ec7 | 2018-07-05 06:20:41 +0000 | [diff] [blame] | 54 | #include "llvm/Support/ScopedPrinter.h" |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 55 | #include <algorithm> |
| 56 | #include <iterator> |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 57 | |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 58 | // We log detailed candidate here if you run with -debug-only=codecomplete. |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 59 | #define DEBUG_TYPE "CodeComplete" |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 60 | |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 61 | namespace clang { |
| 62 | namespace clangd { |
| 63 | namespace { |
| 64 | |
Eric Liu | 6f648df | 2017-12-19 16:50:37 +0000 | [diff] [blame] | 65 | CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) { |
| 66 | using SK = index::SymbolKind; |
| 67 | switch (Kind) { |
| 68 | case SK::Unknown: |
| 69 | return CompletionItemKind::Missing; |
| 70 | case SK::Module: |
| 71 | case SK::Namespace: |
| 72 | case SK::NamespaceAlias: |
| 73 | return CompletionItemKind::Module; |
| 74 | case SK::Macro: |
| 75 | return CompletionItemKind::Text; |
| 76 | case SK::Enum: |
| 77 | return CompletionItemKind::Enum; |
| 78 | // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the |
| 79 | // protocol. |
| 80 | case SK::Struct: |
| 81 | case SK::Class: |
| 82 | case SK::Protocol: |
| 83 | case SK::Extension: |
| 84 | case SK::Union: |
| 85 | return CompletionItemKind::Class; |
| 86 | // FIXME(ioeric): figure out whether reference is the right type for aliases. |
| 87 | case SK::TypeAlias: |
| 88 | case SK::Using: |
| 89 | return CompletionItemKind::Reference; |
| 90 | case SK::Function: |
| 91 | // FIXME(ioeric): this should probably be an operator. This should be fixed |
| 92 | // when `Operator` is support type in the protocol. |
| 93 | case SK::ConversionFunction: |
| 94 | return CompletionItemKind::Function; |
| 95 | case SK::Variable: |
| 96 | case SK::Parameter: |
| 97 | return CompletionItemKind::Variable; |
| 98 | case SK::Field: |
| 99 | return CompletionItemKind::Field; |
| 100 | // FIXME(ioeric): use LSP enum constant when it is supported in the protocol. |
| 101 | case SK::EnumConstant: |
| 102 | return CompletionItemKind::Value; |
| 103 | case SK::InstanceMethod: |
| 104 | case SK::ClassMethod: |
| 105 | case SK::StaticMethod: |
| 106 | case SK::Destructor: |
| 107 | return CompletionItemKind::Method; |
| 108 | case SK::InstanceProperty: |
| 109 | case SK::ClassProperty: |
| 110 | case SK::StaticProperty: |
| 111 | return CompletionItemKind::Property; |
| 112 | case SK::Constructor: |
| 113 | return CompletionItemKind::Constructor; |
| 114 | } |
| 115 | llvm_unreachable("Unhandled clang::index::SymbolKind."); |
| 116 | } |
| 117 | |
Sam McCall | 8330589 | 2018-06-08 21:17:19 +0000 | [diff] [blame] | 118 | CompletionItemKind |
| 119 | toCompletionItemKind(CodeCompletionResult::ResultKind ResKind, |
Sam McCall | 4c077f9 | 2018-09-18 09:08:28 +0000 | [diff] [blame] | 120 | const NamedDecl *Decl, |
| 121 | CodeCompletionContext::Kind CtxKind) { |
Sam McCall | 8330589 | 2018-06-08 21:17:19 +0000 | [diff] [blame] | 122 | if (Decl) |
| 123 | return toCompletionItemKind(index::getSymbolInfo(Decl).Kind); |
Sam McCall | 4c077f9 | 2018-09-18 09:08:28 +0000 | [diff] [blame] | 124 | if (CtxKind == CodeCompletionContext::CCC_IncludedFile) |
| 125 | return CompletionItemKind::File; |
Sam McCall | 8330589 | 2018-06-08 21:17:19 +0000 | [diff] [blame] | 126 | switch (ResKind) { |
| 127 | case CodeCompletionResult::RK_Declaration: |
| 128 | llvm_unreachable("RK_Declaration without Decl"); |
| 129 | case CodeCompletionResult::RK_Keyword: |
| 130 | return CompletionItemKind::Keyword; |
| 131 | case CodeCompletionResult::RK_Macro: |
| 132 | return CompletionItemKind::Text; // unfortunately, there's no 'Macro' |
| 133 | // completion items in LSP. |
| 134 | case CodeCompletionResult::RK_Pattern: |
| 135 | return CompletionItemKind::Snippet; |
| 136 | } |
| 137 | llvm_unreachable("Unhandled CodeCompletionResult::ResultKind."); |
| 138 | } |
| 139 | |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 140 | /// Get the optional chunk as a string. This function is possibly recursive. |
| 141 | /// |
| 142 | /// The parameter info for each parameter is appended to the Parameters. |
Kadir Cetinkaya | e486e37 | 2018-08-13 08:40:05 +0000 | [diff] [blame] | 143 | std::string getOptionalParameters(const CodeCompletionString &CCS, |
| 144 | std::vector<ParameterInformation> &Parameters, |
| 145 | SignatureQualitySignals &Signal) { |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 146 | std::string Result; |
| 147 | for (const auto &Chunk : CCS) { |
| 148 | switch (Chunk.Kind) { |
| 149 | case CodeCompletionString::CK_Optional: |
| 150 | assert(Chunk.Optional && |
| 151 | "Expected the optional code completion string to be non-null."); |
Kadir Cetinkaya | e486e37 | 2018-08-13 08:40:05 +0000 | [diff] [blame] | 152 | Result += getOptionalParameters(*Chunk.Optional, Parameters, Signal); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 153 | break; |
| 154 | case CodeCompletionString::CK_VerticalSpace: |
| 155 | break; |
| 156 | case CodeCompletionString::CK_Placeholder: |
| 157 | // A string that acts as a placeholder for, e.g., a function call |
| 158 | // argument. |
| 159 | // Intentional fallthrough here. |
| 160 | case CodeCompletionString::CK_CurrentParameter: { |
| 161 | // A piece of text that describes the parameter that corresponds to |
| 162 | // the code-completion location within a function call, message send, |
| 163 | // macro invocation, etc. |
| 164 | Result += Chunk.Text; |
| 165 | ParameterInformation Info; |
| 166 | Info.label = Chunk.Text; |
| 167 | Parameters.push_back(std::move(Info)); |
Kadir Cetinkaya | e486e37 | 2018-08-13 08:40:05 +0000 | [diff] [blame] | 168 | Signal.ContainsActiveParameter = true; |
| 169 | Signal.NumberOfOptionalParameters++; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 170 | break; |
| 171 | } |
| 172 | default: |
| 173 | Result += Chunk.Text; |
| 174 | break; |
| 175 | } |
| 176 | } |
| 177 | return Result; |
| 178 | } |
| 179 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 180 | /// A code completion result, in clang-native form. |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 181 | /// It may be promoted to a CompletionItem if it's among the top-ranked results. |
| 182 | struct CompletionCandidate { |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 183 | llvm::StringRef Name; // Used for filtering and sorting. |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 184 | // We may have a result from Sema, from the index, or both. |
| 185 | const CodeCompletionResult *SemaResult = nullptr; |
| 186 | const Symbol *IndexResult = nullptr; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 187 | llvm::SmallVector<llvm::StringRef, 1> RankedIncludeHeaders; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 188 | |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 189 | // Returns a token identifying the overload set this is part of. |
| 190 | // 0 indicates it's not part of any overload set. |
| 191 | size_t overloadSet() const { |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 192 | llvm::SmallString<256> Scratch; |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 193 | if (IndexResult) { |
| 194 | switch (IndexResult->SymInfo.Kind) { |
| 195 | case index::SymbolKind::ClassMethod: |
| 196 | case index::SymbolKind::InstanceMethod: |
| 197 | case index::SymbolKind::StaticMethod: |
Fangrui Song | 12e4ee7 | 2018-11-02 05:59:29 +0000 | [diff] [blame] | 198 | #ifndef NDEBUG |
| 199 | llvm_unreachable("Don't expect members from index in code completion"); |
| 200 | #else |
Fangrui Song | a3ed05b | 2018-11-02 04:23:50 +0000 | [diff] [blame] | 201 | LLVM_FALLTHROUGH; |
Fangrui Song | 12e4ee7 | 2018-11-02 05:59:29 +0000 | [diff] [blame] | 202 | #endif |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 203 | case index::SymbolKind::Function: |
| 204 | // We can't group overloads together that need different #includes. |
| 205 | // This could break #include insertion. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 206 | return llvm::hash_combine( |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 207 | (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch), |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 208 | headerToInsertIfAllowed().getValueOr("")); |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 209 | default: |
| 210 | return 0; |
| 211 | } |
| 212 | } |
| 213 | assert(SemaResult); |
| 214 | // We need to make sure we're consistent with the IndexResult case! |
| 215 | const NamedDecl *D = SemaResult->Declaration; |
| 216 | if (!D || !D->isFunctionOrFunctionTemplate()) |
| 217 | return 0; |
| 218 | { |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 219 | llvm::raw_svector_ostream OS(Scratch); |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 220 | D->printQualifiedName(OS); |
| 221 | } |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 222 | return llvm::hash_combine(Scratch, |
| 223 | headerToInsertIfAllowed().getValueOr("")); |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 224 | } |
| 225 | |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 226 | // The best header to include if include insertion is allowed. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 227 | llvm::Optional<llvm::StringRef> headerToInsertIfAllowed() const { |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 228 | if (RankedIncludeHeaders.empty()) |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 229 | return None; |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 230 | if (SemaResult && SemaResult->Declaration) { |
| 231 | // Avoid inserting new #include if the declaration is found in the current |
| 232 | // file e.g. the symbol is forward declared. |
| 233 | auto &SM = SemaResult->Declaration->getASTContext().getSourceManager(); |
| 234 | for (const Decl *RD : SemaResult->Declaration->redecls()) |
Stephen Kelly | 43465bf | 2018-08-09 22:42:26 +0000 | [diff] [blame] | 235 | if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc()))) |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 236 | return None; |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 237 | } |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 238 | return RankedIncludeHeaders[0]; |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 239 | } |
| 240 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 241 | using Bundle = llvm::SmallVector<CompletionCandidate, 4>; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 242 | }; |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 243 | using ScoredBundle = |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 244 | std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>; |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 245 | struct ScoredBundleGreater { |
| 246 | bool operator()(const ScoredBundle &L, const ScoredBundle &R) { |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 247 | if (L.second.Total != R.second.Total) |
| 248 | return L.second.Total > R.second.Total; |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 249 | return L.first.front().Name < |
| 250 | R.first.front().Name; // Earlier name is better. |
| 251 | } |
| 252 | }; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 253 | |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 254 | // Assembles a code completion out of a bundle of >=1 completion candidates. |
| 255 | // Many of the expensive strings are only computed at this point, once we know |
| 256 | // the candidate bundle is going to be returned. |
| 257 | // |
| 258 | // Many fields are the same for all candidates in a bundle (e.g. name), and are |
| 259 | // computed from the first candidate, in the constructor. |
| 260 | // Others vary per candidate, so add() must be called for remaining candidates. |
| 261 | struct CodeCompletionBuilder { |
| 262 | CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C, |
| 263 | CodeCompletionString *SemaCCS, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 264 | llvm::ArrayRef<std::string> QueryScopes, |
| 265 | const IncludeInserter &Includes, |
| 266 | llvm::StringRef FileName, |
Sam McCall | 4c077f9 | 2018-09-18 09:08:28 +0000 | [diff] [blame] | 267 | CodeCompletionContext::Kind ContextKind, |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 268 | const CodeCompleteOptions &Opts) |
Kadir Cetinkaya | 516fcda | 2018-08-23 12:19:39 +0000 | [diff] [blame] | 269 | : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments), |
| 270 | EnableFunctionArgSnippets(Opts.EnableFunctionArgSnippets) { |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 271 | add(C, SemaCCS); |
| 272 | if (C.SemaResult) { |
Sam McCall | 4e5742a | 2018-07-06 11:50:49 +0000 | [diff] [blame] | 273 | Completion.Origin |= SymbolOrigin::AST; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 274 | Completion.Name = llvm::StringRef(SemaCCS->getTypedText()); |
Eric Liu | f433c2d | 2018-07-18 15:31:14 +0000 | [diff] [blame] | 275 | if (Completion.Scope.empty()) { |
| 276 | if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) || |
| 277 | (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern)) |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 278 | if (const auto *D = C.SemaResult->getDeclaration()) |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 279 | if (const auto *ND = dyn_cast<NamedDecl>(D)) |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 280 | Completion.Scope = |
| 281 | splitQualifiedName(printQualifiedName(*ND)).first; |
Eric Liu | f433c2d | 2018-07-18 15:31:14 +0000 | [diff] [blame] | 282 | } |
Sam McCall | 4c077f9 | 2018-09-18 09:08:28 +0000 | [diff] [blame] | 283 | Completion.Kind = toCompletionItemKind( |
| 284 | C.SemaResult->Kind, C.SemaResult->Declaration, ContextKind); |
Kadir Cetinkaya | 0ed5d29 | 2018-09-27 14:21:07 +0000 | [diff] [blame] | 285 | // Sema could provide more info on whether the completion was a file or |
| 286 | // folder. |
| 287 | if (Completion.Kind == CompletionItemKind::File && |
| 288 | Completion.Name.back() == '/') |
| 289 | Completion.Kind = CompletionItemKind::Folder; |
Kadir Cetinkaya | 2f84d91 | 2018-08-08 08:59:29 +0000 | [diff] [blame] | 290 | for (const auto &FixIt : C.SemaResult->FixIts) { |
| 291 | Completion.FixIts.push_back( |
| 292 | toTextEdit(FixIt, ASTCtx.getSourceManager(), ASTCtx.getLangOpts())); |
| 293 | } |
Kirill Bobyrev | 4a5ff88 | 2018-10-07 14:49:41 +0000 | [diff] [blame] | 294 | llvm::sort(Completion.FixIts, [](const TextEdit &X, const TextEdit &Y) { |
| 295 | return std::tie(X.range.start.line, X.range.start.character) < |
| 296 | std::tie(Y.range.start.line, Y.range.start.character); |
| 297 | }); |
Eric Liu | 6df6600 | 2018-09-06 18:52:26 +0000 | [diff] [blame] | 298 | Completion.Deprecated |= |
| 299 | (C.SemaResult->Availability == CXAvailability_Deprecated); |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 300 | } |
| 301 | if (C.IndexResult) { |
Sam McCall | 4e5742a | 2018-07-06 11:50:49 +0000 | [diff] [blame] | 302 | Completion.Origin |= C.IndexResult->Origin; |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 303 | if (Completion.Scope.empty()) |
| 304 | Completion.Scope = C.IndexResult->Scope; |
| 305 | if (Completion.Kind == CompletionItemKind::Missing) |
| 306 | Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind); |
| 307 | if (Completion.Name.empty()) |
| 308 | Completion.Name = C.IndexResult->Name; |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 309 | // If the completion was visible to Sema, no qualifier is needed. This |
| 310 | // avoids unneeded qualifiers in cases like with `using ns::X`. |
| 311 | if (Completion.RequiredQualifier.empty() && !C.SemaResult) { |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 312 | llvm::StringRef ShortestQualifier = C.IndexResult->Scope; |
| 313 | for (llvm::StringRef Scope : QueryScopes) { |
| 314 | llvm::StringRef Qualifier = C.IndexResult->Scope; |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 315 | if (Qualifier.consume_front(Scope) && |
| 316 | Qualifier.size() < ShortestQualifier.size()) |
| 317 | ShortestQualifier = Qualifier; |
| 318 | } |
| 319 | Completion.RequiredQualifier = ShortestQualifier; |
| 320 | } |
Eric Liu | 6df6600 | 2018-09-06 18:52:26 +0000 | [diff] [blame] | 321 | Completion.Deprecated |= (C.IndexResult->Flags & Symbol::Deprecated); |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 322 | } |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 323 | |
| 324 | // Turn absolute path into a literal string that can be #included. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 325 | auto Inserted = [&](llvm::StringRef Header) |
| 326 | -> llvm::Expected<std::pair<std::string, bool>> { |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 327 | auto ResolvedDeclaring = |
| 328 | toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName); |
| 329 | if (!ResolvedDeclaring) |
| 330 | return ResolvedDeclaring.takeError(); |
| 331 | auto ResolvedInserted = toHeaderFile(Header, FileName); |
| 332 | if (!ResolvedInserted) |
| 333 | return ResolvedInserted.takeError(); |
| 334 | return std::make_pair( |
| 335 | Includes.calculateIncludePath(*ResolvedDeclaring, *ResolvedInserted), |
| 336 | Includes.shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted)); |
| 337 | }; |
| 338 | bool ShouldInsert = C.headerToInsertIfAllowed().hasValue(); |
| 339 | // Calculate include paths and edits for all possible headers. |
| 340 | for (const auto &Inc : C.RankedIncludeHeaders) { |
| 341 | if (auto ToInclude = Inserted(Inc)) { |
| 342 | CodeCompletion::IncludeCandidate Include; |
| 343 | Include.Header = ToInclude->first; |
| 344 | if (ToInclude->second && ShouldInsert) |
| 345 | Include.Insertion = Includes.insert(ToInclude->first); |
| 346 | Completion.Includes.push_back(std::move(Include)); |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 347 | } else |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 348 | log("Failed to generate include insertion edits for adding header " |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 349 | "(FileURI='{0}', IncludeHeader='{1}') into {2}", |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 350 | C.IndexResult->CanonicalDeclaration.FileURI, Inc, FileName); |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 351 | } |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 352 | // Prefer includes that do not need edits (i.e. already exist). |
| 353 | std::stable_partition(Completion.Includes.begin(), |
| 354 | Completion.Includes.end(), |
| 355 | [](const CodeCompletion::IncludeCandidate &I) { |
| 356 | return !I.Insertion.hasValue(); |
| 357 | }); |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 358 | } |
| 359 | |
| 360 | void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) { |
| 361 | assert(bool(C.SemaResult) == bool(SemaCCS)); |
| 362 | Bundled.emplace_back(); |
| 363 | BundledEntry &S = Bundled.back(); |
| 364 | if (C.SemaResult) { |
| 365 | getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix, |
| 366 | &Completion.RequiredQualifier); |
| 367 | S.ReturnType = getReturnType(*SemaCCS); |
| 368 | } else if (C.IndexResult) { |
| 369 | S.Signature = C.IndexResult->Signature; |
| 370 | S.SnippetSuffix = C.IndexResult->CompletionSnippetSuffix; |
Sam McCall | 2e5700f | 2018-08-31 13:55:01 +0000 | [diff] [blame] | 371 | S.ReturnType = C.IndexResult->ReturnType; |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 372 | } |
| 373 | if (ExtractDocumentation && Completion.Documentation.empty()) { |
Sam McCall | 2e5700f | 2018-08-31 13:55:01 +0000 | [diff] [blame] | 374 | if (C.IndexResult) |
| 375 | Completion.Documentation = C.IndexResult->Documentation; |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 376 | else if (C.SemaResult) |
| 377 | Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult, |
| 378 | /*CommentsFromHeader=*/false); |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | CodeCompletion build() { |
| 383 | Completion.ReturnType = summarizeReturnType(); |
| 384 | Completion.Signature = summarizeSignature(); |
| 385 | Completion.SnippetSuffix = summarizeSnippet(); |
| 386 | Completion.BundleSize = Bundled.size(); |
| 387 | return std::move(Completion); |
| 388 | } |
| 389 | |
| 390 | private: |
| 391 | struct BundledEntry { |
| 392 | std::string SnippetSuffix; |
| 393 | std::string Signature; |
| 394 | std::string ReturnType; |
| 395 | }; |
| 396 | |
| 397 | // If all BundledEntrys have the same value for a property, return it. |
| 398 | template <std::string BundledEntry::*Member> |
| 399 | const std::string *onlyValue() const { |
| 400 | auto B = Bundled.begin(), E = Bundled.end(); |
| 401 | for (auto I = B + 1; I != E; ++I) |
| 402 | if (I->*Member != B->*Member) |
| 403 | return nullptr; |
| 404 | return &(B->*Member); |
| 405 | } |
| 406 | |
Kadir Cetinkaya | f8b85a3 | 2018-08-23 13:14:50 +0000 | [diff] [blame] | 407 | template <bool BundledEntry::*Member> const bool *onlyValue() const { |
| 408 | auto B = Bundled.begin(), E = Bundled.end(); |
| 409 | for (auto I = B + 1; I != E; ++I) |
| 410 | if (I->*Member != B->*Member) |
| 411 | return nullptr; |
| 412 | return &(B->*Member); |
| 413 | } |
| 414 | |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 415 | std::string summarizeReturnType() const { |
| 416 | if (auto *RT = onlyValue<&BundledEntry::ReturnType>()) |
| 417 | return *RT; |
| 418 | return ""; |
| 419 | } |
| 420 | |
| 421 | std::string summarizeSnippet() const { |
Kadir Cetinkaya | 516fcda | 2018-08-23 12:19:39 +0000 | [diff] [blame] | 422 | auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>(); |
| 423 | if (!Snippet) |
| 424 | // All bundles are function calls. |
Ilya Biryukov | 4f98470 | 2018-09-26 05:45:31 +0000 | [diff] [blame] | 425 | // FIXME(ibiryukov): sometimes add template arguments to a snippet, e.g. |
| 426 | // we need to complete 'forward<$1>($0)'. |
Kadir Cetinkaya | 516fcda | 2018-08-23 12:19:39 +0000 | [diff] [blame] | 427 | return "($0)"; |
Ilya Biryukov | 4f98470 | 2018-09-26 05:45:31 +0000 | [diff] [blame] | 428 | if (EnableFunctionArgSnippets) |
| 429 | return *Snippet; |
| 430 | |
| 431 | // Replace argument snippets with a simplified pattern. |
| 432 | if (Snippet->empty()) |
| 433 | return ""; |
| 434 | if (Completion.Kind == CompletionItemKind::Function || |
| 435 | Completion.Kind == CompletionItemKind::Method) { |
| 436 | // Functions snippets can be of 2 types: |
| 437 | // - containing only function arguments, e.g. |
| 438 | // foo(${1:int p1}, ${2:int p2}); |
| 439 | // We transform this pattern to '($0)' or '()'. |
| 440 | // - template arguments and function arguments, e.g. |
| 441 | // foo<${1:class}>(${2:int p1}). |
| 442 | // We transform this pattern to '<$1>()$0' or '<$0>()'. |
| 443 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 444 | bool EmptyArgs = llvm::StringRef(*Snippet).endswith("()"); |
Ilya Biryukov | 4f98470 | 2018-09-26 05:45:31 +0000 | [diff] [blame] | 445 | if (Snippet->front() == '<') |
| 446 | return EmptyArgs ? "<$1>()$0" : "<$1>($0)"; |
| 447 | if (Snippet->front() == '(') |
| 448 | return EmptyArgs ? "()" : "($0)"; |
| 449 | return *Snippet; // Not an arg snippet? |
| 450 | } |
| 451 | if (Completion.Kind == CompletionItemKind::Reference || |
| 452 | Completion.Kind == CompletionItemKind::Class) { |
| 453 | if (Snippet->front() != '<') |
| 454 | return *Snippet; // Not an arg snippet? |
| 455 | |
| 456 | // Classes and template using aliases can only have template arguments, |
| 457 | // e.g. Foo<${1:class}>. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 458 | if (llvm::StringRef(*Snippet).endswith("<>")) |
Ilya Biryukov | 4f98470 | 2018-09-26 05:45:31 +0000 | [diff] [blame] | 459 | return "<>"; // can happen with defaulted template arguments. |
| 460 | return "<$0>"; |
| 461 | } |
Kadir Cetinkaya | 516fcda | 2018-08-23 12:19:39 +0000 | [diff] [blame] | 462 | return *Snippet; |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 463 | } |
| 464 | |
| 465 | std::string summarizeSignature() const { |
| 466 | if (auto *Signature = onlyValue<&BundledEntry::Signature>()) |
| 467 | return *Signature; |
| 468 | // All bundles are function calls. |
| 469 | return "(…)"; |
| 470 | } |
| 471 | |
| 472 | ASTContext &ASTCtx; |
| 473 | CodeCompletion Completion; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 474 | llvm::SmallVector<BundledEntry, 1> Bundled; |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 475 | bool ExtractDocumentation; |
Kadir Cetinkaya | 516fcda | 2018-08-23 12:19:39 +0000 | [diff] [blame] | 476 | bool EnableFunctionArgSnippets; |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 477 | }; |
| 478 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 479 | // Determine the symbol ID for a Sema code completion result, if possible. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 480 | llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R, |
| 481 | const SourceManager &SM) { |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 482 | switch (R.Kind) { |
| 483 | case CodeCompletionResult::RK_Declaration: |
| 484 | case CodeCompletionResult::RK_Pattern: { |
Haojian Wu | c6ddb46 | 2018-08-07 08:57:52 +0000 | [diff] [blame] | 485 | return clang::clangd::getSymbolID(R.Declaration); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 486 | } |
| 487 | case CodeCompletionResult::RK_Macro: |
Eric Liu | d25f121 | 2018-09-06 09:59:37 +0000 | [diff] [blame] | 488 | return clang::clangd::getSymbolID(*R.Macro, R.MacroDefInfo, SM); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 489 | case CodeCompletionResult::RK_Keyword: |
| 490 | return None; |
| 491 | } |
| 492 | llvm_unreachable("unknown CodeCompletionResult kind"); |
| 493 | } |
| 494 | |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 495 | // Scopes of the paritial identifier we're trying to complete. |
| 496 | // It is used when we query the index for more completion results. |
Eric Liu | 6f648df | 2017-12-19 16:50:37 +0000 | [diff] [blame] | 497 | struct SpecifiedScope { |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 498 | // The scopes we should look in, determined by Sema. |
| 499 | // |
| 500 | // If the qualifier was fully resolved, we look for completions in these |
| 501 | // scopes; if there is an unresolved part of the qualifier, it should be |
| 502 | // resolved within these scopes. |
| 503 | // |
| 504 | // Examples of qualified completion: |
| 505 | // |
| 506 | // "::vec" => {""} |
| 507 | // "using namespace std; ::vec^" => {"", "std::"} |
| 508 | // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"} |
| 509 | // "std::vec^" => {""} // "std" unresolved |
| 510 | // |
| 511 | // Examples of unqualified completion: |
| 512 | // |
| 513 | // "vec^" => {""} |
| 514 | // "using namespace std; vec^" => {"", "std::"} |
| 515 | // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""} |
| 516 | // |
| 517 | // "" for global namespace, "ns::" for normal namespace. |
| 518 | std::vector<std::string> AccessibleScopes; |
| 519 | // The full scope qualifier as typed by the user (without the leading "::"). |
| 520 | // Set if the qualifier is not fully resolved by Sema. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 521 | llvm::Optional<std::string> UnresolvedQualifier; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 522 | |
Eric Liu | abbd713 | 2018-11-06 11:17:40 +0000 | [diff] [blame] | 523 | // Construct scopes being queried in indexes. The results are deduplicated. |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 524 | // This method format the scopes to match the index request representation. |
| 525 | std::vector<std::string> scopesForIndexQuery() { |
Eric Liu | abbd713 | 2018-11-06 11:17:40 +0000 | [diff] [blame] | 526 | std::set<std::string> Results; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 527 | for (llvm::StringRef AS : AccessibleScopes) |
Eric Liu | abbd713 | 2018-11-06 11:17:40 +0000 | [diff] [blame] | 528 | Results.insert( |
| 529 | ((UnresolvedQualifier ? *UnresolvedQualifier : "") + AS).str()); |
| 530 | return {Results.begin(), Results.end()}; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 531 | } |
Eric Liu | 6f648df | 2017-12-19 16:50:37 +0000 | [diff] [blame] | 532 | }; |
| 533 | |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 534 | // Get all scopes that will be queried in indexes and whether symbols from |
Eric Liu | 3fac4ef | 2018-10-17 11:19:02 +0000 | [diff] [blame] | 535 | // any scope is allowed. The first scope in the list is the preferred scope |
| 536 | // (e.g. enclosing namespace). |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 537 | std::pair<std::vector<std::string>, bool> |
Eric Liu | 3fac4ef | 2018-10-17 11:19:02 +0000 | [diff] [blame] | 538 | getQueryScopes(CodeCompletionContext &CCContext, const Sema &CCSema, |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 539 | const CodeCompleteOptions &Opts) { |
Kirill Bobyrev | 5a267ed | 2018-05-29 11:50:51 +0000 | [diff] [blame] | 540 | auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) { |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 541 | SpecifiedScope Info; |
Kirill Bobyrev | 5a267ed | 2018-05-29 11:50:51 +0000 | [diff] [blame] | 542 | for (auto *Context : CCContext.getVisitedContexts()) { |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 543 | if (isa<TranslationUnitDecl>(Context)) |
| 544 | Info.AccessibleScopes.push_back(""); // global namespace |
Mikael Holmen | fa41add | 2018-10-18 06:00:39 +0000 | [diff] [blame] | 545 | else if (isa<NamespaceDecl>(Context)) |
Eric Liu | 3fac4ef | 2018-10-17 11:19:02 +0000 | [diff] [blame] | 546 | Info.AccessibleScopes.push_back(printNamespaceScope(*Context)); |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 547 | } |
| 548 | return Info; |
| 549 | }; |
| 550 | |
| 551 | auto SS = CCContext.getCXXScopeSpecifier(); |
| 552 | |
| 553 | // Unqualified completion (e.g. "vec^"). |
| 554 | if (!SS) { |
Eric Liu | 3fac4ef | 2018-10-17 11:19:02 +0000 | [diff] [blame] | 555 | std::vector<std::string> Scopes; |
| 556 | std::string EnclosingScope = printNamespaceScope(*CCSema.CurContext); |
| 557 | Scopes.push_back(EnclosingScope); |
| 558 | for (auto &S : GetAllAccessibleScopes(CCContext).scopesForIndexQuery()) { |
| 559 | if (EnclosingScope != S) |
| 560 | Scopes.push_back(std::move(S)); |
| 561 | } |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 562 | // Allow AllScopes completion only for there is no explicit scope qualifier. |
| 563 | return {Scopes, Opts.AllScopes}; |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 564 | } |
| 565 | |
| 566 | // Qualified completion ("std::vec^"), we have two cases depending on whether |
| 567 | // the qualifier can be resolved by Sema. |
| 568 | if ((*SS)->isValid()) { // Resolved qualifier. |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 569 | return {GetAllAccessibleScopes(CCContext).scopesForIndexQuery(), false}; |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 570 | } |
| 571 | |
| 572 | // Unresolved qualifier. |
| 573 | // FIXME: When Sema can resolve part of a scope chain (e.g. |
| 574 | // "known::unknown::id"), we should expand the known part ("known::") rather |
| 575 | // than treating the whole thing as unknown. |
| 576 | SpecifiedScope Info; |
| 577 | Info.AccessibleScopes.push_back(""); // global namespace |
| 578 | |
| 579 | Info.UnresolvedQualifier = |
Eric Liu | 3fac4ef | 2018-10-17 11:19:02 +0000 | [diff] [blame] | 580 | Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), |
| 581 | CCSema.SourceMgr, clang::LangOptions()) |
Kirill Bobyrev | 5a267ed | 2018-05-29 11:50:51 +0000 | [diff] [blame] | 582 | .ltrim("::"); |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 583 | // Sema excludes the trailing "::". |
| 584 | if (!Info.UnresolvedQualifier->empty()) |
| 585 | *Info.UnresolvedQualifier += "::"; |
| 586 | |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 587 | return {Info.scopesForIndexQuery(), false}; |
Haojian Wu | 061c73e | 2018-01-23 11:37:26 +0000 | [diff] [blame] | 588 | } |
| 589 | |
Eric Liu | 42abe41 | 2018-05-24 11:20:19 +0000 | [diff] [blame] | 590 | // Should we perform index-based completion in a context of the specified kind? |
| 591 | // FIXME: consider allowing completion, but restricting the result types. |
| 592 | bool contextAllowsIndex(enum CodeCompletionContext::Kind K) { |
| 593 | switch (K) { |
| 594 | case CodeCompletionContext::CCC_TopLevel: |
| 595 | case CodeCompletionContext::CCC_ObjCInterface: |
| 596 | case CodeCompletionContext::CCC_ObjCImplementation: |
| 597 | case CodeCompletionContext::CCC_ObjCIvarList: |
| 598 | case CodeCompletionContext::CCC_ClassStructUnion: |
| 599 | case CodeCompletionContext::CCC_Statement: |
| 600 | case CodeCompletionContext::CCC_Expression: |
| 601 | case CodeCompletionContext::CCC_ObjCMessageReceiver: |
| 602 | case CodeCompletionContext::CCC_EnumTag: |
| 603 | case CodeCompletionContext::CCC_UnionTag: |
| 604 | case CodeCompletionContext::CCC_ClassOrStructTag: |
| 605 | case CodeCompletionContext::CCC_ObjCProtocolName: |
| 606 | case CodeCompletionContext::CCC_Namespace: |
| 607 | case CodeCompletionContext::CCC_Type: |
Eric Liu | 42abe41 | 2018-05-24 11:20:19 +0000 | [diff] [blame] | 608 | case CodeCompletionContext::CCC_ParenthesizedExpression: |
| 609 | case CodeCompletionContext::CCC_ObjCInterfaceName: |
| 610 | case CodeCompletionContext::CCC_ObjCCategoryName: |
Kadir Cetinkaya | b915790 | 2018-10-24 15:24:29 +0000 | [diff] [blame] | 611 | case CodeCompletionContext::CCC_Symbol: |
| 612 | case CodeCompletionContext::CCC_SymbolOrNewName: |
Eric Liu | 42abe41 | 2018-05-24 11:20:19 +0000 | [diff] [blame] | 613 | return true; |
Eric Liu | 42abe41 | 2018-05-24 11:20:19 +0000 | [diff] [blame] | 614 | case CodeCompletionContext::CCC_OtherWithMacros: |
| 615 | case CodeCompletionContext::CCC_DotMemberAccess: |
| 616 | case CodeCompletionContext::CCC_ArrowMemberAccess: |
| 617 | case CodeCompletionContext::CCC_ObjCPropertyAccess: |
| 618 | case CodeCompletionContext::CCC_MacroName: |
| 619 | case CodeCompletionContext::CCC_MacroNameUse: |
| 620 | case CodeCompletionContext::CCC_PreprocessorExpression: |
| 621 | case CodeCompletionContext::CCC_PreprocessorDirective: |
Eric Liu | 42abe41 | 2018-05-24 11:20:19 +0000 | [diff] [blame] | 622 | case CodeCompletionContext::CCC_SelectorName: |
| 623 | case CodeCompletionContext::CCC_TypeQualifiers: |
| 624 | case CodeCompletionContext::CCC_ObjCInstanceMessage: |
| 625 | case CodeCompletionContext::CCC_ObjCClassMessage: |
Sam McCall | 4c077f9 | 2018-09-18 09:08:28 +0000 | [diff] [blame] | 626 | case CodeCompletionContext::CCC_IncludedFile: |
Kadir Cetinkaya | b915790 | 2018-10-24 15:24:29 +0000 | [diff] [blame] | 627 | // FIXME: Provide identifier based completions for the following contexts: |
| 628 | case CodeCompletionContext::CCC_Other: // Be conservative. |
| 629 | case CodeCompletionContext::CCC_NaturalLanguage: |
Eric Liu | 42abe41 | 2018-05-24 11:20:19 +0000 | [diff] [blame] | 630 | case CodeCompletionContext::CCC_Recovery: |
Kadir Cetinkaya | b915790 | 2018-10-24 15:24:29 +0000 | [diff] [blame] | 631 | case CodeCompletionContext::CCC_NewName: |
Eric Liu | 42abe41 | 2018-05-24 11:20:19 +0000 | [diff] [blame] | 632 | return false; |
| 633 | } |
| 634 | llvm_unreachable("unknown code completion context"); |
| 635 | } |
| 636 | |
Eric Liu | b1317fa | 2018-11-30 11:12:40 +0000 | [diff] [blame] | 637 | static bool isInjectedClass(const NamedDecl &D) { |
| 638 | if (auto *R = dyn_cast_or_null<RecordDecl>(&D)) |
| 639 | if (R->isInjectedClassName()) |
| 640 | return true; |
| 641 | return false; |
| 642 | } |
| 643 | |
Sam McCall | 4caa851 | 2018-06-07 12:49:17 +0000 | [diff] [blame] | 644 | // Some member calls are blacklisted because they're so rarely useful. |
| 645 | static bool isBlacklistedMember(const NamedDecl &D) { |
| 646 | // Destructor completion is rarely useful, and works inconsistently. |
| 647 | // (s.^ completes ~string, but s.~st^ is an error). |
| 648 | if (D.getKind() == Decl::CXXDestructor) |
| 649 | return true; |
| 650 | // Injected name may be useful for A::foo(), but who writes A::A::foo()? |
Eric Liu | b1317fa | 2018-11-30 11:12:40 +0000 | [diff] [blame] | 651 | if (isInjectedClass(D)) |
| 652 | return true; |
Sam McCall | 4caa851 | 2018-06-07 12:49:17 +0000 | [diff] [blame] | 653 | // Explicit calls to operators are also rare. |
| 654 | auto NameKind = D.getDeclName().getNameKind(); |
| 655 | if (NameKind == DeclarationName::CXXOperatorName || |
| 656 | NameKind == DeclarationName::CXXLiteralOperatorName || |
| 657 | NameKind == DeclarationName::CXXConversionFunctionName) |
| 658 | return true; |
| 659 | return false; |
| 660 | } |
| 661 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 662 | // The CompletionRecorder captures Sema code-complete output, including context. |
| 663 | // It filters out ignored results (but doesn't apply fuzzy-filtering yet). |
| 664 | // It doesn't do scoring or conversion to CompletionItem yet, as we want to |
| 665 | // merge with index results first. |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 666 | // Generally the fields and methods of this object should only be used from |
| 667 | // within the callback. |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 668 | struct CompletionRecorder : public CodeCompleteConsumer { |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 669 | CompletionRecorder(const CodeCompleteOptions &Opts, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 670 | llvm::unique_function<void()> ResultsCallback) |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 671 | : CodeCompleteConsumer(Opts.getClangCompleteOpts(), |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 672 | /*OutputIsBinary=*/false), |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 673 | CCContext(CodeCompletionContext::CCC_Other), Opts(Opts), |
| 674 | CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()), |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 675 | CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) { |
| 676 | assert(this->ResultsCallback); |
| 677 | } |
| 678 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 679 | std::vector<CodeCompletionResult> Results; |
| 680 | CodeCompletionContext CCContext; |
| 681 | Sema *CCSema = nullptr; // Sema that created the results. |
| 682 | // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead? |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 683 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 684 | void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context, |
| 685 | CodeCompletionResult *InResults, |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 686 | unsigned NumResults) override final { |
Eric Liu | 485074f | 2018-07-11 13:15:31 +0000 | [diff] [blame] | 687 | // Results from recovery mode are generally useless, and the callback after |
| 688 | // recovery (if any) is usually more interesting. To make sure we handle the |
| 689 | // future callback from sema, we just ignore all callbacks in recovery mode, |
| 690 | // as taking only results from recovery mode results in poor completion |
| 691 | // results. |
| 692 | // FIXME: in case there is no future sema completion callback after the |
| 693 | // recovery mode, we might still want to provide some results (e.g. trivial |
| 694 | // identifier-based completion). |
| 695 | if (Context.getKind() == CodeCompletionContext::CCC_Recovery) { |
| 696 | log("Code complete: Ignoring sema code complete callback with Recovery " |
| 697 | "context."); |
| 698 | return; |
| 699 | } |
Eric Liu | 42abe41 | 2018-05-24 11:20:19 +0000 | [diff] [blame] | 700 | // If a callback is called without any sema result and the context does not |
| 701 | // support index-based completion, we simply skip it to give way to |
| 702 | // potential future callbacks with results. |
| 703 | if (NumResults == 0 && !contextAllowsIndex(Context.getKind())) |
| 704 | return; |
Ilya Biryukov | 94da7bd | 2018-03-16 15:23:44 +0000 | [diff] [blame] | 705 | if (CCSema) { |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 706 | log("Multiple code complete callbacks (parser backtracked?). " |
Ilya Biryukov | 94da7bd | 2018-03-16 15:23:44 +0000 | [diff] [blame] | 707 | "Dropping results from context {0}, keeping results from {1}.", |
Eric Liu | 42abe41 | 2018-05-24 11:20:19 +0000 | [diff] [blame] | 708 | getCompletionKindString(Context.getKind()), |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 709 | getCompletionKindString(this->CCContext.getKind())); |
Ilya Biryukov | 94da7bd | 2018-03-16 15:23:44 +0000 | [diff] [blame] | 710 | return; |
| 711 | } |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 712 | // Record the completion context. |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 713 | CCSema = &S; |
| 714 | CCContext = Context; |
Eric Liu | 6f648df | 2017-12-19 16:50:37 +0000 | [diff] [blame] | 715 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 716 | // Retain the results we might want. |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 717 | for (unsigned I = 0; I < NumResults; ++I) { |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 718 | auto &Result = InResults[I]; |
Sam McCall | e8437cb | 2018-10-24 13:51:44 +0000 | [diff] [blame] | 719 | // Class members that are shadowed by subclasses are usually noise. |
| 720 | if (Result.Hidden && Result.Declaration && |
| 721 | Result.Declaration->isCXXClassMember()) |
Ilya Biryukov | f60bf34 | 2018-01-10 13:51:09 +0000 | [diff] [blame] | 722 | continue; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 723 | if (!Opts.IncludeIneligibleResults && |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 724 | (Result.Availability == CXAvailability_NotAvailable || |
| 725 | Result.Availability == CXAvailability_NotAccessible)) |
| 726 | continue; |
Sam McCall | 4caa851 | 2018-06-07 12:49:17 +0000 | [diff] [blame] | 727 | if (Result.Declaration && |
| 728 | !Context.getBaseType().isNull() // is this a member-access context? |
| 729 | && isBlacklistedMember(*Result.Declaration)) |
Sam McCall | d2a9592 | 2018-01-22 21:05:00 +0000 | [diff] [blame] | 730 | continue; |
Eric Liu | b1317fa | 2018-11-30 11:12:40 +0000 | [diff] [blame] | 731 | // Skip injected class name when no class scope is not explicitly set. |
| 732 | // E.g. show injected A::A in `using A::A^` but not in "A^". |
| 733 | if (Result.Declaration && !Context.getCXXScopeSpecifier().hasValue() && |
| 734 | isInjectedClass(*Result.Declaration)) |
| 735 | continue; |
Ilya Biryukov | 53d6d93 | 2018-03-06 16:45:21 +0000 | [diff] [blame] | 736 | // We choose to never append '::' to completion results in clangd. |
| 737 | Result.StartsNestedNameSpecifier = false; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 738 | Results.push_back(Result); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 739 | } |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 740 | ResultsCallback(); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 741 | } |
| 742 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 743 | CodeCompletionAllocator &getAllocator() override { return *CCAllocator; } |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 744 | CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } |
| 745 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 746 | // Returns the filtering/sorting name for Result, which must be from Results. |
| 747 | // Returned string is owned by this recorder (or the AST). |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 748 | llvm::StringRef getName(const CodeCompletionResult &Result) { |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 749 | switch (Result.Kind) { |
| 750 | case CodeCompletionResult::RK_Declaration: |
| 751 | if (auto *ID = Result.Declaration->getIdentifier()) |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 752 | return ID->getName(); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 753 | break; |
| 754 | case CodeCompletionResult::RK_Keyword: |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 755 | return Result.Keyword; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 756 | case CodeCompletionResult::RK_Macro: |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 757 | return Result.Macro->getName(); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 758 | case CodeCompletionResult::RK_Pattern: |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 759 | return Result.Pattern->getTypedText(); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 760 | } |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 761 | auto *CCS = codeCompletionString(Result); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 762 | return CCS->getTypedText(); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 763 | } |
| 764 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 765 | // Build a CodeCompletion string for R, which must be from Results. |
| 766 | // The CCS will be owned by this recorder. |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 767 | CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) { |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 768 | // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway. |
| 769 | return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString( |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 770 | *CCSema, CCContext, *CCAllocator, CCTUInfo, |
| 771 | /*IncludeBriefComments=*/false); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 772 | } |
| 773 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 774 | private: |
| 775 | CodeCompleteOptions Opts; |
| 776 | std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 777 | CodeCompletionTUInfo CCTUInfo; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 778 | llvm::unique_function<void()> ResultsCallback; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 779 | }; |
| 780 | |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 781 | struct ScoredSignature { |
| 782 | // When set, requires documentation to be requested from the index with this |
| 783 | // ID. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 784 | llvm::Optional<SymbolID> IDForDoc; |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 785 | SignatureInformation Signature; |
| 786 | SignatureQualitySignals Quality; |
| 787 | }; |
Kadir Cetinkaya | e486e37 | 2018-08-13 08:40:05 +0000 | [diff] [blame] | 788 | |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 789 | class SignatureHelpCollector final : public CodeCompleteConsumer { |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 790 | public: |
| 791 | SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts, |
Sam McCall | 046557b | 2018-09-03 16:37:59 +0000 | [diff] [blame] | 792 | const SymbolIndex *Index, SignatureHelp &SigHelp) |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 793 | : CodeCompleteConsumer(CodeCompleteOpts, |
| 794 | /*OutputIsBinary=*/false), |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 795 | SigHelp(SigHelp), |
| 796 | Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()), |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 797 | CCTUInfo(Allocator), Index(Index) {} |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 798 | |
| 799 | void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, |
| 800 | OverloadCandidate *Candidates, |
Ilya Biryukov | 43c292c | 2018-08-30 13:14:31 +0000 | [diff] [blame] | 801 | unsigned NumCandidates, |
| 802 | SourceLocation OpenParLoc) override { |
| 803 | assert(!OpenParLoc.isInvalid()); |
| 804 | SourceManager &SrcMgr = S.getSourceManager(); |
| 805 | OpenParLoc = SrcMgr.getFileLoc(OpenParLoc); |
| 806 | if (SrcMgr.isInMainFile(OpenParLoc)) |
| 807 | SigHelp.argListStart = sourceLocToPosition(SrcMgr, OpenParLoc); |
| 808 | else |
| 809 | elog("Location oustide main file in signature help: {0}", |
| 810 | OpenParLoc.printToString(SrcMgr)); |
| 811 | |
Kadir Cetinkaya | e486e37 | 2018-08-13 08:40:05 +0000 | [diff] [blame] | 812 | std::vector<ScoredSignature> ScoredSignatures; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 813 | SigHelp.signatures.reserve(NumCandidates); |
Kadir Cetinkaya | e486e37 | 2018-08-13 08:40:05 +0000 | [diff] [blame] | 814 | ScoredSignatures.reserve(NumCandidates); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 815 | // FIXME(rwols): How can we determine the "active overload candidate"? |
| 816 | // Right now the overloaded candidates seem to be provided in a "best fit" |
| 817 | // order, so I'm not too worried about this. |
| 818 | SigHelp.activeSignature = 0; |
| 819 | assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() && |
| 820 | "too many arguments"); |
| 821 | SigHelp.activeParameter = static_cast<int>(CurrentArg); |
| 822 | for (unsigned I = 0; I < NumCandidates; ++I) { |
Ilya Biryukov | 8fd44bb | 2018-08-14 09:36:32 +0000 | [diff] [blame] | 823 | OverloadCandidate Candidate = Candidates[I]; |
| 824 | // We want to avoid showing instantiated signatures, because they may be |
| 825 | // long in some cases (e.g. when 'T' is substituted with 'std::string', we |
| 826 | // would get 'std::basic_string<char>'). |
| 827 | if (auto *Func = Candidate.getFunction()) { |
| 828 | if (auto *Pattern = Func->getTemplateInstantiationPattern()) |
| 829 | Candidate = OverloadCandidate(Pattern); |
| 830 | } |
| 831 | |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 832 | const auto *CCS = Candidate.CreateSignatureString( |
| 833 | CurrentArg, S, *Allocator, CCTUInfo, true); |
| 834 | assert(CCS && "Expected the CodeCompletionString to be non-null"); |
Kadir Cetinkaya | e486e37 | 2018-08-13 08:40:05 +0000 | [diff] [blame] | 835 | ScoredSignatures.push_back(processOverloadCandidate( |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 836 | Candidate, *CCS, |
Ilya Biryukov | 5f4a351 | 2018-08-17 09:29:38 +0000 | [diff] [blame] | 837 | Candidate.getFunction() |
| 838 | ? getDeclComment(S.getASTContext(), *Candidate.getFunction()) |
| 839 | : "")); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 840 | } |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 841 | |
| 842 | // Sema does not load the docs from the preamble, so we need to fetch extra |
| 843 | // docs from the index instead. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 844 | llvm::DenseMap<SymbolID, std::string> FetchedDocs; |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 845 | if (Index) { |
| 846 | LookupRequest IndexRequest; |
| 847 | for (const auto &S : ScoredSignatures) { |
| 848 | if (!S.IDForDoc) |
| 849 | continue; |
| 850 | IndexRequest.IDs.insert(*S.IDForDoc); |
| 851 | } |
| 852 | Index->lookup(IndexRequest, [&](const Symbol &S) { |
Sam McCall | 2e5700f | 2018-08-31 13:55:01 +0000 | [diff] [blame] | 853 | if (!S.Documentation.empty()) |
| 854 | FetchedDocs[S.ID] = S.Documentation; |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 855 | }); |
| 856 | log("SigHelp: requested docs for {0} symbols from the index, got {1} " |
| 857 | "symbols with non-empty docs in the response", |
| 858 | IndexRequest.IDs.size(), FetchedDocs.size()); |
| 859 | } |
| 860 | |
Ilya Biryukov | 22fa465 | 2019-01-03 13:28:05 +0000 | [diff] [blame] | 861 | llvm::sort(ScoredSignatures, [](const ScoredSignature &L, |
| 862 | const ScoredSignature &R) { |
| 863 | // Ordering follows: |
| 864 | // - Less number of parameters is better. |
| 865 | // - Function is better than FunctionType which is better than |
| 866 | // Function Template. |
| 867 | // - High score is better. |
| 868 | // - Shorter signature is better. |
| 869 | // - Alphebatically smaller is better. |
| 870 | if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters) |
| 871 | return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters; |
| 872 | if (L.Quality.NumberOfOptionalParameters != |
| 873 | R.Quality.NumberOfOptionalParameters) |
| 874 | return L.Quality.NumberOfOptionalParameters < |
| 875 | R.Quality.NumberOfOptionalParameters; |
| 876 | if (L.Quality.Kind != R.Quality.Kind) { |
| 877 | using OC = CodeCompleteConsumer::OverloadCandidate; |
| 878 | switch (L.Quality.Kind) { |
| 879 | case OC::CK_Function: |
| 880 | return true; |
| 881 | case OC::CK_FunctionType: |
| 882 | return R.Quality.Kind != OC::CK_Function; |
| 883 | case OC::CK_FunctionTemplate: |
| 884 | return false; |
| 885 | } |
| 886 | llvm_unreachable("Unknown overload candidate type."); |
| 887 | } |
| 888 | if (L.Signature.label.size() != R.Signature.label.size()) |
| 889 | return L.Signature.label.size() < R.Signature.label.size(); |
| 890 | return L.Signature.label < R.Signature.label; |
| 891 | }); |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 892 | |
| 893 | for (auto &SS : ScoredSignatures) { |
| 894 | auto IndexDocIt = |
| 895 | SS.IDForDoc ? FetchedDocs.find(*SS.IDForDoc) : FetchedDocs.end(); |
| 896 | if (IndexDocIt != FetchedDocs.end()) |
| 897 | SS.Signature.documentation = IndexDocIt->second; |
| 898 | |
| 899 | SigHelp.signatures.push_back(std::move(SS.Signature)); |
| 900 | } |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 901 | } |
| 902 | |
| 903 | GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; } |
| 904 | |
| 905 | CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } |
| 906 | |
| 907 | private: |
Eric Liu | 63696e1 | 2017-12-20 17:24:31 +0000 | [diff] [blame] | 908 | // FIXME(ioeric): consider moving CodeCompletionString logic here to |
| 909 | // CompletionString.h. |
Kadir Cetinkaya | e486e37 | 2018-08-13 08:40:05 +0000 | [diff] [blame] | 910 | ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate, |
| 911 | const CodeCompletionString &CCS, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 912 | llvm::StringRef DocComment) const { |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 913 | SignatureInformation Signature; |
Kadir Cetinkaya | e486e37 | 2018-08-13 08:40:05 +0000 | [diff] [blame] | 914 | SignatureQualitySignals Signal; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 915 | const char *ReturnType = nullptr; |
| 916 | |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 917 | Signature.documentation = formatDocumentation(CCS, DocComment); |
Kadir Cetinkaya | e486e37 | 2018-08-13 08:40:05 +0000 | [diff] [blame] | 918 | Signal.Kind = Candidate.getKind(); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 919 | |
| 920 | for (const auto &Chunk : CCS) { |
| 921 | switch (Chunk.Kind) { |
| 922 | case CodeCompletionString::CK_ResultType: |
| 923 | // A piece of text that describes the type of an entity or, |
| 924 | // for functions and methods, the return type. |
| 925 | assert(!ReturnType && "Unexpected CK_ResultType"); |
| 926 | ReturnType = Chunk.Text; |
| 927 | break; |
| 928 | case CodeCompletionString::CK_Placeholder: |
| 929 | // A string that acts as a placeholder for, e.g., a function call |
| 930 | // argument. |
| 931 | // Intentional fallthrough here. |
| 932 | case CodeCompletionString::CK_CurrentParameter: { |
| 933 | // A piece of text that describes the parameter that corresponds to |
| 934 | // the code-completion location within a function call, message send, |
| 935 | // macro invocation, etc. |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 936 | Signature.label += Chunk.Text; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 937 | ParameterInformation Info; |
| 938 | Info.label = Chunk.Text; |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 939 | Signature.parameters.push_back(std::move(Info)); |
Kadir Cetinkaya | e486e37 | 2018-08-13 08:40:05 +0000 | [diff] [blame] | 940 | Signal.NumberOfParameters++; |
| 941 | Signal.ContainsActiveParameter = true; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 942 | break; |
| 943 | } |
| 944 | case CodeCompletionString::CK_Optional: { |
| 945 | // The rest of the parameters are defaulted/optional. |
| 946 | assert(Chunk.Optional && |
| 947 | "Expected the optional code completion string to be non-null."); |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 948 | Signature.label += getOptionalParameters(*Chunk.Optional, |
| 949 | Signature.parameters, Signal); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 950 | break; |
| 951 | } |
| 952 | case CodeCompletionString::CK_VerticalSpace: |
| 953 | break; |
| 954 | default: |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 955 | Signature.label += Chunk.Text; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 956 | break; |
| 957 | } |
| 958 | } |
| 959 | if (ReturnType) { |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 960 | Signature.label += " -> "; |
| 961 | Signature.label += ReturnType; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 962 | } |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 963 | dlog("Signal for {0}: {1}", Signature, Signal); |
| 964 | ScoredSignature Result; |
| 965 | Result.Signature = std::move(Signature); |
| 966 | Result.Quality = Signal; |
| 967 | Result.IDForDoc = |
| 968 | Result.Signature.documentation.empty() && Candidate.getFunction() |
| 969 | ? clangd::getSymbolID(Candidate.getFunction()) |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 970 | : None; |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 971 | return Result; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 972 | } |
| 973 | |
| 974 | SignatureHelp &SigHelp; |
| 975 | std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator; |
| 976 | CodeCompletionTUInfo CCTUInfo; |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 977 | const SymbolIndex *Index; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 978 | }; // SignatureHelpCollector |
| 979 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 980 | struct SemaCompleteInput { |
| 981 | PathRef FileName; |
| 982 | const tooling::CompileCommand &Command; |
Eric Liu | b1d7542 | 2018-10-02 10:43:55 +0000 | [diff] [blame] | 983 | const PreambleData *Preamble; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 984 | llvm::StringRef Contents; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 985 | Position Pos; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 986 | llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 987 | std::shared_ptr<PCHContainerOperations> PCHs; |
| 988 | }; |
| 989 | |
| 990 | // Invokes Sema code completion on a file. |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 991 | // If \p Includes is set, it will be updated based on the compiler invocation. |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 992 | bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer, |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 993 | const clang::CodeCompleteOptions &Options, |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 994 | const SemaCompleteInput &Input, |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 995 | IncludeStructure *Includes = nullptr) { |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 996 | trace::Span Tracer("Sema completion"); |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 997 | llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = Input.VFS; |
Eric Liu | b1d7542 | 2018-10-02 10:43:55 +0000 | [diff] [blame] | 998 | if (Input.Preamble && Input.Preamble->StatCache) |
| 999 | VFS = Input.Preamble->StatCache->getConsumingFS(std::move(VFS)); |
Eric Liu | dd66277 | 2019-01-28 14:01:55 +0000 | [diff] [blame] | 1000 | ParseInputs ParseInput; |
| 1001 | ParseInput.CompileCommand = Input.Command; |
| 1002 | ParseInput.FS = VFS; |
| 1003 | ParseInput.Contents = Input.Contents; |
| 1004 | ParseInput.Opts = ParseOptions(); |
| 1005 | auto CI = buildCompilerInvocation(ParseInput); |
Ilya Biryukov | b6ad25c | 2018-02-09 13:51:57 +0000 | [diff] [blame] | 1006 | if (!CI) { |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 1007 | elog("Couldn't create CompilerInvocation"); |
Ilya Biryukov | b6ad25c | 2018-02-09 13:51:57 +0000 | [diff] [blame] | 1008 | return false; |
| 1009 | } |
Ilya Biryukov | 981a35d | 2018-05-28 12:11:37 +0000 | [diff] [blame] | 1010 | auto &FrontendOpts = CI->getFrontendOpts(); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1011 | FrontendOpts.SkipFunctionBodies = true; |
Ilya Biryukov | 981a35d | 2018-05-28 12:11:37 +0000 | [diff] [blame] | 1012 | // Disable typo correction in Sema. |
| 1013 | CI->getLangOpts()->SpellChecking = false; |
| 1014 | // Setup code completion. |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1015 | FrontendOpts.CodeCompleteOpts = Options; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1016 | FrontendOpts.CodeCompletionAt.FileName = Input.FileName; |
Sam McCall | a4962cc | 2018-04-27 11:59:28 +0000 | [diff] [blame] | 1017 | auto Offset = positionToOffset(Input.Contents, Input.Pos); |
| 1018 | if (!Offset) { |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 1019 | elog("Code completion position was invalid {0}", Offset.takeError()); |
Sam McCall | a4962cc | 2018-04-27 11:59:28 +0000 | [diff] [blame] | 1020 | return false; |
| 1021 | } |
| 1022 | std::tie(FrontendOpts.CodeCompletionAt.Line, |
| 1023 | FrontendOpts.CodeCompletionAt.Column) = |
| 1024 | offsetToClangLineColumn(Input.Contents, *Offset); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1025 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1026 | std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer = |
| 1027 | llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName); |
Ilya Biryukov | 981a35d | 2018-05-28 12:11:37 +0000 | [diff] [blame] | 1028 | // The diagnostic options must be set before creating a CompilerInstance. |
| 1029 | CI->getDiagnosticOpts().IgnoreWarnings = true; |
| 1030 | // We reuse the preamble whether it's valid or not. This is a |
| 1031 | // correctness/performance tradeoff: building without a preamble is slow, and |
| 1032 | // completion is latency-sensitive. |
Sam McCall | ebef812 | 2018-09-14 12:36:06 +0000 | [diff] [blame] | 1033 | // However, if we're completing *inside* the preamble section of the draft, |
| 1034 | // overriding the preamble will break sema completion. Fortunately we can just |
| 1035 | // skip all includes in this case; these completions are really simple. |
| 1036 | bool CompletingInPreamble = |
| 1037 | ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0).Size > |
| 1038 | *Offset; |
Ilya Biryukov | 981a35d | 2018-05-28 12:11:37 +0000 | [diff] [blame] | 1039 | // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise |
| 1040 | // the remapped buffers do not get freed. |
Kadir Cetinkaya | a65bcbf | 2019-01-22 09:58:53 +0000 | [diff] [blame] | 1041 | IgnoreDiagnostics DummyDiagsConsumer; |
Ilya Biryukov | 981a35d | 2018-05-28 12:11:37 +0000 | [diff] [blame] | 1042 | auto Clang = prepareCompilerInstance( |
Eric Liu | b1d7542 | 2018-10-02 10:43:55 +0000 | [diff] [blame] | 1043 | std::move(CI), |
| 1044 | (Input.Preamble && !CompletingInPreamble) ? &Input.Preamble->Preamble |
| 1045 | : nullptr, |
| 1046 | std::move(ContentsBuffer), std::move(Input.PCHs), std::move(VFS), |
Sam McCall | ebef812 | 2018-09-14 12:36:06 +0000 | [diff] [blame] | 1047 | DummyDiagsConsumer); |
| 1048 | Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble; |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1049 | Clang->setCodeCompletionConsumer(Consumer.release()); |
| 1050 | |
| 1051 | SyntaxOnlyAction Action; |
| 1052 | if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) { |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 1053 | log("BeginSourceFile() failed when running codeComplete for {0}", |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 1054 | Input.FileName); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1055 | return false; |
| 1056 | } |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 1057 | if (Includes) |
| 1058 | Clang->getPreprocessor().addPPCallbacks( |
| 1059 | collectIncludeStructureCallback(Clang->getSourceManager(), Includes)); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1060 | if (!Action.Execute()) { |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 1061 | log("Execute() failed when running codeComplete for {0}", Input.FileName); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1062 | return false; |
| 1063 | } |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1064 | Action.EndSourceFile(); |
| 1065 | |
| 1066 | return true; |
| 1067 | } |
| 1068 | |
Ilya Biryukov | a907ba4 | 2018-05-14 10:50:04 +0000 | [diff] [blame] | 1069 | // Should we allow index completions in the specified context? |
| 1070 | bool allowIndex(CodeCompletionContext &CC) { |
| 1071 | if (!contextAllowsIndex(CC.getKind())) |
| 1072 | return false; |
| 1073 | // We also avoid ClassName::bar (but allow namespace::bar). |
| 1074 | auto Scope = CC.getCXXScopeSpecifier(); |
| 1075 | if (!Scope) |
| 1076 | return true; |
| 1077 | NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep(); |
| 1078 | if (!NameSpec) |
| 1079 | return true; |
| 1080 | // We only query the index when qualifier is a namespace. |
| 1081 | // If it's a class, we rely solely on sema completions. |
| 1082 | switch (NameSpec->getKind()) { |
| 1083 | case NestedNameSpecifier::Global: |
| 1084 | case NestedNameSpecifier::Namespace: |
| 1085 | case NestedNameSpecifier::NamespaceAlias: |
| 1086 | return true; |
| 1087 | case NestedNameSpecifier::Super: |
| 1088 | case NestedNameSpecifier::TypeSpec: |
| 1089 | case NestedNameSpecifier::TypeSpecWithTemplate: |
| 1090 | // Unresolved inside a template. |
| 1091 | case NestedNameSpecifier::Identifier: |
| 1092 | return false; |
| 1093 | } |
Ilya Biryukov | a6556e2 | 2018-05-14 11:47:30 +0000 | [diff] [blame] | 1094 | llvm_unreachable("invalid NestedNameSpecifier kind"); |
Ilya Biryukov | a907ba4 | 2018-05-14 10:50:04 +0000 | [diff] [blame] | 1095 | } |
| 1096 | |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1097 | std::future<SymbolSlab> startAsyncFuzzyFind(const SymbolIndex &Index, |
| 1098 | const FuzzyFindRequest &Req) { |
| 1099 | return runAsync<SymbolSlab>([&Index, Req]() { |
| 1100 | trace::Span Tracer("Async fuzzyFind"); |
| 1101 | SymbolSlab::Builder Syms; |
| 1102 | Index.fuzzyFind(Req, [&Syms](const Symbol &Sym) { Syms.insert(Sym); }); |
| 1103 | return std::move(Syms).build(); |
| 1104 | }); |
| 1105 | } |
| 1106 | |
| 1107 | // Creates a `FuzzyFindRequest` based on the cached index request from the |
| 1108 | // last completion, if any, and the speculated completion filter text in the |
| 1109 | // source code. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1110 | llvm::Optional<FuzzyFindRequest> |
| 1111 | speculativeFuzzyFindRequestForCompletion(FuzzyFindRequest CachedReq, |
| 1112 | PathRef File, llvm::StringRef Content, |
| 1113 | Position Pos) { |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1114 | auto Filter = speculateCompletionFilter(Content, Pos); |
| 1115 | if (!Filter) { |
| 1116 | elog("Failed to speculate filter text for code completion at Pos " |
| 1117 | "{0}:{1}: {2}", |
| 1118 | Pos.line, Pos.character, Filter.takeError()); |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame] | 1119 | return None; |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1120 | } |
| 1121 | CachedReq.Query = *Filter; |
| 1122 | return CachedReq; |
| 1123 | } |
| 1124 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1125 | // Runs Sema-based (AST) and Index-based completion, returns merged results. |
| 1126 | // |
| 1127 | // There are a few tricky considerations: |
| 1128 | // - the AST provides information needed for the index query (e.g. which |
| 1129 | // namespaces to search in). So Sema must start first. |
| 1130 | // - we only want to return the top results (Opts.Limit). |
| 1131 | // Building CompletionItems for everything else is wasteful, so we want to |
| 1132 | // preserve the "native" format until we're done with scoring. |
| 1133 | // - the data underlying Sema completion items is owned by the AST and various |
| 1134 | // other arenas, which must stay alive for us to build CompletionItems. |
| 1135 | // - we may get duplicate results from Sema and the Index, we need to merge. |
| 1136 | // |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 1137 | // 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] | 1138 | // We use the Sema context information to query the index. |
| 1139 | // Then we merge the two result sets, producing items that are Sema/Index/Both. |
| 1140 | // These items are scored, and the top N are synthesized into the LSP response. |
| 1141 | // Finally, we can clean up the data structures created by Sema completion. |
| 1142 | // |
| 1143 | // Main collaborators are: |
| 1144 | // - semaCodeComplete sets up the compiler machinery to run code completion. |
| 1145 | // - CompletionRecorder captures Sema completion results, including context. |
| 1146 | // - SymbolIndex (Opts.Index) provides index completion results as Symbols |
| 1147 | // - CompletionCandidates are the result of merging Sema and Index results. |
| 1148 | // Each candidate points to an underlying CodeCompletionResult (Sema), a |
| 1149 | // Symbol (Index), or both. It computes the result quality score. |
| 1150 | // CompletionCandidate also does conversion to CompletionItem (at the end). |
| 1151 | // - FuzzyMatcher scores how the candidate matches the partial identifier. |
| 1152 | // This score is combined with the result quality score for the final score. |
| 1153 | // - TopN determines the results with the best score. |
| 1154 | class CodeCompleteFlow { |
Eric Liu | c5105f9 | 2018-02-16 14:15:55 +0000 | [diff] [blame] | 1155 | PathRef FileName; |
Ilya Biryukov | 22fa465 | 2019-01-03 13:28:05 +0000 | [diff] [blame] | 1156 | IncludeStructure Includes; // Complete once the compiler runs. |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1157 | SpeculativeFuzzyFind *SpecFuzzyFind; // Can be nullptr. |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1158 | const CodeCompleteOptions &Opts; |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1159 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1160 | // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup. |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 1161 | CompletionRecorder *Recorder = nullptr; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1162 | int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging. |
Ilya Biryukov | 22fa465 | 2019-01-03 13:28:05 +0000 | [diff] [blame] | 1163 | bool Incomplete = false; // Would more be available with a higher limit? |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1164 | llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs. |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 1165 | std::vector<std::string> QueryScopes; // Initialized once Sema runs. |
Eric Liu | 3fac4ef | 2018-10-17 11:19:02 +0000 | [diff] [blame] | 1166 | // Initialized once QueryScopes is initialized, if there are scopes. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1167 | llvm::Optional<ScopeDistance> ScopeProximity; |
Ilya Biryukov | 647da3e | 2018-11-26 15:38:01 +0000 | [diff] [blame] | 1168 | llvm::Optional<OpaqueType> PreferredType; // Initialized once Sema runs. |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 1169 | // Whether to query symbols from any scope. Initialized once Sema runs. |
| 1170 | bool AllScopes = false; |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 1171 | // Include-insertion and proximity scoring rely on the include structure. |
| 1172 | // This is available after Sema has run. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1173 | llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema. |
| 1174 | llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs. |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1175 | /// Speculative request based on the cached request and the filter text before |
| 1176 | /// the cursor. |
| 1177 | /// Initialized right before sema run. This is only set if `SpecFuzzyFind` is |
| 1178 | /// set and contains a cached request. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1179 | llvm::Optional<FuzzyFindRequest> SpecReq; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1180 | |
| 1181 | public: |
| 1182 | // A CodeCompleteFlow object is only useful for calling run() exactly once. |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 1183 | CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes, |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1184 | SpeculativeFuzzyFind *SpecFuzzyFind, |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 1185 | const CodeCompleteOptions &Opts) |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1186 | : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind), |
| 1187 | Opts(Opts) {} |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1188 | |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1189 | CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && { |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 1190 | trace::Span Tracer("CodeCompleteFlow"); |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1191 | if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq.hasValue()) { |
| 1192 | assert(!SpecFuzzyFind->Result.valid()); |
| 1193 | if ((SpecReq = speculativeFuzzyFindRequestForCompletion( |
| 1194 | *SpecFuzzyFind->CachedReq, SemaCCInput.FileName, |
| 1195 | SemaCCInput.Contents, SemaCCInput.Pos))) |
| 1196 | SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq); |
| 1197 | } |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 1198 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1199 | // We run Sema code completion first. It builds an AST and calculates: |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 1200 | // - completion results based on the AST. |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1201 | // - partial identifier and context. We need these for the index query. |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1202 | CodeCompleteResult Output; |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 1203 | auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() { |
| 1204 | assert(Recorder && "Recorder is not set"); |
Eric Liu | dd66277 | 2019-01-28 14:01:55 +0000 | [diff] [blame] | 1205 | auto Style = getFormatStyleForFile( |
| 1206 | SemaCCInput.FileName, SemaCCInput.Contents, SemaCCInput.VFS.get()); |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 1207 | // If preprocessor was run, inclusions from preprocessor callback should |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 1208 | // already be added to Includes. |
| 1209 | Inserter.emplace( |
Eric Liu | dd66277 | 2019-01-28 14:01:55 +0000 | [diff] [blame] | 1210 | SemaCCInput.FileName, SemaCCInput.Contents, Style, |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 1211 | SemaCCInput.Command.Directory, |
| 1212 | Recorder->CCSema->getPreprocessor().getHeaderSearchInfo()); |
| 1213 | for (const auto &Inc : Includes.MainFileIncludes) |
| 1214 | Inserter->addExisting(Inc); |
| 1215 | |
| 1216 | // Most of the cost of file proximity is in initializing the FileDistance |
| 1217 | // structures based on the observed includes, once per query. Conceptually |
| 1218 | // that happens here (though the per-URI-scheme initialization is lazy). |
| 1219 | // The per-result proximity scoring is (amortized) very cheap. |
| 1220 | FileDistanceOptions ProxOpts{}; // Use defaults. |
| 1221 | const auto &SM = Recorder->CCSema->getSourceManager(); |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1222 | llvm::StringMap<SourceParams> ProxSources; |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 1223 | for (auto &Entry : Includes.includeDepth( |
| 1224 | SM.getFileEntryForID(SM.getMainFileID())->getName())) { |
| 1225 | auto &Source = ProxSources[Entry.getKey()]; |
| 1226 | Source.Cost = Entry.getValue() * ProxOpts.IncludeCost; |
| 1227 | // Symbols near our transitive includes are good, but only consider |
| 1228 | // things in the same directory or below it. Otherwise there can be |
| 1229 | // many false positives. |
| 1230 | if (Entry.getValue() > 0) |
| 1231 | Source.MaxUpTraversals = 1; |
| 1232 | } |
| 1233 | FileProximity.emplace(ProxSources, ProxOpts); |
| 1234 | |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 1235 | Output = runWithSema(); |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 1236 | Inserter.reset(); // Make sure this doesn't out-live Clang. |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 1237 | SPAN_ATTACH(Tracer, "sema_completion_kind", |
| 1238 | getCompletionKindString(Recorder->CCContext.getKind())); |
Ilya Biryukov | 647da3e | 2018-11-26 15:38:01 +0000 | [diff] [blame] | 1239 | log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), " |
| 1240 | "expected type {3}", |
Eric Liu | bc25ef7 | 2018-07-05 08:29:33 +0000 | [diff] [blame] | 1241 | getCompletionKindString(Recorder->CCContext.getKind()), |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1242 | llvm::join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes, |
Ilya Biryukov | 647da3e | 2018-11-26 15:38:01 +0000 | [diff] [blame] | 1243 | PreferredType ? Recorder->CCContext.getPreferredType().getAsString() |
| 1244 | : "<none>"); |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 1245 | }); |
| 1246 | |
| 1247 | Recorder = RecorderOwner.get(); |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1248 | |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 1249 | semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(), |
Eric Liu | 63f419a | 2018-05-15 15:29:32 +0000 | [diff] [blame] | 1250 | SemaCCInput, &Includes); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1251 | |
Sam McCall | 2b78016 | 2018-01-30 17:20:54 +0000 | [diff] [blame] | 1252 | SPAN_ATTACH(Tracer, "sema_results", NSema); |
| 1253 | SPAN_ATTACH(Tracer, "index_results", NIndex); |
| 1254 | SPAN_ATTACH(Tracer, "merged_results", NBoth); |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 1255 | SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size())); |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1256 | SPAN_ATTACH(Tracer, "incomplete", Output.HasMore); |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 1257 | log("Code complete: {0} results from Sema, {1} from Index, " |
| 1258 | "{2} matched, {3} returned{4}.", |
| 1259 | NSema, NIndex, NBoth, Output.Completions.size(), |
| 1260 | Output.HasMore ? " (incomplete)" : ""); |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1261 | assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1262 | // We don't assert that isIncomplete means we hit a limit. |
| 1263 | // Indexes may choose to impose their own limits even if we don't have one. |
| 1264 | return Output; |
| 1265 | } |
| 1266 | |
| 1267 | private: |
| 1268 | // This is called by run() once Sema code completion is done, but before the |
| 1269 | // Sema data structures are torn down. It does all the real work. |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1270 | CodeCompleteResult runWithSema() { |
Kadir Cetinkaya | a9c9d00 | 2018-08-13 08:23:01 +0000 | [diff] [blame] | 1271 | const auto &CodeCompletionRange = CharSourceRange::getCharRange( |
| 1272 | Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange()); |
| 1273 | Range TextEditRange; |
| 1274 | // When we are getting completions with an empty identifier, for example |
| 1275 | // std::vector<int> asdf; |
| 1276 | // asdf.^; |
| 1277 | // Then the range will be invalid and we will be doing insertion, use |
| 1278 | // current cursor position in such cases as range. |
| 1279 | if (CodeCompletionRange.isValid()) { |
| 1280 | TextEditRange = halfOpenToRange(Recorder->CCSema->getSourceManager(), |
| 1281 | CodeCompletionRange); |
| 1282 | } else { |
| 1283 | const auto &Pos = sourceLocToPosition( |
| 1284 | Recorder->CCSema->getSourceManager(), |
| 1285 | Recorder->CCSema->getPreprocessor().getCodeCompletionLoc()); |
| 1286 | TextEditRange.start = TextEditRange.end = Pos; |
| 1287 | } |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1288 | Filter = FuzzyMatcher( |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 1289 | Recorder->CCSema->getPreprocessor().getCodeCompletionFilter()); |
Eric Liu | 3fac4ef | 2018-10-17 11:19:02 +0000 | [diff] [blame] | 1290 | std::tie(QueryScopes, AllScopes) = |
| 1291 | getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts); |
| 1292 | if (!QueryScopes.empty()) |
| 1293 | ScopeProximity.emplace(QueryScopes); |
Ilya Biryukov | 647da3e | 2018-11-26 15:38:01 +0000 | [diff] [blame] | 1294 | PreferredType = |
| 1295 | OpaqueType::fromType(Recorder->CCSema->getASTContext(), |
| 1296 | Recorder->CCContext.getPreferredType()); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1297 | // Sema provides the needed context to query the index. |
| 1298 | // FIXME: in addition to querying for extra/overlapping symbols, we should |
| 1299 | // explicitly request symbols corresponding to Sema results. |
| 1300 | // We can use their signals even if the index can't suggest them. |
| 1301 | // We must copy index results to preserve them, but there are at most Limit. |
Eric Liu | 8f3678d | 2018-06-15 13:34:18 +0000 | [diff] [blame] | 1302 | auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext)) |
| 1303 | ? queryIndex() |
| 1304 | : SymbolSlab(); |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1305 | trace::Span Tracer("Populate CodeCompleteResult"); |
Kadir Cetinkaya | b15b8dc | 2018-10-02 09:42:17 +0000 | [diff] [blame] | 1306 | // Merge Sema and Index results, score them, and pick the winners. |
| 1307 | auto Top = mergeResults(Recorder->Results, IndexResults); |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1308 | CodeCompleteResult Output; |
Kadir Cetinkaya | f8b85a3 | 2018-08-23 13:14:50 +0000 | [diff] [blame] | 1309 | |
| 1310 | // Convert the results to final form, assembling the expensive strings. |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1311 | for (auto &C : Top) { |
| 1312 | Output.Completions.push_back(toCodeCompletion(C.first)); |
| 1313 | Output.Completions.back().Score = C.second; |
Kadir Cetinkaya | a9c9d00 | 2018-08-13 08:23:01 +0000 | [diff] [blame] | 1314 | Output.Completions.back().CompletionTokenRange = TextEditRange; |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1315 | } |
| 1316 | Output.HasMore = Incomplete; |
Eric Liu | 5d2a807 | 2018-07-23 10:56:37 +0000 | [diff] [blame] | 1317 | Output.Context = Recorder->CCContext.getKind(); |
Kadir Cetinkaya | f8b85a3 | 2018-08-23 13:14:50 +0000 | [diff] [blame] | 1318 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1319 | return Output; |
| 1320 | } |
| 1321 | |
| 1322 | SymbolSlab queryIndex() { |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 1323 | trace::Span Tracer("Query index"); |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 1324 | SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit)); |
Sam McCall | 2b78016 | 2018-01-30 17:20:54 +0000 | [diff] [blame] | 1325 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1326 | // Build the query. |
| 1327 | FuzzyFindRequest Req; |
Haojian Wu | 48b4865 | 2018-01-25 09:20:09 +0000 | [diff] [blame] | 1328 | if (Opts.Limit) |
Kirill Bobyrev | e6dd080 | 2018-09-13 14:27:03 +0000 | [diff] [blame] | 1329 | Req.Limit = Opts.Limit; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1330 | Req.Query = Filter->pattern(); |
Marc-Andre Laperle | 945b5a3 | 2018-06-05 14:01:40 +0000 | [diff] [blame] | 1331 | Req.RestrictForCodeCompletion = true; |
Eric Liu | bc25ef7 | 2018-07-05 08:29:33 +0000 | [diff] [blame] | 1332 | Req.Scopes = QueryScopes; |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 1333 | Req.AnyScope = AllScopes; |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 1334 | // FIXME: we should send multiple weighted paths here. |
Eric Liu | 6de95ec | 2018-06-12 08:48:20 +0000 | [diff] [blame] | 1335 | Req.ProximityPaths.push_back(FileName); |
Kirill Bobyrev | 09f00dc | 2018-09-10 11:51:05 +0000 | [diff] [blame] | 1336 | vlog("Code complete: fuzzyFind({0:2})", toJSON(Req)); |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1337 | |
| 1338 | if (SpecFuzzyFind) |
| 1339 | SpecFuzzyFind->NewReq = Req; |
| 1340 | if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) { |
| 1341 | vlog("Code complete: speculative fuzzy request matches the actual index " |
| 1342 | "request. Waiting for the speculative index results."); |
| 1343 | SPAN_ATTACH(Tracer, "Speculative results", true); |
| 1344 | |
| 1345 | trace::Span WaitSpec("Wait speculative results"); |
| 1346 | return SpecFuzzyFind->Result.get(); |
| 1347 | } |
| 1348 | |
| 1349 | SPAN_ATTACH(Tracer, "Speculative results", false); |
| 1350 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1351 | // Run the query against the index. |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1352 | SymbolSlab::Builder ResultsBuilder; |
Sam McCall | ab8e393 | 2018-02-19 13:04:41 +0000 | [diff] [blame] | 1353 | if (Opts.Index->fuzzyFind( |
| 1354 | Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); })) |
| 1355 | Incomplete = true; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1356 | return std::move(ResultsBuilder).build(); |
| 1357 | } |
| 1358 | |
Kadir Cetinkaya | b15b8dc | 2018-10-02 09:42:17 +0000 | [diff] [blame] | 1359 | // Merges Sema and Index results where possible, to form CompletionCandidates. |
| 1360 | // Groups overloads if desired, to form CompletionCandidate::Bundles. The |
| 1361 | // bundles are scored and top results are returned, best to worst. |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 1362 | std::vector<ScoredBundle> |
Kadir Cetinkaya | f8b85a3 | 2018-08-23 13:14:50 +0000 | [diff] [blame] | 1363 | mergeResults(const std::vector<CodeCompletionResult> &SemaResults, |
Kadir Cetinkaya | b15b8dc | 2018-10-02 09:42:17 +0000 | [diff] [blame] | 1364 | const SymbolSlab &IndexResults) { |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 1365 | trace::Span Tracer("Merge and score results"); |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 1366 | std::vector<CompletionCandidate::Bundle> Bundles; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1367 | llvm::DenseMap<size_t, size_t> BundleLookup; |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 1368 | auto AddToBundles = [&](const CodeCompletionResult *SemaResult, |
Kadir Cetinkaya | b15b8dc | 2018-10-02 09:42:17 +0000 | [diff] [blame] | 1369 | const Symbol *IndexResult) { |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 1370 | CompletionCandidate C; |
| 1371 | C.SemaResult = SemaResult; |
| 1372 | C.IndexResult = IndexResult; |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 1373 | if (C.IndexResult) |
| 1374 | C.RankedIncludeHeaders = getRankedIncludes(*C.IndexResult); |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 1375 | C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult); |
| 1376 | if (auto OverloadSet = Opts.BundleOverloads ? C.overloadSet() : 0) { |
| 1377 | auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size()); |
| 1378 | if (Ret.second) |
| 1379 | Bundles.emplace_back(); |
| 1380 | Bundles[Ret.first->second].push_back(std::move(C)); |
| 1381 | } else { |
| 1382 | Bundles.emplace_back(); |
| 1383 | Bundles.back().push_back(std::move(C)); |
| 1384 | } |
| 1385 | }; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1386 | llvm::DenseSet<const Symbol *> UsedIndexResults; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1387 | auto CorrespondingIndexResult = |
| 1388 | [&](const CodeCompletionResult &SemaResult) -> const Symbol * { |
Eric Liu | d25f121 | 2018-09-06 09:59:37 +0000 | [diff] [blame] | 1389 | if (auto SymID = |
| 1390 | getSymbolID(SemaResult, Recorder->CCSema->getSourceManager())) { |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1391 | auto I = IndexResults.find(*SymID); |
| 1392 | if (I != IndexResults.end()) { |
| 1393 | UsedIndexResults.insert(&*I); |
| 1394 | return &*I; |
| 1395 | } |
| 1396 | } |
| 1397 | return nullptr; |
| 1398 | }; |
| 1399 | // Emit all Sema results, merging them with Index results if possible. |
Ilya Biryukov | ddf6a33 | 2018-03-02 12:28:27 +0000 | [diff] [blame] | 1400 | for (auto &SemaResult : Recorder->Results) |
Kadir Cetinkaya | b15b8dc | 2018-10-02 09:42:17 +0000 | [diff] [blame] | 1401 | AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult)); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1402 | // Now emit any Index-only results. |
| 1403 | for (const auto &IndexResult : IndexResults) { |
| 1404 | if (UsedIndexResults.count(&IndexResult)) |
| 1405 | continue; |
Kadir Cetinkaya | b15b8dc | 2018-10-02 09:42:17 +0000 | [diff] [blame] | 1406 | AddToBundles(/*SemaResult=*/nullptr, &IndexResult); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1407 | } |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 1408 | // We only keep the best N results at any time, in "native" format. |
| 1409 | TopN<ScoredBundle, ScoredBundleGreater> Top( |
| 1410 | Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit); |
| 1411 | for (auto &Bundle : Bundles) |
| 1412 | addCandidate(Top, std::move(Bundle)); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1413 | return std::move(Top).items(); |
| 1414 | } |
| 1415 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1416 | llvm::Optional<float> fuzzyScore(const CompletionCandidate &C) { |
Sam McCall | 80ad707 | 2018-06-08 13:32:25 +0000 | [diff] [blame] | 1417 | // Macros can be very spammy, so we only support prefix completion. |
| 1418 | // We won't end up with underfull index results, as macros are sema-only. |
| 1419 | if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro && |
| 1420 | !C.Name.startswith_lower(Filter->pattern())) |
| 1421 | return None; |
| 1422 | return Filter->match(C.Name); |
| 1423 | } |
| 1424 | |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1425 | // Scores a candidate and adds it to the TopN structure. |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 1426 | void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates, |
| 1427 | CompletionCandidate::Bundle Bundle) { |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 1428 | SymbolQualitySignals Quality; |
| 1429 | SymbolRelevanceSignals Relevance; |
Eric Liu | 5d2a807 | 2018-07-23 10:56:37 +0000 | [diff] [blame] | 1430 | Relevance.Context = Recorder->CCContext.getKind(); |
Sam McCall | d9b54f0 | 2018-06-05 16:30:25 +0000 | [diff] [blame] | 1431 | Relevance.Query = SymbolRelevanceSignals::CodeComplete; |
Sam McCall | f84dd02 | 2018-07-05 08:26:53 +0000 | [diff] [blame] | 1432 | Relevance.FileProximityMatch = FileProximity.getPointer(); |
Eric Liu | 3fac4ef | 2018-10-17 11:19:02 +0000 | [diff] [blame] | 1433 | if (ScopeProximity) |
| 1434 | Relevance.ScopeProximityMatch = ScopeProximity.getPointer(); |
Ilya Biryukov | 647da3e | 2018-11-26 15:38:01 +0000 | [diff] [blame] | 1435 | if (PreferredType) |
| 1436 | Relevance.HadContextType = true; |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 1437 | |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 1438 | auto &First = Bundle.front(); |
| 1439 | if (auto FuzzyScore = fuzzyScore(First)) |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 1440 | Relevance.NameMatch = *FuzzyScore; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1441 | else |
| 1442 | return; |
Sam McCall | 2161ec7 | 2018-07-05 06:20:41 +0000 | [diff] [blame] | 1443 | SymbolOrigin Origin = SymbolOrigin::Unknown; |
Sam McCall | 4e5742a | 2018-07-06 11:50:49 +0000 | [diff] [blame] | 1444 | bool FromIndex = false; |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 1445 | for (const auto &Candidate : Bundle) { |
| 1446 | if (Candidate.IndexResult) { |
| 1447 | Quality.merge(*Candidate.IndexResult); |
| 1448 | Relevance.merge(*Candidate.IndexResult); |
Sam McCall | 4e5742a | 2018-07-06 11:50:49 +0000 | [diff] [blame] | 1449 | Origin |= Candidate.IndexResult->Origin; |
| 1450 | FromIndex = true; |
Ilya Biryukov | 647da3e | 2018-11-26 15:38:01 +0000 | [diff] [blame] | 1451 | if (!Candidate.IndexResult->Type.empty()) |
| 1452 | Relevance.HadSymbolType |= true; |
| 1453 | if (PreferredType && |
| 1454 | PreferredType->raw() == Candidate.IndexResult->Type) { |
| 1455 | Relevance.TypeMatchesPreferred = true; |
| 1456 | } |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 1457 | } |
| 1458 | if (Candidate.SemaResult) { |
| 1459 | Quality.merge(*Candidate.SemaResult); |
| 1460 | Relevance.merge(*Candidate.SemaResult); |
Ilya Biryukov | 647da3e | 2018-11-26 15:38:01 +0000 | [diff] [blame] | 1461 | if (PreferredType) { |
| 1462 | if (auto CompletionType = OpaqueType::fromCompletionResult( |
| 1463 | Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) { |
| 1464 | Relevance.HadSymbolType |= true; |
| 1465 | if (PreferredType == CompletionType) |
| 1466 | Relevance.TypeMatchesPreferred = true; |
| 1467 | } |
| 1468 | } |
Sam McCall | 4e5742a | 2018-07-06 11:50:49 +0000 | [diff] [blame] | 1469 | Origin |= SymbolOrigin::AST; |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 1470 | } |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 1471 | } |
| 1472 | |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1473 | CodeCompletion::Scores Scores; |
| 1474 | Scores.Quality = Quality.evaluate(); |
| 1475 | Scores.Relevance = Relevance.evaluate(); |
| 1476 | Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance); |
| 1477 | // NameMatch is in fact a multiplier on total score, so rescoring is sound. |
| 1478 | Scores.ExcludingName = Relevance.NameMatch |
| 1479 | ? Scores.Total / Relevance.NameMatch |
| 1480 | : Scores.Quality; |
Sam McCall | c5707b6 | 2018-05-15 17:43:27 +0000 | [diff] [blame] | 1481 | |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 1482 | dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1483 | llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality), |
| 1484 | llvm::to_string(Relevance)); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1485 | |
Sam McCall | 2161ec7 | 2018-07-05 06:20:41 +0000 | [diff] [blame] | 1486 | NSema += bool(Origin & SymbolOrigin::AST); |
Sam McCall | 4e5742a | 2018-07-06 11:50:49 +0000 | [diff] [blame] | 1487 | NIndex += FromIndex; |
| 1488 | NBoth += bool(Origin & SymbolOrigin::AST) && FromIndex; |
Sam McCall | c18c280 | 2018-06-15 11:06:29 +0000 | [diff] [blame] | 1489 | if (Candidates.push({std::move(Bundle), Scores})) |
Sam McCall | ab8e393 | 2018-02-19 13:04:41 +0000 | [diff] [blame] | 1490 | Incomplete = true; |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1491 | } |
| 1492 | |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1493 | CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) { |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1494 | llvm::Optional<CodeCompletionBuilder> Builder; |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1495 | for (const auto &Item : Bundle) { |
| 1496 | CodeCompletionString *SemaCCS = |
| 1497 | Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult) |
| 1498 | : nullptr; |
| 1499 | if (!Builder) |
| 1500 | Builder.emplace(Recorder->CCSema->getASTContext(), Item, SemaCCS, |
Eric Liu | 670c147 | 2018-09-27 18:46:00 +0000 | [diff] [blame] | 1501 | QueryScopes, *Inserter, FileName, |
| 1502 | Recorder->CCContext.getKind(), Opts); |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1503 | else |
| 1504 | Builder->add(Item, SemaCCS); |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 1505 | } |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1506 | return Builder->build(); |
Sam McCall | 545a20d | 2018-01-19 14:34:02 +0000 | [diff] [blame] | 1507 | } |
| 1508 | }; |
| 1509 | |
Haojian Wu | 9ff5001 | 2019-01-03 15:36:18 +0000 | [diff] [blame] | 1510 | } // namespace |
| 1511 | |
| 1512 | clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const { |
| 1513 | clang::CodeCompleteOptions Result; |
| 1514 | Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns; |
| 1515 | Result.IncludeMacros = IncludeMacros; |
| 1516 | Result.IncludeGlobals = true; |
| 1517 | // We choose to include full comments and not do doxygen parsing in |
| 1518 | // completion. |
| 1519 | // FIXME: ideally, we should support doxygen in some form, e.g. do markdown |
| 1520 | // formatting of the comments. |
| 1521 | Result.IncludeBriefComments = false; |
| 1522 | |
| 1523 | // When an is used, Sema is responsible for completing the main file, |
| 1524 | // the index can provide results from the preamble. |
| 1525 | // Tell Sema not to deserialize the preamble to look for results. |
| 1526 | Result.LoadExternal = !Index; |
| 1527 | Result.IncludeFixIts = IncludeFixIts; |
| 1528 | |
| 1529 | return Result; |
| 1530 | } |
| 1531 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1532 | llvm::Expected<llvm::StringRef> |
| 1533 | speculateCompletionFilter(llvm::StringRef Content, Position Pos) { |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1534 | auto Offset = positionToOffset(Content, Pos); |
| 1535 | if (!Offset) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1536 | return llvm::make_error<llvm::StringError>( |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1537 | "Failed to convert position to offset in content.", |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1538 | llvm::inconvertibleErrorCode()); |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1539 | if (*Offset == 0) |
| 1540 | return ""; |
| 1541 | |
| 1542 | // Start from the character before the cursor. |
| 1543 | int St = *Offset - 1; |
| 1544 | // FIXME(ioeric): consider UTF characters? |
Haojian Wu | aa3ed5a | 2019-01-25 15:14:03 +0000 | [diff] [blame] | 1545 | auto IsValidIdentifierChar = [](char C) { |
| 1546 | return ((C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z') || |
| 1547 | (C >= '0' && C <= '9') || (C == '_')); |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1548 | }; |
| 1549 | size_t Len = 0; |
| 1550 | for (; (St >= 0) && IsValidIdentifierChar(Content[St]); --St, ++Len) { |
| 1551 | } |
| 1552 | if (Len > 0) |
| 1553 | St++; // Shift to the first valid character. |
| 1554 | return Content.substr(St, Len); |
| 1555 | } |
| 1556 | |
| 1557 | CodeCompleteResult |
| 1558 | codeComplete(PathRef FileName, const tooling::CompileCommand &Command, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1559 | const PreambleData *Preamble, llvm::StringRef Contents, |
| 1560 | Position Pos, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, |
Eric Liu | 25d74e9 | 2018-08-24 11:23:56 +0000 | [diff] [blame] | 1561 | std::shared_ptr<PCHContainerOperations> PCHs, |
| 1562 | CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind) { |
Eric Liu | b1d7542 | 2018-10-02 10:43:55 +0000 | [diff] [blame] | 1563 | return CodeCompleteFlow(FileName, |
| 1564 | Preamble ? Preamble->Includes : IncludeStructure(), |
| 1565 | SpecFuzzyFind, Opts) |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 1566 | .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs}); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1567 | } |
| 1568 | |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 1569 | SignatureHelp signatureHelp(PathRef FileName, |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 1570 | const tooling::CompileCommand &Command, |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1571 | const PreambleData *Preamble, |
| 1572 | llvm::StringRef Contents, Position Pos, |
| 1573 | llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 1574 | std::shared_ptr<PCHContainerOperations> PCHs, |
Sam McCall | 046557b | 2018-09-03 16:37:59 +0000 | [diff] [blame] | 1575 | const SymbolIndex *Index) { |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1576 | SignatureHelp Result; |
| 1577 | clang::CodeCompleteOptions Options; |
| 1578 | Options.IncludeGlobals = false; |
| 1579 | Options.IncludeMacros = false; |
| 1580 | Options.IncludeCodePatterns = false; |
Ilya Biryukov | 4371450 | 2018-05-16 12:32:44 +0000 | [diff] [blame] | 1581 | Options.IncludeBriefComments = false; |
Sam McCall | 3f0243f | 2018-07-03 08:09:29 +0000 | [diff] [blame] | 1582 | IncludeStructure PreambleInclusions; // Unused for signatureHelp |
Ilya Biryukov | 8a0f76b | 2018-08-17 09:32:30 +0000 | [diff] [blame] | 1583 | semaCodeComplete( |
| 1584 | llvm::make_unique<SignatureHelpCollector>(Options, Index, Result), |
| 1585 | Options, |
| 1586 | {FileName, Command, Preamble, Contents, Pos, std::move(VFS), |
| 1587 | std::move(PCHs)}); |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1588 | return Result; |
| 1589 | } |
| 1590 | |
Marc-Andre Laperle | 945b5a3 | 2018-06-05 14:01:40 +0000 | [diff] [blame] | 1591 | bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) { |
Haojian Wu | dd61ccb | 2018-12-03 12:53:19 +0000 | [diff] [blame] | 1592 | auto InTopLevelScope = [](const NamedDecl &ND) { |
| 1593 | switch (ND.getDeclContext()->getDeclKind()) { |
| 1594 | case Decl::TranslationUnit: |
| 1595 | case Decl::Namespace: |
| 1596 | case Decl::LinkageSpec: |
| 1597 | return true; |
| 1598 | default: |
| 1599 | break; |
| 1600 | }; |
| 1601 | return false; |
| 1602 | }; |
| 1603 | if (InTopLevelScope(ND)) |
| 1604 | return true; |
| 1605 | |
| 1606 | if (const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext())) |
| 1607 | return InTopLevelScope(*EnumDecl) && !EnumDecl->isScoped(); |
| 1608 | |
| 1609 | return false; |
Marc-Andre Laperle | 945b5a3 | 2018-06-05 14:01:40 +0000 | [diff] [blame] | 1610 | } |
| 1611 | |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1612 | CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const { |
| 1613 | CompletionItem LSP; |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 1614 | const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0]; |
| 1615 | LSP.label = ((InsertInclude && InsertInclude->Insertion) |
| 1616 | ? Opts.IncludeIndicator.Insert |
| 1617 | : Opts.IncludeIndicator.NoInsert) + |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1618 | (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") + |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1619 | RequiredQualifier + Name + Signature; |
Sam McCall | 2161ec7 | 2018-07-05 06:20:41 +0000 | [diff] [blame] | 1620 | |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1621 | LSP.kind = Kind; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1622 | LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize) |
| 1623 | : ReturnType; |
Eric Liu | 6df6600 | 2018-09-06 18:52:26 +0000 | [diff] [blame] | 1624 | LSP.deprecated = Deprecated; |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 1625 | if (InsertInclude) |
| 1626 | LSP.detail += "\n" + InsertInclude->Header; |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1627 | LSP.documentation = Documentation; |
| 1628 | LSP.sortText = sortText(Score.Total, Name); |
| 1629 | LSP.filterText = Name; |
Kadir Cetinkaya | a9c9d00 | 2018-08-13 08:23:01 +0000 | [diff] [blame] | 1630 | LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name}; |
Fangrui Song | 445bdd1 | 2018-09-05 08:01:37 +0000 | [diff] [blame] | 1631 | // Merge continuous additionalTextEdits into main edit. The main motivation |
Kadir Cetinkaya | a9c9d00 | 2018-08-13 08:23:01 +0000 | [diff] [blame] | 1632 | // behind this is to help LSP clients, it seems most of them are confused when |
| 1633 | // they are provided with additionalTextEdits that are consecutive to main |
| 1634 | // edit. |
| 1635 | // Note that we store additional text edits from back to front in a line. That |
| 1636 | // is mainly to help LSP clients again, so that changes do not effect each |
| 1637 | // other. |
| 1638 | for (const auto &FixIt : FixIts) { |
Haojian Wu | aa3ed5a | 2019-01-25 15:14:03 +0000 | [diff] [blame] | 1639 | if (isRangeConsecutive(FixIt.range, LSP.textEdit->range)) { |
Kadir Cetinkaya | a9c9d00 | 2018-08-13 08:23:01 +0000 | [diff] [blame] | 1640 | LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText; |
| 1641 | LSP.textEdit->range.start = FixIt.range.start; |
| 1642 | } else { |
| 1643 | LSP.additionalTextEdits.push_back(FixIt); |
| 1644 | } |
| 1645 | } |
Kadir Cetinkaya | 516fcda | 2018-08-23 12:19:39 +0000 | [diff] [blame] | 1646 | if (Opts.EnableSnippets) |
| 1647 | LSP.textEdit->newText += SnippetSuffix; |
Kadir Cetinkaya | 6c9f15c | 2018-08-17 15:42:54 +0000 | [diff] [blame] | 1648 | |
Kadir Cetinkaya | a9c9d00 | 2018-08-13 08:23:01 +0000 | [diff] [blame] | 1649 | // FIXME(kadircet): Do not even fill insertText after making sure textEdit is |
| 1650 | // compatible with most of the editors. |
| 1651 | LSP.insertText = LSP.textEdit->newText; |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1652 | LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet |
| 1653 | : InsertTextFormat::PlainText; |
Eric Liu | 83f63e4 | 2018-09-03 10:18:21 +0000 | [diff] [blame] | 1654 | if (InsertInclude && InsertInclude->Insertion) |
| 1655 | LSP.additionalTextEdits.push_back(*InsertInclude->Insertion); |
Eric Liu | 6df6600 | 2018-09-06 18:52:26 +0000 | [diff] [blame] | 1656 | |
Sam McCall | 27c979a | 2018-06-29 14:47:57 +0000 | [diff] [blame] | 1657 | return LSP; |
| 1658 | } |
| 1659 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1660 | llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const CodeCompletion &C) { |
Sam McCall | e746a2b | 2018-07-02 11:13:16 +0000 | [diff] [blame] | 1661 | // For now just lean on CompletionItem. |
| 1662 | return OS << C.render(CodeCompleteOptions()); |
| 1663 | } |
| 1664 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 1665 | llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, |
| 1666 | const CodeCompleteResult &R) { |
Sam McCall | e746a2b | 2018-07-02 11:13:16 +0000 | [diff] [blame] | 1667 | OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "") |
Eric Liu | 5d2a807 | 2018-07-23 10:56:37 +0000 | [diff] [blame] | 1668 | << " (" << getCompletionKindString(R.Context) << ")" |
Sam McCall | e746a2b | 2018-07-02 11:13:16 +0000 | [diff] [blame] | 1669 | << " items:\n"; |
| 1670 | for (const auto &C : R.Completions) |
| 1671 | OS << C << "\n"; |
| 1672 | return OS; |
| 1673 | } |
| 1674 | |
Sam McCall | 98775c5 | 2017-12-04 13:49:59 +0000 | [diff] [blame] | 1675 | } // namespace clangd |
| 1676 | } // namespace clang |