clang 19.0.0git
CodeCompleteConsumer.cpp
Go to the documentation of this file.
1//===- CodeCompleteConsumer.cpp - Code Completion Interface ---------------===//
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// This file implements the CodeCompleteConsumer class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "clang-c/Index.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclBase.h"
17#include "clang/AST/DeclObjC.h"
20#include "clang/AST/Type.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"
34#include <algorithm>
35#include <cassert>
36#include <cstdint>
37#include <string>
38
39using namespace clang;
40
41//===----------------------------------------------------------------------===//
42// Code completion context implementation
43//===----------------------------------------------------------------------===//
44
46 switch (CCKind) {
47 case CCC_Recovery:
48 case CCC_Statement:
49 case CCC_Expression:
52 case CCC_Symbol:
55 return true;
56
57 case CCC_TopLevel:
65 case CCC_EnumTag:
66 case CCC_UnionTag:
69 case CCC_Namespace:
70 case CCC_Type:
71 case CCC_NewName:
72 case CCC_MacroName:
79 case CCC_Other:
86 case CCC_Attribute:
88 return false;
89 }
90
91 llvm_unreachable("Invalid CodeCompletionContext::Kind!");
92}
93
95 using CCKind = CodeCompletionContext::Kind;
96 switch (Kind) {
97 case CCKind::CCC_Other:
98 return "Other";
99 case CCKind::CCC_OtherWithMacros:
100 return "OtherWithMacros";
101 case CCKind::CCC_TopLevel:
102 return "TopLevel";
103 case CCKind::CCC_ObjCInterface:
104 return "ObjCInterface";
105 case CCKind::CCC_ObjCImplementation:
106 return "ObjCImplementation";
107 case CCKind::CCC_ObjCIvarList:
108 return "ObjCIvarList";
109 case CCKind::CCC_ClassStructUnion:
110 return "ClassStructUnion";
111 case CCKind::CCC_Statement:
112 return "Statement";
113 case CCKind::CCC_Expression:
114 return "Expression";
115 case CCKind::CCC_ObjCMessageReceiver:
116 return "ObjCMessageReceiver";
117 case CCKind::CCC_DotMemberAccess:
118 return "DotMemberAccess";
119 case CCKind::CCC_ArrowMemberAccess:
120 return "ArrowMemberAccess";
121 case CCKind::CCC_ObjCPropertyAccess:
122 return "ObjCPropertyAccess";
123 case CCKind::CCC_EnumTag:
124 return "EnumTag";
125 case CCKind::CCC_UnionTag:
126 return "UnionTag";
127 case CCKind::CCC_ClassOrStructTag:
128 return "ClassOrStructTag";
129 case CCKind::CCC_ObjCProtocolName:
130 return "ObjCProtocolName";
131 case CCKind::CCC_Namespace:
132 return "Namespace";
133 case CCKind::CCC_Type:
134 return "Type";
135 case CCKind::CCC_NewName:
136 return "NewName";
137 case CCKind::CCC_Symbol:
138 return "Symbol";
139 case CCKind::CCC_SymbolOrNewName:
140 return "SymbolOrNewName";
141 case CCKind::CCC_MacroName:
142 return "MacroName";
143 case CCKind::CCC_MacroNameUse:
144 return "MacroNameUse";
145 case CCKind::CCC_PreprocessorExpression:
146 return "PreprocessorExpression";
147 case CCKind::CCC_PreprocessorDirective:
148 return "PreprocessorDirective";
149 case CCKind::CCC_NaturalLanguage:
150 return "NaturalLanguage";
151 case CCKind::CCC_SelectorName:
152 return "SelectorName";
153 case CCKind::CCC_TypeQualifiers:
154 return "TypeQualifiers";
155 case CCKind::CCC_ParenthesizedExpression:
156 return "ParenthesizedExpression";
157 case CCKind::CCC_ObjCInstanceMessage:
158 return "ObjCInstanceMessage";
159 case CCKind::CCC_ObjCClassMessage:
160 return "ObjCClassMessage";
161 case CCKind::CCC_ObjCInterfaceName:
162 return "ObjCInterfaceName";
163 case CCKind::CCC_ObjCCategoryName:
164 return "ObjCCategoryName";
165 case CCKind::CCC_IncludedFile:
166 return "IncludedFile";
167 case CCKind::CCC_Attribute:
168 return "Attribute";
169 case CCKind::CCC_Recovery:
170 return "Recovery";
171 case CCKind::CCC_ObjCClassForwardDecl:
172 return "ObjCClassForwardDecl";
173 case CCKind::CCC_TopLevelOrExpression:
174 return "ReplTopLevel";
175 }
176 llvm_unreachable("Invalid CodeCompletionContext::Kind!");
177}
178
179//===----------------------------------------------------------------------===//
180// Code completion string implementation
181//===----------------------------------------------------------------------===//
182
184 : Kind(Kind), Text("") {
185 switch (Kind) {
186 case CK_TypedText:
187 case CK_Text:
188 case CK_Placeholder:
189 case CK_Informative:
190 case CK_ResultType:
192 this->Text = Text;
193 break;
194
195 case CK_Optional:
196 llvm_unreachable("Optional strings cannot be created from text");
197
198 case CK_LeftParen:
199 this->Text = "(";
200 break;
201
202 case CK_RightParen:
203 this->Text = ")";
204 break;
205
206 case CK_LeftBracket:
207 this->Text = "[";
208 break;
209
210 case CK_RightBracket:
211 this->Text = "]";
212 break;
213
214 case CK_LeftBrace:
215 this->Text = "{";
216 break;
217
218 case CK_RightBrace:
219 this->Text = "}";
220 break;
221
222 case CK_LeftAngle:
223 this->Text = "<";
224 break;
225
226 case CK_RightAngle:
227 this->Text = ">";
228 break;
229
230 case CK_Comma:
231 this->Text = ", ";
232 break;
233
234 case CK_Colon:
235 this->Text = ":";
236 break;
237
238 case CK_SemiColon:
239 this->Text = ";";
240 break;
241
242 case CK_Equal:
243 this->Text = " = ";
244 break;
245
247 this->Text = " ";
248 break;
249
250 case CK_VerticalSpace:
251 this->Text = "\n";
252 break;
253 }
254}
255
258 return Chunk(CK_Text, Text);
259}
260
264 Result.Kind = CK_Optional;
265 Result.Optional = Optional;
266 return Result;
267}
268
271 return Chunk(CK_Placeholder, Placeholder);
272}
273
276 return Chunk(CK_Informative, Informative);
277}
278
281 return Chunk(CK_ResultType, ResultType);
282}
283
285 const char *CurrentParameter) {
286 return Chunk(CK_CurrentParameter, CurrentParameter);
287}
288
289CodeCompletionString::CodeCompletionString(
290 const Chunk *Chunks, unsigned NumChunks, unsigned Priority,
291 CXAvailabilityKind Availability, const char **Annotations,
292 unsigned NumAnnotations, StringRef ParentName, const char *BriefComment)
293 : NumChunks(NumChunks), NumAnnotations(NumAnnotations), Priority(Priority),
294 Availability(Availability), ParentName(ParentName),
295 BriefComment(BriefComment) {
296 assert(NumChunks <= 0xffff);
297 assert(NumAnnotations <= 0xffff);
298
299 Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
300 for (unsigned I = 0; I != NumChunks; ++I)
301 StoredChunks[I] = Chunks[I];
302
303 const char **StoredAnnotations =
304 reinterpret_cast<const char **>(StoredChunks + NumChunks);
305 for (unsigned I = 0; I != NumAnnotations; ++I)
306 StoredAnnotations[I] = Annotations[I];
307}
308
310 return NumAnnotations;
311}
312
313const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
314 if (AnnotationNr < NumAnnotations)
315 return reinterpret_cast<const char *const *>(end())[AnnotationNr];
316 else
317 return nullptr;
318}
319
321 std::string Result;
322 llvm::raw_string_ostream OS(Result);
323
324 for (const Chunk &C : *this) {
325 switch (C.Kind) {
326 case CK_Optional:
327 OS << "{#" << C.Optional->getAsString() << "#}";
328 break;
329 case CK_Placeholder:
330 OS << "<#" << C.Text << "#>";
331 break;
332 case CK_Informative:
333 case CK_ResultType:
334 OS << "[#" << C.Text << "#]";
335 break;
337 OS << "<#" << C.Text << "#>";
338 break;
339 default:
340 OS << C.Text;
341 break;
342 }
343 }
344 return Result;
345}
346
348 for (const Chunk &C : *this)
349 if (C.Kind == CK_TypedText)
350 return C.Text;
351
352 return nullptr;
353}
354
356 std::string Res;
357 for (const Chunk &C : *this)
358 if (C.Kind == CK_TypedText)
359 Res += C.Text;
360
361 return Res;
362}
363
364const char *CodeCompletionAllocator::CopyString(const Twine &String) {
366 StringRef Ref = String.toStringRef(Data);
367 // FIXME: It would be more efficient to teach Twine to tell us its size and
368 // then add a routine there to fill in an allocated char* with the contents
369 // of the string.
370 char *Mem = (char *)Allocate(Ref.size() + 1, 1);
371 std::copy(Ref.begin(), Ref.end(), Mem);
372 Mem[Ref.size()] = 0;
373 return Mem;
374}
375
377 if (!isa<NamedDecl>(DC))
378 return {};
379
380 // Check whether we've already cached the parent name.
381 StringRef &CachedParentName = ParentNames[DC];
382 if (!CachedParentName.empty())
383 return CachedParentName;
384
385 // If we already processed this DeclContext and assigned empty to it, the
386 // data pointer will be non-null.
387 if (CachedParentName.data() != nullptr)
388 return {};
389
390 // Find the interesting names.
392 while (DC && !DC->isFunctionOrMethod()) {
393 if (const auto *ND = dyn_cast<NamedDecl>(DC)) {
394 if (ND->getIdentifier())
395 Contexts.push_back(DC);
396 }
397
398 DC = DC->getParent();
399 }
400
401 {
403 llvm::raw_svector_ostream OS(S);
404 bool First = true;
405 for (const DeclContext *CurDC : llvm::reverse(Contexts)) {
406 if (First)
407 First = false;
408 else {
409 OS << "::";
410 }
411
412 if (const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
413 CurDC = CatImpl->getCategoryDecl();
414
415 if (const auto *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
416 const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
417 if (!Interface) {
418 // Assign an empty StringRef but with non-null data to distinguish
419 // between empty because we didn't process the DeclContext yet.
420 CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0);
421 return {};
422 }
423
424 OS << Interface->getName() << '(' << Cat->getName() << ')';
425 } else {
426 OS << cast<NamedDecl>(CurDC)->getName();
427 }
428 }
429
430 CachedParentName = AllocatorRef->CopyString(OS.str());
431 }
432
433 return CachedParentName;
434}
435
437 void *Mem = getAllocator().Allocate(
438 sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
439 sizeof(const char *) * Annotations.size(),
440 alignof(CodeCompletionString));
442 Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(),
443 Annotations.size(), ParentName, BriefComment);
444 Chunks.clear();
445 return Result;
446}
447
450}
451
453 Chunks.push_back(Chunk::CreateText(Text));
454}
455
457 Chunks.push_back(Chunk::CreateOptional(Optional));
458}
459
460void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
461 Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
462}
463
465 Chunks.push_back(Chunk::CreateInformative(Text));
466}
467
468void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
469 Chunks.push_back(Chunk::CreateResultType(ResultType));
470}
471
473 const char *CurrentParameter) {
474 Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
475}
476
478 const char *Text) {
479 Chunks.push_back(Chunk(CK, Text));
480}
481
483 if (DC->isTranslationUnit())
484 return;
485
486 if (DC->isFunctionOrMethod())
487 return;
488
489 if (!isa<NamedDecl>(DC))
490 return;
491
492 ParentName = getCodeCompletionTUInfo().getParentName(DC);
493}
494
496 BriefComment = Allocator.CopyString(Comment);
497}
498
499//===----------------------------------------------------------------------===//
500// Code completion overload candidate implementation
501//===----------------------------------------------------------------------===//
503 if (getKind() == CK_Function)
504 return Function;
505 else if (getKind() == CK_FunctionTemplate)
506 return FunctionTemplate->getTemplatedDecl();
507 else
508 return nullptr;
509}
510
511const FunctionType *
513 switch (Kind) {
514 case CK_Function:
515 return Function->getType()->getAs<FunctionType>();
516
517 case CK_FunctionTemplate:
518 return FunctionTemplate->getTemplatedDecl()
519 ->getType()
520 ->getAs<FunctionType>();
521
522 case CK_FunctionType:
523 return Type;
524 case CK_FunctionProtoTypeLoc:
525 return ProtoTypeLoc.getTypePtr();
526 case CK_Template:
527 case CK_Aggregate:
528 return nullptr;
529 }
530
531 llvm_unreachable("Invalid CandidateKind!");
532}
533
536 if (Kind == CK_FunctionProtoTypeLoc)
537 return ProtoTypeLoc;
538 return FunctionProtoTypeLoc();
539}
540
542 if (Kind == CK_Template)
543 return Template->getTemplateParameters()->size();
544
545 if (Kind == CK_Aggregate) {
546 unsigned Count =
547 std::distance(AggregateType->field_begin(), AggregateType->field_end());
548 if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType))
549 Count += CRD->getNumBases();
550 return Count;
551 }
552
553 if (const auto *FT = getFunctionType())
554 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT))
555 return FPT->getNumParams();
556
557 return 0;
558}
559
562 if (Kind == CK_Aggregate) {
563 if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType)) {
564 if (N < CRD->getNumBases())
565 return std::next(CRD->bases_begin(), N)->getType();
566 N -= CRD->getNumBases();
567 }
568 for (const auto *Field : AggregateType->fields())
569 if (N-- == 0)
570 return Field->getType();
571 return QualType();
572 }
573
574 if (Kind == CK_Template) {
575 TemplateParameterList *TPL = getTemplate()->getTemplateParameters();
576 if (N < TPL->size())
577 if (const auto *D = dyn_cast<NonTypeTemplateParmDecl>(TPL->getParam(N)))
578 return D->getType();
579 return QualType();
580 }
581
582 if (const auto *FT = getFunctionType())
583 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT))
584 if (N < FPT->getNumParams())
585 return FPT->getParamType(N);
586 return QualType();
587}
588
589const NamedDecl *
591 if (Kind == CK_Aggregate) {
592 if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType)) {
593 if (N < CRD->getNumBases())
594 return std::next(CRD->bases_begin(), N)->getType()->getAsTagDecl();
595 N -= CRD->getNumBases();
596 }
597 for (const auto *Field : AggregateType->fields())
598 if (N-- == 0)
599 return Field;
600 return nullptr;
601 }
602
603 if (Kind == CK_Template) {
604 TemplateParameterList *TPL = getTemplate()->getTemplateParameters();
605 if (N < TPL->size())
606 return TPL->getParam(N);
607 return nullptr;
608 }
609
610 // Note that if we only have a FunctionProtoType, we don't have param decls.
611 if (const auto *FD = getFunction()) {
612 if (N < FD->param_size())
613 return FD->getParamDecl(N);
614 } else if (Kind == CK_FunctionProtoTypeLoc) {
615 if (N < ProtoTypeLoc.getNumParams()) {
616 return ProtoTypeLoc.getParam(N);
617 }
618 }
619
620 return nullptr;
621}
622
623//===----------------------------------------------------------------------===//
624// Code completion consumer implementation
625//===----------------------------------------------------------------------===//
626
628
630 StringRef Filter, CodeCompletionResult Result) {
631 switch (Result.Kind) {
633 return !(
634 Result.Declaration->getIdentifier() &&
635 Result.Declaration->getIdentifier()->getName().starts_with(Filter));
637 return !StringRef(Result.Keyword).starts_with(Filter);
639 return !Result.Macro->getName().starts_with(Filter);
641 return !(Result.Pattern->getTypedText() &&
642 StringRef(Result.Pattern->getTypedText()).starts_with(Filter));
643 }
644 llvm_unreachable("Unknown code completion result Kind.");
645}
646
648 Sema &SemaRef, CodeCompletionContext Context, CodeCompletionResult *Results,
649 unsigned NumResults) {
650 std::stable_sort(Results, Results + NumResults);
651
652 if (!Context.getPreferredType().isNull())
653 OS << "PREFERRED-TYPE: " << Context.getPreferredType() << '\n';
654
655 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
656 // Print the completions.
657 for (unsigned I = 0; I != NumResults; ++I) {
658 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
659 continue;
660 OS << "COMPLETION: ";
661 switch (Results[I].Kind) {
663 OS << *Results[I].Declaration;
664 {
665 std::vector<std::string> Tags;
666 if (Results[I].Hidden)
667 Tags.push_back("Hidden");
668 if (Results[I].InBaseClass)
669 Tags.push_back("InBase");
670 if (Results[I].Availability ==
671 CXAvailabilityKind::CXAvailability_NotAccessible)
672 Tags.push_back("Inaccessible");
673 if (!Tags.empty())
674 OS << " (" << llvm::join(Tags, ",") << ")";
675 }
676 if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
677 SemaRef, Context, getAllocator(), CCTUInfo,
678 includeBriefComments())) {
679 OS << " : " << CCS->getAsString();
680 if (const char *BriefComment = CCS->getBriefComment())
681 OS << " : " << BriefComment;
682 }
683 break;
684
686 OS << Results[I].Keyword;
687 break;
688
690 OS << Results[I].Macro->getName();
691 if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
692 SemaRef, Context, getAllocator(), CCTUInfo,
693 includeBriefComments())) {
694 OS << " : " << CCS->getAsString();
695 }
696 break;
697
699 OS << "Pattern : " << Results[I].Pattern->getAsString();
700 break;
701 }
702 for (const FixItHint &FixIt : Results[I].FixIts) {
703 const SourceLocation BLoc = FixIt.RemoveRange.getBegin();
704 const SourceLocation ELoc = FixIt.RemoveRange.getEnd();
705
706 SourceManager &SM = SemaRef.SourceMgr;
707 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
708 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
709 // Adjust for token ranges.
710 if (FixIt.RemoveRange.isTokenRange())
711 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, SemaRef.LangOpts);
712
713 OS << " (requires fix-it:"
714 << " {" << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
715 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
716 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
717 << SM.getColumnNumber(EInfo.first, EInfo.second) << "}"
718 << " to \"" << FixIt.CodeToInsert << "\")";
719 }
720 OS << '\n';
721 }
722}
723
724// This function is used solely to preserve the former presentation of overloads
725// by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
726// needs to be improved for printing the newer and more detailed overload
727// chunks.
728static std::string getOverloadAsString(const CodeCompletionString &CCS) {
729 std::string Result;
730 llvm::raw_string_ostream OS(Result);
731
732 for (auto &C : CCS) {
733 switch (C.Kind) {
736 OS << "[#" << C.Text << "#]";
737 break;
738
740 OS << "<#" << C.Text << "#>";
741 break;
742
743 // FIXME: We can also print optional parameters of an overload.
745 break;
746
747 default:
748 OS << C.Text;
749 break;
750 }
751 }
752 return Result;
753}
754
756 Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates,
757 unsigned NumCandidates, SourceLocation OpenParLoc, bool Braced) {
758 OS << "OPENING_PAREN_LOC: ";
759 OpenParLoc.print(OS, SemaRef.getSourceManager());
760 OS << "\n";
761
762 for (unsigned I = 0; I != NumCandidates; ++I) {
763 if (CodeCompletionString *CCS = Candidates[I].CreateSignatureString(
764 CurrentArg, SemaRef, getAllocator(), CCTUInfo,
765 includeBriefComments(), Braced)) {
766 OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
767 }
768 }
769}
770
771/// Retrieve the effective availability of the given declaration.
774 if (isa<EnumConstantDecl>(D))
775 AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
776 return AR;
777}
778
779void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
780 switch (Kind) {
781 case RK_Pattern:
782 if (!Declaration) {
783 // Do nothing: Patterns can come with cursor kinds!
784 break;
785 }
786 [[fallthrough]];
787
788 case RK_Declaration: {
789 // Set the availability based on attributes.
791 case AR_Available:
793 Availability = CXAvailability_Available;
794 break;
795
796 case AR_Deprecated:
797 Availability = CXAvailability_Deprecated;
798 break;
799
800 case AR_Unavailable:
801 Availability = CXAvailability_NotAvailable;
802 break;
803 }
804
805 if (const auto *Function = dyn_cast<FunctionDecl>(Declaration))
806 if (Function->isDeleted())
807 Availability = CXAvailability_NotAvailable;
808
809 CursorKind = getCursorKindForDecl(Declaration);
810 if (CursorKind == CXCursor_UnexposedDecl) {
811 // FIXME: Forward declarations of Objective-C classes and protocols
812 // are not directly exposed, but we want code completion to treat them
813 // like a definition.
814 if (isa<ObjCInterfaceDecl>(Declaration))
815 CursorKind = CXCursor_ObjCInterfaceDecl;
816 else if (isa<ObjCProtocolDecl>(Declaration))
817 CursorKind = CXCursor_ObjCProtocolDecl;
818 else
819 CursorKind = CXCursor_NotImplemented;
820 }
821 break;
822 }
823
824 case RK_Macro:
825 case RK_Keyword:
826 llvm_unreachable("Macro and keyword kinds are handled by the constructors");
827 }
828
829 if (!Accessible)
830 Availability = CXAvailability_NotAccessible;
831}
832
833/// Retrieve the name that should be used to order a result.
834///
835/// If the name needs to be constructed as a string, that string will be
836/// saved into Saved and the returned StringRef will refer to it.
837StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const {
838 switch (Kind) {
839 case RK_Keyword:
840 return Keyword;
841 case RK_Pattern:
842 return Pattern->getTypedText();
843 case RK_Macro:
844 return Macro->getName();
845 case RK_Declaration:
846 // Handle declarations below.
847 break;
848 }
849
850 DeclarationName Name = Declaration->getDeclName();
851
852 // If the name is a simple identifier (by far the common case), or a
853 // zero-argument selector, just return a reference to that identifier.
854 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
855 return Id->getName();
856 if (Name.isObjCZeroArgSelector())
857 if (const IdentifierInfo *Id =
858 Name.getObjCSelector().getIdentifierInfoForSlot(0))
859 return Id->getName();
860
861 Saved = Name.getAsString();
862 return Saved;
863}
864
866 const CodeCompletionResult &Y) {
867 std::string XSaved, YSaved;
868 StringRef XStr = X.getOrderedName(XSaved);
869 StringRef YStr = Y.getOrderedName(YSaved);
870 int cmp = XStr.compare_insensitive(YStr);
871 if (cmp)
872 return cmp < 0;
873
874 // If case-insensitive comparison fails, try case-sensitive comparison.
875 return XStr.compare(YStr) < 0;
876}
int Id
Definition: ASTDiff.cpp:190
#define SM(sm)
Definition: Cuda.cpp:82
static AvailabilityResult getDeclAvailability(const Decl *D)
Retrieve the effective availability of the given declaration.
static std::string getOverloadAsString(const CodeCompletionString &CCS)
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1109
Defines the C++ template declaration subclasses.
StringRef Text
Definition: Format.cpp:2972
int Priority
Definition: Format.cpp:2975
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
#define X(type, name)
Definition: Value.h:143
Defines the clang::Preprocessor interface.
C Language Family Type Representation.
QualType getParamType(unsigned N) const
Get the type of the Nth parameter.
const FunctionType * getFunctionType() const
Retrieve the function type of the entity, regardless of how the function is stored.
FunctionDecl * getFunction() const
Retrieve the function overload candidate or the templated function declaration for a function templat...
const FunctionProtoTypeLoc getFunctionProtoTypeLoc() const
Retrieve the function ProtoTypeLoc candidate.
const NamedDecl * getParamDecl(unsigned N) const
Get the declaration of the Nth parameter.
unsigned getNumParams() const
Get the number of parameters in this signature.
virtual ~CodeCompleteConsumer()
Deregisters and destroys this code-completion consumer.
const char * CopyString(const Twine &String)
Copy the given string into this allocator.
CodeCompletionString * TakeString()
Take the resulting completion string.
void AddPlaceholderChunk(const char *Placeholder)
Add a new placeholder chunk.
void AddTextChunk(const char *Text)
Add a new text chunk.
void addParentContext(const DeclContext *DC)
Add the parent context information to this code completion.
void addBriefComment(StringRef Comment)
void AddCurrentParameterChunk(const char *CurrentParameter)
Add a new current-parameter chunk.
void AddResultTypeChunk(const char *ResultType)
Add a new result-type chunk.
void AddInformativeChunk(const char *Text)
Add a new informative chunk.
void AddOptionalChunk(CodeCompletionString *Optional)
Add a new optional chunk.
void AddTypedTextChunk(const char *Text)
Add a new typed-text chunk.
void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text="")
Add a new chunk.
The context in which code completion occurred, so that the code-completion consumer can process the r...
@ CCC_TypeQualifiers
Code completion within a type-qualifier list.
@ CCC_ObjCMessageReceiver
Code completion occurred where an Objective-C message receiver is expected.
@ CCC_PreprocessorExpression
Code completion occurred within a preprocessor expression.
@ CCC_ObjCCategoryName
Code completion where an Objective-C category name is expected.
@ CCC_ObjCIvarList
Code completion occurred within the instance variable list of an Objective-C interface,...
@ CCC_Statement
Code completion occurred where a statement (or declaration) is expected in a function,...
@ CCC_Type
Code completion occurred where a type name is expected.
@ CCC_ArrowMemberAccess
Code completion occurred on the right-hand side of a member access expression using the arrow operato...
@ CCC_ClassStructUnion
Code completion occurred within a class, struct, or union.
@ CCC_ObjCInterface
Code completion occurred within an Objective-C interface, protocol, or category interface.
@ CCC_ObjCPropertyAccess
Code completion occurred on the right-hand side of an Objective-C property access expression.
@ CCC_Expression
Code completion occurred where an expression is expected.
@ CCC_SelectorName
Code completion for a selector, as in an @selector expression.
@ CCC_TopLevelOrExpression
Code completion at a top level, i.e.
@ CCC_EnumTag
Code completion occurred after the "enum" keyword, to indicate an enumeration name.
@ CCC_UnionTag
Code completion occurred after the "union" keyword, to indicate a union name.
@ CCC_ParenthesizedExpression
Code completion in a parenthesized expression, which means that we may also have types here in C and ...
@ CCC_TopLevel
Code completion occurred within a "top-level" completion context, e.g., at namespace or global scope.
@ CCC_ClassOrStructTag
Code completion occurred after the "struct" or "class" keyword, to indicate a struct or class name.
@ CCC_ObjCClassMessage
Code completion where an Objective-C class message is expected.
@ CCC_ObjCImplementation
Code completion occurred within an Objective-C implementation or category implementation.
@ CCC_IncludedFile
Code completion inside the filename part of a #include directive.
@ CCC_ObjCInstanceMessage
Code completion where an Objective-C instance message is expected.
@ CCC_SymbolOrNewName
Code completion occurred where both a new name and an existing symbol is permissible.
@ CCC_Recovery
An unknown context, in which we are recovering from a parsing error and don't know which completions ...
@ CCC_ObjCProtocolName
Code completion occurred where a protocol name is expected.
@ CCC_OtherWithMacros
An unspecified code-completion context where we should also add macro completions.
@ CCC_NewName
Code completion occurred where a new name is expected.
@ CCC_MacroNameUse
Code completion occurred where a macro name is expected (without any arguments, in the case of a func...
@ CCC_Symbol
Code completion occurred where an existing name(such as type, function or variable) is expected.
@ CCC_Attribute
Code completion of an attribute name.
@ CCC_Other
An unspecified code-completion context.
@ CCC_DotMemberAccess
Code completion occurred on the right-hand side of a member access expression using the dot operator.
@ CCC_MacroName
Code completion occurred where an macro is being defined.
@ CCC_Namespace
Code completion occurred where a namespace or namespace alias is expected.
@ CCC_PreprocessorDirective
Code completion occurred where a preprocessor directive is expected.
@ CCC_NaturalLanguage
Code completion occurred in a context where natural language is expected, e.g., a comment or string l...
@ CCC_ObjCInterfaceName
Code completion where the name of an Objective-C class is expected.
bool wantConstructorResults() const
Determines whether we want C++ constructors as results within this context.
Captures a result of code completion.
StringRef getOrderedName(std::string &Saved) const
Retrieve the name that should be used to order a result.
@ RK_Pattern
Refers to a precomputed pattern.
@ RK_Declaration
Refers to a declaration.
@ RK_Keyword
Refers to a keyword or symbol.
A "string" used to describe how code completion can be performed for an entity.
ChunkKind
The different kinds of "chunks" that can occur within a code completion string.
@ CK_Optional
A code completion string that is entirely optional.
@ CK_CurrentParameter
A piece of text that describes the parameter that corresponds to the code-completion location within ...
@ CK_Comma
A comma separator (',').
@ CK_Text
A piece of text that should be placed in the buffer, e.g., parentheses or a comma in a function call.
@ CK_Placeholder
A string that acts as a placeholder for, e.g., a function call argument.
@ CK_LeftParen
A left parenthesis ('(').
@ CK_HorizontalSpace
Horizontal whitespace (' ').
@ CK_RightAngle
A right angle bracket ('>').
@ CK_Informative
A piece of text that describes something about the result but should not be inserted into the buffer.
@ CK_LeftBracket
A left bracket ('[').
@ CK_RightParen
A right parenthesis (')').
@ CK_RightBrace
A right brace ('}').
@ CK_VerticalSpace
Vertical whitespace ('\n' or '\r\n', depending on the platform).
@ CK_TypedText
The piece of text that the user is expected to type to match the code-completion string,...
@ CK_ResultType
A piece of text that describes the type of an entity or, for functions and methods,...
@ CK_RightBracket
A right bracket (']').
@ CK_LeftBrace
A left brace ('{').
@ CK_LeftAngle
A left angle bracket ('<').
std::string getAsString() const
Retrieve a string representation of the code completion string, which is mainly useful for debugging.
std::string getAllTypedText() const
Returns the combined text from all TypedText chunks.
const char * getTypedText() const
Returns the text in the first TypedText chunk.
unsigned getAnnotationCount() const
Retrieve the number of annotations for this code completion result.
const char * getAnnotation(unsigned AnnotationNr) const
Retrieve the annotation string specified by AnnotationNr.
StringRef getParentName(const DeclContext *DC)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool isTranslationUnit() const
Definition: DeclBase.h:2142
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:709
DeclContext * getDeclContext()
Definition: DeclBase.h:454
The name of a declaration.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
Represents a function declaration or definition.
Definition: Decl.h:1971
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4252
One of these records is kept for each identifier that is lexed.
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition: Lexer.cpp:499
This represents a decl that may have a name.
Definition: Decl.h:249
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
StringRef getCodeCompletionFilter()
Get the code completion token for filtering purposes.
void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, CodeCompletionResult *Results, unsigned NumResults) override
Prints the finalized code-completion results.
void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, OverloadCandidate *Candidates, unsigned NumCandidates, SourceLocation OpenParLoc, bool Braced) override
bool isResultFilteredOut(StringRef Filter, CodeCompletionResult Results) override
A (possibly-)qualified type.
Definition: Type.h:940
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
Preprocessor & getPreprocessor() const
Definition: Sema.h:526
const LangOptions & LangOpts
Definition: Sema.h:856
SourceManager & getSourceManager() const
Definition: Sema.h:525
SourceManager & SourceMgr
Definition: Sema.h:861
Encodes a location in the source.
void print(raw_ostream &OS, const SourceManager &SM) const
This class handles loading and caching of source files into memory.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
The base class of the type hierarchy.
Definition: Type.h:1813
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8119
CXAvailabilityKind
Describes the availability of a particular entity, which indicates whether the use of this entity wil...
Definition: Index.h:130
@ CXCursor_ObjCInterfaceDecl
An Objective-C @interface.
Definition: Index.h:1220
@ CXCursor_ObjCProtocolDecl
An Objective-C @protocol declaration.
Definition: Index.h:1224
@ CXCursor_UnexposedDecl
A declaration whose specific kind is not exposed via this interface.
Definition: Index.h:1197
@ CXCursor_NotImplemented
Definition: Index.h:1384
@ CXAvailability_Available
The entity is available.
Definition: Index.h:134
@ CXAvailability_Deprecated
The entity is available, but has been deprecated (and its use is not recommended).
Definition: Index.h:139
@ CXAvailability_NotAccessible
The entity is available, but not accessible; any use of it will be an error.
Definition: Index.h:148
@ CXAvailability_NotAvailable
The entity is not available; any use of it will be an error.
Definition: Index.h:143
The JSON file list parser is used to communicate input to InstallAPI.
CXCursorKind getCursorKindForDecl(const Decl *D)
Determine the libclang cursor kind associated with the given declaration.
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
@ Result
The result type of a method or function.
AvailabilityResult
Captures the result of checking the availability of a declaration.
Definition: DeclBase.h:72
@ AR_NotYetIntroduced
Definition: DeclBase.h:74
@ AR_Available
Definition: DeclBase.h:73
@ AR_Deprecated
Definition: DeclBase.h:75
@ AR_Unavailable
Definition: DeclBase.h:76
llvm::StringRef getCompletionKindString(CodeCompletionContext::Kind Kind)
Get string representation of Kind, useful for debugging.
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
One piece of the code completion string.
static Chunk CreateOptional(CodeCompletionString *Optional)
Create a new optional chunk.
ChunkKind Kind
The kind of data stored in this piece of the code completion string.
static Chunk CreatePlaceholder(const char *Placeholder)
Create a new placeholder chunk.
static Chunk CreateCurrentParameter(const char *CurrentParameter)
Create a new current-parameter chunk.
static Chunk CreateInformative(const char *Informative)
Create a new informative chunk.
static Chunk CreateResultType(const char *ResultType)
Create a new result type chunk.
const char * Text
The text string associated with a CK_Text, CK_Placeholder, CK_Informative, or CK_Comma chunk.
static Chunk CreateText(const char *Text)
Create a new text chunk.