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