clang-tools 23.0.0git
CodeComplete.cpp
Go to the documentation of this file.
1//===--- CodeComplete.cpp ----------------------------------------*- C++-*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Code completion has several moving parts:
10// - AST-based completions are provided using the completion hooks in Sema.
11// - external completions are retrieved from the index (using hints from Sema)
12// - the two sources overlap, and must be merged and overloads bundled
13// - results must be scored and ranked (see Quality.h) before rendering
14//
15// Signature help works in a similar way as code completion, but it is simpler:
16// it's purely AST-based, and there are few candidates.
17//
18//===----------------------------------------------------------------------===//
19
20#include "CodeComplete.h"
21#include "AST.h"
23#include "Compiler.h"
24#include "Config.h"
25#include "ExpectedTypes.h"
26#include "Feature.h"
27#include "FileDistance.h"
28#include "FuzzyMatch.h"
29#include "Headers.h"
30#include "Hover.h"
31#include "Preamble.h"
32#include "Protocol.h"
33#include "Quality.h"
34#include "SourceCode.h"
35#include "URI.h"
36#include "index/Index.h"
37#include "index/Symbol.h"
38#include "index/SymbolOrigin.h"
39#include "support/Logger.h"
40#include "support/Markup.h"
41#include "support/Threading.h"
43#include "support/Trace.h"
44#include "clang/AST/Decl.h"
45#include "clang/AST/DeclBase.h"
46#include "clang/AST/DeclTemplate.h"
47#include "clang/Basic/CharInfo.h"
48#include "clang/Basic/LangOptions.h"
49#include "clang/Basic/SourceLocation.h"
50#include "clang/Basic/TokenKinds.h"
51#include "clang/Format/Format.h"
52#include "clang/Frontend/CompilerInstance.h"
53#include "clang/Frontend/FrontendActions.h"
54#include "clang/Lex/ExternalPreprocessorSource.h"
55#include "clang/Lex/Lexer.h"
56#include "clang/Lex/Preprocessor.h"
57#include "clang/Lex/PreprocessorOptions.h"
58#include "clang/Sema/CodeCompleteConsumer.h"
59#include "clang/Sema/DeclSpec.h"
60#include "clang/Sema/Sema.h"
61#include "llvm/ADT/ArrayRef.h"
62#include "llvm/ADT/SmallVector.h"
63#include "llvm/ADT/StringExtras.h"
64#include "llvm/ADT/StringRef.h"
65#include "llvm/Support/Casting.h"
66#include "llvm/Support/Compiler.h"
67#include "llvm/Support/Debug.h"
68#include "llvm/Support/Error.h"
69#include "llvm/Support/FormatVariadic.h"
70#include "llvm/Support/ScopedPrinter.h"
71#include <algorithm>
72#include <iterator>
73#include <limits>
74#include <optional>
75#include <utility>
76
77// We log detailed candidate here if you run with -debug-only=codecomplete.
78#define DEBUG_TYPE "CodeComplete"
79
80namespace clang {
81namespace clangd {
82
83#if CLANGD_DECISION_FOREST
84const CodeCompleteOptions::CodeCompletionRankingModel
85 CodeCompleteOptions::DefaultRankingModel =
86 CodeCompleteOptions::DecisionForest;
87#else
88const CodeCompleteOptions::CodeCompletionRankingModel
89 CodeCompleteOptions::DefaultRankingModel = CodeCompleteOptions::Heuristics;
90#endif
91
92namespace {
93
94// Note: changes to this function should also be reflected in the
95// CodeCompletionResult overload where appropriate.
96CompletionItemKind
97toCompletionItemKind(index::SymbolKind Kind,
98 const llvm::StringRef *Signature = nullptr) {
99 using SK = index::SymbolKind;
100 switch (Kind) {
101 // FIXME: for backwards compatibility, the include directive kind is treated
102 // the same as Unknown
103 case SK::IncludeDirective:
104 case SK::Unknown:
106 case SK::Module:
107 case SK::Namespace:
108 case SK::NamespaceAlias:
110 case SK::Macro:
111 // Use macro signature (if provided) to tell apart function-like and
112 // object-like macros.
113 return Signature && Signature->contains('(') ? CompletionItemKind::Function
115 case SK::Enum:
117 case SK::Struct:
119 case SK::Class:
120 case SK::Extension:
121 case SK::Union:
123 case SK::Protocol:
124 // Use interface instead of class for differentiation of classes and
125 // protocols with the same name (e.g. @interface NSObject vs. @protocol
126 // NSObject).
128 case SK::TypeAlias:
129 // We use the same kind as the VSCode C++ extension.
130 // FIXME: pick a better option when we have one.
132 case SK::Using:
134 case SK::Function:
135 case SK::ConversionFunction:
137 case SK::Variable:
138 case SK::Parameter:
139 case SK::NonTypeTemplateParm:
141 case SK::Field:
143 case SK::EnumConstant:
145 case SK::InstanceMethod:
146 case SK::ClassMethod:
147 case SK::StaticMethod:
148 case SK::Destructor:
150 case SK::InstanceProperty:
151 case SK::ClassProperty:
152 case SK::StaticProperty:
154 case SK::Constructor:
156 case SK::TemplateTypeParm:
157 case SK::TemplateTemplateParm:
159 case SK::Concept:
161 }
162 llvm_unreachable("Unhandled clang::index::SymbolKind.");
163}
164
165// Note: changes to this function should also be reflected in the
166// index::SymbolKind overload where appropriate.
167CompletionItemKind toCompletionItemKind(const CodeCompletionResult &Res,
168 CodeCompletionContext::Kind CtxKind) {
169 if (Res.Declaration)
170 return toCompletionItemKind(index::getSymbolInfo(Res.Declaration).Kind);
171 if (CtxKind == CodeCompletionContext::CCC_IncludedFile)
173 switch (Res.Kind) {
174 case CodeCompletionResult::RK_Declaration:
175 llvm_unreachable("RK_Declaration without Decl");
176 case CodeCompletionResult::RK_Keyword:
178 case CodeCompletionResult::RK_Macro:
179 // There is no 'Macro' kind in LSP.
180 // Avoid using 'Text' to avoid confusion with client-side word-based
181 // completion proposals.
182 return Res.MacroDefInfo && Res.MacroDefInfo->isFunctionLike()
185 case CodeCompletionResult::RK_Pattern:
187 }
188 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
189}
190
191// FIXME: find a home for this (that can depend on both markup and Protocol).
192MarkupContent renderDoc(const markup::Document &Doc, MarkupKind Kind) {
193 MarkupContent Result;
194 Result.kind = Kind;
195 switch (Kind) {
197 Result.value.append(Doc.asPlainText());
198 break;
200 if (Config::current().Documentation.CommentFormat ==
202 Result.value.append(Doc.asEscapedMarkdown());
203 else
204 Result.value.append(Doc.asMarkdown());
205 break;
206 }
207 return Result;
208}
209
210Symbol::IncludeDirective insertionDirective(const CodeCompleteOptions &Opts) {
211 if (!Opts.ImportInsertions || !Opts.MainFileSignals)
213 return Opts.MainFileSignals->InsertionDirective;
214}
215
216// Identifier code completion result.
217struct RawIdentifier {
218 llvm::StringRef Name;
219 unsigned References; // # of usages in file.
220};
221
222/// A code completion result, in clang-native form.
223/// It may be promoted to a CompletionItem if it's among the top-ranked results.
224struct CompletionCandidate {
225 llvm::StringRef Name; // Used for filtering and sorting.
226 // We may have a result from Sema, from the index, or both.
227 const CodeCompletionResult *SemaResult = nullptr;
228 const Symbol *IndexResult = nullptr;
229 const RawIdentifier *IdentifierResult = nullptr;
230 llvm::SmallVector<SymbolInclude, 1> RankedIncludeHeaders;
231
232 // Returns a token identifying the overload set this is part of.
233 // 0 indicates it's not part of any overload set.
234 size_t overloadSet(const CodeCompleteOptions &Opts, llvm::StringRef FileName,
235 IncludeInserter *Inserter,
236 CodeCompletionContext::Kind CCContextKind) const {
237 if (!Opts.BundleOverloads.value_or(false))
238 return 0;
239
240 // Depending on the index implementation, we can see different header
241 // strings (literal or URI) mapping to the same file. We still want to
242 // bundle those, so we must resolve the header to be included here.
243 std::string HeaderForHash;
244 if (Inserter) {
245 if (auto Header = headerToInsertIfAllowed(Opts, CCContextKind)) {
246 if (auto HeaderFile = toHeaderFile(*Header, FileName)) {
247 if (auto Spelled =
248 Inserter->calculateIncludePath(*HeaderFile, FileName))
249 HeaderForHash = *Spelled;
250 } else {
251 vlog("Code completion header path manipulation failed {0}",
252 HeaderFile.takeError());
253 }
254 }
255 }
256
257 llvm::SmallString<256> Scratch;
258 if (IndexResult) {
259 switch (IndexResult->SymInfo.Kind) {
260 case index::SymbolKind::ClassMethod:
261 case index::SymbolKind::InstanceMethod:
262 case index::SymbolKind::StaticMethod:
263#ifndef NDEBUG
264 llvm_unreachable("Don't expect members from index in code completion");
265#else
266 [[fallthrough]];
267#endif
268 case index::SymbolKind::Function:
269 // We can't group overloads together that need different #includes.
270 // This could break #include insertion.
271 return llvm::hash_combine(
272 (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
273 HeaderForHash);
274 default:
275 return 0;
276 }
277 }
278 if (SemaResult) {
279 // We need to make sure we're consistent with the IndexResult case!
280 const NamedDecl *D = SemaResult->Declaration;
281 if (!D || !D->isFunctionOrFunctionTemplate())
282 return 0;
283 {
284 llvm::raw_svector_ostream OS(Scratch);
285 D->printQualifiedName(OS);
286 }
287 return llvm::hash_combine(Scratch, HeaderForHash);
288 }
289 assert(IdentifierResult);
290 return 0;
291 }
292
293 bool contextAllowsHeaderInsertion(CodeCompletionContext::Kind Kind) const {
294 // Explicitly disable insertions for forward declarations since they don't
295 // reference the declaration.
296 if (Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
297 return false;
298 return true;
299 }
300
301 // The best header to include if include insertion is allowed.
302 std::optional<llvm::StringRef>
303 headerToInsertIfAllowed(const CodeCompleteOptions &Opts,
304 CodeCompletionContext::Kind ContextKind) const {
305 if (Opts.InsertIncludes == Config::HeaderInsertionPolicy::NeverInsert ||
306 RankedIncludeHeaders.empty() ||
307 !contextAllowsHeaderInsertion(ContextKind))
308 return std::nullopt;
309 if (SemaResult && SemaResult->Declaration) {
310 // Avoid inserting new #include if the declaration is found in the current
311 // file e.g. the symbol is forward declared.
312 auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
313 for (const Decl *RD : SemaResult->Declaration->redecls())
314 if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
315 return std::nullopt;
316 }
317 Symbol::IncludeDirective Directive = insertionDirective(Opts);
318 for (const auto &Inc : RankedIncludeHeaders)
319 if ((Inc.Directive & Directive) != 0)
320 return Inc.Header;
321 return std::nullopt;
322 }
323
324 using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
325};
326using ScoredBundle =
327 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
328struct ScoredBundleGreater {
329 bool operator()(const ScoredBundle &L, const ScoredBundle &R) {
330 if (L.second.Total != R.second.Total)
331 return L.second.Total > R.second.Total;
332 return L.first.front().Name <
333 R.first.front().Name; // Earlier name is better.
334 }
335};
336
337// Remove the first template argument from Signature.
338// If Signature only contains a single argument an empty string is returned.
339std::string removeFirstTemplateArg(llvm::StringRef Signature) {
340 auto Rest = Signature.split(",").second;
341 if (Rest.empty())
342 return "";
343 return ("<" + Rest.ltrim()).str();
344}
345
346// Assembles a code completion out of a bundle of >=1 completion candidates.
347// Many of the expensive strings are only computed at this point, once we know
348// the candidate bundle is going to be returned.
349//
350// Many fields are the same for all candidates in a bundle (e.g. name), and are
351// computed from the first candidate, in the constructor.
352// Others vary per candidate, so add() must be called for remaining candidates.
353struct CodeCompletionBuilder {
354 CodeCompletionBuilder(ASTContext *ASTCtx, const CompletionCandidate &C,
355 CodeCompletionString *SemaCCS,
356 llvm::ArrayRef<std::string> AccessibleScopes,
357 const IncludeInserter &Includes,
358 llvm::StringRef FileName,
359 CodeCompletionContext::Kind ContextKind,
360 const CodeCompleteOptions &Opts,
361 bool IsUsingDeclaration, tok::TokenKind NextTokenKind)
362 : ASTCtx(ASTCtx), ArgumentLists(Opts.ArgumentLists),
363 IsUsingDeclaration(IsUsingDeclaration), NextTokenKind(NextTokenKind) {
364 Completion.Deprecated = true; // cleared by any non-deprecated overload.
365 add(C, SemaCCS, ContextKind);
366 if (C.SemaResult) {
367 assert(ASTCtx);
368 Completion.Origin |= SymbolOrigin::AST;
369 Completion.Name = std::string(llvm::StringRef(SemaCCS->getTypedText()));
370 Completion.FilterText = SemaCCS->getAllTypedText();
371 if (Completion.Scope.empty()) {
372 if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
373 (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
374 if (const auto *D = C.SemaResult->getDeclaration())
375 if (const auto *ND = dyn_cast<NamedDecl>(D))
376 Completion.Scope = std::string(
378 }
379 Completion.Kind = toCompletionItemKind(*C.SemaResult, ContextKind);
380 // Sema could provide more info on whether the completion was a file or
381 // folder.
382 if (Completion.Kind == CompletionItemKind::File &&
383 Completion.Name.back() == '/')
384 Completion.Kind = CompletionItemKind::Folder;
385 for (const auto &FixIt : C.SemaResult->FixIts) {
386 Completion.FixIts.push_back(toTextEdit(
387 FixIt, ASTCtx->getSourceManager(), ASTCtx->getLangOpts()));
388 }
389 llvm::sort(Completion.FixIts, [](const TextEdit &X, const TextEdit &Y) {
390 return std::tie(X.range.start.line, X.range.start.character) <
391 std::tie(Y.range.start.line, Y.range.start.character);
392 });
393 }
394 if (C.IndexResult) {
395 Completion.Origin |= C.IndexResult->Origin;
396 if (Completion.Scope.empty())
397 Completion.Scope = std::string(C.IndexResult->Scope);
398 if (Completion.Kind == CompletionItemKind::Missing)
399 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind,
400 &C.IndexResult->Signature);
401 if (Completion.Name.empty())
402 Completion.Name = std::string(C.IndexResult->Name);
403 if (Completion.FilterText.empty())
404 Completion.FilterText = Completion.Name;
405 // If the completion was visible to Sema, no qualifier is needed. This
406 // avoids unneeded qualifiers in cases like with `using ns::X`.
407 if (Completion.RequiredQualifier.empty() && !C.SemaResult) {
408 llvm::StringRef ShortestQualifier = C.IndexResult->Scope;
409 for (llvm::StringRef Scope : AccessibleScopes) {
410 llvm::StringRef Qualifier = C.IndexResult->Scope;
411 if (Qualifier.consume_front(Scope) &&
412 Qualifier.size() < ShortestQualifier.size())
413 ShortestQualifier = Qualifier;
414 }
415 Completion.RequiredQualifier = std::string(ShortestQualifier);
416 }
417 }
418 if (C.IdentifierResult) {
419 Completion.Origin |= SymbolOrigin::Identifier;
420 Completion.Kind = CompletionItemKind::Text;
421 Completion.Name = std::string(C.IdentifierResult->Name);
422 Completion.FilterText = Completion.Name;
423 }
424
425 // Turn absolute path into a literal string that can be #included.
426 auto Inserted = [&](llvm::StringRef Header)
427 -> llvm::Expected<std::pair<std::string, bool>> {
428 auto ResolvedDeclaring =
429 URI::resolve(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
430 if (!ResolvedDeclaring)
431 return ResolvedDeclaring.takeError();
432 auto ResolvedInserted = toHeaderFile(Header, FileName);
433 if (!ResolvedInserted)
434 return ResolvedInserted.takeError();
435 auto Spelled = Includes.calculateIncludePath(*ResolvedInserted, FileName);
436 if (!Spelled)
437 return error("Header not on include path");
438 return std::make_pair(
439 std::move(*Spelled),
440 Includes.shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted));
441 };
442 bool ShouldInsert =
443 C.headerToInsertIfAllowed(Opts, ContextKind).has_value();
444 Symbol::IncludeDirective Directive = insertionDirective(Opts);
445 // Calculate include paths and edits for all possible headers.
446 for (const auto &Inc : C.RankedIncludeHeaders) {
447 if ((Inc.Directive & Directive) == 0)
448 continue;
449
450 if (auto ToInclude = Inserted(Inc.Header)) {
451 CodeCompletion::IncludeCandidate Include;
452 Include.Header = ToInclude->first;
453 if (ToInclude->second && ShouldInsert)
454 Include.Insertion = Includes.insert(
455 ToInclude->first, Directive == Symbol::Import
456 ? tooling::IncludeDirective::Import
457 : tooling::IncludeDirective::Include);
458 Completion.Includes.push_back(std::move(Include));
459 } else
460 log("Failed to generate include insertion edits for adding header "
461 "(FileURI='{0}', IncludeHeader='{1}') into {2}: {3}",
462 C.IndexResult->CanonicalDeclaration.FileURI, Inc.Header, FileName,
463 ToInclude.takeError());
464 }
465 // Prefer includes that do not need edits (i.e. already exist).
466 std::stable_partition(Completion.Includes.begin(),
467 Completion.Includes.end(),
468 [](const CodeCompletion::IncludeCandidate &I) {
469 return !I.Insertion.has_value();
470 });
471 }
472
473 void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS,
474 CodeCompletionContext::Kind ContextKind) {
475 assert(bool(C.SemaResult) == bool(SemaCCS));
476 Bundled.emplace_back();
477 BundledEntry &S = Bundled.back();
478 bool IsConcept = false;
479 if (C.SemaResult) {
480 getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix, C.SemaResult->Kind,
481 C.SemaResult->CursorKind,
482 /*IncludeFunctionArguments=*/C.SemaResult->FunctionCanBeCall,
483 /*RequiredQualifiers=*/&Completion.RequiredQualifier);
484 S.ReturnType = getReturnType(*SemaCCS);
485 if (C.SemaResult->Kind == CodeCompletionResult::RK_Declaration)
486 if (const auto *D = C.SemaResult->getDeclaration())
487 if (isa<ConceptDecl>(D))
488 IsConcept = true;
489 } else if (C.IndexResult) {
490 S.Signature = std::string(C.IndexResult->Signature);
491 S.SnippetSuffix = std::string(C.IndexResult->CompletionSnippetSuffix);
492 S.ReturnType = std::string(C.IndexResult->ReturnType);
493 if (C.IndexResult->SymInfo.Kind == index::SymbolKind::Concept)
494 IsConcept = true;
495 }
496
497 /// When a concept is used as a type-constraint (e.g. `Iterator auto x`),
498 /// and in some other contexts, its first type argument is not written.
499 /// Drop the parameter from the signature.
500 if (IsConcept && ContextKind == CodeCompletionContext::CCC_TopLevel) {
501 S.Signature = removeFirstTemplateArg(S.Signature);
502 // Dropping the first placeholder from the suffix will leave a $2
503 // with no $1.
504 S.SnippetSuffix = removeFirstTemplateArg(S.SnippetSuffix);
505 }
506
507 if (!Completion.Documentation) {
508 auto SetDoc = [&](llvm::StringRef Doc) {
509 if (!Doc.empty()) {
510 Completion.Documentation.emplace();
511 parseDocumentation(Doc, *Completion.Documentation);
512 }
513 };
514 if (C.IndexResult) {
515 SetDoc(C.IndexResult->Documentation);
516 } else if (C.SemaResult) {
517 const auto DocComment = getDocComment(*ASTCtx, *C.SemaResult,
518 /*CommentsFromHeaders=*/false);
519 SetDoc(formatDocumentation(*SemaCCS, DocComment));
520 }
521 }
522 if (Completion.Deprecated) {
523 if (C.SemaResult)
524 Completion.Deprecated &=
525 C.SemaResult->Availability == CXAvailability_Deprecated;
526 if (C.IndexResult)
527 Completion.Deprecated &=
528 bool(C.IndexResult->Flags & Symbol::Deprecated);
529 }
530 }
531
532 CodeCompletion build() {
533 Completion.ReturnType = summarizeReturnType();
534 Completion.Signature = summarizeSignature();
535 Completion.SnippetSuffix = summarizeSnippet();
536 Completion.BundleSize = Bundled.size();
537 return std::move(Completion);
538 }
539
540private:
541 struct BundledEntry {
542 std::string SnippetSuffix;
543 std::string Signature;
544 std::string ReturnType;
545 };
546
547 // If all BundledEntries have the same value for a property, return it.
548 template <std::string BundledEntry::*Member>
549 const std::string *onlyValue() const {
550 auto B = Bundled.begin(), E = Bundled.end();
551 for (auto *I = B + 1; I != E; ++I)
552 if (I->*Member != B->*Member)
553 return nullptr;
554 return &(B->*Member);
555 }
556
557 template <bool BundledEntry::*Member> const bool *onlyValue() const {
558 auto B = Bundled.begin(), E = Bundled.end();
559 for (auto *I = B + 1; I != E; ++I)
560 if (I->*Member != B->*Member)
561 return nullptr;
562 return &(B->*Member);
563 }
564
565 std::string summarizeReturnType() const {
566 if (auto *RT = onlyValue<&BundledEntry::ReturnType>())
567 return *RT;
568 return "";
569 }
570
571 std::string summarizeSnippet() const {
572 /// localize ArgumentLists tests for better readability
573 const bool None = ArgumentLists == Config::ArgumentListsPolicy::None;
574 const bool Open =
576 const bool Delim = ArgumentLists == Config::ArgumentListsPolicy::Delimiters;
577 const bool Full =
579 (!None && !Open && !Delim); // <-- failsafe: Full is default
580
581 if (IsUsingDeclaration)
582 return "";
583 auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>();
584 if (!Snippet)
585 // All bundles are function calls.
586 // FIXME(ibiryukov): sometimes add template arguments to a snippet, e.g.
587 // we need to complete 'forward<$1>($0)'.
588 return None ? "" : (Open ? "(" : "($0)");
589
590 if (Snippet->empty())
591 return "";
592
593 bool MayHaveArgList =
594 Completion.Kind == CompletionItemKind::Function ||
595 Completion.Kind == CompletionItemKind::Method ||
596 Completion.Kind == CompletionItemKind::Constructor ||
597 Completion.Kind == CompletionItemKind::Text /*Macro*/ ||
598 Completion.Kind == CompletionItemKind::Variable /*Lambda*/;
599 // If likely arg list already exists, don't add new parens & placeholders.
600 // Snippet: function(int x, int y)
601 // func^(1,2) -> function(1, 2)
602 // NOT function(int x, int y)(1, 2)
603 if (MayHaveArgList) {
604 // Check for a template argument list in the code.
605 // Snippet: function<class T>(int x)
606 // fu^<int>(1) -> function<int>(1)
607 if (NextTokenKind == tok::less && Snippet->front() == '<')
608 return "";
609 // Potentially followed by regular argument list.
610 if (NextTokenKind == tok::l_paren) {
611 // Snippet: function<class T>(int x)
612 // fu^(1,2) -> function<class T>(1, 2)
613 if (Snippet->front() == '<') {
614 // Find matching '>', handling nested brackets.
615 int Balance = 0;
616 size_t I = 0;
617 do {
618 if (Snippet->at(I) == '>')
619 --Balance;
620 else if (Snippet->at(I) == '<')
621 ++Balance;
622 ++I;
623 } while (Balance > 0);
624 return Snippet->substr(0, I);
625 }
626 return "";
627 }
628 }
629 if (Full)
630 return *Snippet;
631
632 // Replace argument snippets with a simplified pattern.
633 if (MayHaveArgList && llvm::StringRef(*Snippet).contains("(")) {
634 // Functions snippets can be of 2 types:
635 // - containing only function arguments, e.g.
636 // foo(${1:int p1}, ${2:int p2});
637 // We transform this pattern to '($0)' or '()'.
638 // - template arguments and function arguments, e.g.
639 // foo<${1:class}>(${2:int p1}).
640 // We transform this pattern to '<$1>()$0' or '<$0>()'.
641
642 bool EmptyArgs = llvm::StringRef(*Snippet).ends_with("()");
643 if (Snippet->front() == '<')
644 return None ? "" : (Open ? "<" : (EmptyArgs ? "<$1>()$0" : "<$1>($0)"));
645 if (Snippet->front() == '(')
646 return None ? "" : (Open ? "(" : (EmptyArgs ? "()" : "($0)"));
647 return *Snippet; // Not an arg snippet?
648 }
649 // 'CompletionItemKind::Interface' matches template type aliases.
650 if (Completion.Kind == CompletionItemKind::Interface ||
651 Completion.Kind == CompletionItemKind::Class ||
652 Completion.Kind == CompletionItemKind::Variable) {
653 if (Snippet->front() != '<')
654 return *Snippet; // Not an arg snippet?
655
656 // Classes and template using aliases can only have template arguments,
657 // e.g. Foo<${1:class}>.
658 if (llvm::StringRef(*Snippet).ends_with("<>"))
659 return "<>"; // can happen with defaulted template arguments.
660 return None ? "" : (Open ? "<" : "<$0>");
661 }
662 return *Snippet;
663 }
664
665 std::string summarizeSignature() const {
666 if (auto *Signature = onlyValue<&BundledEntry::Signature>())
667 return *Signature;
668 // All bundles are function calls.
669 return "(…)";
670 }
671
672 // ASTCtx can be nullptr if not run with sema.
673 ASTContext *ASTCtx;
674 CodeCompletion Completion;
675 llvm::SmallVector<BundledEntry, 1> Bundled;
676 /// the way argument lists are handled.
677 Config::ArgumentListsPolicy ArgumentLists;
678 // No snippets will be generated for using declarations and when the function
679 // arguments are already present.
680 bool IsUsingDeclaration;
681 tok::TokenKind NextTokenKind;
682};
683
684// Determine the symbol ID for a Sema code completion result, if possible.
685SymbolID getSymbolID(const CodeCompletionResult &R, const SourceManager &SM) {
686 switch (R.Kind) {
687 case CodeCompletionResult::RK_Declaration:
688 case CodeCompletionResult::RK_Pattern: {
689 // Computing USR caches linkage, which may change after code completion.
690 if (hasUnstableLinkage(R.Declaration))
691 return {};
692 return clang::clangd::getSymbolID(R.Declaration);
693 }
694 case CodeCompletionResult::RK_Macro:
695 return clang::clangd::getSymbolID(R.Macro->getName(), R.MacroDefInfo, SM);
696 case CodeCompletionResult::RK_Keyword:
697 return {};
698 }
699 llvm_unreachable("unknown CodeCompletionResult kind");
700}
701
702// Scopes of the partial identifier we're trying to complete.
703// It is used when we query the index for more completion results.
704struct SpecifiedScope {
705 // The scopes we should look in, determined by Sema.
706 //
707 // If the qualifier was fully resolved, we look for completions in these
708 // scopes; if there is an unresolved part of the qualifier, it should be
709 // resolved within these scopes.
710 //
711 // Examples of qualified completion:
712 //
713 // "::vec" => {""}
714 // "using namespace std; ::vec^" => {"", "std::"}
715 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
716 // "std::vec^" => {""} // "std" unresolved
717 //
718 // Examples of unqualified completion:
719 //
720 // "vec^" => {""}
721 // "using namespace std; vec^" => {"", "std::"}
722 // "namespace ns {inline namespace ni { struct Foo {}}}
723 // using namespace ns::ni; Fo^ " => {"", "ns::ni::"}
724 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
725 //
726 // "" for global namespace, "ns::" for normal namespace.
727 std::vector<std::string> AccessibleScopes;
728 // This is an overestimate of AccessibleScopes, e.g. it ignores inline
729 // namespaces, to fetch more relevant symbols from index.
730 std::vector<std::string> QueryScopes;
731 // The full scope qualifier as typed by the user (without the leading "::").
732 // Set if the qualifier is not fully resolved by Sema.
733 std::optional<std::string> UnresolvedQualifier;
734
735 std::optional<std::string> EnclosingNamespace;
736
737 bool AllowAllScopes = false;
738
739 // Scopes that are accessible from current context. Used for dropping
740 // unnecessary namespecifiers.
741 std::vector<std::string> scopesForQualification() {
742 std::set<std::string> Results;
743 for (llvm::StringRef AS : AccessibleScopes)
744 Results.insert(
745 (AS + (UnresolvedQualifier ? *UnresolvedQualifier : "")).str());
746 return {Results.begin(), Results.end()};
747 }
748
749 // Construct scopes being queried in indexes. The results are deduplicated.
750 // This method formats the scopes to match the index request representation.
751 std::vector<std::string> scopesForIndexQuery() {
752 // The enclosing namespace must be first, it gets a quality boost.
753 std::vector<std::string> EnclosingAtFront;
754 if (EnclosingNamespace.has_value())
755 EnclosingAtFront.push_back(*EnclosingNamespace);
756 std::set<std::string> Deduplicated;
757 for (llvm::StringRef S : QueryScopes)
758 if (S != EnclosingNamespace)
759 Deduplicated.insert((S + UnresolvedQualifier.value_or("")).str());
760
761 EnclosingAtFront.reserve(EnclosingAtFront.size() + Deduplicated.size());
762 llvm::copy(Deduplicated, std::back_inserter(EnclosingAtFront));
763
764 return EnclosingAtFront;
765 }
766};
767
768// Get all scopes that will be queried in indexes and whether symbols from
769// any scope is allowed. The first scope in the list is the preferred scope
770// (e.g. enclosing namespace).
771SpecifiedScope getQueryScopes(CodeCompletionContext &CCContext,
772 const Sema &CCSema,
773 const CompletionPrefix &HeuristicPrefix,
774 const CodeCompleteOptions &Opts) {
775 SpecifiedScope Scopes;
776 for (auto *Context : CCContext.getVisitedContexts()) {
777 if (isa<TranslationUnitDecl>(Context)) {
778 Scopes.QueryScopes.push_back("");
779 Scopes.AccessibleScopes.push_back("");
780 } else if (const auto *ND = dyn_cast<NamespaceDecl>(Context)) {
781 Scopes.QueryScopes.push_back(printNamespaceScope(*Context));
782 Scopes.AccessibleScopes.push_back(printQualifiedName(*ND) + "::");
783 }
784 }
785
786 const CXXScopeSpec *SemaSpecifier =
787 CCContext.getCXXScopeSpecifier().value_or(nullptr);
788 // Case 1: unqualified completion.
789 if (!SemaSpecifier) {
790 // Case 2 (exception): sema saw no qualifier, but there appears to be one!
791 // This can happen e.g. in incomplete macro expansions. Use heuristics.
792 if (!HeuristicPrefix.Qualifier.empty()) {
793 vlog("Sema said no scope specifier, but we saw {0} in the source code",
794 HeuristicPrefix.Qualifier);
795 StringRef SpelledSpecifier = HeuristicPrefix.Qualifier;
796 if (SpelledSpecifier.consume_front("::")) {
797 Scopes.AccessibleScopes = {""};
798 Scopes.QueryScopes = {""};
799 }
800 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
801 return Scopes;
802 }
803 /// FIXME: When the enclosing namespace contains an inline namespace,
804 /// it's dropped here. This leads to a behavior similar to
805 /// https://github.com/clangd/clangd/issues/1451
806 Scopes.EnclosingNamespace = printNamespaceScope(*CCSema.CurContext);
807 // Allow AllScopes completion as there is no explicit scope qualifier.
808 Scopes.AllowAllScopes = Opts.AllScopes;
809 return Scopes;
810 }
811 // Case 3: sema saw and resolved a scope qualifier.
812 if (SemaSpecifier && SemaSpecifier->isValid())
813 return Scopes;
814
815 // Case 4: There was a qualifier, and Sema didn't resolve it.
816 Scopes.QueryScopes.push_back(""); // Make sure global scope is included.
817 llvm::StringRef SpelledSpecifier = Lexer::getSourceText(
818 CharSourceRange::getCharRange(SemaSpecifier->getRange()),
819 CCSema.SourceMgr, clang::LangOptions());
820 if (SpelledSpecifier.consume_front("::"))
821 Scopes.QueryScopes = {""};
822 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
823 // Sema excludes the trailing "::".
824 if (!Scopes.UnresolvedQualifier->empty())
825 *Scopes.UnresolvedQualifier += "::";
826
827 Scopes.AccessibleScopes = Scopes.QueryScopes;
828
829 return Scopes;
830}
831
832// Should we perform index-based completion in a context of the specified kind?
833// FIXME: consider allowing completion, but restricting the result types.
834bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
835 switch (K) {
836 case CodeCompletionContext::CCC_TopLevel:
837 case CodeCompletionContext::CCC_ObjCInterface:
838 case CodeCompletionContext::CCC_ObjCImplementation:
839 case CodeCompletionContext::CCC_ObjCIvarList:
840 case CodeCompletionContext::CCC_ClassStructUnion:
841 case CodeCompletionContext::CCC_Statement:
842 case CodeCompletionContext::CCC_Expression:
843 case CodeCompletionContext::CCC_ObjCMessageReceiver:
844 case CodeCompletionContext::CCC_EnumTag:
845 case CodeCompletionContext::CCC_UnionTag:
846 case CodeCompletionContext::CCC_ClassOrStructTag:
847 case CodeCompletionContext::CCC_ObjCProtocolName:
848 case CodeCompletionContext::CCC_Namespace:
849 case CodeCompletionContext::CCC_Type:
850 case CodeCompletionContext::CCC_ParenthesizedExpression:
851 case CodeCompletionContext::CCC_ObjCInterfaceName:
852 case CodeCompletionContext::CCC_Symbol:
853 case CodeCompletionContext::CCC_SymbolOrNewName:
854 case CodeCompletionContext::CCC_ObjCClassForwardDecl:
855 case CodeCompletionContext::CCC_TopLevelOrExpression:
856 return true;
857 case CodeCompletionContext::CCC_OtherWithMacros:
858 case CodeCompletionContext::CCC_DotMemberAccess:
859 case CodeCompletionContext::CCC_ArrowMemberAccess:
860 case CodeCompletionContext::CCC_ObjCCategoryName:
861 case CodeCompletionContext::CCC_ObjCPropertyAccess:
862 case CodeCompletionContext::CCC_MacroName:
863 case CodeCompletionContext::CCC_MacroNameUse:
864 case CodeCompletionContext::CCC_PreprocessorExpression:
865 case CodeCompletionContext::CCC_PreprocessorDirective:
866 case CodeCompletionContext::CCC_SelectorName:
867 case CodeCompletionContext::CCC_TypeQualifiers:
868 case CodeCompletionContext::CCC_ObjCInstanceMessage:
869 case CodeCompletionContext::CCC_ObjCClassMessage:
870 case CodeCompletionContext::CCC_IncludedFile:
871 case CodeCompletionContext::CCC_Attribute:
872 // FIXME: Provide identifier based completions for the following contexts:
873 case CodeCompletionContext::CCC_Other: // Be conservative.
874 case CodeCompletionContext::CCC_NaturalLanguage:
875 case CodeCompletionContext::CCC_Recovery:
876 case CodeCompletionContext::CCC_NewName:
877 return false;
878 }
879 llvm_unreachable("unknown code completion context");
880}
881
882static bool isInjectedClass(const NamedDecl &D) {
883 if (auto *R = dyn_cast_or_null<CXXRecordDecl>(&D))
884 if (R->isInjectedClassName())
885 return true;
886 return false;
887}
888
889// Some member calls are excluded because they're so rarely useful.
890static bool isExcludedMember(const NamedDecl &D) {
891 // Destructor completion is rarely useful, and works inconsistently.
892 // (s.^ completes ~string, but s.~st^ is an error).
893 if (D.getKind() == Decl::CXXDestructor)
894 return true;
895 // Injected name may be useful for A::foo(), but who writes A::A::foo()?
896 if (isInjectedClass(D))
897 return true;
898 // Explicit calls to operators are also rare.
899 auto NameKind = D.getDeclName().getNameKind();
900 if (NameKind == DeclarationName::CXXOperatorName ||
901 NameKind == DeclarationName::CXXLiteralOperatorName ||
902 NameKind == DeclarationName::CXXConversionFunctionName)
903 return true;
904 return false;
905}
906
907// The CompletionRecorder captures Sema code-complete output, including context.
908// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
909// It doesn't do scoring or conversion to CompletionItem yet, as we want to
910// merge with index results first.
911// Generally the fields and methods of this object should only be used from
912// within the callback.
913struct CompletionRecorder : public CodeCompleteConsumer {
914 CompletionRecorder(const CodeCompleteOptions &Opts,
915 llvm::unique_function<void()> ResultsCallback)
916 : CodeCompleteConsumer(Opts.getClangCompleteOpts()),
917 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
918 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
919 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
920 assert(this->ResultsCallback);
921 }
922
923 std::vector<CodeCompletionResult> Results;
924 CodeCompletionContext CCContext;
925 Sema *CCSema = nullptr; // Sema that created the results.
926 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
927
928 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
929 CodeCompletionResult *InResults,
930 unsigned NumResults) final {
931 // Results from recovery mode are generally useless, and the callback after
932 // recovery (if any) is usually more interesting. To make sure we handle the
933 // future callback from sema, we just ignore all callbacks in recovery mode,
934 // as taking only results from recovery mode results in poor completion
935 // results.
936 // FIXME: in case there is no future sema completion callback after the
937 // recovery mode, we might still want to provide some results (e.g. trivial
938 // identifier-based completion).
939 CodeCompletionContext::Kind ContextKind = Context.getKind();
940 if (ContextKind == CodeCompletionContext::CCC_Recovery) {
941 log("Code complete: Ignoring sema code complete callback with Recovery "
942 "context.");
943 return;
944 }
945 // If a callback is called without any sema result and the context does not
946 // support index-based completion, we simply skip it to give way to
947 // potential future callbacks with results.
948 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
949 return;
950 if (CCSema) {
951 log("Multiple code complete callbacks (parser backtracked?). "
952 "Dropping results from context {0}, keeping results from {1}.",
953 getCompletionKindString(Context.getKind()),
954 getCompletionKindString(this->CCContext.getKind()));
955 return;
956 }
957 // Record the completion context.
958 CCSema = &S;
959 CCContext = Context;
960
961 // Retain the results we might want.
962 for (unsigned I = 0; I < NumResults; ++I) {
963 auto &Result = InResults[I];
964 if (Config::current().Completion.CodePatterns ==
966 Result.Kind == CodeCompletionResult::RK_Pattern &&
967 // keep allowing the include files autocomplete suggestions
968 ContextKind != CodeCompletionContext::CCC_IncludedFile)
969 continue;
970 // Class members that are shadowed by subclasses are usually noise.
971 if (Result.Hidden && Result.Declaration &&
972 Result.Declaration->isCXXClassMember())
973 continue;
974 if (!Opts.IncludeIneligibleResults &&
975 (Result.Availability == CXAvailability_NotAvailable ||
976 Result.Availability == CXAvailability_NotAccessible))
977 continue;
978 if (Result.Declaration &&
979 !Context.getBaseType().isNull() // is this a member-access context?
980 && isExcludedMember(*Result.Declaration))
981 continue;
982 // Skip injected class name when no class scope is not explicitly set.
983 // E.g. show injected A::A in `using A::A^` but not in "A^".
984 if (Result.Declaration && !Context.getCXXScopeSpecifier() &&
985 isInjectedClass(*Result.Declaration))
986 continue;
987 // We choose to never append '::' to completion results in clangd.
988 Result.StartsNestedNameSpecifier = false;
989 Results.push_back(Result);
990 }
991 ResultsCallback();
992 }
993
994 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
995 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
996
997 // Returns the filtering/sorting name for Result, which must be from Results.
998 // Returned string is owned by this recorder (or the AST).
999 llvm::StringRef getName(const CodeCompletionResult &Result) {
1000 switch (Result.Kind) {
1001 case CodeCompletionResult::RK_Declaration:
1002 if (auto *ID = Result.Declaration->getIdentifier())
1003 return ID->getName();
1004 break;
1005 case CodeCompletionResult::RK_Keyword:
1006 return Result.Keyword;
1007 case CodeCompletionResult::RK_Macro:
1008 return Result.Macro->getName();
1009 case CodeCompletionResult::RK_Pattern:
1010 break;
1011 }
1012 auto *CCS = codeCompletionString(Result);
1013 const CodeCompletionString::Chunk *OnlyText = nullptr;
1014 for (auto &C : *CCS) {
1015 if (C.Kind != CodeCompletionString::CK_TypedText)
1016 continue;
1017 if (OnlyText)
1018 return CCAllocator->CopyString(CCS->getAllTypedText());
1019 OnlyText = &C;
1020 }
1021 return OnlyText ? OnlyText->Text : llvm::StringRef();
1022 }
1023
1024 // Build a CodeCompletion string for R, which must be from Results.
1025 // The CCS will be owned by this recorder.
1026 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
1027 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
1028 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
1029 *CCSema, CCContext, *CCAllocator, CCTUInfo,
1030 /*IncludeBriefComments=*/false);
1031 }
1032
1033private:
1034 CodeCompleteOptions Opts;
1035 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
1036 CodeCompletionTUInfo CCTUInfo;
1037 llvm::unique_function<void()> ResultsCallback;
1038};
1039
1040struct ScoredSignature {
1041 // When not null, requires documentation to be requested from the index with
1042 // this ID.
1043 SymbolID IDForDoc;
1044 SignatureInformation Signature;
1045 SignatureQualitySignals Quality;
1046};
1047
1048// Returns the index of the parameter matching argument number "Arg.
1049// This is usually just "Arg", except for variadic functions/templates, where
1050// "Arg" might be higher than the number of parameters. When that happens, we
1051// assume the last parameter is variadic and assume all further args are
1052// part of it.
1053int paramIndexForArg(const CodeCompleteConsumer::OverloadCandidate &Candidate,
1054 int Arg) {
1055 int NumParams = Candidate.getNumParams();
1056 if (auto *T = Candidate.getFunctionType()) {
1057 if (auto *Proto = T->getAs<FunctionProtoType>()) {
1058 if (Proto->isVariadic())
1059 ++NumParams;
1060 }
1061 }
1062 return std::min(Arg, std::max(NumParams - 1, 0));
1063}
1064
1065class SignatureHelpCollector final : public CodeCompleteConsumer {
1066public:
1067 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
1068 MarkupKind DocumentationFormat,
1069 const SymbolIndex *Index, SignatureHelp &SigHelp)
1070 : CodeCompleteConsumer(CodeCompleteOpts), SigHelp(SigHelp),
1071 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1072 CCTUInfo(Allocator), Index(Index),
1073 DocumentationFormat(DocumentationFormat) {}
1074
1075 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1076 OverloadCandidate *Candidates,
1077 unsigned NumCandidates,
1078 SourceLocation OpenParLoc,
1079 bool Braced) override {
1080 assert(!OpenParLoc.isInvalid());
1081 SourceManager &SrcMgr = S.getSourceManager();
1082 OpenParLoc = SrcMgr.getFileLoc(OpenParLoc);
1083 if (SrcMgr.isInMainFile(OpenParLoc))
1084 SigHelp.argListStart = sourceLocToPosition(SrcMgr, OpenParLoc);
1085 else
1086 elog("Location oustide main file in signature help: {0}",
1087 OpenParLoc.printToString(SrcMgr));
1088
1089 std::vector<ScoredSignature> ScoredSignatures;
1090 SigHelp.signatures.reserve(NumCandidates);
1091 ScoredSignatures.reserve(NumCandidates);
1092 // FIXME(rwols): How can we determine the "active overload candidate"?
1093 // Right now the overloaded candidates seem to be provided in a "best fit"
1094 // order, so I'm not too worried about this.
1095 SigHelp.activeSignature = 0;
1096 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
1097 "too many arguments");
1098
1099 SigHelp.activeParameter = static_cast<int>(CurrentArg);
1100
1101 for (unsigned I = 0; I < NumCandidates; ++I) {
1102 OverloadCandidate Candidate = Candidates[I];
1103 // We want to avoid showing instantiated signatures, because they may be
1104 // long in some cases (e.g. when 'T' is substituted with 'std::string', we
1105 // would get 'std::basic_string<char>').
1106 if (auto *Func = Candidate.getFunction()) {
1107 if (auto *Pattern = Func->getTemplateInstantiationPattern())
1108 Candidate = OverloadCandidate(Pattern);
1109 }
1110 if (static_cast<int>(I) == SigHelp.activeSignature) {
1111 // The activeParameter in LSP relates to the activeSignature. There is
1112 // another, per-signature field, but we currently do not use it and not
1113 // all clients might support it.
1114 // FIXME: Add support for per-signature activeParameter field.
1115 SigHelp.activeParameter =
1116 paramIndexForArg(Candidate, SigHelp.activeParameter);
1117 }
1118
1119 const auto *CCS = Candidate.CreateSignatureString(
1120 CurrentArg, S, *Allocator, CCTUInfo,
1121 /*IncludeBriefComments=*/true, Braced);
1122 assert(CCS && "Expected the CodeCompletionString to be non-null");
1123 ScoredSignatures.push_back(processOverloadCandidate(
1124 Candidate, *CCS,
1125 Candidate.getFunction()
1126 ? getDeclComment(S.getASTContext(), *Candidate.getFunction())
1127 : ""));
1128 }
1129
1130 // Sema does not load the docs from the preamble, so we need to fetch extra
1131 // docs from the index instead.
1132 llvm::DenseMap<SymbolID, std::string> FetchedDocs;
1133 if (Index) {
1134 LookupRequest IndexRequest;
1135 for (const auto &S : ScoredSignatures) {
1136 if (!S.IDForDoc)
1137 continue;
1138 IndexRequest.IDs.insert(S.IDForDoc);
1139 }
1140 Index->lookup(IndexRequest, [&](const Symbol &S) {
1141 if (!S.Documentation.empty())
1142 FetchedDocs[S.ID] = std::string(S.Documentation);
1143 });
1144 vlog("SigHelp: requested docs for {0} symbols from the index, got {1} "
1145 "symbols with non-empty docs in the response",
1146 IndexRequest.IDs.size(), FetchedDocs.size());
1147 }
1148
1149 llvm::sort(ScoredSignatures, [](const ScoredSignature &L,
1150 const ScoredSignature &R) {
1151 // Ordering follows:
1152 // - Less number of parameters is better.
1153 // - Aggregate > Function > FunctionType > FunctionTemplate
1154 // - High score is better.
1155 // - Shorter signature is better.
1156 // - Alphabetically smaller is better.
1157 if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
1158 return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
1159 if (L.Quality.NumberOfOptionalParameters !=
1160 R.Quality.NumberOfOptionalParameters)
1161 return L.Quality.NumberOfOptionalParameters <
1162 R.Quality.NumberOfOptionalParameters;
1163 if (L.Quality.Kind != R.Quality.Kind) {
1164 using OC = CodeCompleteConsumer::OverloadCandidate;
1165 auto KindPriority = [&](OC::CandidateKind K) {
1166 switch (K) {
1167 case OC::CK_Aggregate:
1168 return 0;
1169 case OC::CK_Function:
1170 return 1;
1171 case OC::CK_FunctionType:
1172 return 2;
1173 case OC::CK_FunctionProtoTypeLoc:
1174 return 3;
1175 case OC::CK_FunctionTemplate:
1176 return 4;
1177 case OC::CK_Template:
1178 return 5;
1179 }
1180 llvm_unreachable("Unknown overload candidate type.");
1181 };
1182 return KindPriority(L.Quality.Kind) < KindPriority(R.Quality.Kind);
1183 }
1184 if (L.Signature.label.size() != R.Signature.label.size())
1185 return L.Signature.label.size() < R.Signature.label.size();
1186 return L.Signature.label < R.Signature.label;
1187 });
1188
1189 for (auto &SS : ScoredSignatures) {
1190 auto IndexDocIt =
1191 SS.IDForDoc ? FetchedDocs.find(SS.IDForDoc) : FetchedDocs.end();
1192 if (IndexDocIt != FetchedDocs.end()) {
1193 markup::Document SignatureComment;
1194 parseDocumentation(IndexDocIt->second, SignatureComment);
1195 SS.Signature.documentation =
1196 renderDoc(SignatureComment, DocumentationFormat);
1197 }
1198
1199 SigHelp.signatures.push_back(std::move(SS.Signature));
1200 }
1201 }
1202
1203 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
1204
1205 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
1206
1207private:
1208 void processParameterChunk(llvm::StringRef ChunkText,
1209 SignatureInformation &Signature) const {
1210 // (!) this is O(n), should still be fast compared to building ASTs.
1211 unsigned ParamStartOffset = lspLength(Signature.label);
1212 unsigned ParamEndOffset = ParamStartOffset + lspLength(ChunkText);
1213 // A piece of text that describes the parameter that corresponds to
1214 // the code-completion location within a function call, message send,
1215 // macro invocation, etc.
1216 Signature.label += ChunkText;
1217 ParameterInformation Info;
1218 Info.labelOffsets.emplace(ParamStartOffset, ParamEndOffset);
1219 // FIXME: only set 'labelOffsets' when all clients migrate out of it.
1220 Info.labelString = std::string(ChunkText);
1221
1222 Signature.parameters.push_back(std::move(Info));
1223 }
1224
1225 void processOptionalChunk(const CodeCompletionString &CCS,
1226 SignatureInformation &Signature,
1227 SignatureQualitySignals &Signal) const {
1228 for (const auto &Chunk : CCS) {
1229 switch (Chunk.Kind) {
1230 case CodeCompletionString::CK_Optional:
1231 assert(Chunk.Optional &&
1232 "Expected the optional code completion string to be non-null.");
1233 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1234 break;
1235 case CodeCompletionString::CK_VerticalSpace:
1236 break;
1237 case CodeCompletionString::CK_CurrentParameter:
1238 case CodeCompletionString::CK_Placeholder:
1239 processParameterChunk(Chunk.Text, Signature);
1240 Signal.NumberOfOptionalParameters++;
1241 break;
1242 default:
1243 Signature.label += Chunk.Text;
1244 break;
1245 }
1246 }
1247 }
1248
1249 // FIXME(ioeric): consider moving CodeCompletionString logic here to
1250 // CompletionString.h.
1251 ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
1252 const CodeCompletionString &CCS,
1253 llvm::StringRef DocComment) const {
1254 SignatureInformation Signature;
1255 SignatureQualitySignals Signal;
1256 const char *ReturnType = nullptr;
1257
1258 markup::Document OverloadComment;
1259 parseDocumentation(formatDocumentation(CCS, DocComment), OverloadComment);
1260 Signature.documentation = renderDoc(OverloadComment, DocumentationFormat);
1261 Signal.Kind = Candidate.getKind();
1262
1263 for (const auto &Chunk : CCS) {
1264 switch (Chunk.Kind) {
1265 case CodeCompletionString::CK_ResultType:
1266 // A piece of text that describes the type of an entity or,
1267 // for functions and methods, the return type.
1268 assert(!ReturnType && "Unexpected CK_ResultType");
1269 ReturnType = Chunk.Text;
1270 break;
1271 case CodeCompletionString::CK_CurrentParameter:
1272 case CodeCompletionString::CK_Placeholder:
1273 processParameterChunk(Chunk.Text, Signature);
1274 Signal.NumberOfParameters++;
1275 break;
1276 case CodeCompletionString::CK_Optional: {
1277 // The rest of the parameters are defaulted/optional.
1278 assert(Chunk.Optional &&
1279 "Expected the optional code completion string to be non-null.");
1280 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1281 break;
1282 }
1283 case CodeCompletionString::CK_VerticalSpace:
1284 break;
1285 default:
1286 Signature.label += Chunk.Text;
1287 break;
1288 }
1289 }
1290 if (ReturnType) {
1291 Signature.label += " -> ";
1292 Signature.label += ReturnType;
1293 }
1294 dlog("Signal for {0}: {1}", Signature, Signal);
1295 ScoredSignature Result;
1296 Result.Signature = std::move(Signature);
1297 Result.Quality = Signal;
1298 const FunctionDecl *Func = Candidate.getFunction();
1299 if (Func && Result.Signature.documentation.value.empty()) {
1300 // Computing USR caches linkage, which may change after code completion.
1301 if (!hasUnstableLinkage(Func))
1302 Result.IDForDoc = clangd::getSymbolID(Func);
1303 }
1304 return Result;
1305 }
1306
1307 SignatureHelp &SigHelp;
1308 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1309 CodeCompletionTUInfo CCTUInfo;
1310 const SymbolIndex *Index;
1311 MarkupKind DocumentationFormat;
1312}; // SignatureHelpCollector
1313
1314// Used only for completion of C-style comments in function call (i.e.
1315// /*foo=*/7). Similar to SignatureHelpCollector, but needs to do less work.
1316class ParamNameCollector final : public CodeCompleteConsumer {
1317public:
1318 ParamNameCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
1319 std::set<std::string> &ParamNames)
1320 : CodeCompleteConsumer(CodeCompleteOpts),
1321 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1322 CCTUInfo(Allocator), ParamNames(ParamNames) {}
1323
1324 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1325 OverloadCandidate *Candidates,
1326 unsigned NumCandidates,
1327 SourceLocation OpenParLoc,
1328 bool Braced) override {
1329 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
1330 "too many arguments");
1331
1332 for (unsigned I = 0; I < NumCandidates; ++I) {
1333 if (const NamedDecl *ND = Candidates[I].getParamDecl(CurrentArg))
1334 if (const auto *II = ND->getIdentifier())
1335 ParamNames.emplace(II->getName());
1336 }
1337 }
1338
1339private:
1340 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
1341
1342 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
1343
1344 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1345 CodeCompletionTUInfo CCTUInfo;
1346 std::set<std::string> &ParamNames;
1347};
1348
1349struct SemaCompleteInput {
1350 PathRef FileName;
1351 size_t Offset;
1352 const PreambleData &Preamble;
1353 const std::optional<PreamblePatch> Patch;
1354 const ParseInputs &ParseInput;
1355};
1356
1357void loadMainFilePreambleMacros(const Preprocessor &PP,
1358 const PreambleData &Preamble) {
1359 // The ExternalPreprocessorSource has our macros, if we know where to look.
1360 // We can read all the macros using PreambleMacros->ReadDefinedMacros(),
1361 // but this includes transitively included files, so may deserialize a lot.
1362 ExternalPreprocessorSource *PreambleMacros = PP.getExternalSource();
1363 // As we have the names of the macros, we can look up their IdentifierInfo
1364 // and then use this to load just the macros we want.
1365 const auto &ITable = PP.getIdentifierTable();
1366 IdentifierInfoLookup *PreambleIdentifiers =
1367 ITable.getExternalIdentifierLookup();
1368
1369 if (!PreambleIdentifiers || !PreambleMacros)
1370 return;
1371 for (const auto &MacroName : Preamble.Macros.Names) {
1372 if (ITable.find(MacroName.getKey()) != ITable.end())
1373 continue;
1374 if (auto *II = PreambleIdentifiers->get(MacroName.getKey()))
1375 if (II->isOutOfDate())
1376 PreambleMacros->updateOutOfDateIdentifier(*II);
1377 }
1378}
1379
1380// Invokes Sema code completion on a file.
1381// If \p Includes is set, it will be updated based on the compiler invocation.
1382bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
1383 const clang::CodeCompleteOptions &Options,
1384 const SemaCompleteInput &Input,
1385 IncludeStructure *Includes = nullptr) {
1386 trace::Span Tracer("Sema completion");
1387
1388 IgnoreDiagnostics IgnoreDiags;
1389 auto CI = buildCompilerInvocation(Input.ParseInput, IgnoreDiags);
1390 if (!CI) {
1391 elog("Couldn't create CompilerInvocation");
1392 return false;
1393 }
1394 auto &FrontendOpts = CI->getFrontendOpts();
1395 FrontendOpts.SkipFunctionBodies = true;
1396 // Disable typo correction in Sema.
1397 CI->getLangOpts().SpellChecking = false;
1398 // Code completion won't trigger in delayed template bodies.
1399 // This is on-by-default in windows to allow parsing SDK headers; we're only
1400 // disabling it for the main-file (not preamble).
1401 CI->getLangOpts().DelayedTemplateParsing = false;
1402 // Setup code completion.
1403 FrontendOpts.CodeCompleteOpts = Options;
1404 FrontendOpts.CodeCompletionAt.FileName = std::string(Input.FileName);
1405 std::tie(FrontendOpts.CodeCompletionAt.Line,
1406 FrontendOpts.CodeCompletionAt.Column) =
1407 offsetToClangLineColumn(Input.ParseInput.Contents, Input.Offset);
1408
1409 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1410 llvm::MemoryBuffer::getMemBuffer(Input.ParseInput.Contents,
1411 Input.FileName);
1412 // The diagnostic options must be set before creating a CompilerInstance.
1413 CI->getDiagnosticOpts().IgnoreWarnings = true;
1414 // We reuse the preamble whether it's valid or not. This is a
1415 // correctness/performance tradeoff: building without a preamble is slow, and
1416 // completion is latency-sensitive.
1417 // However, if we're completing *inside* the preamble section of the draft,
1418 // overriding the preamble will break sema completion. Fortunately we can just
1419 // skip all includes in this case; these completions are really simple.
1420 PreambleBounds PreambleRegion =
1421 ComputePreambleBounds(CI->getLangOpts(), *ContentsBuffer, 0);
1422 bool CompletingInPreamble = Input.Offset < PreambleRegion.Size ||
1423 (!PreambleRegion.PreambleEndsAtStartOfLine &&
1424 Input.Offset == PreambleRegion.Size);
1425 if (Input.Patch)
1426 Input.Patch->apply(*CI);
1427 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
1428 // the remapped buffers do not get freed.
1429 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
1430 Input.ParseInput.TFS->view(Input.ParseInput.CompileCommand.Directory);
1431 if (Input.Preamble.StatCache)
1432 VFS = Input.Preamble.StatCache->getConsumingFS(std::move(VFS));
1433 auto Clang = prepareCompilerInstance(
1434 std::move(CI), !CompletingInPreamble ? &Input.Preamble.Preamble : nullptr,
1435 std::move(ContentsBuffer), std::move(VFS), IgnoreDiags);
1436 Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
1437 Clang->setCodeCompletionConsumer(Consumer.release());
1438
1439 if (Input.Preamble.RequiredModules)
1440 Input.Preamble.RequiredModules->adjustHeaderSearchOptions(
1441 Clang->getHeaderSearchOpts());
1442
1443 SyntaxOnlyAction Action;
1444 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
1445 log("BeginSourceFile() failed when running codeComplete for {0}",
1446 Input.FileName);
1447 return false;
1448 }
1449 // Macros can be defined within the preamble region of the main file.
1450 // They don't fall nicely into our index/Sema dichotomy:
1451 // - they're not indexed for completion (they're not available across files)
1452 // - but Sema code complete won't see them: as part of the preamble, they're
1453 // deserialized only when mentioned.
1454 // Force them to be deserialized so SemaCodeComplete sees them.
1455 loadMainFilePreambleMacros(Clang->getPreprocessor(), Input.Preamble);
1456 if (Includes)
1457 Includes->collect(*Clang);
1458 if (llvm::Error Err = Action.Execute()) {
1459 log("Execute() failed when running codeComplete for {0}: {1}",
1460 Input.FileName, toString(std::move(Err)));
1461 return false;
1462 }
1463 Action.EndSourceFile();
1464
1465 return true;
1466}
1467
1468// Should we allow index completions in the specified context?
1469bool allowIndex(CodeCompletionContext &CC) {
1470 if (!contextAllowsIndex(CC.getKind()))
1471 return false;
1472 // We also avoid ClassName::bar (but allow namespace::bar).
1473 auto Scope = CC.getCXXScopeSpecifier();
1474 if (!Scope)
1475 return true;
1476 // We only query the index when qualifier is a namespace.
1477 // If it's a class, we rely solely on sema completions.
1478 switch ((*Scope)->getScopeRep().getKind()) {
1479 case NestedNameSpecifier::Kind::Null:
1480 case NestedNameSpecifier::Kind::Global:
1481 case NestedNameSpecifier::Kind::Namespace:
1482 return true;
1483 case NestedNameSpecifier::Kind::MicrosoftSuper:
1484 case NestedNameSpecifier::Kind::Type:
1485 return false;
1486 }
1487 llvm_unreachable("invalid NestedNameSpecifier kind");
1488}
1489
1490// Should we include a symbol from the index given the completion kind?
1491// FIXME: Ideally we can filter in the fuzzy find request itself.
1492bool includeSymbolFromIndex(CodeCompletionContext::Kind Kind,
1493 const Symbol &Sym) {
1494 // Objective-C protocols are only useful in ObjC protocol completions,
1495 // in other places they're confusing, especially when they share the same
1496 // identifier with a class.
1497 if (Sym.SymInfo.Kind == index::SymbolKind::Protocol &&
1498 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC)
1499 return Kind == CodeCompletionContext::CCC_ObjCProtocolName;
1500 else if (Kind == CodeCompletionContext::CCC_ObjCProtocolName)
1501 // Don't show anything else in ObjC protocol completions.
1502 return false;
1503
1504 if (Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
1505 return Sym.SymInfo.Kind == index::SymbolKind::Class &&
1506 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC;
1507 return true;
1508}
1509
1510std::future<std::pair<bool, SymbolSlab>>
1511startAsyncFuzzyFind(const SymbolIndex &Index, const FuzzyFindRequest &Req) {
1512 return runAsync<std::pair<bool, SymbolSlab>>([&Index, Req]() {
1513 trace::Span Tracer("Async fuzzyFind");
1514 SymbolSlab::Builder Syms;
1515 bool Incomplete =
1516 Index.fuzzyFind(Req, [&Syms](const Symbol &Sym) { Syms.insert(Sym); });
1517 return std::make_pair(Incomplete, std::move(Syms).build());
1518 });
1519}
1520
1521// Creates a `FuzzyFindRequest` based on the cached index request from the
1522// last completion, if any, and the speculated completion filter text in the
1523// source code.
1524FuzzyFindRequest speculativeFuzzyFindRequestForCompletion(
1525 FuzzyFindRequest CachedReq, const CompletionPrefix &HeuristicPrefix) {
1526 CachedReq.Query = std::string(HeuristicPrefix.Name);
1527 return CachedReq;
1528}
1529
1530// This function is similar to Lexer::findNextToken(), but assumes
1531// that the input SourceLocation is the completion point (which is
1532// a case findNextToken() does not handle).
1533std::optional<Token>
1534findTokenAfterCompletionPoint(SourceLocation CompletionPoint,
1535 const SourceManager &SM,
1536 const LangOptions &LangOpts) {
1537 SourceLocation Loc = CompletionPoint;
1538 if (Loc.isMacroID()) {
1539 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1540 return std::nullopt;
1541 }
1542
1543 // Advance to the next SourceLocation after the completion point.
1544 // Lexer::findNextToken() would call MeasureTokenLength() here,
1545 // which does not handle the completion point (and can't, because
1546 // the Lexer instance it constructs internally doesn't have a
1547 // Preprocessor and so doesn't know about the completion point).
1548 Loc = Loc.getLocWithOffset(1);
1549
1550 // Break down the source location.
1551 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1552
1553 // Try to load the file buffer.
1554 bool InvalidTemp = false;
1555 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1556 if (InvalidTemp)
1557 return std::nullopt;
1558
1559 const char *TokenBegin = File.data() + LocInfo.second;
1560
1561 // Lex from the start of the given location.
1562 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1563 TokenBegin, File.end());
1564 // Find the token.
1565 Token Tok;
1566 TheLexer.LexFromRawLexer(Tok);
1567 return Tok;
1568}
1569
1570// Runs Sema-based (AST) and Index-based completion, returns merged results.
1571//
1572// There are a few tricky considerations:
1573// - the AST provides information needed for the index query (e.g. which
1574// namespaces to search in). So Sema must start first.
1575// - we only want to return the top results (Opts.Limit).
1576// Building CompletionItems for everything else is wasteful, so we want to
1577// preserve the "native" format until we're done with scoring.
1578// - the data underlying Sema completion items is owned by the AST and various
1579// other arenas, which must stay alive for us to build CompletionItems.
1580// - we may get duplicate results from Sema and the Index, we need to merge.
1581//
1582// So we start Sema completion first, and do all our work in its callback.
1583// We use the Sema context information to query the index.
1584// Then we merge the two result sets, producing items that are Sema/Index/Both.
1585// These items are scored, and the top N are synthesized into the LSP response.
1586// Finally, we can clean up the data structures created by Sema completion.
1587//
1588// Main collaborators are:
1589// - semaCodeComplete sets up the compiler machinery to run code completion.
1590// - CompletionRecorder captures Sema completion results, including context.
1591// - SymbolIndex (Opts.Index) provides index completion results as Symbols
1592// - CompletionCandidates are the result of merging Sema and Index results.
1593// Each candidate points to an underlying CodeCompletionResult (Sema), a
1594// Symbol (Index), or both. It computes the result quality score.
1595// CompletionCandidate also does conversion to CompletionItem (at the end).
1596// - FuzzyMatcher scores how the candidate matches the partial identifier.
1597// This score is combined with the result quality score for the final score.
1598// - TopN determines the results with the best score.
1599class CodeCompleteFlow {
1600 PathRef FileName;
1601 IncludeStructure Includes; // Complete once the compiler runs.
1602 SpeculativeFuzzyFind *SpecFuzzyFind; // Can be nullptr.
1603 const CodeCompleteOptions &Opts;
1604
1605 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
1606 CompletionRecorder *Recorder = nullptr;
1607 CodeCompletionContext::Kind CCContextKind = CodeCompletionContext::CCC_Other;
1608 bool IsUsingDeclaration = false;
1609 // The snippets will not be generated if the token following completion
1610 // location is an opening parenthesis (tok::l_paren) because this would add
1611 // extra parenthesis.
1612 tok::TokenKind NextTokenKind = tok::eof;
1613 // Counters for logging.
1614 int NSema = 0, NIndex = 0, NSemaAndIndex = 0, NIdent = 0;
1615 bool Incomplete = false; // Would more be available with a higher limit?
1616 CompletionPrefix HeuristicPrefix;
1617 std::optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
1618 Range ReplacedRange;
1619 std::vector<std::string> QueryScopes; // Initialized once Sema runs.
1620 std::vector<std::string> AccessibleScopes; // Initialized once Sema runs.
1621 // Initialized once QueryScopes is initialized, if there are scopes.
1622 std::optional<ScopeDistance> ScopeProximity;
1623 std::optional<OpaqueType> PreferredType; // Initialized once Sema runs.
1624 // Whether to query symbols from any scope. Initialized once Sema runs.
1625 bool AllScopes = false;
1626 llvm::StringSet<> ContextWords;
1627 // Include-insertion and proximity scoring rely on the include structure.
1628 // This is available after Sema has run.
1629 std::optional<IncludeInserter> Inserter; // Available during runWithSema.
1630 std::optional<URIDistance> FileProximity; // Initialized once Sema runs.
1631 /// Speculative request based on the cached request and the filter text before
1632 /// the cursor.
1633 /// Initialized right before sema run. This is only set if `SpecFuzzyFind` is
1634 /// set and contains a cached request.
1635 std::optional<FuzzyFindRequest> SpecReq;
1636
1637public:
1638 // A CodeCompleteFlow object is only useful for calling run() exactly once.
1639 CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes,
1640 SpeculativeFuzzyFind *SpecFuzzyFind,
1641 const CodeCompleteOptions &Opts)
1642 : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind),
1643 Opts(Opts) {}
1644
1645 CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
1646 trace::Span Tracer("CodeCompleteFlow");
1647 HeuristicPrefix = guessCompletionPrefix(SemaCCInput.ParseInput.Contents,
1648 SemaCCInput.Offset);
1649 populateContextWords(SemaCCInput.ParseInput.Contents);
1650 if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq) {
1651 assert(!SpecFuzzyFind->Result.valid());
1652 SpecReq = speculativeFuzzyFindRequestForCompletion(
1653 *SpecFuzzyFind->CachedReq, HeuristicPrefix);
1654 SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq);
1655 }
1656
1657 // We run Sema code completion first. It builds an AST and calculates:
1658 // - completion results based on the AST.
1659 // - partial identifier and context. We need these for the index query.
1660 CodeCompleteResult Output;
1661 auto RecorderOwner = std::make_unique<CompletionRecorder>(Opts, [&]() {
1662 assert(Recorder && "Recorder is not set");
1663 CCContextKind = Recorder->CCContext.getKind();
1664 IsUsingDeclaration = Recorder->CCContext.isUsingDeclaration();
1665 auto Style = getFormatStyleForFile(SemaCCInput.FileName,
1666 SemaCCInput.ParseInput.Contents,
1667 *SemaCCInput.ParseInput.TFS, false);
1668 const auto NextToken = findTokenAfterCompletionPoint(
1669 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc(),
1670 Recorder->CCSema->getSourceManager(), Recorder->CCSema->LangOpts);
1671 if (NextToken)
1672 NextTokenKind = NextToken->getKind();
1673 // If preprocessor was run, inclusions from preprocessor callback should
1674 // already be added to Includes.
1675 Inserter.emplace(
1676 SemaCCInput.FileName, SemaCCInput.ParseInput.Contents, Style,
1677 SemaCCInput.ParseInput.CompileCommand.Directory,
1678 &Recorder->CCSema->getPreprocessor().getHeaderSearchInfo(),
1681 for (const auto &Inc : Includes.MainFileIncludes)
1682 Inserter->addExisting(Inc);
1683
1684 // Most of the cost of file proximity is in initializing the FileDistance
1685 // structures based on the observed includes, once per query. Conceptually
1686 // that happens here (though the per-URI-scheme initialization is lazy).
1687 // The per-result proximity scoring is (amortized) very cheap.
1688 FileDistanceOptions ProxOpts{}; // Use defaults.
1689 const auto &SM = Recorder->CCSema->getSourceManager();
1690 llvm::StringMap<SourceParams> ProxSources;
1691 auto MainFileID =
1692 Includes.getID(SM.getFileEntryForID(SM.getMainFileID()));
1693 assert(MainFileID);
1694 for (auto &HeaderIDAndDepth : Includes.includeDepth(*MainFileID)) {
1695 auto &Source =
1696 ProxSources[Includes.getRealPath(HeaderIDAndDepth.getFirst())];
1697 Source.Cost = HeaderIDAndDepth.getSecond() * ProxOpts.IncludeCost;
1698 // Symbols near our transitive includes are good, but only consider
1699 // things in the same directory or below it. Otherwise there can be
1700 // many false positives.
1701 if (HeaderIDAndDepth.getSecond() > 0)
1702 Source.MaxUpTraversals = 1;
1703 }
1704 FileProximity.emplace(ProxSources, ProxOpts);
1705
1706 Output = runWithSema();
1707 Inserter.reset(); // Make sure this doesn't out-live Clang.
1708 SPAN_ATTACH(Tracer, "sema_completion_kind",
1709 getCompletionKindString(CCContextKind));
1710 log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
1711 "expected type {3}{4}",
1712 getCompletionKindString(CCContextKind),
1713 llvm::join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
1714 PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
1715 : "<none>",
1716 IsUsingDeclaration ? ", inside using declaration" : "");
1717 });
1718
1719 Recorder = RecorderOwner.get();
1720
1721 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
1722 SemaCCInput, &Includes);
1723 logResults(Output, Tracer);
1724 return Output;
1725 }
1726
1727 void logResults(const CodeCompleteResult &Output, const trace::Span &Tracer) {
1728 SPAN_ATTACH(Tracer, "sema_results", NSema);
1729 SPAN_ATTACH(Tracer, "index_results", NIndex);
1730 SPAN_ATTACH(Tracer, "merged_results", NSemaAndIndex);
1731 SPAN_ATTACH(Tracer, "identifier_results", NIdent);
1732 SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size()));
1733 SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
1734 log("Code complete: {0} results from Sema, {1} from Index, "
1735 "{2} matched, {3} from identifiers, {4} returned{5}.",
1736 NSema, NIndex, NSemaAndIndex, NIdent, Output.Completions.size(),
1737 Output.HasMore ? " (incomplete)" : "");
1738 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
1739 // We don't assert that isIncomplete means we hit a limit.
1740 // Indexes may choose to impose their own limits even if we don't have one.
1741 }
1742
1743 CodeCompleteResult runWithoutSema(llvm::StringRef Content, size_t Offset,
1744 const ThreadsafeFS &TFS) && {
1745 trace::Span Tracer("CodeCompleteWithoutSema");
1746 // Fill in fields normally set by runWithSema()
1747 HeuristicPrefix = guessCompletionPrefix(Content, Offset);
1748 populateContextWords(Content);
1749 CCContextKind = CodeCompletionContext::CCC_Recovery;
1750 IsUsingDeclaration = false;
1751 Filter = FuzzyMatcher(HeuristicPrefix.Name);
1752 auto Pos = offsetToPosition(Content, Offset);
1753 ReplacedRange.start = ReplacedRange.end = Pos;
1754 ReplacedRange.start.character -= HeuristicPrefix.Name.size();
1755
1756 llvm::StringMap<SourceParams> ProxSources;
1757 ProxSources[FileName].Cost = 0;
1758 FileProximity.emplace(ProxSources);
1759
1760 auto Style = getFormatStyleForFile(FileName, Content, TFS, false);
1761 // This will only insert verbatim headers.
1762 Inserter.emplace(FileName, Content, Style,
1763 /*BuildDir=*/"", /*HeaderSearchInfo=*/nullptr,
1764 Config::current().Style.QuotedHeaders,
1766
1767 auto Identifiers = collectIdentifiers(Content, Style);
1768 std::vector<RawIdentifier> IdentifierResults;
1769 for (const auto &IDAndCount : Identifiers) {
1770 RawIdentifier ID;
1771 ID.Name = IDAndCount.first();
1772 ID.References = IDAndCount.second;
1773 // Avoid treating typed filter as an identifier.
1774 if (ID.Name == HeuristicPrefix.Name)
1775 --ID.References;
1776 if (ID.References > 0)
1777 IdentifierResults.push_back(std::move(ID));
1778 }
1779
1780 // Simplified version of getQueryScopes():
1781 // - accessible scopes are determined heuristically.
1782 // - all-scopes query if no qualifier was typed (and it's allowed).
1783 SpecifiedScope Scopes;
1784 Scopes.QueryScopes = visibleNamespaces(
1785 Content.take_front(Offset), format::getFormattingLangOpts(Style));
1786 for (std::string &S : Scopes.QueryScopes)
1787 if (!S.empty())
1788 S.append("::"); // visibleNamespaces doesn't include trailing ::.
1789 if (HeuristicPrefix.Qualifier.empty())
1790 AllScopes = Opts.AllScopes;
1791 else if (HeuristicPrefix.Qualifier.starts_with("::")) {
1792 Scopes.QueryScopes = {""};
1793 Scopes.UnresolvedQualifier =
1794 std::string(HeuristicPrefix.Qualifier.drop_front(2));
1795 } else
1796 Scopes.UnresolvedQualifier = std::string(HeuristicPrefix.Qualifier);
1797 // First scope is the (modified) enclosing scope.
1798 QueryScopes = Scopes.scopesForIndexQuery();
1799 AccessibleScopes = QueryScopes;
1800 ScopeProximity.emplace(QueryScopes);
1801
1802 SymbolSlab IndexResults = Opts.Index ? queryIndex() : SymbolSlab();
1803
1804 CodeCompleteResult Output = toCodeCompleteResult(mergeResults(
1805 /*SemaResults=*/{}, IndexResults, IdentifierResults));
1806 Output.RanParser = false;
1807 logResults(Output, Tracer);
1808 return Output;
1809 }
1810
1811private:
1812 void populateContextWords(llvm::StringRef Content) {
1813 // Take last 3 lines before the completion point.
1814 unsigned RangeEnd = HeuristicPrefix.Qualifier.begin() - Content.data(),
1815 RangeBegin = RangeEnd;
1816 for (size_t I = 0; I < 3 && RangeBegin > 0; ++I) {
1817 auto PrevNL = Content.rfind('\n', RangeBegin);
1818 if (PrevNL == StringRef::npos) {
1819 RangeBegin = 0;
1820 break;
1821 }
1822 RangeBegin = PrevNL;
1823 }
1824
1825 ContextWords = collectWords(Content.slice(RangeBegin, RangeEnd));
1826 dlog("Completion context words: {0}",
1827 llvm::join(ContextWords.keys(), ", "));
1828 }
1829
1830 // This is called by run() once Sema code completion is done, but before the
1831 // Sema data structures are torn down. It does all the real work.
1832 CodeCompleteResult runWithSema() {
1833 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1834 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1835 // When we are getting completions with an empty identifier, for example
1836 // std::vector<int> asdf;
1837 // asdf.^;
1838 // Then the range will be invalid and we will be doing insertion, use
1839 // current cursor position in such cases as range.
1840 if (CodeCompletionRange.isValid()) {
1841 ReplacedRange = halfOpenToRange(Recorder->CCSema->getSourceManager(),
1842 CodeCompletionRange);
1843 } else {
1844 const auto &Pos = sourceLocToPosition(
1845 Recorder->CCSema->getSourceManager(),
1846 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1847 ReplacedRange.start = ReplacedRange.end = Pos;
1848 }
1849 Filter = FuzzyMatcher(
1850 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
1851 auto SpecifiedScopes = getQueryScopes(
1852 Recorder->CCContext, *Recorder->CCSema, HeuristicPrefix, Opts);
1853
1854 QueryScopes = SpecifiedScopes.scopesForIndexQuery();
1855 AccessibleScopes = SpecifiedScopes.scopesForQualification();
1856 AllScopes = SpecifiedScopes.AllowAllScopes;
1857 if (!QueryScopes.empty())
1858 ScopeProximity.emplace(QueryScopes);
1859 PreferredType =
1860 OpaqueType::fromType(Recorder->CCSema->getASTContext(),
1861 Recorder->CCContext.getPreferredType());
1862 // Sema provides the needed context to query the index.
1863 // FIXME: in addition to querying for extra/overlapping symbols, we should
1864 // explicitly request symbols corresponding to Sema results.
1865 // We can use their signals even if the index can't suggest them.
1866 // We must copy index results to preserve them, but there are at most Limit.
1867 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1868 ? queryIndex()
1869 : SymbolSlab();
1870 trace::Span Tracer("Populate CodeCompleteResult");
1871 // Merge Sema and Index results, score them, and pick the winners.
1872 auto Top =
1873 mergeResults(Recorder->Results, IndexResults, /*Identifiers*/ {});
1874 return toCodeCompleteResult(Top);
1875 }
1876
1877 CodeCompleteResult
1878 toCodeCompleteResult(const std::vector<ScoredBundle> &Scored) {
1879 CodeCompleteResult Output;
1880
1881 // Convert the results to final form, assembling the expensive strings.
1882 // If necessary, search the index for documentation comments.
1883 LookupRequest Req;
1884 llvm::DenseMap<SymbolID, uint32_t> SymbolToCompletion;
1885 for (auto &C : Scored) {
1886 Output.Completions.push_back(toCodeCompletion(C.first));
1887 Output.Completions.back().Score = C.second;
1888 Output.Completions.back().CompletionTokenRange = ReplacedRange;
1889 if (Opts.Index && !Output.Completions.back().Documentation) {
1890 for (auto &Cand : C.first) {
1891 if (Cand.SemaResult &&
1892 Cand.SemaResult->Kind == CodeCompletionResult::RK_Declaration) {
1893 const NamedDecl *DeclToLookup = Cand.SemaResult->getDeclaration();
1894 // For instantiations of members of class templates, the
1895 // documentation will be stored at the member's original
1896 // declaration.
1897 if (const NamedDecl *Adjusted =
1898 dyn_cast<NamedDecl>(&adjustDeclToTemplate(*DeclToLookup))) {
1899 DeclToLookup = Adjusted;
1900 }
1901 auto ID = clangd::getSymbolID(DeclToLookup);
1902 if (!ID)
1903 continue;
1904 Req.IDs.insert(ID);
1905 SymbolToCompletion[ID] = Output.Completions.size() - 1;
1906 }
1907 }
1908 }
1909 }
1910 Output.HasMore = Incomplete;
1911 Output.Context = CCContextKind;
1912 Output.CompletionRange = ReplacedRange;
1913
1914 // Look up documentation from the index.
1915 if (Opts.Index) {
1916 Opts.Index->lookup(Req, [&](const Symbol &S) {
1917 if (S.Documentation.empty())
1918 return;
1919 auto &C = Output.Completions[SymbolToCompletion.at(S.ID)];
1920 C.Documentation.emplace();
1921 parseDocumentation(S.Documentation, *C.Documentation);
1922 });
1923 }
1924
1925 return Output;
1926 }
1927
1928 SymbolSlab queryIndex() {
1929 trace::Span Tracer("Query index");
1930 SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit));
1931
1932 // Build the query.
1933 FuzzyFindRequest Req;
1934 if (Opts.Limit)
1935 Req.Limit = Opts.Limit;
1936 Req.Query = std::string(Filter->pattern());
1937 Req.RestrictForCodeCompletion = true;
1938 Req.Scopes = QueryScopes;
1939 Req.AnyScope = AllScopes;
1940 // FIXME: we should send multiple weighted paths here.
1941 Req.ProximityPaths.push_back(std::string(FileName));
1942 if (PreferredType)
1943 Req.PreferredTypes.push_back(std::string(PreferredType->raw()));
1944 vlog("Code complete: fuzzyFind({0:2})", toJSON(Req));
1945
1946 if (SpecFuzzyFind)
1947 SpecFuzzyFind->NewReq = Req;
1948 if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) {
1949 vlog("Code complete: speculative fuzzy request matches the actual index "
1950 "request. Waiting for the speculative index results.");
1951 SPAN_ATTACH(Tracer, "Speculative results", true);
1952
1953 trace::Span WaitSpec("Wait speculative results");
1954 auto SpecRes = SpecFuzzyFind->Result.get();
1955 Incomplete |= SpecRes.first;
1956 return std::move(SpecRes.second);
1957 }
1958
1959 SPAN_ATTACH(Tracer, "Speculative results", false);
1960
1961 // Run the query against the index.
1962 SymbolSlab::Builder ResultsBuilder;
1963 Incomplete |= Opts.Index->fuzzyFind(
1964 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); });
1965 return std::move(ResultsBuilder).build();
1966 }
1967
1968 // Merges Sema and Index results where possible, to form CompletionCandidates.
1969 // \p Identifiers is raw identifiers that can also be completion candidates.
1970 // Identifiers are not merged with results from index or sema.
1971 // Groups overloads if desired, to form CompletionCandidate::Bundles. The
1972 // bundles are scored and top results are returned, best to worst.
1973 std::vector<ScoredBundle>
1974 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
1975 const SymbolSlab &IndexResults,
1976 const std::vector<RawIdentifier> &IdentifierResults) {
1977 trace::Span Tracer("Merge and score results");
1978 std::vector<CompletionCandidate::Bundle> Bundles;
1979 llvm::DenseMap<size_t, size_t> BundleLookup;
1980 auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
1981 const Symbol *IndexResult,
1982 const RawIdentifier *IdentifierResult) {
1983 CompletionCandidate C;
1984 C.SemaResult = SemaResult;
1985 C.IndexResult = IndexResult;
1986 C.IdentifierResult = IdentifierResult;
1987 if (C.IndexResult) {
1988 C.Name = IndexResult->Name;
1989 C.RankedIncludeHeaders = getRankedIncludes(*C.IndexResult);
1990 } else if (C.SemaResult) {
1991 C.Name = Recorder->getName(*SemaResult);
1992 } else {
1993 assert(IdentifierResult);
1994 C.Name = IdentifierResult->Name;
1995 }
1996 if (auto OverloadSet = C.overloadSet(
1997 Opts, FileName, Inserter ? &*Inserter : nullptr, CCContextKind)) {
1998 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1999 if (Ret.second)
2000 Bundles.emplace_back();
2001 Bundles[Ret.first->second].push_back(std::move(C));
2002 } else {
2003 Bundles.emplace_back();
2004 Bundles.back().push_back(std::move(C));
2005 }
2006 };
2007 llvm::DenseSet<const Symbol *> UsedIndexResults;
2008 auto CorrespondingIndexResult =
2009 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
2010 if (auto SymID =
2011 getSymbolID(SemaResult, Recorder->CCSema->getSourceManager())) {
2012 auto I = IndexResults.find(SymID);
2013 if (I != IndexResults.end()) {
2014 UsedIndexResults.insert(&*I);
2015 return &*I;
2016 }
2017 }
2018 return nullptr;
2019 };
2020 // Emit all Sema results, merging them with Index results if possible.
2021 for (auto &SemaResult : SemaResults)
2022 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult), nullptr);
2023 // Now emit any Index-only results.
2024 for (const auto &IndexResult : IndexResults) {
2025 if (UsedIndexResults.count(&IndexResult))
2026 continue;
2027 if (!includeSymbolFromIndex(CCContextKind, IndexResult))
2028 continue;
2029 AddToBundles(/*SemaResult=*/nullptr, &IndexResult, nullptr);
2030 }
2031 // Emit identifier results.
2032 for (const auto &Ident : IdentifierResults)
2033 AddToBundles(/*SemaResult=*/nullptr, /*IndexResult=*/nullptr, &Ident);
2034 // We only keep the best N results at any time, in "native" format.
2035 TopN<ScoredBundle, ScoredBundleGreater> Top(
2036 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
2037 for (auto &Bundle : Bundles)
2038 addCandidate(Top, std::move(Bundle));
2039 return std::move(Top).items();
2040 }
2041
2042 std::optional<float> fuzzyScore(const CompletionCandidate &C) {
2043 using MacroFilterPolicy = Config::MacroFilterPolicy;
2044
2045 const auto IsMacroResult =
2046 ((C.SemaResult &&
2047 C.SemaResult->Kind == CodeCompletionResult::RK_Macro) ||
2048 (C.IndexResult &&
2049 C.IndexResult->SymInfo.Kind == index::SymbolKind::Macro));
2050
2051 if (!IsMacroResult)
2052 return Filter->match(C.Name);
2053
2054 // macros with underscores are probably noisy, so don't suggest them
2055 bool RequireExactPrefix =
2056 Opts.MacroFilter == MacroFilterPolicy::ExactPrefix ||
2057 C.Name.starts_with_insensitive("_") ||
2058 C.Name.ends_with_insensitive("_");
2059
2060 if (RequireExactPrefix &&
2061 !C.Name.starts_with_insensitive(Filter->pattern())) {
2062 return std::nullopt;
2063 }
2064
2065 return Filter->match(C.Name);
2066 }
2067
2068 CodeCompletion::Scores
2069 evaluateCompletion(const SymbolQualitySignals &Quality,
2070 const SymbolRelevanceSignals &Relevance) {
2071 using RM = CodeCompleteOptions::CodeCompletionRankingModel;
2072 CodeCompletion::Scores Scores;
2073 switch (Opts.RankingModel) {
2074 case RM::Heuristics:
2075 Scores.Quality = Quality.evaluateHeuristics();
2076 Scores.Relevance = Relevance.evaluateHeuristics();
2077 Scores.Total =
2078 evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
2079 // NameMatch is in fact a multiplier on total score, so rescoring is
2080 // sound.
2081 Scores.ExcludingName =
2082 Relevance.NameMatch > std::numeric_limits<float>::epsilon()
2083 ? Scores.Total / Relevance.NameMatch
2084 : Scores.Quality;
2085 return Scores;
2086
2087 case RM::DecisionForest:
2088 DecisionForestScores DFScores = Opts.DecisionForestScorer(
2089 Quality, Relevance, Opts.DecisionForestBase);
2090 Scores.ExcludingName = DFScores.ExcludingName;
2091 Scores.Total = DFScores.Total;
2092 return Scores;
2093 }
2094 llvm_unreachable("Unhandled CodeCompletion ranking model.");
2095 }
2096
2097 // Scores a candidate and adds it to the TopN structure.
2098 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
2099 CompletionCandidate::Bundle Bundle) {
2100 SymbolQualitySignals Quality;
2101 SymbolRelevanceSignals Relevance;
2102 Relevance.Context = CCContextKind;
2103 Relevance.Name = Bundle.front().Name;
2104 Relevance.FilterLength = HeuristicPrefix.Name.size();
2105 Relevance.Query = SymbolRelevanceSignals::CodeComplete;
2106 Relevance.FileProximityMatch = &*FileProximity;
2107 if (ScopeProximity)
2108 Relevance.ScopeProximityMatch = &*ScopeProximity;
2109 if (PreferredType)
2110 Relevance.HadContextType = true;
2111 Relevance.ContextWords = &ContextWords;
2112 Relevance.MainFileSignals = Opts.MainFileSignals;
2113
2114 auto &First = Bundle.front();
2115 if (auto FuzzyScore = fuzzyScore(First))
2116 Relevance.NameMatch = *FuzzyScore;
2117 else
2118 return;
2119 SymbolOrigin Origin = SymbolOrigin::Unknown;
2120 bool FromIndex = false;
2121 for (const auto &Candidate : Bundle) {
2122 if (Candidate.IndexResult) {
2123 Quality.merge(*Candidate.IndexResult);
2124 Relevance.merge(*Candidate.IndexResult);
2125 Origin |= Candidate.IndexResult->Origin;
2126 FromIndex = true;
2127 if (!Candidate.IndexResult->Type.empty())
2128 Relevance.HadSymbolType |= true;
2129 if (PreferredType &&
2130 PreferredType->raw() == Candidate.IndexResult->Type) {
2131 Relevance.TypeMatchesPreferred = true;
2132 }
2133 }
2134 if (Candidate.SemaResult) {
2135 Quality.merge(*Candidate.SemaResult);
2136 Relevance.merge(*Candidate.SemaResult);
2137 if (PreferredType) {
2138 if (auto CompletionType = OpaqueType::fromCompletionResult(
2139 Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
2140 Relevance.HadSymbolType |= true;
2141 if (PreferredType == CompletionType)
2142 Relevance.TypeMatchesPreferred = true;
2143 }
2144 }
2145 Origin |= SymbolOrigin::AST;
2146 }
2147 if (Candidate.IdentifierResult) {
2148 Quality.References = Candidate.IdentifierResult->References;
2149 Relevance.Scope = SymbolRelevanceSignals::FileScope;
2150 Origin |= SymbolOrigin::Identifier;
2151 }
2152 }
2153
2154 CodeCompletion::Scores Scores = evaluateCompletion(Quality, Relevance);
2155 if (Opts.RecordCCResult)
2156 Opts.RecordCCResult(toCodeCompletion(Bundle), Quality, Relevance,
2157 Scores.Total);
2158
2159 dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
2160 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
2161 llvm::to_string(Relevance));
2162
2163 NSema += bool(Origin & SymbolOrigin::AST);
2164 NIndex += FromIndex;
2165 NSemaAndIndex += bool(Origin & SymbolOrigin::AST) && FromIndex;
2166 NIdent += bool(Origin & SymbolOrigin::Identifier);
2167 if (Candidates.push({std::move(Bundle), Scores}))
2168 Incomplete = true;
2169 }
2170
2171 CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
2172 std::optional<CodeCompletionBuilder> Builder;
2173 for (const auto &Item : Bundle) {
2174 CodeCompletionString *SemaCCS =
2175 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
2176 : nullptr;
2177 if (!Builder)
2178 Builder.emplace(Recorder ? &Recorder->CCSema->getASTContext() : nullptr,
2179 Item, SemaCCS, AccessibleScopes, *Inserter, FileName,
2180 CCContextKind, Opts, IsUsingDeclaration, NextTokenKind);
2181 else
2182 Builder->add(Item, SemaCCS, CCContextKind);
2183 }
2184 return Builder->build();
2185 }
2186};
2187
2188} // namespace
2189
2190clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
2191 clang::CodeCompleteOptions Result;
2192 Result.IncludeCodePatterns =
2193 EnableSnippets && (CodePatterns != Config::CodePatternsPolicy::None);
2194 Result.IncludeMacros = true;
2195 Result.IncludeGlobals = true;
2196 // We choose to include full comments and not do doxygen parsing in
2197 // completion.
2198 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
2199 // formatting of the comments.
2200 Result.IncludeBriefComments = false;
2201
2202 // When an is used, Sema is responsible for completing the main file,
2203 // the index can provide results from the preamble.
2204 // Tell Sema not to deserialize the preamble to look for results.
2205 Result.LoadExternal = ForceLoadPreamble || !Index;
2206 Result.IncludeFixIts = IncludeFixIts;
2207
2208 return Result;
2209}
2210
2212 unsigned Offset) {
2213 assert(Offset <= Content.size());
2214 StringRef Rest = Content.take_front(Offset);
2215 CompletionPrefix Result;
2216
2217 // Consume the unqualified name. We only handle ASCII characters.
2218 // isAsciiIdentifierContinue will let us match "0invalid", but we don't mind.
2219 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2220 Rest = Rest.drop_back();
2221 Result.Name = Content.slice(Rest.size(), Offset);
2222
2223 // Consume qualifiers.
2224 while (Rest.consume_back("::") && !Rest.ends_with(":")) // reject ::::
2225 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2226 Rest = Rest.drop_back();
2227 Result.Qualifier =
2228 Content.slice(Rest.size(), Result.Name.begin() - Content.begin());
2229
2230 return Result;
2231}
2232
2233// Code complete the argument name on "/*" inside function call.
2234// Offset should be pointing to the start of the comment, i.e.:
2235// foo(^/*, rather than foo(/*^) where the cursor probably is.
2236CodeCompleteResult codeCompleteComment(PathRef FileName, unsigned Offset,
2237 llvm::StringRef Prefix,
2238 const PreambleData *Preamble,
2239 const ParseInputs &ParseInput) {
2240 if (Preamble == nullptr) // Can't run without Sema.
2241 return CodeCompleteResult();
2242
2243 clang::CodeCompleteOptions Options;
2244 Options.IncludeGlobals = false;
2245 Options.IncludeMacros = false;
2246 Options.IncludeCodePatterns = false;
2247 Options.IncludeBriefComments = false;
2248 std::set<std::string> ParamNames;
2249 // We want to see signatures coming from newly introduced includes, hence a
2250 // full patch.
2251 semaCodeComplete(
2252 std::make_unique<ParamNameCollector>(Options, ParamNames), Options,
2253 {FileName, Offset, *Preamble,
2254 PreamblePatch::createFullPatch(FileName, ParseInput, *Preamble),
2255 ParseInput});
2256 if (ParamNames.empty())
2257 return CodeCompleteResult();
2258
2259 CodeCompleteResult Result;
2260 Range CompletionRange;
2261 // Skip /*
2262 Offset += 2;
2263 CompletionRange.start = offsetToPosition(ParseInput.Contents, Offset);
2264 CompletionRange.end =
2265 offsetToPosition(ParseInput.Contents, Offset + Prefix.size());
2266 Result.CompletionRange = CompletionRange;
2267 Result.Context = CodeCompletionContext::CCC_NaturalLanguage;
2268 for (llvm::StringRef Name : ParamNames) {
2269 if (!Name.starts_with(Prefix))
2270 continue;
2271 CodeCompletion Item;
2272 Item.Name = Name.str() + "=*/";
2273 Item.FilterText = Item.Name;
2274 Item.Kind = CompletionItemKind::Text;
2275 Item.CompletionTokenRange = CompletionRange;
2276 Item.Origin = SymbolOrigin::AST;
2277 Result.Completions.push_back(Item);
2278 }
2279
2280 return Result;
2281}
2282
2283// If Offset is inside what looks like argument comment (e.g.
2284// "/*^" or "/* foo^"), returns new offset pointing to the start of the /*
2285// (place where semaCodeComplete should run).
2286std::optional<unsigned>
2287maybeFunctionArgumentCommentStart(llvm::StringRef Content) {
2288 while (!Content.empty() && isAsciiIdentifierContinue(Content.back()))
2289 Content = Content.drop_back();
2290 Content = Content.rtrim();
2291 if (Content.ends_with("/*"))
2292 return Content.size() - 2;
2293 return std::nullopt;
2294}
2295
2296CodeCompleteResult codeComplete(PathRef FileName, Position Pos,
2297 const PreambleData *Preamble,
2298 const ParseInputs &ParseInput,
2300 SpeculativeFuzzyFind *SpecFuzzyFind) {
2301 auto Offset = positionToOffset(ParseInput.Contents, Pos);
2302 if (!Offset) {
2303 elog("Code completion position was invalid {0}", Offset.takeError());
2304 return CodeCompleteResult();
2305 }
2306
2307 auto Content = llvm::StringRef(ParseInput.Contents).take_front(*Offset);
2308 if (auto OffsetBeforeComment = maybeFunctionArgumentCommentStart(Content)) {
2309 // We are doing code completion of a comment, where we currently only
2310 // support completing param names in function calls. To do this, we
2311 // require information from Sema, but Sema's comment completion stops at
2312 // parsing, so we must move back the position before running it, extract
2313 // information we need and construct completion items ourselves.
2314 auto CommentPrefix = Content.substr(*OffsetBeforeComment + 2).trim();
2315 return codeCompleteComment(FileName, *OffsetBeforeComment, CommentPrefix,
2316 Preamble, ParseInput);
2317 }
2318
2319 auto Flow = CodeCompleteFlow(
2320 FileName, Preamble ? Preamble->Includes : IncludeStructure(),
2321 SpecFuzzyFind, Opts);
2322 return (!Preamble || Opts.RunParser == CodeCompleteOptions::NeverParse)
2323 ? std::move(Flow).runWithoutSema(ParseInput.Contents, *Offset,
2324 *ParseInput.TFS)
2325 : std::move(Flow).run({FileName, *Offset, *Preamble,
2326 /*PreamblePatch=*/
2328 FileName, ParseInput, *Preamble),
2329 ParseInput});
2330}
2331
2333 const PreambleData &Preamble,
2334 const ParseInputs &ParseInput,
2335 MarkupKind DocumentationFormat) {
2336 auto Offset = positionToOffset(ParseInput.Contents, Pos);
2337 if (!Offset) {
2338 elog("Signature help position was invalid {0}", Offset.takeError());
2339 return SignatureHelp();
2340 }
2341 SignatureHelp Result;
2342 clang::CodeCompleteOptions Options;
2343 Options.IncludeGlobals = false;
2344 Options.IncludeMacros = false;
2345 Options.IncludeCodePatterns = false;
2346 Options.IncludeBriefComments = false;
2347 semaCodeComplete(
2348 std::make_unique<SignatureHelpCollector>(Options, DocumentationFormat,
2349 ParseInput.Index, Result),
2350 Options,
2351 {FileName, *Offset, Preamble,
2352 PreamblePatch::createFullPatch(FileName, ParseInput, Preamble),
2353 ParseInput});
2354 return Result;
2355}
2356
2357bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
2358 auto InTopLevelScope = [](const NamedDecl &ND) {
2359 switch (ND.getDeclContext()->getDeclKind()) {
2360 case Decl::TranslationUnit:
2361 case Decl::Namespace:
2362 case Decl::LinkageSpec:
2363 return true;
2364 default:
2365 break;
2366 };
2367 return false;
2368 };
2369 auto InClassScope = [](const NamedDecl &ND) {
2370 return ND.getDeclContext()->getDeclKind() == Decl::CXXRecord;
2371 };
2372 // We only complete symbol's name, which is the same as the name of the
2373 // *primary* template in case of template specializations.
2375 return false;
2376
2377 // Category decls are not useful on their own outside the interface or
2378 // implementation blocks. Moreover, sema already provides completion for
2379 // these, even if it requires preamble deserialization. So by excluding them
2380 // from the index, we reduce the noise in all the other completion scopes.
2381 if (llvm::isa<ObjCCategoryDecl>(&ND) || llvm::isa<ObjCCategoryImplDecl>(&ND))
2382 return false;
2383
2384 if (InTopLevelScope(ND))
2385 return true;
2386
2387 // Always index enum constants, even if they're not in the top level scope:
2388 // when
2389 // --all-scopes-completion is set, we'll want to complete those as well.
2390 if (const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext()))
2391 return (InTopLevelScope(*EnumDecl) || InClassScope(*EnumDecl));
2392
2393 return false;
2394}
2395
2396CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
2397 CompletionItem LSP;
2398 const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0];
2399 // We could move our indicators from label into labelDetails->description.
2400 // In VSCode there are rendering issues that prevent these being aligned.
2401 LSP.label = ((InsertInclude && InsertInclude->Insertion)
2402 ? Opts.IncludeIndicator.Insert
2403 : Opts.IncludeIndicator.NoInsert) +
2404 (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
2405 RequiredQualifier + Name;
2406 LSP.labelDetails.emplace();
2407 LSP.labelDetails->detail = Signature;
2408
2409 LSP.kind = Kind;
2410 LSP.detail = BundleSize > 1
2411 ? std::string(llvm::formatv("[{0} overloads]", BundleSize))
2412 : ReturnType;
2413 LSP.deprecated = Deprecated;
2414 // Combine header information and documentation in LSP `documentation` field.
2415 // This is not quite right semantically, but tends to display well in editors.
2416 if (InsertInclude || Documentation) {
2417 markup::Document Doc;
2418 if (InsertInclude)
2419 Doc.addParagraph().appendText("From ").appendCode(InsertInclude->Header);
2420 if (Documentation)
2421 Doc.append(*Documentation);
2422 LSP.documentation = renderDoc(Doc, Opts.DocumentationFormat);
2423 }
2424 LSP.sortText = sortText(Score.Total, FilterText);
2425 LSP.filterText = FilterText;
2426 LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name, ""};
2427 // Merge continuous additionalTextEdits into main edit. The main motivation
2428 // behind this is to help LSP clients, it seems most of them are confused when
2429 // they are provided with additionalTextEdits that are consecutive to main
2430 // edit.
2431 // Note that we store additional text edits from back to front in a line. That
2432 // is mainly to help LSP clients again, so that changes do not effect each
2433 // other.
2434 for (const auto &FixIt : FixIts) {
2435 if (FixIt.range.end == LSP.textEdit->range.start) {
2436 LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
2437 LSP.textEdit->range.start = FixIt.range.start;
2438 } else {
2439 LSP.additionalTextEdits.push_back(FixIt);
2440 }
2441 }
2442 if (Opts.EnableSnippets)
2443 LSP.textEdit->newText += SnippetSuffix;
2444
2445 // FIXME(kadircet): Do not even fill insertText after making sure textEdit is
2446 // compatible with most of the editors.
2447 LSP.insertText = LSP.textEdit->newText;
2448 // Some clients support snippets but work better with plaintext.
2449 // So if the snippet is trivial, let the client know.
2450 // https://github.com/clangd/clangd/issues/922
2451 LSP.insertTextFormat = (Opts.EnableSnippets && !SnippetSuffix.empty())
2454 if (InsertInclude && InsertInclude->Insertion)
2455 LSP.additionalTextEdits.push_back(*InsertInclude->Insertion);
2456
2457 LSP.score = Score.ExcludingName;
2458
2459 return LSP;
2460}
2461
2462llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const CodeCompletion &C) {
2463 OS << "Signature: " << "\"" << C.Signature << "\", "
2464 << "SnippetSuffix: " << "\"" << C.SnippetSuffix << "\""
2465 << ", Rendered:";
2466 // For now just lean on CompletionItem.
2467 return OS << C.render(CodeCompleteOptions());
2468}
2469
2470llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
2471 const CodeCompleteResult &R) {
2472 OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
2473 << " (" << getCompletionKindString(R.Context) << ")"
2474 << " items:\n";
2475 for (const auto &C : R.Completions)
2476 OS << C << "\n";
2477 return OS;
2478}
2479
2480// Heuristically detect whether the `Line` is an unterminated include filename.
2481bool isIncludeFile(llvm::StringRef Line) {
2482 Line = Line.ltrim();
2483 if (!Line.consume_front("#"))
2484 return false;
2485 Line = Line.ltrim();
2486 if (!(Line.consume_front("include_next") || Line.consume_front("include") ||
2487 Line.consume_front("import")))
2488 return false;
2489 Line = Line.ltrim();
2490 if (Line.consume_front("<"))
2491 return Line.count('>') == 0;
2492 if (Line.consume_front("\""))
2493 return Line.count('"') == 0;
2494 return false;
2495}
2496
2497bool allowImplicitCompletion(llvm::StringRef Content, unsigned Offset) {
2498 // Look at last line before completion point only.
2499 Content = Content.take_front(Offset);
2500 auto Pos = Content.rfind('\n');
2501 if (Pos != llvm::StringRef::npos)
2502 Content = Content.substr(Pos + 1);
2503
2504 // Complete after scope operators.
2505 if (Content.ends_with(".") || Content.ends_with("->") ||
2506 Content.ends_with("::") || Content.ends_with("/*"))
2507 return true;
2508 // Complete after `#include <` and #include `<foo/`.
2509 if ((Content.ends_with("<") || Content.ends_with("\"") ||
2510 Content.ends_with("/")) &&
2511 isIncludeFile(Content))
2512 return true;
2513
2514 // Complete words. Give non-ascii characters the benefit of the doubt.
2515 return !Content.empty() && (isAsciiIdentifierContinue(Content.back()) ||
2516 !llvm::isASCII(Content.back()));
2517}
2518
2519} // namespace clangd
2520} // namespace clang
static clang::FrontendPluginRegistry::Add< clang::tidy::ClangTidyPluginAction > X("clang-tidy", "clang-tidy")
#define dlog(...)
Definition Logger.h:101
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
Definition Trace.h:164
static std::optional< OpaqueType > fromCompletionResult(ASTContext &Ctx, const CodeCompletionResult &R)
Create a type from a code completion result.
static std::optional< OpaqueType > fromType(ASTContext &Ctx, QualType Type)
Construct an instance from a clang::QualType.
static PreamblePatch createMacroPatch(llvm::StringRef FileName, const ParseInputs &Modified, const PreambleData &Baseline)
Definition Preamble.cpp:905
static PreamblePatch createFullPatch(llvm::StringRef FileName, const ParseInputs &Modified, const PreambleData &Baseline)
Builds a patch that contains new PP directives introduced to the preamble section of Modified compare...
Definition Preamble.cpp:899
static llvm::Expected< std::string > resolve(const URI &U, llvm::StringRef HintPath="")
Resolves the absolute path of U.
Definition URI.cpp:244
std::pair< StringRef, StringRef > splitQualifiedName(StringRef QName)
@ Info
An information message.
Definition Protocol.h:738
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
Definition AST.cpp:354
std::string formatDocumentation(const CodeCompletionString &CCS, llvm::StringRef DocComment)
Assembles formatted documentation for a completion result.
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
std::string sortText(float Score, llvm::StringRef Name)
Returns a string that sorts in the same order as (-Score, Tiebreak), for LSP.
Definition Quality.cpp:552
std::string getDeclComment(const ASTContext &Ctx, const NamedDecl &Decl)
Similar to getDocComment, but returns the comment for a NamedDecl.
bool isIncludeFile(llvm::StringRef Line)
TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M, const LangOptions &L)
Position offsetToPosition(llvm::StringRef Code, size_t Offset)
Turn an offset in Code into a [line, column] pair.
size_t lspLength(llvm::StringRef Code)
CompletionPrefix guessCompletionPrefix(llvm::StringRef Content, unsigned Offset)
std::unique_ptr< CompilerInvocation > buildCompilerInvocation(const ParseInputs &Inputs, clang::DiagnosticConsumer &D, std::vector< std::string > *CC1Args)
Builds compiler invocation that could be used to build AST or preamble.
Definition Compiler.cpp:96
bool isExplicitTemplateSpecialization(const NamedDecl *D)
Indicates if D is an explicit template specialization, e.g.
Definition AST.cpp:187
bool allowImplicitCompletion(llvm::StringRef Content, unsigned Offset)
void vlog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:72
static const char * toString(OffsetEncoding OE)
CodeCompleteResult codeCompleteComment(PathRef FileName, unsigned Offset, llvm::StringRef Prefix, const PreambleData *Preamble, const ParseInputs &ParseInput)
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
Definition Logger.h:79
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
std::string getReturnType(const CodeCompletionString &CCS)
Gets detail to be used as the detail field in an LSP completion item.
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
llvm::StringMap< unsigned > collectIdentifiers(llvm::StringRef Content, const format::FormatStyle &Style)
Collects identifiers with counts in the source code.
bool hasUnstableLinkage(const Decl *D)
Whether we must avoid computing linkage for D during code completion.
Definition AST.cpp:735
llvm::json::Value toJSON(const FuzzyFindRequest &Request)
Definition Index.cpp:45
std::vector< std::string > visibleNamespaces(llvm::StringRef Code, const LangOptions &LangOpts)
Heuristically determine namespaces visible at a point, without parsing Code.
llvm::Expected< HeaderFile > toHeaderFile(llvm::StringRef Header, llvm::StringRef HintPath)
Creates a HeaderFile from Header which can be either a URI or a literal include.
Definition Headers.cpp:143
std::unique_ptr< CompilerInstance > prepareCompilerInstance(std::unique_ptr< clang::CompilerInvocation > CI, const PrecompiledPreamble *Preamble, std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, DiagnosticConsumer &DiagsClient)
Definition Compiler.cpp:131
std::future< T > runAsync(llvm::unique_function< T()> Action)
Runs Action asynchronously with a new std::thread.
Definition Threading.h:127
void log(const char *Fmt, Ts &&... Vals)
Definition Logger.h:67
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
std::optional< unsigned > maybeFunctionArgumentCommentStart(llvm::StringRef Content)
llvm::StringSet collectWords(llvm::StringRef Content)
Collects words from the source code.
void getSignature(const CodeCompletionString &CCS, std::string *Signature, std::string *Snippet, CodeCompletionResult::ResultKind ResultKind, CXCursorKind CursorKind, bool IncludeFunctionArguments, std::string *RequiredQualifiers)
Formats the signature for an item, as a display string and snippet.
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition Path.h:29
llvm::SmallVector< SymbolInclude, 1 > getRankedIncludes(const Symbol &Sym)
Definition Headers.cpp:163
std::pair< size_t, size_t > offsetToClangLineColumn(llvm::StringRef Code, size_t Offset)
@ Deprecated
Deprecated or obsolete code.
Definition Protocol.h:919
@ Full
Documents are synced by always sending the full content of the document.
Definition Protocol.h:330
void parseDocumentation(llvm::StringRef Input, markup::Document &Output)
Definition Hover.cpp:1795
float evaluateSymbolAndRelevance(float SymbolQuality, float SymbolRelevance)
Combine symbol quality and relevance into a single score.
Definition Quality.cpp:534
CodeCompleteResult codeComplete(PathRef FileName, Position Pos, const PreambleData *Preamble, const ParseInputs &ParseInput, CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind)
Gets code completions at a specified Pos in FileName.
@ PlainText
The primary text to be inserted is treated as a plain string.
Definition Protocol.h:1310
@ Snippet
The primary text to be inserted is treated as a snippet.
Definition Protocol.h:1320
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
Definition AST.cpp:206
SignatureHelp signatureHelp(PathRef FileName, Position Pos, const PreambleData &Preamble, const ParseInputs &ParseInput, MarkupKind DocumentationFormat)
Get signature help at a specified Pos in FileName.
void elog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:61
std::string getDocComment(const ASTContext &Ctx, const CodeCompletionResult &Result, bool CommentsFromHeaders)
Gets a minimally formatted documentation comment of Result, with comment markers stripped.
std::string printNamespaceScope(const DeclContext &DC)
Returns the first enclosing namespace scope starting from DC.
Definition AST.cpp:303
bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx)
format::FormatStyle getFormatStyleForFile(llvm::StringRef File, llvm::StringRef Content, const ThreadsafeFS &TFS, bool FormatFile)
Choose the clang-format style we should apply to a certain file.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
-clang-tidy
clang::CodeCompleteOptions getClangCompleteOpts() const
Returns options that can be passed to clang's completion engine.
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
Definition Config.cpp:17
ArgumentListsPolicy
controls the completion options for argument lists.
Definition Config.h:139
@ None
nothing, no argument list and also NO Delimiters "()" or "<>".
Definition Config.h:141
@ Delimiters
empty pair of delimiters "()" or "<>".
Definition Config.h:145
@ OpenDelimiter
open, only opening delimiter "(" or "<".
Definition Config.h:143
@ FullPlaceholders
full name of both type and variable.
Definition Config.h:147
@ PlainText
Treat comments as plain text.
Definition Config.h:213
std::vector< std::function< bool(llvm::StringRef)> > QuotedHeaders
Definition Config.h:134
CodePatternsPolicy CodePatterns
Enables code patterns & snippets suggestions.
Definition Config.h:176
CommentFormatPolicy CommentFormat
Definition Config.h:221
std::vector< std::function< bool(llvm::StringRef)> > AngledHeaders
Definition Config.h:135
struct clang::clangd::Config::@365336221326264215251130354321073040111277322060 Style
Style of the codebase.
Information required to run clang, e.g. to parse AST or do code completion.
Definition Compiler.h:49
const ThreadsafeFS * TFS
Definition Compiler.h:51
const SymbolIndex * Index
Definition Compiler.h:59
The parsed preamble and associated data.
Definition Preamble.h:97
Position start
The range's start position.
Definition Protocol.h:187
Position end
The range's end position.
Definition Protocol.h:190
Represents the signature of a callable.
Definition Protocol.h:1456
@ Deprecated
Indicates if the symbol is deprecated.
Definition Symbol.h:143
@ Include
#include "header.h"
Definition Symbol.h:93
@ Import
#import "header.h"
Definition Symbol.h:95