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/Type.h"
19 #include "clang/Sema/CodeCompleteOptions.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/Support/Allocator.h"
30 /// \brief Default priority values for code-completion results based
33 /// \brief Priority for the next initialization in a constructor initializer
35 CCP_NextInitializer = 7,
36 /// \brief Priority for an enumeration constant inside a switch whose
37 /// condition is of the enumeration type.
39 /// \brief Priority for a send-to-super completion.
40 CCP_SuperCompletion = 20,
41 /// \brief Priority for a declaration that is in the local scope.
42 CCP_LocalDeclaration = 34,
43 /// \brief Priority for a member declaration found from the current
44 /// method or member function.
45 CCP_MemberDeclaration = 35,
46 /// \brief Priority for a language keyword (that isn't any of the other
49 /// \brief Priority for a code pattern.
51 /// \brief Priority for a non-type declaration.
53 /// \brief Priority for a type.
54 CCP_Type = CCP_Declaration,
55 /// \brief Priority for a constant value (e.g., enumerator).
57 /// \brief Priority for a preprocessor macro.
59 /// \brief Priority for a nested-name-specifier.
60 CCP_NestedNameSpecifier = 75,
61 /// \brief Priority for a result that isn't likely to be what the user wants,
62 /// but is included for completeness.
65 /// \brief Priority for the Objective-C "_cmd" implicit parameter.
66 CCP_ObjC_cmd = CCP_Unlikely
69 /// \brief Priority value deltas that are added to code-completion results
70 /// based on the context of the result.
72 /// \brief The result is in a base class.
74 /// \brief The result is a C++ non-static member function whose qualifiers
75 /// exactly match the object type on which the member function can be called.
76 CCD_ObjectQualifierMatch = -1,
77 /// \brief The selector of the given message exactly matches the selector
78 /// of the current method, which might imply that some kind of delegation
80 CCD_SelectorMatch = -3,
82 /// \brief Adjustment to the "bool" type in Objective-C, where the typedef
83 /// "BOOL" is preferred.
86 /// \brief Adjustment for KVC code pattern priorities when it doesn't look
88 CCD_ProbablyNotObjCCollection = 15,
90 /// \brief An Objective-C method being used as a property.
91 CCD_MethodAsProperty = 2
94 /// \brief Priority value factors by which we will divide or multiply the
95 /// priority of a code-completion result.
97 /// \brief Divide by this factor when a code-completion result's type exactly
98 /// matches the type we expect.
99 CCF_ExactTypeMatch = 4,
100 /// \brief Divide by this factor when a code-completion result's type is
101 /// similar to the type we expect (e.g., both arithmetic types, both
102 /// Objective-C object pointer types).
103 CCF_SimilarTypeMatch = 2
106 /// \brief A simplified classification of types used when determining
107 /// "similar" types for code completion.
108 enum SimplifiedTypeClass {
120 /// \brief Determine the simplified type class of the given canonical type.
121 SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
123 /// \brief Determine the type that this declaration will have if it is used
124 /// as a type or in an expression.
125 QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND);
127 /// \brief Determine the priority to be given to a macro code completion result
128 /// with the given name.
130 /// \param MacroName The name of the macro.
132 /// \param LangOpts Options describing the current language dialect.
134 /// \param PreferredTypeIsPointer Whether the preferred type for the context
135 /// of this macro is a pointer type.
136 unsigned getMacroUsagePriority(StringRef MacroName,
137 const LangOptions &LangOpts,
138 bool PreferredTypeIsPointer = false);
140 /// \brief Determine the libclang cursor kind associated with the given
142 CXCursorKind getCursorKindForDecl(const Decl *D);
146 class FunctionTemplateDecl;
147 class IdentifierInfo;
149 class NestedNameSpecifier;
152 /// \brief The context in which code completion occurred, so that the
153 /// code-completion consumer can process the results accordingly.
154 class CodeCompletionContext {
157 /// \brief An unspecified code-completion context.
159 /// \brief An unspecified code-completion context where we should also add
160 /// macro completions.
162 /// \brief Code completion occurred within a "top-level" completion context,
163 /// e.g., at namespace or global scope.
165 /// \brief Code completion occurred within an Objective-C interface,
166 /// protocol, or category interface.
168 /// \brief Code completion occurred within an Objective-C implementation
169 /// or category implementation.
170 CCC_ObjCImplementation,
171 /// \brief Code completion occurred within the instance variable list of
172 /// an Objective-C interface, implementation, or category implementation.
174 /// \brief Code completion occurred within a class, struct, or union.
175 CCC_ClassStructUnion,
176 /// \brief Code completion occurred where a statement (or declaration) is
177 /// expected in a function, method, or block.
179 /// \brief Code completion occurred where an expression is expected.
181 /// \brief Code completion occurred where an Objective-C message receiver
183 CCC_ObjCMessageReceiver,
184 /// \brief Code completion occurred on the right-hand side of a member
185 /// access expression using the dot operator.
187 /// The results of this completion are the members of the type being
188 /// accessed. The type itself is available via
189 /// \c CodeCompletionContext::getType().
191 /// \brief Code completion occurred on the right-hand side of a member
192 /// access expression using the arrow operator.
194 /// The results of this completion are the members of the type being
195 /// accessed. The type itself is available via
196 /// \c CodeCompletionContext::getType().
197 CCC_ArrowMemberAccess,
198 /// \brief Code completion occurred on the right-hand side of an Objective-C
199 /// property access expression.
201 /// The results of this completion are the members of the type being
202 /// accessed. The type itself is available via
203 /// \c CodeCompletionContext::getType().
204 CCC_ObjCPropertyAccess,
205 /// \brief Code completion occurred after the "enum" keyword, to indicate
206 /// an enumeration name.
208 /// \brief Code completion occurred after the "union" keyword, to indicate
211 /// \brief Code completion occurred after the "struct" or "class" keyword,
212 /// to indicate a struct or class name.
213 CCC_ClassOrStructTag,
214 /// \brief Code completion occurred where a protocol name is expected.
215 CCC_ObjCProtocolName,
216 /// \brief Code completion occurred where a namespace or namespace alias
219 /// \brief Code completion occurred where a type name is expected.
221 /// \brief Code completion occurred where a new name is expected.
223 /// \brief Code completion occurred where a new name is expected and a
224 /// qualified name is permissible.
225 CCC_PotentiallyQualifiedName,
226 /// \brief Code completion occurred where an macro is being defined.
228 /// \brief Code completion occurred where a macro name is expected
229 /// (without any arguments, in the case of a function-like macro).
231 /// \brief Code completion occurred within a preprocessor expression.
232 CCC_PreprocessorExpression,
233 /// \brief Code completion occurred where a preprocessor directive is
235 CCC_PreprocessorDirective,
236 /// \brief Code completion occurred in a context where natural language is
237 /// expected, e.g., a comment or string literal.
239 /// This context usually implies that no completions should be added,
240 /// unless they come from an appropriate natural-language dictionary.
242 /// \brief Code completion for a selector, as in an \@selector expression.
244 /// \brief Code completion within a type-qualifier list.
246 /// \brief Code completion in a parenthesized expression, which means that
247 /// we may also have types here in C and Objective-C (as well as in C++).
248 CCC_ParenthesizedExpression,
249 /// \brief Code completion where an Objective-C instance message is
251 CCC_ObjCInstanceMessage,
252 /// \brief Code completion where an Objective-C class message is expected.
253 CCC_ObjCClassMessage,
254 /// \brief Code completion where the name of an Objective-C class is
256 CCC_ObjCInterfaceName,
257 /// \brief Code completion where an Objective-C category name is expected.
258 CCC_ObjCCategoryName,
259 /// \brief An unknown context, in which we are recovering from a parsing
260 /// error and don't know which completions we should give.
267 /// \brief The type that would prefer to see at this point (e.g., the type
268 /// of an initializer or function parameter).
269 QualType PreferredType;
271 /// \brief The type of the base object in a member access expression.
274 /// \brief The identifiers for Objective-C selector parts.
275 ArrayRef<IdentifierInfo *> SelIdents;
278 /// \brief Construct a new code-completion context of the given kind.
279 CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(None) { }
281 /// \brief Construct a new code-completion context of the given kind.
282 CodeCompletionContext(enum Kind Kind, QualType T,
283 ArrayRef<IdentifierInfo *> SelIdents = None)
285 SelIdents(SelIdents) {
286 if (Kind == CCC_DotMemberAccess || Kind == CCC_ArrowMemberAccess ||
287 Kind == CCC_ObjCPropertyAccess || Kind == CCC_ObjCClassMessage ||
288 Kind == CCC_ObjCInstanceMessage)
294 /// \brief Retrieve the kind of code-completion context.
295 enum Kind getKind() const { return Kind; }
297 /// \brief Retrieve the type that this expression would prefer to have, e.g.,
298 /// if the expression is a variable initializer or a function argument, the
299 /// type of the corresponding variable or function parameter.
300 QualType getPreferredType() const { return PreferredType; }
302 /// \brief Retrieve the type of the base object in a member-access
304 QualType getBaseType() const { return BaseType; }
306 /// \brief Retrieve the Objective-C selector identifiers.
307 ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; }
309 /// \brief Determines whether we want C++ constructors as results within this
311 bool wantConstructorResults() const;
315 /// \brief A "string" used to describe how code completion can
316 /// be performed for an entity.
318 /// A code completion string typically shows how a particular entity can be
319 /// used. For example, the code completion string for a function would show
320 /// the syntax to call it, including the parentheses, placeholders for the
322 class CodeCompletionString {
324 /// \brief The different kinds of "chunks" that can occur within a code
325 /// completion string.
327 /// \brief The piece of text that the user is expected to type to
328 /// match the code-completion string, typically a keyword or the name of a
329 /// declarator or macro.
331 /// \brief A piece of text that should be placed in the buffer, e.g.,
332 /// parentheses or a comma in a function call.
334 /// \brief A code completion string that is entirely optional. For example,
335 /// an optional code completion string that describes the default arguments
336 /// in a function call.
338 /// \brief A string that acts as a placeholder for, e.g., a function
341 /// \brief A piece of text that describes something about the result but
342 /// should not be inserted into the buffer.
344 /// \brief A piece of text that describes the type of an entity or, for
345 /// functions and methods, the return type.
347 /// \brief A piece of text that describes the parameter that corresponds
348 /// to the code-completion location within a function call, message send,
349 /// macro invocation, etc.
351 /// \brief A left parenthesis ('(').
353 /// \brief A right parenthesis (')').
355 /// \brief A left bracket ('[').
357 /// \brief A right bracket (']').
359 /// \brief A left brace ('{').
361 /// \brief A right brace ('}').
363 /// \brief A left angle bracket ('<').
365 /// \brief A right angle bracket ('>').
367 /// \brief A comma separator (',').
369 /// \brief A colon (':').
371 /// \brief A semicolon (';').
373 /// \brief An '=' sign.
375 /// \brief Horizontal whitespace (' ').
377 /// \brief Vertical whitespace ('\\n' or '\\r\\n', depending on the
382 /// \brief One piece of the code completion string.
384 /// \brief The kind of data stored in this piece of the code completion
389 /// \brief The text string associated with a CK_Text, CK_Placeholder,
390 /// CK_Informative, or CK_Comma chunk.
391 /// The string is owned by the chunk and will be deallocated
392 /// (with delete[]) when the chunk is destroyed.
395 /// \brief The code completion string associated with a CK_Optional chunk.
396 /// The optional code completion string is owned by the chunk, and will
397 /// be deallocated (with delete) when the chunk is destroyed.
398 CodeCompletionString *Optional;
401 Chunk() : Kind(CK_Text), Text(nullptr) { }
403 explicit Chunk(ChunkKind Kind, const char *Text = "");
405 /// \brief Create a new text chunk.
406 static Chunk CreateText(const char *Text);
408 /// \brief Create a new optional chunk.
409 static Chunk CreateOptional(CodeCompletionString *Optional);
411 /// \brief Create a new placeholder chunk.
412 static Chunk CreatePlaceholder(const char *Placeholder);
414 /// \brief Create a new informative chunk.
415 static Chunk CreateInformative(const char *Informative);
417 /// \brief Create a new result type chunk.
418 static Chunk CreateResultType(const char *ResultType);
420 /// \brief Create a new current-parameter chunk.
421 static Chunk CreateCurrentParameter(const char *CurrentParameter);
425 /// \brief The number of chunks stored in this string.
426 unsigned NumChunks : 16;
428 /// \brief The number of annotations for this code-completion result.
429 unsigned NumAnnotations : 16;
431 /// \brief The priority of this code-completion string.
432 unsigned Priority : 16;
434 /// \brief The availability of this code-completion result.
435 unsigned Availability : 2;
437 /// \brief The name of the parent context.
438 StringRef ParentName;
440 /// \brief A brief documentation comment attached to the declaration of
441 /// entity being completed by this result.
442 const char *BriefComment;
444 CodeCompletionString(const CodeCompletionString &) = delete;
445 void operator=(const CodeCompletionString &) = delete;
447 CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
448 unsigned Priority, CXAvailabilityKind Availability,
449 const char **Annotations, unsigned NumAnnotations,
450 StringRef ParentName,
451 const char *BriefComment);
452 ~CodeCompletionString() = default;
454 friend class CodeCompletionBuilder;
455 friend class CodeCompletionResult;
458 typedef const Chunk *iterator;
459 iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
460 iterator end() const { return begin() + NumChunks; }
461 bool empty() const { return NumChunks == 0; }
462 unsigned size() const { return NumChunks; }
464 const Chunk &operator[](unsigned I) const {
465 assert(I < size() && "Chunk index out-of-range");
469 /// \brief Returns the text in the TypedText chunk.
470 const char *getTypedText() const;
472 /// \brief Retrieve the priority of this code completion result.
473 unsigned getPriority() const { return Priority; }
475 /// \brief Retrieve the availability of this code completion result.
476 unsigned getAvailability() const { return Availability; }
478 /// \brief Retrieve the number of annotations for this code completion result.
479 unsigned getAnnotationCount() const;
481 /// \brief Retrieve the annotation string specified by \c AnnotationNr.
482 const char *getAnnotation(unsigned AnnotationNr) const;
484 /// \brief Retrieve the name of the parent context.
485 StringRef getParentContextName() const {
489 const char *getBriefComment() const {
493 /// \brief Retrieve a string representation of the code completion string,
494 /// which is mainly useful for debugging.
495 std::string getAsString() const;
498 /// \brief An allocator used specifically for the purpose of code completion.
499 class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
501 /// \brief Copy the given string into this allocator.
502 const char *CopyString(const Twine &String);
505 /// \brief Allocator for a cached set of global code completions.
506 class GlobalCodeCompletionAllocator
507 : public CodeCompletionAllocator,
508 public RefCountedBase<GlobalCodeCompletionAllocator>
513 class CodeCompletionTUInfo {
514 llvm::DenseMap<const DeclContext *, StringRef> ParentNames;
515 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> AllocatorRef;
518 explicit CodeCompletionTUInfo(
519 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> Allocator)
520 : AllocatorRef(Allocator) { }
522 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> getAllocatorRef() const {
525 CodeCompletionAllocator &getAllocator() const {
526 assert(AllocatorRef);
527 return *AllocatorRef;
530 StringRef getParentName(const DeclContext *DC);
533 } // end namespace clang
536 template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
537 static const bool value = true;
543 /// \brief A builder class used to construct new code-completion strings.
544 class CodeCompletionBuilder {
546 typedef CodeCompletionString::Chunk Chunk;
549 CodeCompletionAllocator &Allocator;
550 CodeCompletionTUInfo &CCTUInfo;
552 CXAvailabilityKind Availability;
553 StringRef ParentName;
554 const char *BriefComment;
556 /// \brief The chunks stored in this string.
557 SmallVector<Chunk, 4> Chunks;
559 SmallVector<const char *, 2> Annotations;
562 CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
563 CodeCompletionTUInfo &CCTUInfo)
564 : Allocator(Allocator), CCTUInfo(CCTUInfo),
565 Priority(0), Availability(CXAvailability_Available),
566 BriefComment(nullptr) { }
568 CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
569 CodeCompletionTUInfo &CCTUInfo,
570 unsigned Priority, CXAvailabilityKind Availability)
571 : Allocator(Allocator), CCTUInfo(CCTUInfo),
572 Priority(Priority), Availability(Availability),
573 BriefComment(nullptr) { }
575 /// \brief Retrieve the allocator into which the code completion
576 /// strings should be allocated.
577 CodeCompletionAllocator &getAllocator() const { return Allocator; }
579 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
581 /// \brief Take the resulting completion string.
583 /// This operation can only be performed once.
584 CodeCompletionString *TakeString();
586 /// \brief Add a new typed-text chunk.
587 void AddTypedTextChunk(const char *Text);
589 /// \brief Add a new text chunk.
590 void AddTextChunk(const char *Text);
592 /// \brief Add a new optional chunk.
593 void AddOptionalChunk(CodeCompletionString *Optional);
595 /// \brief Add a new placeholder chunk.
596 void AddPlaceholderChunk(const char *Placeholder);
598 /// \brief Add a new informative chunk.
599 void AddInformativeChunk(const char *Text);
601 /// \brief Add a new result-type chunk.
602 void AddResultTypeChunk(const char *ResultType);
604 /// \brief Add a new current-parameter chunk.
605 void AddCurrentParameterChunk(const char *CurrentParameter);
607 /// \brief Add a new chunk.
608 void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = "");
610 void AddAnnotation(const char *A) { Annotations.push_back(A); }
612 /// \brief Add the parent context information to this code completion.
613 void addParentContext(const DeclContext *DC);
615 const char *getBriefComment() const { return BriefComment; }
616 void addBriefComment(StringRef Comment);
618 StringRef getParentName() const { return ParentName; }
621 /// \brief Captures a result of code completion.
622 class CodeCompletionResult {
624 /// \brief Describes the kind of result generated.
626 RK_Declaration = 0, ///< Refers to a declaration
627 RK_Keyword, ///< Refers to a keyword or symbol.
628 RK_Macro, ///< Refers to a macro
629 RK_Pattern ///< Refers to a precomputed pattern.
632 /// \brief When Kind == RK_Declaration or RK_Pattern, the declaration we are
633 /// referring to. In the latter case, the declaration might be NULL.
634 const NamedDecl *Declaration;
637 /// \brief When Kind == RK_Keyword, the string representing the keyword
638 /// or symbol's spelling.
641 /// \brief When Kind == RK_Pattern, the code-completion string that
642 /// describes the completion text to insert.
643 CodeCompletionString *Pattern;
645 /// \brief When Kind == RK_Macro, the identifier that refers to a macro.
646 const IdentifierInfo *Macro;
649 /// \brief The priority of this particular code-completion result.
652 /// \brief Specifies which parameter (of a function, Objective-C method,
653 /// macro, etc.) we should start with when formatting the result.
654 unsigned StartParameter;
656 /// \brief The kind of result stored here.
659 /// \brief The cursor kind that describes this result.
660 CXCursorKind CursorKind;
662 /// \brief The availability of this result.
663 CXAvailabilityKind Availability;
665 /// \brief Whether this result is hidden by another name.
668 /// \brief Whether this result was found via lookup into a base class.
669 bool QualifierIsInformative : 1;
671 /// \brief Whether this declaration is the beginning of a
672 /// nested-name-specifier and, therefore, should be followed by '::'.
673 bool StartsNestedNameSpecifier : 1;
675 /// \brief Whether all parameters (of a function, Objective-C
676 /// method, etc.) should be considered "informative".
677 bool AllParametersAreInformative : 1;
679 /// \brief Whether we're completing a declaration of the given entity,
680 /// rather than a use of that entity.
681 bool DeclaringEntity : 1;
683 /// \brief If the result should have a nested-name-specifier, this is it.
684 /// When \c QualifierIsInformative, the nested-name-specifier is
685 /// informative rather than required.
686 NestedNameSpecifier *Qualifier;
688 /// \brief Build a result that refers to a declaration.
689 CodeCompletionResult(const NamedDecl *Declaration,
691 NestedNameSpecifier *Qualifier = nullptr,
692 bool QualifierIsInformative = false,
693 bool Accessible = true)
694 : Declaration(Declaration), Priority(Priority),
695 StartParameter(0), Kind(RK_Declaration),
696 Availability(CXAvailability_Available), Hidden(false),
697 QualifierIsInformative(QualifierIsInformative),
698 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
699 DeclaringEntity(false), Qualifier(Qualifier) {
700 computeCursorKindAndAvailability(Accessible);
703 /// \brief Build a result that refers to a keyword or symbol.
704 CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
705 : Declaration(nullptr), Keyword(Keyword), Priority(Priority),
706 StartParameter(0), Kind(RK_Keyword), CursorKind(CXCursor_NotImplemented),
707 Availability(CXAvailability_Available), Hidden(false),
708 QualifierIsInformative(0), StartsNestedNameSpecifier(false),
709 AllParametersAreInformative(false), DeclaringEntity(false),
710 Qualifier(nullptr) {}
712 /// \brief Build a result that refers to a macro.
713 CodeCompletionResult(const IdentifierInfo *Macro,
714 unsigned Priority = CCP_Macro)
715 : Declaration(nullptr), Macro(Macro), Priority(Priority), StartParameter(0),
716 Kind(RK_Macro), CursorKind(CXCursor_MacroDefinition),
717 Availability(CXAvailability_Available), Hidden(false),
718 QualifierIsInformative(0), StartsNestedNameSpecifier(false),
719 AllParametersAreInformative(false), DeclaringEntity(false),
720 Qualifier(nullptr) {}
722 /// \brief Build a result that refers to a pattern.
723 CodeCompletionResult(CodeCompletionString *Pattern,
724 unsigned Priority = CCP_CodePattern,
725 CXCursorKind CursorKind = CXCursor_NotImplemented,
726 CXAvailabilityKind Availability = CXAvailability_Available,
727 const NamedDecl *D = nullptr)
728 : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
729 Kind(RK_Pattern), CursorKind(CursorKind), Availability(Availability),
730 Hidden(false), QualifierIsInformative(0),
731 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
732 DeclaringEntity(false), Qualifier(nullptr)
736 /// \brief Build a result that refers to a pattern with an associated
738 CodeCompletionResult(CodeCompletionString *Pattern, NamedDecl *D,
740 : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
741 Kind(RK_Pattern), Availability(CXAvailability_Available), Hidden(false),
742 QualifierIsInformative(false), StartsNestedNameSpecifier(false),
743 AllParametersAreInformative(false), DeclaringEntity(false),
745 computeCursorKindAndAvailability();
748 /// \brief Retrieve the declaration stored in this result.
749 const NamedDecl *getDeclaration() const {
750 assert(Kind == RK_Declaration && "Not a declaration result");
754 /// \brief Retrieve the keyword stored in this result.
755 const char *getKeyword() const {
756 assert(Kind == RK_Keyword && "Not a keyword result");
760 /// \brief Create a new code-completion string that describes how to insert
761 /// this result into a program.
763 /// \param S The semantic analysis that created the result.
765 /// \param Allocator The allocator that will be used to allocate the
767 CodeCompletionString *CreateCodeCompletionString(Sema &S,
768 const CodeCompletionContext &CCContext,
769 CodeCompletionAllocator &Allocator,
770 CodeCompletionTUInfo &CCTUInfo,
771 bool IncludeBriefComments);
772 CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
774 const CodeCompletionContext &CCContext,
775 CodeCompletionAllocator &Allocator,
776 CodeCompletionTUInfo &CCTUInfo,
777 bool IncludeBriefComments);
780 void computeCursorKindAndAvailability(bool Accessible = true);
783 bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
785 inline bool operator>(const CodeCompletionResult &X,
786 const CodeCompletionResult &Y) {
790 inline bool operator<=(const CodeCompletionResult &X,
791 const CodeCompletionResult &Y) {
795 inline bool operator>=(const CodeCompletionResult &X,
796 const CodeCompletionResult &Y) {
801 raw_ostream &operator<<(raw_ostream &OS,
802 const CodeCompletionString &CCS);
804 /// \brief Abstract interface for a consumer of code-completion
806 class CodeCompleteConsumer {
808 const CodeCompleteOptions CodeCompleteOpts;
810 /// \brief Whether the output format for the code-completion consumer is
815 class OverloadCandidate {
817 /// \brief Describes the type of overload candidate.
819 /// \brief The candidate is a function declaration.
821 /// \brief The candidate is a function template.
823 /// \brief The "candidate" is actually a variable, expression, or block
824 /// for which we only have a function prototype.
829 /// \brief The kind of overload candidate.
833 /// \brief The function overload candidate, available when
834 /// Kind == CK_Function.
835 FunctionDecl *Function;
837 /// \brief The function template overload candidate, available when
838 /// Kind == CK_FunctionTemplate.
839 FunctionTemplateDecl *FunctionTemplate;
841 /// \brief The function type that describes the entity being called,
842 /// when Kind == CK_FunctionType.
843 const FunctionType *Type;
847 OverloadCandidate(FunctionDecl *Function)
848 : Kind(CK_Function), Function(Function) { }
850 OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
851 : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) { }
853 OverloadCandidate(const FunctionType *Type)
854 : Kind(CK_FunctionType), Type(Type) { }
856 /// \brief Determine the kind of overload candidate.
857 CandidateKind getKind() const { return Kind; }
859 /// \brief Retrieve the function overload candidate or the templated
860 /// function declaration for a function template.
861 FunctionDecl *getFunction() const;
863 /// \brief Retrieve the function template overload candidate.
864 FunctionTemplateDecl *getFunctionTemplate() const {
865 assert(getKind() == CK_FunctionTemplate && "Not a function template");
866 return FunctionTemplate;
869 /// \brief Retrieve the function type of the entity, regardless of how the
870 /// function is stored.
871 const FunctionType *getFunctionType() const;
873 /// \brief Create a new code-completion string that describes the function
874 /// signature of this overload candidate.
875 CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
877 CodeCompletionAllocator &Allocator,
878 CodeCompletionTUInfo &CCTUInfo,
879 bool IncludeBriefComments) const;
882 CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
884 : CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary)
887 /// \brief Whether the code-completion consumer wants to see macros.
888 bool includeMacros() const {
889 return CodeCompleteOpts.IncludeMacros;
892 /// \brief Whether the code-completion consumer wants to see code patterns.
893 bool includeCodePatterns() const {
894 return CodeCompleteOpts.IncludeCodePatterns;
897 /// \brief Whether to include global (top-level) declaration results.
898 bool includeGlobals() const {
899 return CodeCompleteOpts.IncludeGlobals;
902 /// \brief Whether to include brief documentation comments within the set of
903 /// code completions returned.
904 bool includeBriefComments() const {
905 return CodeCompleteOpts.IncludeBriefComments;
908 /// \brief Determine whether the output of this consumer is binary.
909 bool isOutputBinary() const { return OutputIsBinary; }
911 /// \brief Deregisters and destroys this code-completion consumer.
912 virtual ~CodeCompleteConsumer();
914 /// \name Code-completion callbacks
916 /// \brief Process the finalized code-completion results.
917 virtual void ProcessCodeCompleteResults(Sema &S,
918 CodeCompletionContext Context,
919 CodeCompletionResult *Results,
920 unsigned NumResults) { }
922 /// \param S the semantic-analyzer object for which code-completion is being
925 /// \param CurrentArg the index of the current argument.
927 /// \param Candidates an array of overload candidates.
929 /// \param NumCandidates the number of overload candidates
930 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
931 OverloadCandidate *Candidates,
932 unsigned NumCandidates) { }
935 /// \brief Retrieve the allocator that will be used to allocate
936 /// code completion strings.
937 virtual CodeCompletionAllocator &getAllocator() = 0;
939 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
942 /// \brief A simple code-completion consumer that prints the results it
943 /// receives in a simple format.
944 class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
945 /// \brief The raw output stream.
948 CodeCompletionTUInfo CCTUInfo;
951 /// \brief Create a new printing code-completion consumer that prints its
952 /// results to the given raw output stream.
953 PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
955 : CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS),
956 CCTUInfo(new GlobalCodeCompletionAllocator) {}
958 /// \brief Prints the finalized code-completion results.
959 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
960 CodeCompletionResult *Results,
961 unsigned NumResults) override;
963 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
964 OverloadCandidate *Candidates,
965 unsigned NumCandidates) override;
967 CodeCompletionAllocator &getAllocator() override {
968 return CCTUInfo.getAllocator();
971 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
974 } // end namespace clang
976 #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H