Go to the documentation of this file.
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;
89 llvm_unreachable(
"Invalid CodeCompletionContext::Kind!");
95 case CCKind::CCC_Other:
97 case CCKind::CCC_OtherWithMacros:
98 return "OtherWithMacros";
99 case CCKind::CCC_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:
111 case CCKind::CCC_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:
123 case CCKind::CCC_UnionTag:
125 case CCKind::CCC_ClassOrStructTag:
126 return "ClassOrStructTag";
127 case CCKind::CCC_ObjCProtocolName:
128 return "ObjCProtocolName";
129 case CCKind::CCC_Namespace:
131 case CCKind::CCC_Type:
133 case CCKind::CCC_NewName:
135 case CCKind::CCC_Symbol:
137 case CCKind::CCC_SymbolOrNewName:
138 return "SymbolOrNewName";
139 case CCKind::CCC_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:
167 case CCKind::CCC_Recovery:
170 llvm_unreachable(
"Invalid CodeCompletionContext::Kind!");
190 llvm_unreachable(
"Optional strings cannot be created from text");
279 const char *CurrentParameter) {
283 CodeCompletionString::CodeCompletionString(
284 const Chunk *Chunks,
unsigned NumChunks,
unsigned Priority,
286 unsigned NumAnnotations, StringRef ParentName,
const char *BriefComment)
288 Availability(Availability), ParentName(ParentName),
289 BriefComment(BriefComment) {
290 assert(NumChunks <= 0xffff);
291 assert(NumAnnotations <= 0xffff);
293 Chunk *StoredChunks =
reinterpret_cast<Chunk *
>(
this + 1);
294 for (
unsigned I = 0; I != NumChunks; ++I)
295 StoredChunks[I] = Chunks[I];
297 const char **StoredAnnotations =
298 reinterpret_cast<const char **
>(StoredChunks + NumChunks);
299 for (
unsigned I = 0; I != NumAnnotations; ++I)
300 StoredAnnotations[I] = Annotations[I];
304 return NumAnnotations;
308 if (AnnotationNr < NumAnnotations)
309 return reinterpret_cast<const char *
const *
>(
end())[AnnotationNr];
316 llvm::raw_string_ostream OS(Result);
318 for (
const Chunk &C : *
this) {
321 OS <<
"{#" << C.Optional->getAsString() <<
"#}";
324 OS <<
"<#" << C.Text <<
"#>";
328 OS <<
"[#" << C.Text <<
"#]";
331 OS <<
"<#" << C.Text <<
"#>";
342 for (
const Chunk &C : *
this)
351 StringRef Ref = String.toStringRef(Data);
355 char *Mem = (
char *)Allocate(Ref.size() + 1, 1);
356 std::copy(Ref.begin(), Ref.end(), Mem);
362 if (!isa<NamedDecl>(DC))
366 StringRef &CachedParentName = ParentNames[DC];
367 if (!CachedParentName.empty())
368 return CachedParentName;
372 if (CachedParentName.data() !=
nullptr)
378 if (
const auto *ND = dyn_cast<NamedDecl>(DC)) {
379 if (ND->getIdentifier())
380 Contexts.push_back(DC);
388 llvm::raw_svector_ostream OS(S);
390 for (
const DeclContext *CurDC : llvm::reverse(Contexts)) {
397 if (
const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
398 CurDC = CatImpl->getCategoryDecl();
400 if (
const auto *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
405 CachedParentName = StringRef((
const char *)(
uintptr_t)~0
U, 0);
409 OS << Interface->
getName() <<
'(' << Cat->getName() <<
')';
411 OS << cast<NamedDecl>(CurDC)->getName();
415 CachedParentName = AllocatorRef->CopyString(OS.str());
418 return CachedParentName;
422 void *Mem = getAllocator().Allocate(
424 sizeof(
const char *) * Annotations.size(),
427 Chunks.data(), Chunks.size(),
Priority, Availability, Annotations.data(),
428 Annotations.size(), ParentName, BriefComment);
458 const char *CurrentParameter) {
474 if (!isa<NamedDecl>(DC))
477 ParentName = getCodeCompletionTUInfo().getParentName(DC);
481 BriefComment = Allocator.CopyString(Comment);
490 else if (
getKind() == CK_FunctionTemplate)
491 return FunctionTemplate->getTemplatedDecl();
502 case CK_FunctionTemplate:
503 return FunctionTemplate->getTemplatedDecl()
507 case CK_FunctionType:
515 llvm_unreachable(
"Invalid CandidateKind!");
519 if (
Kind == CK_Template)
520 return Template->getTemplateParameters()->size();
522 if (
Kind == CK_Aggregate) {
524 std::distance(AggregateType->field_begin(), AggregateType->field_end());
525 if (
const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType))
526 Count += CRD->getNumBases();
530 if (
const auto *FT = getFunctionType())
531 if (
const auto *FPT = dyn_cast<FunctionProtoType>(FT))
532 return FPT->getNumParams();
539 if (
Kind == CK_Aggregate) {
540 if (
const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType)) {
541 if (N < CRD->getNumBases())
542 return std::next(CRD->bases_begin(), N)->getType();
543 N -= CRD->getNumBases();
545 for (
const auto *Field : AggregateType->fields())
547 return Field->getType();
551 if (
Kind == CK_Template) {
554 if (
const auto *D = dyn_cast<NonTypeTemplateParmDecl>(TPL->
getParam(N)))
559 if (
const auto *FT = getFunctionType())
560 if (
const auto *FPT = dyn_cast<FunctionProtoType>(FT))
561 if (N < FPT->getNumParams())
562 return FPT->getParamType(N);
568 if (
Kind == CK_Aggregate) {
569 if (
const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType)) {
570 if (N < CRD->getNumBases())
571 return std::next(CRD->bases_begin(), N)->getType()->getAsTagDecl();
572 N -= CRD->getNumBases();
574 for (
const auto *Field : AggregateType->fields())
580 if (
Kind == CK_Template) {
588 if (
const auto *FD = getFunction()) {
589 if (N < FD->param_size())
590 return FD->getParamDecl(N);
603 switch (Result.
Kind) {
608 return !StringRef(Result.Keyword).startswith(
Filter);
612 return !(Result.Pattern->getTypedText() &&
613 StringRef(Result.Pattern->getTypedText()).startswith(
Filter));
615 llvm_unreachable(
"Unknown code completion result Kind.");
620 unsigned NumResults) {
621 std::stable_sort(Results, Results + NumResults);
623 if (!Context.getPreferredType().isNull())
624 OS <<
"PREFERRED-TYPE: " << Context.getPreferredType() <<
'\n';
628 for (
unsigned I = 0; I != NumResults; ++I) {
629 if (!
Filter.empty() && isResultFilteredOut(
Filter, Results[I]))
631 OS <<
"COMPLETION: ";
632 switch (Results[I].
Kind) {
634 OS << *Results[I].Declaration;
636 std::vector<std::string> Tags;
637 if (Results[I].Hidden)
638 Tags.push_back(
"Hidden");
639 if (Results[I].InBaseClass)
640 Tags.push_back(
"InBase");
641 if (Results[I].Availability ==
643 Tags.push_back(
"Inaccessible");
645 OS <<
" (" << llvm::join(Tags,
",") <<
")";
648 SemaRef, Context, getAllocator(), CCTUInfo,
649 includeBriefComments())) {
650 OS <<
" : " << CCS->getAsString();
651 if (
const char *BriefComment = CCS->getBriefComment())
652 OS <<
" : " << BriefComment;
657 OS << Results[I].Keyword;
661 OS << Results[I].Macro->getName();
663 SemaRef, Context, getAllocator(), CCTUInfo,
664 includeBriefComments())) {
665 OS <<
" : " << CCS->getAsString();
670 OS <<
"Pattern : " << Results[I].Pattern->getAsString();
678 std::pair<FileID, unsigned> BInfo =
SM.getDecomposedLoc(BLoc);
679 std::pair<FileID, unsigned> EInfo =
SM.getDecomposedLoc(ELoc);
681 if (
FixIt.RemoveRange.isTokenRange())
684 OS <<
" (requires fix-it:"
685 <<
" {" <<
SM.getLineNumber(BInfo.first, BInfo.second) <<
':'
686 <<
SM.getColumnNumber(BInfo.first, BInfo.second) <<
'-'
687 <<
SM.getLineNumber(EInfo.first, EInfo.second) <<
':'
688 <<
SM.getColumnNumber(EInfo.first, EInfo.second) <<
"}"
689 <<
" to \"" <<
FixIt.CodeToInsert <<
"\")";
701 llvm::raw_string_ostream OS(Result);
703 for (
auto &C : CCS) {
707 OS <<
"[#" << C.Text <<
"#]";
711 OS <<
"<#" << C.Text <<
"#>";
729 OS <<
"OPENING_PAREN_LOC: ";
733 for (
unsigned I = 0; I != NumCandidates; ++I) {
735 CurrentArg, SemaRef, getAllocator(), CCTUInfo,
736 includeBriefComments(), Braced)) {
745 if (isa<EnumConstantDecl>(D))
750 void CodeCompletionResult::computeCursorKindAndAvailability(
bool Accessible) {
759 case RK_Declaration: {
776 if (
const auto *Function = dyn_cast<FunctionDecl>(Declaration))
785 if (isa<ObjCInterfaceDecl>(Declaration))
787 else if (isa<ObjCProtocolDecl>(Declaration))
797 llvm_unreachable(
"Macro and keyword kinds are handled by the constructors");
813 return Pattern->getTypedText();
815 return Macro->getName();
826 return Id->getName();
827 if (Name.isObjCZeroArgSelector())
828 if (
IdentifierInfo *
Id = Name.getObjCSelector().getIdentifierInfoForSlot(0))
829 return Id->getName();
831 Saved = Name.getAsString();
838 StringRef XStr =
X.getOrderedName(XSaved);
840 int cmp = XStr.compare_insensitive(YStr);
845 return XStr.compare(YStr) < 0;
@ CCC_SymbolOrNewName
Code completion occurred where both a new name and an existing symbol is permissible.
Represents an ObjC class declaration.
@ CCC_Other
An unspecified code-completion context.
__DEVICE__ int max(int __a, int __b)
void addParentContext(const DeclContext *DC)
Add the parent context information to this code completion.
unsigned getAnnotationCount() const
Retrieve the number of annotations for this code completion result.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
CodeCompletionString * TakeString()
Take the resulting completion string.
@ CCC_ObjCInstanceMessage
Code completion where an Objective-C instance message is expected.
llvm::Optional< T > Optional
@ CCC_Expression
Code completion occurred where an expression is expected.
void AddOptionalChunk(CodeCompletionString *Optional)
Add a new optional chunk.
SourceManager & SourceMgr
const char * CopyString(const Twine &String)
Copy the given string into this allocator.
bool isResultFilteredOut(StringRef Filter, CodeCompletionResult Results) override
Encodes a location in the source.
@ CCC_Type
Code completion occurred where a type name is expected.
This represents a decl that may have a name.
@ CCC_ObjCImplementation
Code completion occurred within an Objective-C implementation or category implementation.
A (possibly-)qualified type.
void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text="")
Add a new chunk.
@ CK_Text
A piece of text that should be placed in the buffer, e.g., parentheses or a comma in a function call.
const FunctionType * getFunctionType() const
Retrieve the function type of the entity, regardless of how the function is stored.
@ CK_RightParen
A right parenthesis (')').
SourceManager & getSourceManager() const
@ CK_TypedText
The piece of text that the user is expected to type to match the code-completion string,...
const NamedDecl * getParamDecl(unsigned N) const
Get the declaration of the Nth parameter.
@ CCC_IncludedFile
Code completion inside the filename part of a include directive.
@ RK_Keyword
Refers to a keyword or symbol.
@ CK_VerticalSpace
Vertical whitespace ('\n' or '\r\n', depending on the platform).
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 ...
void AddTypedTextChunk(const char *Text)
Add a new typed-text chunk.
FunctionType - C99 6.7.5.3 - Function Declarators.
@ CK_HorizontalSpace
Horizontal whitespace (' ').
The name of a declaration.
@ CXAvailability_NotAvailable
The entity is not available; any use of it will be an error.
@ CK_ResultType
A piece of text that describes the type of an entity or, for functions and methods,...
This class handles loading and caching of source files into memory.
Captures a result of code completion.
The base class of the type hierarchy.
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
ChunkKind
The different kinds of "chunks" that can occur within a code completion string.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
@ CCC_ObjCCategoryName
Code completion where an Objective-C category name is expected.
@ CCC_TopLevel
Code completion occurred within a "top-level" completion context, e.g., at namespace or global scope.
@ CK_LeftAngle
A left angle bracket ('<').
void print(raw_ostream &OS, const SourceManager &SM) const
Kind
Lists the kind of concrete classes of Decl.
void AddCurrentParameterChunk(const char *CurrentParameter)
Add a new current-parameter chunk.
NamedDecl * getParam(unsigned Idx)
@ CCC_Recovery
An unknown context, in which we are recovering from a parsing error and don't know which completions ...
@ CK_RightBracket
A right bracket (']').
@ CCC_ObjCProtocolName
Code completion occurred where a protocol name is expected.
@ CCC_EnumTag
Code completion occurred after the "enum" keyword, to indicate an enumeration name.
static Chunk CreateOptional(CodeCompletionString *Optional)
Create a new optional chunk.
@ CXCursor_NotImplemented
static std::string getOverloadAsString(const CodeCompletionString &CCS)
@ CXCursor_ObjCProtocolDecl
An Objective-C @protocol declaration.
@ CCC_ArrowMemberAccess
Code completion occurred on the right-hand side of a member access expression using the arrow operato...
@ CCC_Symbol
Code completion occurred where an existing name(such as type, function or variable) is expected.
void AddTextChunk(const char *Text)
Add a new text chunk.
static Chunk CreateResultType(const char *ResultType)
Create a new result type chunk.
@ CXAvailability_NotAccessible
The entity is available, but not accessible; any use of it will be an error.
const T * getAs() const
Member-template getAs<specific type>'.
@ CCC_ObjCInterfaceName
Code completion where the name of an Objective-C class is expected.
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
@ CK_Informative
A piece of text that describes something about the result but should not be inserted into the buffer.
bool isTranslationUnit() const
@ CCC_Attribute
Code completion of an attribute name.
@ CK_LeftParen
A left parenthesis ('(').
@ CCC_ObjCMessageReceiver
Code completion occurred where an Objective-C message receiver is expected.
Stores a list of template parameters for a TemplateDecl and its derived classes.
StringRef getCodeCompletionFilter()
Get the code completion token for filtering purposes.
std::string getAsString() const
Retrieve a string representation of the code completion string, which is mainly useful for debugging.
static Decl::Kind getKind(const Decl *D)
A "string" used to describe how code completion can be performed for an entity.
static Chunk CreateCurrentParameter(const char *CurrentParameter)
Create a new current-parameter chunk.
const LangOptions & LangOpts
@ CCC_OtherWithMacros
An unspecified code-completion context where we should also add macro completions.
void AddResultTypeChunk(const char *ResultType)
Add a new result-type chunk.
@ CCC_Namespace
Code completion occurred where a namespace or namespace alias is expected.
@ RK_Macro
Refers to a macro.
void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, OverloadCandidate *Candidates, unsigned NumCandidates, SourceLocation OpenParLoc, bool Braced) override
@ CK_RightBrace
A right brace ('}').
@ CCC_ObjCPropertyAccess
Code completion occurred on the right-hand side of an Objective-C property access expression.
ChunkKind Kind
The kind of data stored in this piece of the code completion string.
@ CK_SemiColon
A semicolon (';').
@ CCC_PreprocessorExpression
Code completion occurred within a preprocessor expression.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
@ CXAvailability_Available
The entity is available.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
CXAvailabilityKind
Describes the availability of a particular entity, which indicates whether the use of this entity wil...
const char * getTypedText() const
Returns the text in the TypedText chunk.
@ FixIt
Parse and apply any fixits to the source.
@ CCC_PreprocessorDirective
Code completion occurred where a preprocessor directive is expected.
Decl - This represents one declaration (or definition), e.g.
void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, CodeCompletionResult *Results, unsigned NumResults) override
Prints the finalized code-completion results.
Sema - This implements semantic analysis and AST building for C.
@ CCC_ClassStructUnion
Code completion occurred within a class, struct, or union.
@ CCC_Statement
Code completion occurred where a statement (or declaration) is expected in a function,...
@ CCC_DotMemberAccess
Code completion occurred on the right-hand side of a member access expression using the dot operator.
@ CK_CurrentParameter
A piece of text that describes the parameter that corresponds to the code-completion location within ...
const char * getAnnotation(unsigned AnnotationNr) const
Retrieve the annotation string specified by AnnotationNr.
One of these records is kept for each identifier that is lexed.
@ CK_LeftBracket
A left bracket ('[').
@ RK_Pattern
Refers to a precomputed pattern.
Preprocessor & getPreprocessor() const
static Chunk CreatePlaceholder(const char *Placeholder)
Create a new placeholder chunk.
@ CCC_NaturalLanguage
Code completion occurred in a context where natural language is expected, e.g., a comment or string l...
@ CK_Placeholder
A string that acts as a placeholder for, e.g., a function call argument.
StringRef getName() const
Return the actual identifier string.
float __ovld __cnfn distance(float, float)
Returns the distance between p0 and p1.
unsigned getNumParams() const
Get the number of parameters in this signature.
@ CCC_NewName
Code completion occurred where a new name is expected.
static Chunk CreateInformative(const char *Informative)
Create a new informative chunk.
AvailabilityResult
Captures the result of checking the availability of a declaration.
StringRef getOrderedName(std::string &Saved) const
Retrieve the name that should be used to order a result.
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
void AddPlaceholderChunk(const char *Placeholder)
Add a new placeholder chunk.
void addBriefComment(StringRef Comment)
@ CXCursor_UnexposedDecl
A declaration whose specific kind is not exposed via this interface.
@ CCC_ObjCIvarList
Code completion occurred within the instance variable list of an Objective-C interface,...
@ CK_RightAngle
A right angle bracket ('>').
@ RK_Declaration
Refers to a declaration.
@ CXAvailability_Deprecated
The entity is available, but has been deprecated (and its use is not recommended).
@ CCC_ParenthesizedExpression
Code completion in a parenthesized expression, which means that we may also have types here in C and ...
static Chunk CreateText(const char *Text)
Create a new text chunk.
bool wantConstructorResults() const
Determines whether we want C++ constructors as results within this context.
One piece of the code completion string.
@ CCC_SelectorName
Code completion for a selector, as in an @selector expression.
virtual ~CodeCompleteConsumer()
Deregisters and destroys this code-completion consumer.
@ CK_Optional
A code completion string that is entirely optional.
CXCursorKind getCursorKindForDecl(const Decl *D)
Determine the libclang cursor kind associated with the given declaration.
The context in which code completion occurred, so that the code-completion consumer can process the r...
llvm::StringRef getCompletionKindString(CodeCompletionContext::Kind Kind)
Get string representation of Kind, useful for for debugging.
void AddInformativeChunk(const char *Text)
Add a new informative chunk.
@ CK_LeftBrace
A left brace ('{').
StringRef getParentName(const DeclContext *DC)
@ CXCursor_ObjCInterfaceDecl
An Objective-C @interface.
bool isFunctionOrMethod() const
@ CK_Comma
A comma separator (',').
const char * Text
The text string associated with a CK_Text, CK_Placeholder, CK_Informative, or CK_Comma chunk.
Represents a function declaration or definition.
static AvailabilityResult getDeclAvailability(const Decl *D)
Retrieve the effective availability of the given declaration.
@ CCC_UnionTag
Code completion occurred after the "union" keyword, to indicate a union name.
FunctionDecl * getFunction() const
Retrieve the function overload candidate or the templated function declaration for a function templat...
QualType getParamType(unsigned N) const
Get the type of the Nth parameter.
@ CCC_MacroName
Code completion occurred where an macro is being defined.
@ CCC_ObjCClassMessage
Code completion where an Objective-C class message is expected.
@ CCC_ObjCInterface
Code completion occurred within an Objective-C interface, protocol, or category interface.
@ CCC_ClassOrStructTag
Code completion occurred after the "struct" or "class" keyword, to indicate a struct or class name.
@ CCC_TypeQualifiers
Code completion within a type-qualifier list.
@ CCC_MacroNameUse
Code completion occurred where a macro name is expected (without any arguments, in the case of a func...
DeclContext * getDeclContext()
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.