1 //===---- CodeCompleteConsumer.h - Code Completion Interface ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the CodeCompleteConsumer class.
12 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
14 #define LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
16 #include "clang-c/Index.h"
17 #include "clang/AST/CanonicalType.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/Type.h"
20 #include "clang/Sema/CodeCompleteOptions.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Support/Allocator.h"
32 /// \brief Default priority values for code-completion results based
35 /// \brief Priority for the next initialization in a constructor initializer
37 CCP_NextInitializer = 7,
38 /// \brief Priority for an enumeration constant inside a switch whose
39 /// condition is of the enumeration type.
41 /// \brief Priority for a send-to-super completion.
42 CCP_SuperCompletion = 20,
43 /// \brief Priority for a declaration that is in the local scope.
44 CCP_LocalDeclaration = 34,
45 /// \brief Priority for a member declaration found from the current
46 /// method or member function.
47 CCP_MemberDeclaration = 35,
48 /// \brief Priority for a language keyword (that isn't any of the other
51 /// \brief Priority for a code pattern.
53 /// \brief Priority for a non-type declaration.
55 /// \brief Priority for a type.
56 CCP_Type = CCP_Declaration,
57 /// \brief Priority for a constant value (e.g., enumerator).
59 /// \brief Priority for a preprocessor macro.
61 /// \brief Priority for a nested-name-specifier.
62 CCP_NestedNameSpecifier = 75,
63 /// \brief Priority for a result that isn't likely to be what the user wants,
64 /// but is included for completeness.
67 /// \brief Priority for the Objective-C "_cmd" implicit parameter.
68 CCP_ObjC_cmd = CCP_Unlikely
71 /// \brief Priority value deltas that are added to code-completion results
72 /// based on the context of the result.
74 /// \brief The result is in a base class.
76 /// \brief The result is a C++ non-static member function whose qualifiers
77 /// exactly match the object type on which the member function can be called.
78 CCD_ObjectQualifierMatch = -1,
79 /// \brief The selector of the given message exactly matches the selector
80 /// of the current method, which might imply that some kind of delegation
82 CCD_SelectorMatch = -3,
84 /// \brief Adjustment to the "bool" type in Objective-C, where the typedef
85 /// "BOOL" is preferred.
88 /// \brief Adjustment for KVC code pattern priorities when it doesn't look
90 CCD_ProbablyNotObjCCollection = 15,
92 /// \brief An Objective-C method being used as a property.
93 CCD_MethodAsProperty = 2
96 /// \brief Priority value factors by which we will divide or multiply the
97 /// priority of a code-completion result.
99 /// \brief Divide by this factor when a code-completion result's type exactly
100 /// matches the type we expect.
101 CCF_ExactTypeMatch = 4,
102 /// \brief Divide by this factor when a code-completion result's type is
103 /// similar to the type we expect (e.g., both arithmetic types, both
104 /// Objective-C object pointer types).
105 CCF_SimilarTypeMatch = 2
108 /// \brief A simplified classification of types used when determining
109 /// "similar" types for code completion.
110 enum SimplifiedTypeClass {
122 /// \brief Determine the simplified type class of the given canonical type.
123 SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
125 /// \brief Determine the type that this declaration will have if it is used
126 /// as a type or in an expression.
127 QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND);
129 /// \brief Determine the priority to be given to a macro code completion result
130 /// with the given name.
132 /// \param MacroName The name of the macro.
134 /// \param LangOpts Options describing the current language dialect.
136 /// \param PreferredTypeIsPointer Whether the preferred type for the context
137 /// of this macro is a pointer type.
138 unsigned getMacroUsagePriority(StringRef MacroName,
139 const LangOptions &LangOpts,
140 bool PreferredTypeIsPointer = false);
142 /// \brief Determine the libclang cursor kind associated with the given
144 CXCursorKind getCursorKindForDecl(const Decl *D);
148 class FunctionTemplateDecl;
149 class IdentifierInfo;
151 class NestedNameSpecifier;
154 /// \brief The context in which code completion occurred, so that the
155 /// code-completion consumer can process the results accordingly.
156 class CodeCompletionContext {
159 /// \brief An unspecified code-completion context.
161 /// \brief An unspecified code-completion context where we should also add
162 /// macro completions.
164 /// \brief Code completion occurred within a "top-level" completion context,
165 /// e.g., at namespace or global scope.
167 /// \brief Code completion occurred within an Objective-C interface,
168 /// protocol, or category interface.
170 /// \brief Code completion occurred within an Objective-C implementation
171 /// or category implementation.
172 CCC_ObjCImplementation,
173 /// \brief Code completion occurred within the instance variable list of
174 /// an Objective-C interface, implementation, or category implementation.
176 /// \brief Code completion occurred within a class, struct, or union.
177 CCC_ClassStructUnion,
178 /// \brief Code completion occurred where a statement (or declaration) is
179 /// expected in a function, method, or block.
181 /// \brief Code completion occurred where an expression is expected.
183 /// \brief Code completion occurred where an Objective-C message receiver
185 CCC_ObjCMessageReceiver,
186 /// \brief Code completion occurred on the right-hand side of a member
187 /// access expression using the dot operator.
189 /// The results of this completion are the members of the type being
190 /// accessed. The type itself is available via
191 /// \c CodeCompletionContext::getType().
193 /// \brief Code completion occurred on the right-hand side of a member
194 /// access expression using the arrow operator.
196 /// The results of this completion are the members of the type being
197 /// accessed. The type itself is available via
198 /// \c CodeCompletionContext::getType().
199 CCC_ArrowMemberAccess,
200 /// \brief Code completion occurred on the right-hand side of an Objective-C
201 /// property access expression.
203 /// The results of this completion are the members of the type being
204 /// accessed. The type itself is available via
205 /// \c CodeCompletionContext::getType().
206 CCC_ObjCPropertyAccess,
207 /// \brief Code completion occurred after the "enum" keyword, to indicate
208 /// an enumeration name.
210 /// \brief Code completion occurred after the "union" keyword, to indicate
213 /// \brief Code completion occurred after the "struct" or "class" keyword,
214 /// to indicate a struct or class name.
215 CCC_ClassOrStructTag,
216 /// \brief Code completion occurred where a protocol name is expected.
217 CCC_ObjCProtocolName,
218 /// \brief Code completion occurred where a namespace or namespace alias
221 /// \brief Code completion occurred where a type name is expected.
223 /// \brief Code completion occurred where a new name is expected.
225 /// \brief Code completion occurred where a new name is expected and a
226 /// qualified name is permissible.
227 CCC_PotentiallyQualifiedName,
228 /// \brief Code completion occurred where an macro is being defined.
230 /// \brief Code completion occurred where a macro name is expected
231 /// (without any arguments, in the case of a function-like macro).
233 /// \brief Code completion occurred within a preprocessor expression.
234 CCC_PreprocessorExpression,
235 /// \brief Code completion occurred where a preprocessor directive is
237 CCC_PreprocessorDirective,
238 /// \brief Code completion occurred in a context where natural language is
239 /// expected, e.g., a comment or string literal.
241 /// This context usually implies that no completions should be added,
242 /// unless they come from an appropriate natural-language dictionary.
244 /// \brief Code completion for a selector, as in an \@selector expression.
246 /// \brief Code completion within a type-qualifier list.
248 /// \brief Code completion in a parenthesized expression, which means that
249 /// we may also have types here in C and Objective-C (as well as in C++).
250 CCC_ParenthesizedExpression,
251 /// \brief Code completion where an Objective-C instance message is
253 CCC_ObjCInstanceMessage,
254 /// \brief Code completion where an Objective-C class message is expected.
255 CCC_ObjCClassMessage,
256 /// \brief Code completion where the name of an Objective-C class is
258 CCC_ObjCInterfaceName,
259 /// \brief Code completion where an Objective-C category name is expected.
260 CCC_ObjCCategoryName,
261 /// \brief An unknown context, in which we are recovering from a parsing
262 /// error and don't know which completions we should give.
269 /// \brief The type that would prefer to see at this point (e.g., the type
270 /// of an initializer or function parameter).
271 QualType PreferredType;
273 /// \brief The type of the base object in a member access expression.
276 /// \brief The identifiers for Objective-C selector parts.
277 ArrayRef<IdentifierInfo *> SelIdents;
280 /// \brief Construct a new code-completion context of the given kind.
281 CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(None) { }
283 /// \brief Construct a new code-completion context of the given kind.
284 CodeCompletionContext(enum Kind Kind, QualType T,
285 ArrayRef<IdentifierInfo *> SelIdents = None)
287 SelIdents(SelIdents) {
288 if (Kind == CCC_DotMemberAccess || Kind == CCC_ArrowMemberAccess ||
289 Kind == CCC_ObjCPropertyAccess || Kind == CCC_ObjCClassMessage ||
290 Kind == CCC_ObjCInstanceMessage)
296 /// \brief Retrieve the kind of code-completion context.
297 enum Kind getKind() const { return Kind; }
299 /// \brief Retrieve the type that this expression would prefer to have, e.g.,
300 /// if the expression is a variable initializer or a function argument, the
301 /// type of the corresponding variable or function parameter.
302 QualType getPreferredType() const { return PreferredType; }
304 /// \brief Retrieve the type of the base object in a member-access
306 QualType getBaseType() const { return BaseType; }
308 /// \brief Retrieve the Objective-C selector identifiers.
309 ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; }
311 /// \brief Determines whether we want C++ constructors as results within this
313 bool wantConstructorResults() const;
317 /// \brief A "string" used to describe how code completion can
318 /// be performed for an entity.
320 /// A code completion string typically shows how a particular entity can be
321 /// used. For example, the code completion string for a function would show
322 /// the syntax to call it, including the parentheses, placeholders for the
324 class CodeCompletionString {
326 /// \brief The different kinds of "chunks" that can occur within a code
327 /// completion string.
329 /// \brief The piece of text that the user is expected to type to
330 /// match the code-completion string, typically a keyword or the name of a
331 /// declarator or macro.
333 /// \brief A piece of text that should be placed in the buffer, e.g.,
334 /// parentheses or a comma in a function call.
336 /// \brief A code completion string that is entirely optional. For example,
337 /// an optional code completion string that describes the default arguments
338 /// in a function call.
340 /// \brief A string that acts as a placeholder for, e.g., a function
343 /// \brief A piece of text that describes something about the result but
344 /// should not be inserted into the buffer.
346 /// \brief A piece of text that describes the type of an entity or, for
347 /// functions and methods, the return type.
349 /// \brief A piece of text that describes the parameter that corresponds
350 /// to the code-completion location within a function call, message send,
351 /// macro invocation, etc.
353 /// \brief A left parenthesis ('(').
355 /// \brief A right parenthesis (')').
357 /// \brief A left bracket ('[').
359 /// \brief A right bracket (']').
361 /// \brief A left brace ('{').
363 /// \brief A right brace ('}').
365 /// \brief A left angle bracket ('<').
367 /// \brief A right angle bracket ('>').
369 /// \brief A comma separator (',').
371 /// \brief A colon (':').
373 /// \brief A semicolon (';').
375 /// \brief An '=' sign.
377 /// \brief Horizontal whitespace (' ').
379 /// \brief Vertical whitespace ('\\n' or '\\r\\n', depending on the
384 /// \brief One piece of the code completion string.
386 /// \brief The kind of data stored in this piece of the code completion
391 /// \brief The text string associated with a CK_Text, CK_Placeholder,
392 /// CK_Informative, or CK_Comma chunk.
393 /// The string is owned by the chunk and will be deallocated
394 /// (with delete[]) when the chunk is destroyed.
397 /// \brief The code completion string associated with a CK_Optional chunk.
398 /// The optional code completion string is owned by the chunk, and will
399 /// be deallocated (with delete) when the chunk is destroyed.
400 CodeCompletionString *Optional;
403 Chunk() : Kind(CK_Text), Text(nullptr) { }
405 explicit Chunk(ChunkKind Kind, const char *Text = "");
407 /// \brief Create a new text chunk.
408 static Chunk CreateText(const char *Text);
410 /// \brief Create a new optional chunk.
411 static Chunk CreateOptional(CodeCompletionString *Optional);
413 /// \brief Create a new placeholder chunk.
414 static Chunk CreatePlaceholder(const char *Placeholder);
416 /// \brief Create a new informative chunk.
417 static Chunk CreateInformative(const char *Informative);
419 /// \brief Create a new result type chunk.
420 static Chunk CreateResultType(const char *ResultType);
422 /// \brief Create a new current-parameter chunk.
423 static Chunk CreateCurrentParameter(const char *CurrentParameter);
427 /// \brief The number of chunks stored in this string.
428 unsigned NumChunks : 16;
430 /// \brief The number of annotations for this code-completion result.
431 unsigned NumAnnotations : 16;
433 /// \brief The priority of this code-completion string.
434 unsigned Priority : 16;
436 /// \brief The availability of this code-completion result.
437 unsigned Availability : 2;
439 /// \brief The name of the parent context.
440 StringRef ParentName;
442 /// \brief A brief documentation comment attached to the declaration of
443 /// entity being completed by this result.
444 const char *BriefComment;
446 CodeCompletionString(const CodeCompletionString &) = delete;
447 void operator=(const CodeCompletionString &) = delete;
449 CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
450 unsigned Priority, CXAvailabilityKind Availability,
451 const char **Annotations, unsigned NumAnnotations,
452 StringRef ParentName,
453 const char *BriefComment);
454 ~CodeCompletionString() = default;
456 friend class CodeCompletionBuilder;
457 friend class CodeCompletionResult;
460 typedef const Chunk *iterator;
461 iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
462 iterator end() const { return begin() + NumChunks; }
463 bool empty() const { return NumChunks == 0; }
464 unsigned size() const { return NumChunks; }
466 const Chunk &operator[](unsigned I) const {
467 assert(I < size() && "Chunk index out-of-range");
471 /// \brief Returns the text in the TypedText chunk.
472 const char *getTypedText() const;
474 /// \brief Retrieve the priority of this code completion result.
475 unsigned getPriority() const { return Priority; }
477 /// \brief Retrieve the availability of this code completion result.
478 unsigned getAvailability() const { return Availability; }
480 /// \brief Retrieve the number of annotations for this code completion result.
481 unsigned getAnnotationCount() const;
483 /// \brief Retrieve the annotation string specified by \c AnnotationNr.
484 const char *getAnnotation(unsigned AnnotationNr) const;
486 /// \brief Retrieve the name of the parent context.
487 StringRef getParentContextName() const {
491 const char *getBriefComment() const {
495 /// \brief Retrieve a string representation of the code completion string,
496 /// which is mainly useful for debugging.
497 std::string getAsString() const;
500 /// \brief An allocator used specifically for the purpose of code completion.
501 class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
503 /// \brief Copy the given string into this allocator.
504 const char *CopyString(const Twine &String);
507 /// \brief Allocator for a cached set of global code completions.
508 class GlobalCodeCompletionAllocator
509 : public CodeCompletionAllocator,
510 public RefCountedBase<GlobalCodeCompletionAllocator>
515 class CodeCompletionTUInfo {
516 llvm::DenseMap<const DeclContext *, StringRef> ParentNames;
517 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> AllocatorRef;
520 explicit CodeCompletionTUInfo(
521 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> Allocator)
522 : AllocatorRef(std::move(Allocator)) {}
524 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> getAllocatorRef() const {
527 CodeCompletionAllocator &getAllocator() const {
528 assert(AllocatorRef);
529 return *AllocatorRef;
532 StringRef getParentName(const DeclContext *DC);
535 } // end namespace clang
538 template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
539 static const bool value = true;
545 /// \brief A builder class used to construct new code-completion strings.
546 class CodeCompletionBuilder {
548 typedef CodeCompletionString::Chunk Chunk;
551 CodeCompletionAllocator &Allocator;
552 CodeCompletionTUInfo &CCTUInfo;
554 CXAvailabilityKind Availability;
555 StringRef ParentName;
556 const char *BriefComment;
558 /// \brief The chunks stored in this string.
559 SmallVector<Chunk, 4> Chunks;
561 SmallVector<const char *, 2> Annotations;
564 CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
565 CodeCompletionTUInfo &CCTUInfo)
566 : Allocator(Allocator), CCTUInfo(CCTUInfo),
567 Priority(0), Availability(CXAvailability_Available),
568 BriefComment(nullptr) { }
570 CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
571 CodeCompletionTUInfo &CCTUInfo,
572 unsigned Priority, CXAvailabilityKind Availability)
573 : Allocator(Allocator), CCTUInfo(CCTUInfo),
574 Priority(Priority), Availability(Availability),
575 BriefComment(nullptr) { }
577 /// \brief Retrieve the allocator into which the code completion
578 /// strings should be allocated.
579 CodeCompletionAllocator &getAllocator() const { return Allocator; }
581 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
583 /// \brief Take the resulting completion string.
585 /// This operation can only be performed once.
586 CodeCompletionString *TakeString();
588 /// \brief Add a new typed-text chunk.
589 void AddTypedTextChunk(const char *Text);
591 /// \brief Add a new text chunk.
592 void AddTextChunk(const char *Text);
594 /// \brief Add a new optional chunk.
595 void AddOptionalChunk(CodeCompletionString *Optional);
597 /// \brief Add a new placeholder chunk.
598 void AddPlaceholderChunk(const char *Placeholder);
600 /// \brief Add a new informative chunk.
601 void AddInformativeChunk(const char *Text);
603 /// \brief Add a new result-type chunk.
604 void AddResultTypeChunk(const char *ResultType);
606 /// \brief Add a new current-parameter chunk.
607 void AddCurrentParameterChunk(const char *CurrentParameter);
609 /// \brief Add a new chunk.
610 void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = "");
612 void AddAnnotation(const char *A) { Annotations.push_back(A); }
614 /// \brief Add the parent context information to this code completion.
615 void addParentContext(const DeclContext *DC);
617 const char *getBriefComment() const { return BriefComment; }
618 void addBriefComment(StringRef Comment);
620 StringRef getParentName() const { return ParentName; }
623 /// \brief Captures a result of code completion.
624 class CodeCompletionResult {
626 /// \brief Describes the kind of result generated.
628 RK_Declaration = 0, ///< Refers to a declaration
629 RK_Keyword, ///< Refers to a keyword or symbol.
630 RK_Macro, ///< Refers to a macro
631 RK_Pattern ///< Refers to a precomputed pattern.
634 /// \brief When Kind == RK_Declaration or RK_Pattern, the declaration we are
635 /// referring to. In the latter case, the declaration might be NULL.
636 const NamedDecl *Declaration;
639 /// \brief When Kind == RK_Keyword, the string representing the keyword
640 /// or symbol's spelling.
643 /// \brief When Kind == RK_Pattern, the code-completion string that
644 /// describes the completion text to insert.
645 CodeCompletionString *Pattern;
647 /// \brief When Kind == RK_Macro, the identifier that refers to a macro.
648 const IdentifierInfo *Macro;
651 /// \brief The priority of this particular code-completion result.
654 /// \brief Specifies which parameter (of a function, Objective-C method,
655 /// macro, etc.) we should start with when formatting the result.
656 unsigned StartParameter;
658 /// \brief The kind of result stored here.
661 /// \brief The cursor kind that describes this result.
662 CXCursorKind CursorKind;
664 /// \brief The availability of this result.
665 CXAvailabilityKind Availability;
667 /// \brief Whether this result is hidden by another name.
670 /// \brief Whether this result was found via lookup into a base class.
671 bool QualifierIsInformative : 1;
673 /// \brief Whether this declaration is the beginning of a
674 /// nested-name-specifier and, therefore, should be followed by '::'.
675 bool StartsNestedNameSpecifier : 1;
677 /// \brief Whether all parameters (of a function, Objective-C
678 /// method, etc.) should be considered "informative".
679 bool AllParametersAreInformative : 1;
681 /// \brief Whether we're completing a declaration of the given entity,
682 /// rather than a use of that entity.
683 bool DeclaringEntity : 1;
685 /// \brief If the result should have a nested-name-specifier, this is it.
686 /// When \c QualifierIsInformative, the nested-name-specifier is
687 /// informative rather than required.
688 NestedNameSpecifier *Qualifier;
690 /// \brief Build a result that refers to a declaration.
691 CodeCompletionResult(const NamedDecl *Declaration,
693 NestedNameSpecifier *Qualifier = nullptr,
694 bool QualifierIsInformative = false,
695 bool Accessible = true)
696 : Declaration(Declaration), Priority(Priority),
697 StartParameter(0), Kind(RK_Declaration),
698 Availability(CXAvailability_Available), Hidden(false),
699 QualifierIsInformative(QualifierIsInformative),
700 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
701 DeclaringEntity(false), Qualifier(Qualifier) {
702 computeCursorKindAndAvailability(Accessible);
705 /// \brief Build a result that refers to a keyword or symbol.
706 CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
707 : Declaration(nullptr), Keyword(Keyword), Priority(Priority),
708 StartParameter(0), Kind(RK_Keyword), CursorKind(CXCursor_NotImplemented),
709 Availability(CXAvailability_Available), Hidden(false),
710 QualifierIsInformative(0), StartsNestedNameSpecifier(false),
711 AllParametersAreInformative(false), DeclaringEntity(false),
712 Qualifier(nullptr) {}
714 /// \brief Build a result that refers to a macro.
715 CodeCompletionResult(const IdentifierInfo *Macro,
716 unsigned Priority = CCP_Macro)
717 : Declaration(nullptr), Macro(Macro), Priority(Priority), StartParameter(0),
718 Kind(RK_Macro), CursorKind(CXCursor_MacroDefinition),
719 Availability(CXAvailability_Available), Hidden(false),
720 QualifierIsInformative(0), StartsNestedNameSpecifier(false),
721 AllParametersAreInformative(false), DeclaringEntity(false),
722 Qualifier(nullptr) {}
724 /// \brief Build a result that refers to a pattern.
725 CodeCompletionResult(CodeCompletionString *Pattern,
726 unsigned Priority = CCP_CodePattern,
727 CXCursorKind CursorKind = CXCursor_NotImplemented,
728 CXAvailabilityKind Availability = CXAvailability_Available,
729 const NamedDecl *D = nullptr)
730 : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
731 Kind(RK_Pattern), CursorKind(CursorKind), Availability(Availability),
732 Hidden(false), QualifierIsInformative(0),
733 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
734 DeclaringEntity(false), Qualifier(nullptr)
738 /// \brief Build a result that refers to a pattern with an associated
740 CodeCompletionResult(CodeCompletionString *Pattern, NamedDecl *D,
742 : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
743 Kind(RK_Pattern), Availability(CXAvailability_Available), Hidden(false),
744 QualifierIsInformative(false), StartsNestedNameSpecifier(false),
745 AllParametersAreInformative(false), DeclaringEntity(false),
747 computeCursorKindAndAvailability();
750 /// \brief Retrieve the declaration stored in this result.
751 const NamedDecl *getDeclaration() const {
752 assert(Kind == RK_Declaration && "Not a declaration result");
756 /// \brief Retrieve the keyword stored in this result.
757 const char *getKeyword() const {
758 assert(Kind == RK_Keyword && "Not a keyword result");
762 /// \brief Create a new code-completion string that describes how to insert
763 /// this result into a program.
765 /// \param S The semantic analysis that created the result.
767 /// \param Allocator The allocator that will be used to allocate the
769 CodeCompletionString *CreateCodeCompletionString(Sema &S,
770 const CodeCompletionContext &CCContext,
771 CodeCompletionAllocator &Allocator,
772 CodeCompletionTUInfo &CCTUInfo,
773 bool IncludeBriefComments);
774 CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
776 const CodeCompletionContext &CCContext,
777 CodeCompletionAllocator &Allocator,
778 CodeCompletionTUInfo &CCTUInfo,
779 bool IncludeBriefComments);
782 void computeCursorKindAndAvailability(bool Accessible = true);
785 bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
787 inline bool operator>(const CodeCompletionResult &X,
788 const CodeCompletionResult &Y) {
792 inline bool operator<=(const CodeCompletionResult &X,
793 const CodeCompletionResult &Y) {
797 inline bool operator>=(const CodeCompletionResult &X,
798 const CodeCompletionResult &Y) {
803 raw_ostream &operator<<(raw_ostream &OS,
804 const CodeCompletionString &CCS);
806 /// \brief Abstract interface for a consumer of code-completion
808 class CodeCompleteConsumer {
810 const CodeCompleteOptions CodeCompleteOpts;
812 /// \brief Whether the output format for the code-completion consumer is
817 class OverloadCandidate {
819 /// \brief Describes the type of overload candidate.
821 /// \brief The candidate is a function declaration.
823 /// \brief The candidate is a function template.
825 /// \brief The "candidate" is actually a variable, expression, or block
826 /// for which we only have a function prototype.
831 /// \brief The kind of overload candidate.
835 /// \brief The function overload candidate, available when
836 /// Kind == CK_Function.
837 FunctionDecl *Function;
839 /// \brief The function template overload candidate, available when
840 /// Kind == CK_FunctionTemplate.
841 FunctionTemplateDecl *FunctionTemplate;
843 /// \brief The function type that describes the entity being called,
844 /// when Kind == CK_FunctionType.
845 const FunctionType *Type;
849 OverloadCandidate(FunctionDecl *Function)
850 : Kind(CK_Function), Function(Function) { }
852 OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
853 : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) { }
855 OverloadCandidate(const FunctionType *Type)
856 : Kind(CK_FunctionType), Type(Type) { }
858 /// \brief Determine the kind of overload candidate.
859 CandidateKind getKind() const { return Kind; }
861 /// \brief Retrieve the function overload candidate or the templated
862 /// function declaration for a function template.
863 FunctionDecl *getFunction() const;
865 /// \brief Retrieve the function template overload candidate.
866 FunctionTemplateDecl *getFunctionTemplate() const {
867 assert(getKind() == CK_FunctionTemplate && "Not a function template");
868 return FunctionTemplate;
871 /// \brief Retrieve the function type of the entity, regardless of how the
872 /// function is stored.
873 const FunctionType *getFunctionType() const;
875 /// \brief Create a new code-completion string that describes the function
876 /// signature of this overload candidate.
877 CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
879 CodeCompletionAllocator &Allocator,
880 CodeCompletionTUInfo &CCTUInfo,
881 bool IncludeBriefComments) const;
884 CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
886 : CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary)
889 /// \brief Whether the code-completion consumer wants to see macros.
890 bool includeMacros() const {
891 return CodeCompleteOpts.IncludeMacros;
894 /// \brief Whether the code-completion consumer wants to see code patterns.
895 bool includeCodePatterns() const {
896 return CodeCompleteOpts.IncludeCodePatterns;
899 /// \brief Whether to include global (top-level) declaration results.
900 bool includeGlobals() const {
901 return CodeCompleteOpts.IncludeGlobals;
904 /// \brief Whether to include brief documentation comments within the set of
905 /// code completions returned.
906 bool includeBriefComments() const {
907 return CodeCompleteOpts.IncludeBriefComments;
910 /// \brief Determine whether the output of this consumer is binary.
911 bool isOutputBinary() const { return OutputIsBinary; }
913 /// \brief Deregisters and destroys this code-completion consumer.
914 virtual ~CodeCompleteConsumer();
916 /// \name Code-completion callbacks
918 /// \brief Process the finalized code-completion results.
919 virtual void ProcessCodeCompleteResults(Sema &S,
920 CodeCompletionContext Context,
921 CodeCompletionResult *Results,
922 unsigned NumResults) { }
924 /// \param S the semantic-analyzer object for which code-completion is being
927 /// \param CurrentArg the index of the current argument.
929 /// \param Candidates an array of overload candidates.
931 /// \param NumCandidates the number of overload candidates
932 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
933 OverloadCandidate *Candidates,
934 unsigned NumCandidates) { }
937 /// \brief Retrieve the allocator that will be used to allocate
938 /// code completion strings.
939 virtual CodeCompletionAllocator &getAllocator() = 0;
941 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
944 /// \brief A simple code-completion consumer that prints the results it
945 /// receives in a simple format.
946 class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
947 /// \brief The raw output stream.
950 CodeCompletionTUInfo CCTUInfo;
953 /// \brief Create a new printing code-completion consumer that prints its
954 /// results to the given raw output stream.
955 PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
957 : CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS),
958 CCTUInfo(new GlobalCodeCompletionAllocator) {}
960 /// \brief Prints the finalized code-completion results.
961 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
962 CodeCompletionResult *Results,
963 unsigned NumResults) override;
965 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
966 OverloadCandidate *Candidates,
967 unsigned NumCandidates) override;
969 CodeCompletionAllocator &getAllocator() override {
970 return CCTUInfo.getAllocator();
973 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
976 } // end namespace clang
978 #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H