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