25 #include "llvm/ADT/SmallString.h" 26 #include "llvm/ADT/SmallVector.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;
88 llvm_unreachable(
"Invalid CodeCompletionContext::Kind!");
94 case CCKind::CCC_Other:
96 case CCKind::CCC_OtherWithMacros:
97 return "OtherWithMacros";
98 case CCKind::CCC_TopLevel:
100 case CCKind::CCC_ObjCInterface:
101 return "ObjCInterface";
102 case CCKind::CCC_ObjCImplementation:
103 return "ObjCImplementation";
104 case CCKind::CCC_ObjCIvarList:
105 return "ObjCIvarList";
106 case CCKind::CCC_ClassStructUnion:
107 return "ClassStructUnion";
108 case CCKind::CCC_Statement:
110 case CCKind::CCC_Expression:
112 case CCKind::CCC_ObjCMessageReceiver:
113 return "ObjCMessageReceiver";
114 case CCKind::CCC_DotMemberAccess:
115 return "DotMemberAccess";
116 case CCKind::CCC_ArrowMemberAccess:
117 return "ArrowMemberAccess";
118 case CCKind::CCC_ObjCPropertyAccess:
119 return "ObjCPropertyAccess";
120 case CCKind::CCC_EnumTag:
122 case CCKind::CCC_UnionTag:
124 case CCKind::CCC_ClassOrStructTag:
125 return "ClassOrStructTag";
126 case CCKind::CCC_ObjCProtocolName:
127 return "ObjCProtocolName";
128 case CCKind::CCC_Namespace:
130 case CCKind::CCC_Type:
132 case CCKind::CCC_NewName:
134 case CCKind::CCC_Symbol:
136 case CCKind::CCC_SymbolOrNewName:
137 return "SymbolOrNewName";
138 case CCKind::CCC_MacroName:
140 case CCKind::CCC_MacroNameUse:
141 return "MacroNameUse";
142 case CCKind::CCC_PreprocessorExpression:
143 return "PreprocessorExpression";
144 case CCKind::CCC_PreprocessorDirective:
145 return "PreprocessorDirective";
146 case CCKind::CCC_NaturalLanguage:
147 return "NaturalLanguage";
148 case CCKind::CCC_SelectorName:
149 return "SelectorName";
150 case CCKind::CCC_TypeQualifiers:
151 return "TypeQualifiers";
152 case CCKind::CCC_ParenthesizedExpression:
153 return "ParenthesizedExpression";
154 case CCKind::CCC_ObjCInstanceMessage:
155 return "ObjCInstanceMessage";
156 case CCKind::CCC_ObjCClassMessage:
157 return "ObjCClassMessage";
158 case CCKind::CCC_ObjCInterfaceName:
159 return "ObjCInterfaceName";
160 case CCKind::CCC_ObjCCategoryName:
161 return "ObjCCategoryName";
162 case CCKind::CCC_IncludedFile:
163 return "IncludedFile";
164 case CCKind::CCC_Recovery:
167 llvm_unreachable(
"Invalid CodeCompletionContext::Kind!");
175 : Kind(Kind), Text(
"") {
187 llvm_unreachable(
"Optional strings cannot be created from text");
276 const char *CurrentParameter) {
280 CodeCompletionString::CodeCompletionString(
281 const Chunk *Chunks,
unsigned NumChunks,
unsigned Priority,
283 unsigned NumAnnotations, StringRef ParentName,
const char *BriefComment)
284 : NumChunks(NumChunks), NumAnnotations(NumAnnotations), Priority(Priority),
285 Availability(Availability), ParentName(ParentName),
286 BriefComment(BriefComment) {
287 assert(NumChunks <= 0xffff);
288 assert(NumAnnotations <= 0xffff);
290 Chunk *StoredChunks =
reinterpret_cast<Chunk *
>(
this + 1);
291 for (
unsigned I = 0; I != NumChunks; ++I)
292 StoredChunks[I] = Chunks[I];
294 const char **StoredAnnotations =
295 reinterpret_cast<const char **
>(StoredChunks + NumChunks);
296 for (
unsigned I = 0; I != NumAnnotations; ++I)
297 StoredAnnotations[I] = Annotations[I];
301 return NumAnnotations;
305 if (AnnotationNr < NumAnnotations)
306 return reinterpret_cast<const char *
const *
>(
end())[AnnotationNr];
313 llvm::raw_string_ostream OS(Result);
315 for (
const Chunk &
C : *
this) {
321 OS <<
"<#" << C.
Text <<
"#>";
325 OS <<
"[#" << C.
Text <<
"#]";
328 OS <<
"<#" << C.
Text <<
"#>";
339 for (
const Chunk &
C : *
this)
348 StringRef Ref = String.toStringRef(Data);
352 char *Mem = (
char *)Allocate(Ref.size() + 1, 1);
353 std::copy(Ref.begin(), Ref.end(), Mem);
364 StringRef &CachedParentName = ParentNames[DC];
365 if (!CachedParentName.empty())
366 return CachedParentName;
370 if (CachedParentName.data() !=
nullptr)
376 if (
const auto *ND = dyn_cast<NamedDecl>(DC)) {
378 Contexts.push_back(DC);
386 llvm::raw_svector_ostream OS(S);
388 for (
unsigned I = Contexts.size(); I != 0; --I) {
396 if (
const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
397 CurDC = CatImpl->getCategoryDecl();
399 if (
const auto *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
404 CachedParentName = StringRef((
const char *)(
uintptr_t)~0U, 0);
408 OS << Interface->
getName() <<
'(' << Cat->getName() <<
')';
410 OS << cast<NamedDecl>(CurDC)->
getName();
414 CachedParentName = AllocatorRef->CopyString(OS.str());
417 return CachedParentName;
421 void *Mem = getAllocator().Allocate(
423 sizeof(
const char *) * Annotations.size(),
426 Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(),
427 Annotations.size(), ParentName, BriefComment);
457 const char *CurrentParameter) {
463 Chunks.push_back(
Chunk(CK, Text));
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:
511 llvm_unreachable(
"Invalid CandidateKind!");
522 switch (Result.
Kind) {
527 return !StringRef(Result.
Keyword).startswith(Filter);
534 llvm_unreachable(
"Unknown code completion result Kind.");
539 unsigned NumResults) {
540 std::stable_sort(Results, Results + NumResults);
548 for (
unsigned I = 0; I != NumResults; ++I) {
549 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
551 OS <<
"COMPLETION: ";
552 switch (Results[I].
Kind) {
556 std::vector<std::string> Tags;
557 if (Results[I].Hidden)
558 Tags.push_back(
"Hidden");
559 if (Results[I].InBaseClass)
560 Tags.push_back(
"InBase");
561 if (Results[I].Availability ==
563 Tags.push_back(
"Inaccessible");
565 OS <<
" (" << llvm::join(Tags,
",") <<
")";
568 SemaRef, Context, getAllocator(), CCTUInfo,
569 includeBriefComments())) {
570 OS <<
" : " << CCS->getAsString();
571 if (
const char *BriefComment = CCS->getBriefComment())
572 OS <<
" : " << BriefComment;
582 if (
FixIt.RemoveRange.isTokenRange())
585 OS <<
" (requires fix-it:" 586 <<
" {" << SM.
getLineNumber(BInfo.first, BInfo.second) <<
':' 590 <<
" to \"" <<
FixIt.CodeToInsert <<
"\")";
596 OS << Results[I].
Keyword <<
'\n';
602 SemaRef, Context, getAllocator(), CCTUInfo,
603 includeBriefComments())) {
604 OS <<
" : " << CCS->getAsString();
622 llvm::raw_string_ostream OS(Result);
624 for (
auto &
C : CCS) {
628 OS <<
"[#" <<
C.Text <<
"#]";
632 OS <<
"<#" <<
C.Text <<
"#>";
650 OS <<
"OPENING_PAREN_LOC: ";
654 for (
unsigned I = 0; I != NumCandidates; ++I) {
656 CurrentArg, SemaRef, getAllocator(), CCTUInfo,
657 includeBriefComments())) {
666 if (isa<EnumConstantDecl>(D))
671 void CodeCompletionResult::computeCursorKindAndAvailability(
bool Accessible) {
680 case RK_Declaration: {
697 if (
const auto *Function = dyn_cast<FunctionDecl>(Declaration))
698 if (Function->isDeleted())
706 if (isa<ObjCInterfaceDecl>(Declaration))
708 else if (isa<ObjCProtocolDecl>(Declaration))
718 llvm_unreachable(
"Macro and keyword kinds are handled by the constructors");
734 return Pattern->getTypedText();
736 return Macro->getName();
747 return Id->getName();
750 return Id->getName();
758 std::string XSaved, YSaved;
761 int cmp = XStr.compare_lower(YStr);
766 return XStr.compare(YStr) < 0;
One piece of the code completion string.
An unknown context, in which we are recovering from a parsing error and don't know which completions ...
A code completion string that is entirely optional.
CXAvailabilityKind
Describes the availability of a particular entity, which indicates whether the use of this entity wil...
Represents a function declaration or definition.
ResultKind Kind
The kind of result stored here.
StringRef getParentName(const DeclContext *DC)
Code completion for a selector, as in an @selector expression.
Code completion occurred where an existing name(such as type, function or variable) is expected...
const FunctionType * getFunctionType() const
Retrieve the function type of the entity, regardless of how the function is stored.
void AddTextChunk(const char *Text)
Add a new text chunk.
Code completion where an Objective-C class message is expected.
FunctionType - C99 6.7.5.3 - Function Declarators.
FunctionDecl * getFunction() const
Retrieve the function overload candidate or the templated function declaration for a function templat...
C Language Family Type Representation.
Code completion within a type-qualifier list.
Decl - This represents one declaration (or definition), e.g.
void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text="")
Add a new chunk.
Selector getObjCSelector() const
Get the Objective-C selector stored in this declaration name.
Defines the C++ template declaration subclasses.
unsigned getColumnNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Return the column # for the specified file position.
static Chunk CreateText(const char *Text)
Create a new text chunk.
The base class of the type hierarchy.
An unspecified code-completion context.
static Chunk CreateOptional(CodeCompletionString *Optional)
Create a new optional chunk.
Code completion occurred where an Objective-C message receiver is expected.
unsigned getAnnotationCount() const
Retrieve the number of annotations for this code completion result.
Code completion occurred on the right-hand side of a member access expression using the arrow operato...
ChunkKind
The different kinds of "chunks" that can occur within a code completion string.
Code completion occurred after the "enum" keyword, to indicate an enumeration name.
A left bracket ('[').
const T * getAs() const
Member-template getAs<specific type>'.
A piece of text that describes the type of an entity or, for functions and methods, the return type.
const char * Keyword
When Kind == RK_Keyword, the string representing the keyword or symbol's spelling.
static Chunk CreateResultType(const char *ResultType)
Create a new result type chunk.
void AddOptionalChunk(CodeCompletionString *Optional)
Add a new optional chunk.
Code completion occurred within the instance variable list of an Objective-C interface, implementation, or category implementation.
void AddTypedTextChunk(const char *Text)
Add a new typed-text chunk.
The entity is not available; any use of it will be an error.
Parse and apply any fixits to the source.
std::string getName(ArrayRef< StringRef > Parts) const
Get the platform-specific name separator.
Code completion occurred where both a new name and an existing symbol is permissible.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
One of these records is kept for each identifier that is lexed.
CodeCompletionString * TakeString()
Take the resulting completion string.
void print(raw_ostream &OS, const SourceManager &SM) const
static Chunk CreateInformative(const char *Informative)
Create a new informative chunk.
A "string" used to describe how code completion can be performed for an entity.
An Objective-C @protocol declaration.
void AddResultTypeChunk(const char *ResultType)
Add a new result-type chunk.
static Chunk CreatePlaceholder(const char *Placeholder)
Create a new placeholder chunk.
CodeCompletionString * Pattern
When Kind == RK_Pattern, the code-completion string that describes the completion text to insert...
Code completion occurred where a preprocessor directive is expected.
Code completion occurred within an Objective-C implementation or category implementation.
Code completion occurred where a namespace or namespace alias is expected.
static Chunk CreateCurrentParameter(const char *CurrentParameter)
Create a new current-parameter chunk.
A right brace ('}').
Represents an ObjC class declaration.
The piece of text that the user is expected to type to match the code-completion string, typically a keyword or the name of a declarator or macro.
A comma separator (',').
bool wantConstructorResults() const
Determines whether we want C++ constructors as results within this context.
const LangOptions & LangOpts
Refers to a keyword or symbol.
AvailabilityResult
Captures the result of checking the availability of a declaration.
A right parenthesis (')').
Code completion where an Objective-C category name is expected.
Sema - This implements semantic analysis and AST building for C.
Code completion occurred within a "top-level" completion context, e.g., at namespace or global scope...
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
static std::string getOverloadAsString(const CodeCompletionString &CCS)
Code completion occurred where a protocol name is expected.
CXCursorKind getCursorKindForDecl(const Decl *D)
Determine the libclang cursor kind associated with the given declaration.
QualType getPreferredType() const
Retrieve the type that this expression would prefer to have, e.g., if the expression is a variable in...
llvm::StringRef getCompletionKindString(CodeCompletionContext::Kind Kind)
Get string representation of Kind, useful for for debugging.
std::string getAsString() const
Retrieve a string representation of the code completion string, which is mainly useful for debugging...
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 ...
const char * Text
The text string associated with a CK_Text, CK_Placeholder, CK_Informative, or CK_Comma chunk...
std::string getAsString() const
Retrieve the human-readable string for this name.
Defines the clang::Preprocessor interface.
const NamedDecl * Declaration
When Kind == RK_Declaration or RK_Pattern, the declaration we are referring to.
DeclContext * getDeclContext()
A semicolon (';').
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
Captures a result of code completion.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
bool isFunctionOrMethod() const
Code completion in a parenthesized expression, which means that we may also have types here in C and ...
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Code completion occurred in a context where natural language is expected, e.g., a comment or string l...
Preprocessor & getPreprocessor() const
A piece of text that should be placed in the buffer, e.g., parentheses or a comma in a function call...
The result type of a method or function.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const char * CopyString(const Twine &String)
Copy the given string into this allocator.
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
const char * getTypedText() const
Returns the text in the TypedText chunk.
CodeCompletionString * Optional
The code completion string associated with a CK_Optional chunk.
The context in which code completion occurred, so that the code-completion consumer can process the r...
const IdentifierInfo * Macro
When Kind == RK_Macro, the identifier that refers to a macro.
Code completion occurred within a class, struct, or union.
IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
Encodes a location in the source.
Code completion occurred where a new name is expected.
const char * getAnnotation(unsigned AnnotationNr) const
Retrieve the annotation string specified by AnnotationNr.
Code completion where the name of an Objective-C class is expected.
Code completion occurred within an Objective-C interface, protocol, or category interface.
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
A right bracket (']').
void addParentContext(const DeclContext *DC)
Add the parent context information to this code completion.
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
The entity is available, but not accessible; any use of it will be an error.
ChunkKind Kind
The kind of data stored in this piece of the code completion string.
A left brace ('{').
void addBriefComment(StringRef Comment)
StringRef getName() const
Return the actual identifier string.
Dataflow Directional Tag Classes.
Code completion occurred where an macro is being defined.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
A piece of text that describes something about the result but should not be inserted into the buffer...
Code completion occurred after the "struct" or "class" keyword, to indicate a struct or class name...
static AvailabilityResult getDeclAvailability(const Decl *D)
Retrieve the effective availability of the given declaration.
void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, CodeCompletionResult *Results, unsigned NumResults) override
Prints the finalized code-completion results.
Code completion occurred after the "union" keyword, to indicate a union name.
Code completion occurred where a macro name is expected (without any arguments, in the case of a func...
Code completion where an Objective-C instance message is expected.
The name of a declaration.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
StringRef getCodeCompletionFilter()
Get the code completion token for filtering purposes.
Refers to a precomputed pattern.
Code completion occurred where a statement (or declaration) is expected in a function, method, or block.
Code completion occurred on the right-hand side of an Objective-C property access expression...
void AddInformativeChunk(const char *Text)
Add a new informative chunk.
void AddCurrentParameterChunk(const char *CurrentParameter)
Add a new current-parameter chunk.
A declaration whose specific kind is not exposed via this interface.
A piece of text that describes the parameter that corresponds to the code-completion location within ...
A string that acts as a placeholder for, e.g., a function call argument.
unsigned getAvailability() const
Retrieve the availability of this code completion result.
A left parenthesis ('(').
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Code completion occurred within a preprocessor expression.
Code completion occurred where an expression is expected.
Code completion inside the filename part of a #include directive.
An unspecified code-completion context where we should also add macro completions.
A left angle bracket ('<').
void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, OverloadCandidate *Candidates, unsigned NumCandidates, SourceLocation OpenParLoc) override
A right angle bracket ('>').
SourceManager & getSourceManager() const
Vertical whitespace ('\n' or '\r\n', depending on the platform).
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
__DEVICE__ int max(int __a, int __b)
static Decl::Kind getKind(const Decl *D)
StringRef getOrderedName(std::string &Saved) const
Retrieve the name that should be used to order a result.
Code completion occurred on the right-hand side of a member access expression using the dot operator...
void AddPlaceholderChunk(const char *Placeholder)
Add a new placeholder chunk.
Code completion occurred where a type name is expected.
Horizontal whitespace (' ').
SourceManager & SourceMgr
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
bool isResultFilteredOut(StringRef Filter, CodeCompletionResult Results) override
The entity is available, but has been deprecated (and its use is not recommended).
This represents a decl that may have a name.
bool isTranslationUnit() const
An Objective-C @interface.
virtual ~CodeCompleteConsumer()
Deregisters and destroys this code-completion consumer.
bool isObjCZeroArgSelector() const
This class handles loading and caching of source files into memory.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.