1 //===- CodeCompleteConsumer.cpp - Code Completion Interface ---------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the CodeCompleteConsumer class.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/CodeCompleteConsumer.h"
14 #include "clang-c/Index.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclBase.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/DeclarationName.h"
20 #include "clang/AST/Type.h"
21 #include "clang/Basic/IdentifierTable.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Sema/Sema.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FormatVariadic.h"
33 #include "llvm/Support/raw_ostream.h"
39 using namespace clang;
41 //===----------------------------------------------------------------------===//
42 // Code completion context implementation
43 //===----------------------------------------------------------------------===//
45 bool CodeCompletionContext::wantConstructorResults() const {
50 case CCC_ObjCMessageReceiver:
51 case CCC_ParenthesizedExpression:
53 case CCC_SymbolOrNewName:
57 case CCC_ObjCInterface:
58 case CCC_ObjCImplementation:
59 case CCC_ObjCIvarList:
60 case CCC_ClassStructUnion:
61 case CCC_DotMemberAccess:
62 case CCC_ArrowMemberAccess:
63 case CCC_ObjCPropertyAccess:
66 case CCC_ClassOrStructTag:
67 case CCC_ObjCProtocolName:
72 case CCC_MacroNameUse:
73 case CCC_PreprocessorExpression:
74 case CCC_PreprocessorDirective:
75 case CCC_NaturalLanguage:
76 case CCC_SelectorName:
77 case CCC_TypeQualifiers:
79 case CCC_OtherWithMacros:
80 case CCC_ObjCInstanceMessage:
81 case CCC_ObjCClassMessage:
82 case CCC_ObjCInterfaceName:
83 case CCC_ObjCCategoryName:
84 case CCC_IncludedFile:
88 llvm_unreachable("Invalid CodeCompletionContext::Kind!");
91 StringRef clang::getCompletionKindString(CodeCompletionContext::Kind Kind) {
92 using CCKind = CodeCompletionContext::Kind;
94 case CCKind::CCC_Other:
96 case CCKind::CCC_OtherWithMacros:
97 return "OtherWithMacros";
98 case CCKind::CCC_TopLevel:
100 case CCKind::CCC_ObjCInterface:
101 return "ObjCInterface";
102 case CCKind::CCC_ObjCImplementation:
103 return "ObjCImplementation";
104 case CCKind::CCC_ObjCIvarList:
105 return "ObjCIvarList";
106 case CCKind::CCC_ClassStructUnion:
107 return "ClassStructUnion";
108 case CCKind::CCC_Statement:
110 case CCKind::CCC_Expression:
112 case CCKind::CCC_ObjCMessageReceiver:
113 return "ObjCMessageReceiver";
114 case CCKind::CCC_DotMemberAccess:
115 return "DotMemberAccess";
116 case CCKind::CCC_ArrowMemberAccess:
117 return "ArrowMemberAccess";
118 case CCKind::CCC_ObjCPropertyAccess:
119 return "ObjCPropertyAccess";
120 case CCKind::CCC_EnumTag:
122 case CCKind::CCC_UnionTag:
124 case CCKind::CCC_ClassOrStructTag:
125 return "ClassOrStructTag";
126 case CCKind::CCC_ObjCProtocolName:
127 return "ObjCProtocolName";
128 case CCKind::CCC_Namespace:
130 case CCKind::CCC_Type:
132 case CCKind::CCC_NewName:
134 case CCKind::CCC_Symbol:
136 case CCKind::CCC_SymbolOrNewName:
137 return "SymbolOrNewName";
138 case CCKind::CCC_MacroName:
140 case CCKind::CCC_MacroNameUse:
141 return "MacroNameUse";
142 case CCKind::CCC_PreprocessorExpression:
143 return "PreprocessorExpression";
144 case CCKind::CCC_PreprocessorDirective:
145 return "PreprocessorDirective";
146 case CCKind::CCC_NaturalLanguage:
147 return "NaturalLanguage";
148 case CCKind::CCC_SelectorName:
149 return "SelectorName";
150 case CCKind::CCC_TypeQualifiers:
151 return "TypeQualifiers";
152 case CCKind::CCC_ParenthesizedExpression:
153 return "ParenthesizedExpression";
154 case CCKind::CCC_ObjCInstanceMessage:
155 return "ObjCInstanceMessage";
156 case CCKind::CCC_ObjCClassMessage:
157 return "ObjCClassMessage";
158 case CCKind::CCC_ObjCInterfaceName:
159 return "ObjCInterfaceName";
160 case CCKind::CCC_ObjCCategoryName:
161 return "ObjCCategoryName";
162 case CCKind::CCC_IncludedFile:
163 return "IncludedFile";
164 case CCKind::CCC_Recovery:
167 llvm_unreachable("Invalid CodeCompletionContext::Kind!");
170 //===----------------------------------------------------------------------===//
171 // Code completion string implementation
172 //===----------------------------------------------------------------------===//
174 CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text)
175 : Kind(Kind), Text("") {
182 case CK_CurrentParameter:
187 llvm_unreachable("Optional strings cannot be created from text");
201 case CK_RightBracket:
237 case CK_HorizontalSpace:
241 case CK_VerticalSpace:
247 CodeCompletionString::Chunk
248 CodeCompletionString::Chunk::CreateText(const char *Text) {
249 return Chunk(CK_Text, Text);
252 CodeCompletionString::Chunk
253 CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
255 Result.Kind = CK_Optional;
256 Result.Optional = Optional;
260 CodeCompletionString::Chunk
261 CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
262 return Chunk(CK_Placeholder, Placeholder);
265 CodeCompletionString::Chunk
266 CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
267 return Chunk(CK_Informative, Informative);
270 CodeCompletionString::Chunk
271 CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
272 return Chunk(CK_ResultType, ResultType);
275 CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateCurrentParameter(
276 const char *CurrentParameter) {
277 return Chunk(CK_CurrentParameter, CurrentParameter);
280 CodeCompletionString::CodeCompletionString(
281 const Chunk *Chunks, unsigned NumChunks, unsigned Priority,
282 CXAvailabilityKind Availability, const char **Annotations,
283 unsigned NumAnnotations, StringRef ParentName, const char *BriefComment)
284 : NumChunks(NumChunks), NumAnnotations(NumAnnotations), Priority(Priority),
285 Availability(Availability), ParentName(ParentName),
286 BriefComment(BriefComment) {
287 assert(NumChunks <= 0xffff);
288 assert(NumAnnotations <= 0xffff);
290 Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
291 for (unsigned I = 0; I != NumChunks; ++I)
292 StoredChunks[I] = Chunks[I];
294 const char **StoredAnnotations =
295 reinterpret_cast<const char **>(StoredChunks + NumChunks);
296 for (unsigned I = 0; I != NumAnnotations; ++I)
297 StoredAnnotations[I] = Annotations[I];
300 unsigned CodeCompletionString::getAnnotationCount() const {
301 return NumAnnotations;
304 const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
305 if (AnnotationNr < NumAnnotations)
306 return reinterpret_cast<const char *const *>(end())[AnnotationNr];
311 std::string CodeCompletionString::getAsString() const {
313 llvm::raw_string_ostream OS(Result);
315 for (const Chunk &C : *this) {
318 OS << "{#" << C.Optional->getAsString() << "#}";
321 OS << "<#" << C.Text << "#>";
325 OS << "[#" << C.Text << "#]";
327 case CK_CurrentParameter:
328 OS << "<#" << C.Text << "#>";
338 const char *CodeCompletionString::getTypedText() const {
339 for (const Chunk &C : *this)
340 if (C.Kind == CK_TypedText)
346 const char *CodeCompletionAllocator::CopyString(const Twine &String) {
347 SmallString<128> Data;
348 StringRef Ref = String.toStringRef(Data);
349 // FIXME: It would be more efficient to teach Twine to tell us its size and
350 // then add a routine there to fill in an allocated char* with the contents
352 char *Mem = (char *)Allocate(Ref.size() + 1, 1);
353 std::copy(Ref.begin(), Ref.end(), Mem);
358 StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
359 const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
363 // Check whether we've already cached the parent name.
364 StringRef &CachedParentName = ParentNames[DC];
365 if (!CachedParentName.empty())
366 return CachedParentName;
368 // If we already processed this DeclContext and assigned empty to it, the
369 // data pointer will be non-null.
370 if (CachedParentName.data() != nullptr)
373 // Find the interesting names.
374 SmallVector<const DeclContext *, 2> Contexts;
375 while (DC && !DC->isFunctionOrMethod()) {
376 if (const auto *ND = dyn_cast<NamedDecl>(DC)) {
377 if (ND->getIdentifier())
378 Contexts.push_back(DC);
381 DC = DC->getParent();
386 llvm::raw_svector_ostream OS(S);
388 for (unsigned I = Contexts.size(); I != 0; --I) {
395 const DeclContext *CurDC = Contexts[I - 1];
396 if (const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
397 CurDC = CatImpl->getCategoryDecl();
399 if (const auto *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
400 const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
402 // Assign an empty StringRef but with non-null data to distinguish
403 // between empty because we didn't process the DeclContext yet.
404 CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0);
408 OS << Interface->getName() << '(' << Cat->getName() << ')';
410 OS << cast<NamedDecl>(CurDC)->getName();
414 CachedParentName = AllocatorRef->CopyString(OS.str());
417 return CachedParentName;
420 CodeCompletionString *CodeCompletionBuilder::TakeString() {
421 void *Mem = getAllocator().Allocate(
422 sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
423 sizeof(const char *) * Annotations.size(),
424 alignof(CodeCompletionString));
425 CodeCompletionString *Result = new (Mem) CodeCompletionString(
426 Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(),
427 Annotations.size(), ParentName, BriefComment);
432 void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
433 Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
436 void CodeCompletionBuilder::AddTextChunk(const char *Text) {
437 Chunks.push_back(Chunk::CreateText(Text));
440 void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
441 Chunks.push_back(Chunk::CreateOptional(Optional));
444 void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
445 Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
448 void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
449 Chunks.push_back(Chunk::CreateInformative(Text));
452 void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
453 Chunks.push_back(Chunk::CreateResultType(ResultType));
456 void CodeCompletionBuilder::AddCurrentParameterChunk(
457 const char *CurrentParameter) {
458 Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
461 void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
463 Chunks.push_back(Chunk(CK, Text));
466 void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
467 if (DC->isTranslationUnit())
470 if (DC->isFunctionOrMethod())
473 const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
477 ParentName = getCodeCompletionTUInfo().getParentName(DC);
480 void CodeCompletionBuilder::addBriefComment(StringRef Comment) {
481 BriefComment = Allocator.CopyString(Comment);
484 //===----------------------------------------------------------------------===//
485 // Code completion overload candidate implementation
486 //===----------------------------------------------------------------------===//
487 FunctionDecl *CodeCompleteConsumer::OverloadCandidate::getFunction() const {
488 if (getKind() == CK_Function)
490 else if (getKind() == CK_FunctionTemplate)
491 return FunctionTemplate->getTemplatedDecl();
497 CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
500 return Function->getType()->getAs<FunctionType>();
502 case CK_FunctionTemplate:
503 return FunctionTemplate->getTemplatedDecl()
505 ->getAs<FunctionType>();
507 case CK_FunctionType:
511 llvm_unreachable("Invalid CandidateKind!");
514 //===----------------------------------------------------------------------===//
515 // Code completion consumer implementation
516 //===----------------------------------------------------------------------===//
518 CodeCompleteConsumer::~CodeCompleteConsumer() = default;
520 bool PrintingCodeCompleteConsumer::isResultFilteredOut(
521 StringRef Filter, CodeCompletionResult Result) {
522 switch (Result.Kind) {
523 case CodeCompletionResult::RK_Declaration:
524 return !(Result.Declaration->getIdentifier() &&
525 Result.Declaration->getIdentifier()->getName().startswith(Filter));
526 case CodeCompletionResult::RK_Keyword:
527 return !StringRef(Result.Keyword).startswith(Filter);
528 case CodeCompletionResult::RK_Macro:
529 return !Result.Macro->getName().startswith(Filter);
530 case CodeCompletionResult::RK_Pattern:
531 return !(Result.Pattern->getTypedText() &&
532 StringRef(Result.Pattern->getTypedText()).startswith(Filter));
534 llvm_unreachable("Unknown code completion result Kind.");
537 void PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(
538 Sema &SemaRef, CodeCompletionContext Context, CodeCompletionResult *Results,
539 unsigned NumResults) {
540 std::stable_sort(Results, Results + NumResults);
542 if (!Context.getPreferredType().isNull())
543 OS << "PREFERRED-TYPE: " << Context.getPreferredType().getAsString()
546 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
547 // Print the completions.
548 for (unsigned I = 0; I != NumResults; ++I) {
549 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
551 OS << "COMPLETION: ";
552 switch (Results[I].Kind) {
553 case CodeCompletionResult::RK_Declaration:
554 OS << *Results[I].Declaration;
556 std::vector<std::string> Tags;
557 if (Results[I].Hidden)
558 Tags.push_back("Hidden");
559 if (Results[I].InBaseClass)
560 Tags.push_back("InBase");
561 if (Results[I].Availability ==
562 CXAvailabilityKind::CXAvailability_NotAccessible)
563 Tags.push_back("Inaccessible");
565 OS << " (" << llvm::join(Tags, ",") << ")";
567 if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
568 SemaRef, Context, getAllocator(), CCTUInfo,
569 includeBriefComments())) {
570 OS << " : " << CCS->getAsString();
571 if (const char *BriefComment = CCS->getBriefComment())
572 OS << " : " << BriefComment;
576 case CodeCompletionResult::RK_Keyword:
577 OS << Results[I].Keyword;
580 case CodeCompletionResult::RK_Macro:
581 OS << Results[I].Macro->getName();
582 if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
583 SemaRef, Context, getAllocator(), CCTUInfo,
584 includeBriefComments())) {
585 OS << " : " << CCS->getAsString();
589 case CodeCompletionResult::RK_Pattern:
590 OS << "Pattern : " << Results[I].Pattern->getAsString();
593 for (const FixItHint &FixIt : Results[I].FixIts) {
594 const SourceLocation BLoc = FixIt.RemoveRange.getBegin();
595 const SourceLocation ELoc = FixIt.RemoveRange.getEnd();
597 SourceManager &SM = SemaRef.SourceMgr;
598 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
599 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
600 // Adjust for token ranges.
601 if (FixIt.RemoveRange.isTokenRange())
602 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, SemaRef.LangOpts);
604 OS << " (requires fix-it:"
605 << " {" << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
606 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
607 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
608 << SM.getColumnNumber(EInfo.first, EInfo.second) << "}"
609 << " to \"" << FixIt.CodeToInsert << "\")";
615 // This function is used solely to preserve the former presentation of overloads
616 // by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
617 // needs to be improved for printing the newer and more detailed overload
619 static std::string getOverloadAsString(const CodeCompletionString &CCS) {
621 llvm::raw_string_ostream OS(Result);
623 for (auto &C : CCS) {
625 case CodeCompletionString::CK_Informative:
626 case CodeCompletionString::CK_ResultType:
627 OS << "[#" << C.Text << "#]";
630 case CodeCompletionString::CK_CurrentParameter:
631 OS << "<#" << C.Text << "#>";
634 // FIXME: We can also print optional parameters of an overload.
635 case CodeCompletionString::CK_Optional:
646 void PrintingCodeCompleteConsumer::ProcessOverloadCandidates(
647 Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates,
648 unsigned NumCandidates, SourceLocation OpenParLoc) {
649 OS << "OPENING_PAREN_LOC: ";
650 OpenParLoc.print(OS, SemaRef.getSourceManager());
653 for (unsigned I = 0; I != NumCandidates; ++I) {
654 if (CodeCompletionString *CCS = Candidates[I].CreateSignatureString(
655 CurrentArg, SemaRef, getAllocator(), CCTUInfo,
656 includeBriefComments())) {
657 OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
662 /// Retrieve the effective availability of the given declaration.
663 static AvailabilityResult getDeclAvailability(const Decl *D) {
664 AvailabilityResult AR = D->getAvailability();
665 if (isa<EnumConstantDecl>(D))
666 AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
670 void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
674 // Do nothing: Patterns can come with cursor kinds!
679 case RK_Declaration: {
680 // Set the availability based on attributes.
681 switch (getDeclAvailability(Declaration)) {
683 case AR_NotYetIntroduced:
684 Availability = CXAvailability_Available;
688 Availability = CXAvailability_Deprecated;
692 Availability = CXAvailability_NotAvailable;
696 if (const auto *Function = dyn_cast<FunctionDecl>(Declaration))
697 if (Function->isDeleted())
698 Availability = CXAvailability_NotAvailable;
700 CursorKind = getCursorKindForDecl(Declaration);
701 if (CursorKind == CXCursor_UnexposedDecl) {
702 // FIXME: Forward declarations of Objective-C classes and protocols
703 // are not directly exposed, but we want code completion to treat them
704 // like a definition.
705 if (isa<ObjCInterfaceDecl>(Declaration))
706 CursorKind = CXCursor_ObjCInterfaceDecl;
707 else if (isa<ObjCProtocolDecl>(Declaration))
708 CursorKind = CXCursor_ObjCProtocolDecl;
710 CursorKind = CXCursor_NotImplemented;
717 llvm_unreachable("Macro and keyword kinds are handled by the constructors");
721 Availability = CXAvailability_NotAccessible;
724 /// Retrieve the name that should be used to order a result.
726 /// If the name needs to be constructed as a string, that string will be
727 /// saved into Saved and the returned StringRef will refer to it.
728 StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const {
733 return Pattern->getTypedText();
735 return Macro->getName();
737 // Handle declarations below.
741 DeclarationName Name = Declaration->getDeclName();
743 // If the name is a simple identifier (by far the common case), or a
744 // zero-argument selector, just return a reference to that identifier.
745 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
746 return Id->getName();
747 if (Name.isObjCZeroArgSelector())
748 if (IdentifierInfo *Id = Name.getObjCSelector().getIdentifierInfoForSlot(0))
749 return Id->getName();
751 Saved = Name.getAsString();
755 bool clang::operator<(const CodeCompletionResult &X,
756 const CodeCompletionResult &Y) {
757 std::string XSaved, YSaved;
758 StringRef XStr = X.getOrderedName(XSaved);
759 StringRef YStr = Y.getOrderedName(YSaved);
760 int cmp = XStr.compare_lower(YStr);
764 // If case-insensitive comparison fails, try case-sensitive comparison.
765 return XStr.compare(YStr) < 0;