clang 17.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:
54 return true;
55
56 case CCC_TopLevel:
64 case CCC_EnumTag:
65 case CCC_UnionTag:
68 case CCC_Namespace:
69 case CCC_Type:
70 case CCC_NewName:
71 case CCC_MacroName:
78 case CCC_Other:
85 case CCC_Attribute:
86 return false;
87 }
88
89 llvm_unreachable("Invalid CodeCompletionContext::Kind!");
90}
91
93 using CCKind = CodeCompletionContext::Kind;
94 switch (Kind) {
95 case CCKind::CCC_Other:
96 return "Other";
97 case CCKind::CCC_OtherWithMacros:
98 return "OtherWithMacros";
99 case CCKind::CCC_TopLevel:
100 return "TopLevel";
101 case CCKind::CCC_ObjCInterface:
102 return "ObjCInterface";
103 case CCKind::CCC_ObjCImplementation:
104 return "ObjCImplementation";
105 case CCKind::CCC_ObjCIvarList:
106 return "ObjCIvarList";
107 case CCKind::CCC_ClassStructUnion:
108 return "ClassStructUnion";
109 case CCKind::CCC_Statement:
110 return "Statement";
111 case CCKind::CCC_Expression:
112 return "Expression";
113 case CCKind::CCC_ObjCMessageReceiver:
114 return "ObjCMessageReceiver";
115 case CCKind::CCC_DotMemberAccess:
116 return "DotMemberAccess";
117 case CCKind::CCC_ArrowMemberAccess:
118 return "ArrowMemberAccess";
119 case CCKind::CCC_ObjCPropertyAccess:
120 return "ObjCPropertyAccess";
121 case CCKind::CCC_EnumTag:
122 return "EnumTag";
123 case CCKind::CCC_UnionTag:
124 return "UnionTag";
125 case CCKind::CCC_ClassOrStructTag:
126 return "ClassOrStructTag";
127 case CCKind::CCC_ObjCProtocolName:
128 return "ObjCProtocolName";
129 case CCKind::CCC_Namespace:
130 return "Namespace";
131 case CCKind::CCC_Type:
132 return "Type";
133 case CCKind::CCC_NewName:
134 return "NewName";
135 case CCKind::CCC_Symbol:
136 return "Symbol";
137 case CCKind::CCC_SymbolOrNewName:
138 return "SymbolOrNewName";
139 case CCKind::CCC_MacroName:
140 return "MacroName";
141 case CCKind::CCC_MacroNameUse:
142 return "MacroNameUse";
143 case CCKind::CCC_PreprocessorExpression:
144 return "PreprocessorExpression";
145 case CCKind::CCC_PreprocessorDirective:
146 return "PreprocessorDirective";
147 case CCKind::CCC_NaturalLanguage:
148 return "NaturalLanguage";
149 case CCKind::CCC_SelectorName:
150 return "SelectorName";
151 case CCKind::CCC_TypeQualifiers:
152 return "TypeQualifiers";
153 case CCKind::CCC_ParenthesizedExpression:
154 return "ParenthesizedExpression";
155 case CCKind::CCC_ObjCInstanceMessage:
156 return "ObjCInstanceMessage";
157 case CCKind::CCC_ObjCClassMessage:
158 return "ObjCClassMessage";
159 case CCKind::CCC_ObjCInterfaceName:
160 return "ObjCInterfaceName";
161 case CCKind::CCC_ObjCCategoryName:
162 return "ObjCCategoryName";
163 case CCKind::CCC_IncludedFile:
164 return "IncludedFile";
165 case CCKind::CCC_Attribute:
166 return "Attribute";
167 case CCKind::CCC_Recovery:
168 return "Recovery";
169 }
170 llvm_unreachable("Invalid CodeCompletionContext::Kind!");
171}
172
173//===----------------------------------------------------------------------===//
174// Code completion string implementation
175//===----------------------------------------------------------------------===//
176
178 : Kind(Kind), Text("") {
179 switch (Kind) {
180 case CK_TypedText:
181 case CK_Text:
182 case CK_Placeholder:
183 case CK_Informative:
184 case CK_ResultType:
186 this->Text = Text;
187 break;
188
189 case CK_Optional:
190 llvm_unreachable("Optional strings cannot be created from text");
191
192 case CK_LeftParen:
193 this->Text = "(";
194 break;
195
196 case CK_RightParen:
197 this->Text = ")";
198 break;
199
200 case CK_LeftBracket:
201 this->Text = "[";
202 break;
203
204 case CK_RightBracket:
205 this->Text = "]";
206 break;
207
208 case CK_LeftBrace:
209 this->Text = "{";
210 break;
211
212 case CK_RightBrace:
213 this->Text = "}";
214 break;
215
216 case CK_LeftAngle:
217 this->Text = "<";
218 break;
219
220 case CK_RightAngle:
221 this->Text = ">";
222 break;
223
224 case CK_Comma:
225 this->Text = ", ";
226 break;
227
228 case CK_Colon:
229 this->Text = ":";
230 break;
231
232 case CK_SemiColon:
233 this->Text = ";";
234 break;
235
236 case CK_Equal:
237 this->Text = " = ";
238 break;
239
241 this->Text = " ";
242 break;
243
244 case CK_VerticalSpace:
245 this->Text = "\n";
246 break;
247 }
248}
249
252 return Chunk(CK_Text, Text);
253}
254
258 Result.Kind = CK_Optional;
259 Result.Optional = Optional;
260 return Result;
261}
262
265 return Chunk(CK_Placeholder, Placeholder);
266}
267
270 return Chunk(CK_Informative, Informative);
271}
272
275 return Chunk(CK_ResultType, ResultType);
276}
277
279 const char *CurrentParameter) {
280 return Chunk(CK_CurrentParameter, CurrentParameter);
281}
282
283CodeCompletionString::CodeCompletionString(
284 const Chunk *Chunks, unsigned NumChunks, unsigned Priority,
285 CXAvailabilityKind Availability, const char **Annotations,
286 unsigned NumAnnotations, StringRef ParentName, const char *BriefComment)
287 : NumChunks(NumChunks), NumAnnotations(NumAnnotations), Priority(Priority),
288 Availability(Availability), ParentName(ParentName),
289 BriefComment(BriefComment) {
290 assert(NumChunks <= 0xffff);
291 assert(NumAnnotations <= 0xffff);
292
293 Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
294 for (unsigned I = 0; I != NumChunks; ++I)
295 StoredChunks[I] = Chunks[I];
296
297 const char **StoredAnnotations =
298 reinterpret_cast<const char **>(StoredChunks + NumChunks);
299 for (unsigned I = 0; I != NumAnnotations; ++I)
300 StoredAnnotations[I] = Annotations[I];
301}
302
304 return NumAnnotations;
305}
306
307const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
308 if (AnnotationNr < NumAnnotations)
309 return reinterpret_cast<const char *const *>(end())[AnnotationNr];
310 else
311 return nullptr;
312}
313
315 std::string Result;
316 llvm::raw_string_ostream OS(Result);
317
318 for (const Chunk &C : *this) {
319 switch (C.Kind) {
320 case CK_Optional:
321 OS << "{#" << C.Optional->getAsString() << "#}";
322 break;
323 case CK_Placeholder:
324 OS << "<#" << C.Text << "#>";
325 break;
326 case CK_Informative:
327 case CK_ResultType:
328 OS << "[#" << C.Text << "#]";
329 break;
331 OS << "<#" << C.Text << "#>";
332 break;
333 default:
334 OS << C.Text;
335 break;
336 }
337 }
338 return Result;
339}
340
342 for (const Chunk &C : *this)
343 if (C.Kind == CK_TypedText)
344 return C.Text;
345
346 return nullptr;
347}
348
350 std::string Res;
351 for (const Chunk &C : *this)
352 if (C.Kind == CK_TypedText)
353 Res += C.Text;
354
355 return Res;
356}
357
358const char *CodeCompletionAllocator::CopyString(const Twine &String) {
360 StringRef Ref = String.toStringRef(Data);
361 // FIXME: It would be more efficient to teach Twine to tell us its size and
362 // then add a routine there to fill in an allocated char* with the contents
363 // of the string.
364 char *Mem = (char *)Allocate(Ref.size() + 1, 1);
365 std::copy(Ref.begin(), Ref.end(), Mem);
366 Mem[Ref.size()] = 0;
367 return Mem;
368}
369
371 if (!isa<NamedDecl>(DC))
372 return {};
373
374 // Check whether we've already cached the parent name.
375 StringRef &CachedParentName = ParentNames[DC];
376 if (!CachedParentName.empty())
377 return CachedParentName;
378
379 // If we already processed this DeclContext and assigned empty to it, the
380 // data pointer will be non-null.
381 if (CachedParentName.data() != nullptr)
382 return {};
383
384 // Find the interesting names.
386 while (DC && !DC->isFunctionOrMethod()) {
387 if (const auto *ND = dyn_cast<NamedDecl>(DC)) {
388 if (ND->getIdentifier())
389 Contexts.push_back(DC);
390 }
391
392 DC = DC->getParent();
393 }
394
395 {
397 llvm::raw_svector_ostream OS(S);
398 bool First = true;
399 for (const DeclContext *CurDC : llvm::reverse(Contexts)) {
400 if (First)
401 First = false;
402 else {
403 OS << "::";
404 }
405
406 if (const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
407 CurDC = CatImpl->getCategoryDecl();
408
409 if (const auto *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
410 const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
411 if (!Interface) {
412 // Assign an empty StringRef but with non-null data to distinguish
413 // between empty because we didn't process the DeclContext yet.
414 CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0);
415 return {};
416 }
417
418 OS << Interface->getName() << '(' << Cat->getName() << ')';
419 } else {
420 OS << cast<NamedDecl>(CurDC)->getName();
421 }
422 }
423
424 CachedParentName = AllocatorRef->CopyString(OS.str());
425 }
426
427 return CachedParentName;
428}
429
431 void *Mem = getAllocator().Allocate(
432 sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
433 sizeof(const char *) * Annotations.size(),
434 alignof(CodeCompletionString));
436 Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(),
437 Annotations.size(), ParentName, BriefComment);
438 Chunks.clear();
439 return Result;
440}
441
444}
445
447 Chunks.push_back(Chunk::CreateText(Text));
448}
449
451 Chunks.push_back(Chunk::CreateOptional(Optional));
452}
453
454void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
455 Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
456}
457
459 Chunks.push_back(Chunk::CreateInformative(Text));
460}
461
462void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
463 Chunks.push_back(Chunk::CreateResultType(ResultType));
464}
465
467 const char *CurrentParameter) {
468 Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
469}
470
472 const char *Text) {
473 Chunks.push_back(Chunk(CK, Text));
474}
475
477 if (DC->isTranslationUnit())
478 return;
479
480 if (DC->isFunctionOrMethod())
481 return;
482
483 if (!isa<NamedDecl>(DC))
484 return;
485
486 ParentName = getCodeCompletionTUInfo().getParentName(DC);
487}
488
490 BriefComment = Allocator.CopyString(Comment);
491}
492
493//===----------------------------------------------------------------------===//
494// Code completion overload candidate implementation
495//===----------------------------------------------------------------------===//
497 if (getKind() == CK_Function)
498 return Function;
499 else if (getKind() == CK_FunctionTemplate)
500 return FunctionTemplate->getTemplatedDecl();
501 else
502 return nullptr;
503}
504
505const FunctionType *
507 switch (Kind) {
508 case CK_Function:
509 return Function->getType()->getAs<FunctionType>();
510
511 case CK_FunctionTemplate:
512 return FunctionTemplate->getTemplatedDecl()
513 ->getType()
514 ->getAs<FunctionType>();
515
516 case CK_FunctionType:
517 return Type;
518 case CK_FunctionProtoTypeLoc:
519 return ProtoTypeLoc.getTypePtr();
520 case CK_Template:
521 case CK_Aggregate:
522 return nullptr;
523 }
524
525 llvm_unreachable("Invalid CandidateKind!");
526}
527
530 if (Kind == CK_FunctionProtoTypeLoc)
531 return ProtoTypeLoc;
532 return FunctionProtoTypeLoc();
533}
534
536 if (Kind == CK_Template)
537 return Template->getTemplateParameters()->size();
538
539 if (Kind == CK_Aggregate) {
540 unsigned Count =
541 std::distance(AggregateType->field_begin(), AggregateType->field_end());
542 if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType))
543 Count += CRD->getNumBases();
544 return Count;
545 }
546
547 if (const auto *FT = getFunctionType())
548 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT))
549 return FPT->getNumParams();
550
551 return 0;
552}
553
556 if (Kind == CK_Aggregate) {
557 if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType)) {
558 if (N < CRD->getNumBases())
559 return std::next(CRD->bases_begin(), N)->getType();
560 N -= CRD->getNumBases();
561 }
562 for (const auto *Field : AggregateType->fields())
563 if (N-- == 0)
564 return Field->getType();
565 return QualType();
566 }
567
568 if (Kind == CK_Template) {
569 TemplateParameterList *TPL = getTemplate()->getTemplateParameters();
570 if (N < TPL->size())
571 if (const auto *D = dyn_cast<NonTypeTemplateParmDecl>(TPL->getParam(N)))
572 return D->getType();
573 return QualType();
574 }
575
576 if (const auto *FT = getFunctionType())
577 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT))
578 if (N < FPT->getNumParams())
579 return FPT->getParamType(N);
580 return QualType();
581}
582
583const NamedDecl *
585 if (Kind == CK_Aggregate) {
586 if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType)) {
587 if (N < CRD->getNumBases())
588 return std::next(CRD->bases_begin(), N)->getType()->getAsTagDecl();
589 N -= CRD->getNumBases();
590 }
591 for (const auto *Field : AggregateType->fields())
592 if (N-- == 0)
593 return Field;
594 return nullptr;
595 }
596
597 if (Kind == CK_Template) {
598 TemplateParameterList *TPL = getTemplate()->getTemplateParameters();
599 if (N < TPL->size())
600 return TPL->getParam(N);
601 return nullptr;
602 }
603
604 // Note that if we only have a FunctionProtoType, we don't have param decls.
605 if (const auto *FD = getFunction()) {
606 if (N < FD->param_size())
607 return FD->getParamDecl(N);
608 } else if (Kind == CK_FunctionProtoTypeLoc) {
609 if (N < ProtoTypeLoc.getNumParams()) {
610 return ProtoTypeLoc.getParam(N);
611 }
612 }
613
614 return nullptr;
615}
616
617//===----------------------------------------------------------------------===//
618// Code completion consumer implementation
619//===----------------------------------------------------------------------===//
620
622
624 StringRef Filter, CodeCompletionResult Result) {
625 switch (Result.Kind) {
627 return !(Result.Declaration->getIdentifier() &&
628 Result.Declaration->getIdentifier()->getName().startswith(Filter));
630 return !StringRef(Result.Keyword).startswith(Filter);
632 return !Result.Macro->getName().startswith(Filter);
634 return !(Result.Pattern->getTypedText() &&
635 StringRef(Result.Pattern->getTypedText()).startswith(Filter));
636 }
637 llvm_unreachable("Unknown code completion result Kind.");
638}
639
641 Sema &SemaRef, CodeCompletionContext Context, CodeCompletionResult *Results,
642 unsigned NumResults) {
643 std::stable_sort(Results, Results + NumResults);
644
645 if (!Context.getPreferredType().isNull())
646 OS << "PREFERRED-TYPE: " << Context.getPreferredType() << '\n';
647
648 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
649 // Print the completions.
650 for (unsigned I = 0; I != NumResults; ++I) {
651 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
652 continue;
653 OS << "COMPLETION: ";
654 switch (Results[I].Kind) {
656 OS << *Results[I].Declaration;
657 {
658 std::vector<std::string> Tags;
659 if (Results[I].Hidden)
660 Tags.push_back("Hidden");
661 if (Results[I].InBaseClass)
662 Tags.push_back("InBase");
663 if (Results[I].Availability ==
664 CXAvailabilityKind::CXAvailability_NotAccessible)
665 Tags.push_back("Inaccessible");
666 if (!Tags.empty())
667 OS << " (" << llvm::join(Tags, ",") << ")";
668 }
669 if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
670 SemaRef, Context, getAllocator(), CCTUInfo,
671 includeBriefComments())) {
672 OS << " : " << CCS->getAsString();
673 if (const char *BriefComment = CCS->getBriefComment())
674 OS << " : " << BriefComment;
675 }
676 break;
677
679 OS << Results[I].Keyword;
680 break;
681
683 OS << Results[I].Macro->getName();
684 if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
685 SemaRef, Context, getAllocator(), CCTUInfo,
686 includeBriefComments())) {
687 OS << " : " << CCS->getAsString();
688 }
689 break;
690
692 OS << "Pattern : " << Results[I].Pattern->getAsString();
693 break;
694 }
695 for (const FixItHint &FixIt : Results[I].FixIts) {
696 const SourceLocation BLoc = FixIt.RemoveRange.getBegin();
697 const SourceLocation ELoc = FixIt.RemoveRange.getEnd();
698
699 SourceManager &SM = SemaRef.SourceMgr;
700 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
701 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
702 // Adjust for token ranges.
703 if (FixIt.RemoveRange.isTokenRange())
704 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, SemaRef.LangOpts);
705
706 OS << " (requires fix-it:"
707 << " {" << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
708 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
709 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
710 << SM.getColumnNumber(EInfo.first, EInfo.second) << "}"
711 << " to \"" << FixIt.CodeToInsert << "\")";
712 }
713 OS << '\n';
714 }
715}
716
717// This function is used solely to preserve the former presentation of overloads
718// by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
719// needs to be improved for printing the newer and more detailed overload
720// chunks.
721static std::string getOverloadAsString(const CodeCompletionString &CCS) {
722 std::string Result;
723 llvm::raw_string_ostream OS(Result);
724
725 for (auto &C : CCS) {
726 switch (C.Kind) {
729 OS << "[#" << C.Text << "#]";
730 break;
731
733 OS << "<#" << C.Text << "#>";
734 break;
735
736 // FIXME: We can also print optional parameters of an overload.
738 break;
739
740 default:
741 OS << C.Text;
742 break;
743 }
744 }
745 return Result;
746}
747
749 Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates,
750 unsigned NumCandidates, SourceLocation OpenParLoc, bool Braced) {
751 OS << "OPENING_PAREN_LOC: ";
752 OpenParLoc.print(OS, SemaRef.getSourceManager());
753 OS << "\n";
754
755 for (unsigned I = 0; I != NumCandidates; ++I) {
756 if (CodeCompletionString *CCS = Candidates[I].CreateSignatureString(
757 CurrentArg, SemaRef, getAllocator(), CCTUInfo,
758 includeBriefComments(), Braced)) {
759 OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
760 }
761 }
762}
763
764/// Retrieve the effective availability of the given declaration.
767 if (isa<EnumConstantDecl>(D))
768 AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
769 return AR;
770}
771
772void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
773 switch (Kind) {
774 case RK_Pattern:
775 if (!Declaration) {
776 // Do nothing: Patterns can come with cursor kinds!
777 break;
778 }
779 [[fallthrough]];
780
781 case RK_Declaration: {
782 // Set the availability based on attributes.
784 case AR_Available:
786 Availability = CXAvailability_Available;
787 break;
788
789 case AR_Deprecated:
790 Availability = CXAvailability_Deprecated;
791 break;
792
793 case AR_Unavailable:
794 Availability = CXAvailability_NotAvailable;
795 break;
796 }
797
798 if (const auto *Function = dyn_cast<FunctionDecl>(Declaration))
799 if (Function->isDeleted())
800 Availability = CXAvailability_NotAvailable;
801
802 CursorKind = getCursorKindForDecl(Declaration);
803 if (CursorKind == CXCursor_UnexposedDecl) {
804 // FIXME: Forward declarations of Objective-C classes and protocols
805 // are not directly exposed, but we want code completion to treat them
806 // like a definition.
807 if (isa<ObjCInterfaceDecl>(Declaration))
808 CursorKind = CXCursor_ObjCInterfaceDecl;
809 else if (isa<ObjCProtocolDecl>(Declaration))
810 CursorKind = CXCursor_ObjCProtocolDecl;
811 else
812 CursorKind = CXCursor_NotImplemented;
813 }
814 break;
815 }
816
817 case RK_Macro:
818 case RK_Keyword:
819 llvm_unreachable("Macro and keyword kinds are handled by the constructors");
820 }
821
822 if (!Accessible)
823 Availability = CXAvailability_NotAccessible;
824}
825
826/// Retrieve the name that should be used to order a result.
827///
828/// If the name needs to be constructed as a string, that string will be
829/// saved into Saved and the returned StringRef will refer to it.
830StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const {
831 switch (Kind) {
832 case RK_Keyword:
833 return Keyword;
834 case RK_Pattern:
835 return Pattern->getTypedText();
836 case RK_Macro:
837 return Macro->getName();
838 case RK_Declaration:
839 // Handle declarations below.
840 break;
841 }
842
843 DeclarationName Name = Declaration->getDeclName();
844
845 // If the name is a simple identifier (by far the common case), or a
846 // zero-argument selector, just return a reference to that identifier.
847 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
848 return Id->getName();
849 if (Name.isObjCZeroArgSelector())
850 if (IdentifierInfo *Id = Name.getObjCSelector().getIdentifierInfoForSlot(0))
851 return Id->getName();
852
853 Saved = Name.getAsString();
854 return Saved;
855}
856
858 const CodeCompletionResult &Y) {
859 std::string XSaved, YSaved;
860 StringRef XStr = X.getOrderedName(XSaved);
861 StringRef YStr = Y.getOrderedName(YSaved);
862 int cmp = XStr.compare_insensitive(YStr);
863 if (cmp)
864 return cmp < 0;
865
866 // If case-insensitive comparison fails, try case-sensitive comparison.
867 return XStr.compare(YStr) < 0;
868}
int Id
Definition: ASTDiff.cpp:190
#define SM(sm)
Definition: Cuda.cpp:78
static AvailabilityResult getDeclAvailability(const Decl *D)
Retrieve the effective availability of the given declaration.
static std::string getOverloadAsString(const CodeCompletionString &CCS)
static CompilationDatabasePluginRegistry::Add< FixedCompilationDatabasePlugin > X("fixed-compilation-database", "Reads plain-text flags file")
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1025
Defines the C++ template declaration subclasses.
StringRef Text
Definition: Format.cpp:2775
int Priority
Definition: Format.cpp:2778
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
llvm::raw_ostream & OS
Definition: Logger.cpp:24
Defines the clang::Preprocessor interface.
const char * Data
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_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:1393
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1933
bool isTranslationUnit() const
Definition: DeclBase.h:2008
bool isFunctionOrMethod() const
Definition: DeclBase.h:1985
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:636
DeclContext * getDeclContext()
Definition: DeclBase.h:441
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:1917
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3694
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:450
This represents a decl that may have a name.
Definition: Decl.h:247
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:274
Represents an ObjC class declaration.
Definition: DeclObjC.h:1147
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:736
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:356
Preprocessor & getPreprocessor() const
Definition: Sema.h:1651
const LangOptions & LangOpts
Definition: Sema.h:405
SourceManager & getSourceManager() const
Definition: Sema.h:1650
SourceManager & SourceMgr
Definition: Sema.h:410
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:138
The base class of the type hierarchy.
Definition: Type.h:1566
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7424
CXAvailabilityKind
Describes the availability of a particular entity, which indicates whether the use of this entity wil...
Definition: Index.h:126
@ CXCursor_ObjCInterfaceDecl
An Objective-C @interface.
Definition: Index.h:1216
@ CXCursor_ObjCProtocolDecl
An Objective-C @protocol declaration.
Definition: Index.h:1220
@ CXCursor_UnexposedDecl
A declaration whose specific kind is not exposed via this interface.
Definition: Index.h:1193
@ CXCursor_NotImplemented
Definition: Index.h:1380
@ CXAvailability_Available
The entity is available.
Definition: Index.h:130
@ CXAvailability_Deprecated
The entity is available, but has been deprecated (and its use is not recommended).
Definition: Index.h:135
@ CXAvailability_NotAccessible
The entity is available, but not accessible; any use of it will be an error.
Definition: Index.h:144
@ CXAvailability_NotAvailable
The entity is not available; any use of it will be an error.
Definition: Index.h:139
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.
@ C
Languages that the frontend can parse and compile.
@ Result
The result type of a method or function.
AvailabilityResult
Captures the result of checking the availability of a declaration.
Definition: DeclBase.h:69
@ AR_NotYetIntroduced
Definition: DeclBase.h:71
@ AR_Available
Definition: DeclBase.h:70
@ AR_Deprecated
Definition: DeclBase.h:72
@ AR_Unavailable
Definition: DeclBase.h:73
llvm::StringRef getCompletionKindString(CodeCompletionContext::Kind Kind)
Get string representation of Kind, useful for debugging.
__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.