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,
95 /// \brief An Objective-C block property completed as a setter with a
96 /// block placeholder.
97 CCD_BlockPropertySetter = 3
100 /// \brief Priority value factors by which we will divide or multiply the
101 /// priority of a code-completion result.
103 /// \brief Divide by this factor when a code-completion result's type exactly
104 /// matches the type we expect.
105 CCF_ExactTypeMatch = 4,
106 /// \brief Divide by this factor when a code-completion result's type is
107 /// similar to the type we expect (e.g., both arithmetic types, both
108 /// Objective-C object pointer types).
109 CCF_SimilarTypeMatch = 2
112 /// \brief A simplified classification of types used when determining
113 /// "similar" types for code completion.
114 enum SimplifiedTypeClass {
126 /// \brief Determine the simplified type class of the given canonical type.
127 SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
129 /// \brief Determine the type that this declaration will have if it is used
130 /// as a type or in an expression.
131 QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND);
133 /// \brief Determine the priority to be given to a macro code completion result
134 /// with the given name.
136 /// \param MacroName The name of the macro.
138 /// \param LangOpts Options describing the current language dialect.
140 /// \param PreferredTypeIsPointer Whether the preferred type for the context
141 /// of this macro is a pointer type.
142 unsigned getMacroUsagePriority(StringRef MacroName,
143 const LangOptions &LangOpts,
144 bool PreferredTypeIsPointer = false);
146 /// \brief Determine the libclang cursor kind associated with the given
148 CXCursorKind getCursorKindForDecl(const Decl *D);
152 class FunctionTemplateDecl;
153 class IdentifierInfo;
155 class NestedNameSpecifier;
158 /// \brief The context in which code completion occurred, so that the
159 /// code-completion consumer can process the results accordingly.
160 class CodeCompletionContext {
163 /// \brief An unspecified code-completion context.
165 /// \brief An unspecified code-completion context where we should also add
166 /// macro completions.
168 /// \brief Code completion occurred within a "top-level" completion context,
169 /// e.g., at namespace or global scope.
171 /// \brief Code completion occurred within an Objective-C interface,
172 /// protocol, or category interface.
174 /// \brief Code completion occurred within an Objective-C implementation
175 /// or category implementation.
176 CCC_ObjCImplementation,
177 /// \brief Code completion occurred within the instance variable list of
178 /// an Objective-C interface, implementation, or category implementation.
180 /// \brief Code completion occurred within a class, struct, or union.
181 CCC_ClassStructUnion,
182 /// \brief Code completion occurred where a statement (or declaration) is
183 /// expected in a function, method, or block.
185 /// \brief Code completion occurred where an expression is expected.
187 /// \brief Code completion occurred where an Objective-C message receiver
189 CCC_ObjCMessageReceiver,
190 /// \brief Code completion occurred on the right-hand side of a member
191 /// access expression using the dot operator.
193 /// The results of this completion are the members of the type being
194 /// accessed. The type itself is available via
195 /// \c CodeCompletionContext::getType().
197 /// \brief Code completion occurred on the right-hand side of a member
198 /// access expression using the arrow operator.
200 /// The results of this completion are the members of the type being
201 /// accessed. The type itself is available via
202 /// \c CodeCompletionContext::getType().
203 CCC_ArrowMemberAccess,
204 /// \brief Code completion occurred on the right-hand side of an Objective-C
205 /// property access expression.
207 /// The results of this completion are the members of the type being
208 /// accessed. The type itself is available via
209 /// \c CodeCompletionContext::getType().
210 CCC_ObjCPropertyAccess,
211 /// \brief Code completion occurred after the "enum" keyword, to indicate
212 /// an enumeration name.
214 /// \brief Code completion occurred after the "union" keyword, to indicate
217 /// \brief Code completion occurred after the "struct" or "class" keyword,
218 /// to indicate a struct or class name.
219 CCC_ClassOrStructTag,
220 /// \brief Code completion occurred where a protocol name is expected.
221 CCC_ObjCProtocolName,
222 /// \brief Code completion occurred where a namespace or namespace alias
225 /// \brief Code completion occurred where a type name is expected.
227 /// \brief Code completion occurred where a new name is expected.
229 /// \brief Code completion occurred where a new name is expected and a
230 /// qualified name is permissible.
231 CCC_PotentiallyQualifiedName,
232 /// \brief Code completion occurred where an macro is being defined.
234 /// \brief Code completion occurred where a macro name is expected
235 /// (without any arguments, in the case of a function-like macro).
237 /// \brief Code completion occurred within a preprocessor expression.
238 CCC_PreprocessorExpression,
239 /// \brief Code completion occurred where a preprocessor directive is
241 CCC_PreprocessorDirective,
242 /// \brief Code completion occurred in a context where natural language is
243 /// expected, e.g., a comment or string literal.
245 /// This context usually implies that no completions should be added,
246 /// unless they come from an appropriate natural-language dictionary.
248 /// \brief Code completion for a selector, as in an \@selector expression.
250 /// \brief Code completion within a type-qualifier list.
252 /// \brief Code completion in a parenthesized expression, which means that
253 /// we may also have types here in C and Objective-C (as well as in C++).
254 CCC_ParenthesizedExpression,
255 /// \brief Code completion where an Objective-C instance message is
257 CCC_ObjCInstanceMessage,
258 /// \brief Code completion where an Objective-C class message is expected.
259 CCC_ObjCClassMessage,
260 /// \brief Code completion where the name of an Objective-C class is
262 CCC_ObjCInterfaceName,
263 /// \brief Code completion where an Objective-C category name is expected.
264 CCC_ObjCCategoryName,
265 /// \brief An unknown context, in which we are recovering from a parsing
266 /// error and don't know which completions we should give.
273 /// \brief The type that would prefer to see at this point (e.g., the type
274 /// of an initializer or function parameter).
275 QualType PreferredType;
277 /// \brief The type of the base object in a member access expression.
280 /// \brief The identifiers for Objective-C selector parts.
281 ArrayRef<IdentifierInfo *> SelIdents;
284 /// \brief Construct a new code-completion context of the given kind.
285 CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(None) { }
287 /// \brief Construct a new code-completion context of the given kind.
288 CodeCompletionContext(enum Kind Kind, QualType T,
289 ArrayRef<IdentifierInfo *> SelIdents = None)
291 SelIdents(SelIdents) {
292 if (Kind == CCC_DotMemberAccess || Kind == CCC_ArrowMemberAccess ||
293 Kind == CCC_ObjCPropertyAccess || Kind == CCC_ObjCClassMessage ||
294 Kind == CCC_ObjCInstanceMessage)
300 /// \brief Retrieve the kind of code-completion context.
301 enum Kind getKind() const { return Kind; }
303 /// \brief Retrieve the type that this expression would prefer to have, e.g.,
304 /// if the expression is a variable initializer or a function argument, the
305 /// type of the corresponding variable or function parameter.
306 QualType getPreferredType() const { return PreferredType; }
308 /// \brief Retrieve the type of the base object in a member-access
310 QualType getBaseType() const { return BaseType; }
312 /// \brief Retrieve the Objective-C selector identifiers.
313 ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; }
315 /// \brief Determines whether we want C++ constructors as results within this
317 bool wantConstructorResults() const;
321 /// \brief A "string" used to describe how code completion can
322 /// be performed for an entity.
324 /// A code completion string typically shows how a particular entity can be
325 /// used. For example, the code completion string for a function would show
326 /// the syntax to call it, including the parentheses, placeholders for the
328 class CodeCompletionString {
330 /// \brief The different kinds of "chunks" that can occur within a code
331 /// completion string.
333 /// \brief The piece of text that the user is expected to type to
334 /// match the code-completion string, typically a keyword or the name of a
335 /// declarator or macro.
337 /// \brief A piece of text that should be placed in the buffer, e.g.,
338 /// parentheses or a comma in a function call.
340 /// \brief A code completion string that is entirely optional. For example,
341 /// an optional code completion string that describes the default arguments
342 /// in a function call.
344 /// \brief A string that acts as a placeholder for, e.g., a function
347 /// \brief A piece of text that describes something about the result but
348 /// should not be inserted into the buffer.
350 /// \brief A piece of text that describes the type of an entity or, for
351 /// functions and methods, the return type.
353 /// \brief A piece of text that describes the parameter that corresponds
354 /// to the code-completion location within a function call, message send,
355 /// macro invocation, etc.
357 /// \brief A left parenthesis ('(').
359 /// \brief A right parenthesis (')').
361 /// \brief A left bracket ('[').
363 /// \brief A right bracket (']').
365 /// \brief A left brace ('{').
367 /// \brief A right brace ('}').
369 /// \brief A left angle bracket ('<').
371 /// \brief A right angle bracket ('>').
373 /// \brief A comma separator (',').
375 /// \brief A colon (':').
377 /// \brief A semicolon (';').
379 /// \brief An '=' sign.
381 /// \brief Horizontal whitespace (' ').
383 /// \brief Vertical whitespace ('\\n' or '\\r\\n', depending on the
388 /// \brief One piece of the code completion string.
390 /// \brief The kind of data stored in this piece of the code completion
395 /// \brief The text string associated with a CK_Text, CK_Placeholder,
396 /// CK_Informative, or CK_Comma chunk.
397 /// The string is owned by the chunk and will be deallocated
398 /// (with delete[]) when the chunk is destroyed.
401 /// \brief The code completion string associated with a CK_Optional chunk.
402 /// The optional code completion string is owned by the chunk, and will
403 /// be deallocated (with delete) when the chunk is destroyed.
404 CodeCompletionString *Optional;
407 Chunk() : Kind(CK_Text), Text(nullptr) { }
409 explicit Chunk(ChunkKind Kind, const char *Text = "");
411 /// \brief Create a new text chunk.
412 static Chunk CreateText(const char *Text);
414 /// \brief Create a new optional chunk.
415 static Chunk CreateOptional(CodeCompletionString *Optional);
417 /// \brief Create a new placeholder chunk.
418 static Chunk CreatePlaceholder(const char *Placeholder);
420 /// \brief Create a new informative chunk.
421 static Chunk CreateInformative(const char *Informative);
423 /// \brief Create a new result type chunk.
424 static Chunk CreateResultType(const char *ResultType);
426 /// \brief Create a new current-parameter chunk.
427 static Chunk CreateCurrentParameter(const char *CurrentParameter);
431 /// \brief The number of chunks stored in this string.
432 unsigned NumChunks : 16;
434 /// \brief The number of annotations for this code-completion result.
435 unsigned NumAnnotations : 16;
437 /// \brief The priority of this code-completion string.
438 unsigned Priority : 16;
440 /// \brief The availability of this code-completion result.
441 unsigned Availability : 2;
443 /// \brief The name of the parent context.
444 StringRef ParentName;
446 /// \brief A brief documentation comment attached to the declaration of
447 /// entity being completed by this result.
448 const char *BriefComment;
450 CodeCompletionString(const CodeCompletionString &) = delete;
451 void operator=(const CodeCompletionString &) = delete;
453 CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
454 unsigned Priority, CXAvailabilityKind Availability,
455 const char **Annotations, unsigned NumAnnotations,
456 StringRef ParentName,
457 const char *BriefComment);
458 ~CodeCompletionString() = default;
460 friend class CodeCompletionBuilder;
461 friend class CodeCompletionResult;
464 typedef const Chunk *iterator;
465 iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
466 iterator end() const { return begin() + NumChunks; }
467 bool empty() const { return NumChunks == 0; }
468 unsigned size() const { return NumChunks; }
470 const Chunk &operator[](unsigned I) const {
471 assert(I < size() && "Chunk index out-of-range");
475 /// \brief Returns the text in the TypedText chunk.
476 const char *getTypedText() const;
478 /// \brief Retrieve the priority of this code completion result.
479 unsigned getPriority() const { return Priority; }
481 /// \brief Retrieve the availability of this code completion result.
482 unsigned getAvailability() const { return Availability; }
484 /// \brief Retrieve the number of annotations for this code completion result.
485 unsigned getAnnotationCount() const;
487 /// \brief Retrieve the annotation string specified by \c AnnotationNr.
488 const char *getAnnotation(unsigned AnnotationNr) const;
490 /// \brief Retrieve the name of the parent context.
491 StringRef getParentContextName() const {
495 const char *getBriefComment() const {
499 /// \brief Retrieve a string representation of the code completion string,
500 /// which is mainly useful for debugging.
501 std::string getAsString() const;
504 /// \brief An allocator used specifically for the purpose of code completion.
505 class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
507 /// \brief Copy the given string into this allocator.
508 const char *CopyString(const Twine &String);
511 /// \brief Allocator for a cached set of global code completions.
512 class GlobalCodeCompletionAllocator : public CodeCompletionAllocator {};
514 class CodeCompletionTUInfo {
515 llvm::DenseMap<const DeclContext *, StringRef> ParentNames;
516 std::shared_ptr<GlobalCodeCompletionAllocator> AllocatorRef;
519 explicit CodeCompletionTUInfo(
520 std::shared_ptr<GlobalCodeCompletionAllocator> Allocator)
521 : AllocatorRef(std::move(Allocator)) {}
523 std::shared_ptr<GlobalCodeCompletionAllocator> getAllocatorRef() const {
526 CodeCompletionAllocator &getAllocator() const {
527 assert(AllocatorRef);
528 return *AllocatorRef;
531 StringRef getParentName(const DeclContext *DC);
534 } // end namespace clang
537 template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
538 static const bool value = true;
544 /// \brief A builder class used to construct new code-completion strings.
545 class CodeCompletionBuilder {
547 typedef CodeCompletionString::Chunk Chunk;
550 CodeCompletionAllocator &Allocator;
551 CodeCompletionTUInfo &CCTUInfo;
553 CXAvailabilityKind Availability;
554 StringRef ParentName;
555 const char *BriefComment;
557 /// \brief The chunks stored in this string.
558 SmallVector<Chunk, 4> Chunks;
560 SmallVector<const char *, 2> Annotations;
563 CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
564 CodeCompletionTUInfo &CCTUInfo)
565 : Allocator(Allocator), CCTUInfo(CCTUInfo),
566 Priority(0), Availability(CXAvailability_Available),
567 BriefComment(nullptr) { }
569 CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
570 CodeCompletionTUInfo &CCTUInfo,
571 unsigned Priority, CXAvailabilityKind Availability)
572 : Allocator(Allocator), CCTUInfo(CCTUInfo),
573 Priority(Priority), Availability(Availability),
574 BriefComment(nullptr) { }
576 /// \brief Retrieve the allocator into which the code completion
577 /// strings should be allocated.
578 CodeCompletionAllocator &getAllocator() const { return Allocator; }
580 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
582 /// \brief Take the resulting completion string.
584 /// This operation can only be performed once.
585 CodeCompletionString *TakeString();
587 /// \brief Add a new typed-text chunk.
588 void AddTypedTextChunk(const char *Text);
590 /// \brief Add a new text chunk.
591 void AddTextChunk(const char *Text);
593 /// \brief Add a new optional chunk.
594 void AddOptionalChunk(CodeCompletionString *Optional);
596 /// \brief Add a new placeholder chunk.
597 void AddPlaceholderChunk(const char *Placeholder);
599 /// \brief Add a new informative chunk.
600 void AddInformativeChunk(const char *Text);
602 /// \brief Add a new result-type chunk.
603 void AddResultTypeChunk(const char *ResultType);
605 /// \brief Add a new current-parameter chunk.
606 void AddCurrentParameterChunk(const char *CurrentParameter);
608 /// \brief Add a new chunk.
609 void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = "");
611 void AddAnnotation(const char *A) { Annotations.push_back(A); }
613 /// \brief Add the parent context information to this code completion.
614 void addParentContext(const DeclContext *DC);
616 const char *getBriefComment() const { return BriefComment; }
617 void addBriefComment(StringRef Comment);
619 StringRef getParentName() const { return ParentName; }
622 /// \brief Captures a result of code completion.
623 class CodeCompletionResult {
625 /// \brief Describes the kind of result generated.
627 RK_Declaration = 0, ///< Refers to a declaration
628 RK_Keyword, ///< Refers to a keyword or symbol.
629 RK_Macro, ///< Refers to a macro
630 RK_Pattern ///< Refers to a precomputed pattern.
633 /// \brief When Kind == RK_Declaration or RK_Pattern, the declaration we are
634 /// referring to. In the latter case, the declaration might be NULL.
635 const NamedDecl *Declaration;
638 /// \brief When Kind == RK_Keyword, the string representing the keyword
639 /// or symbol's spelling.
642 /// \brief When Kind == RK_Pattern, the code-completion string that
643 /// describes the completion text to insert.
644 CodeCompletionString *Pattern;
646 /// \brief When Kind == RK_Macro, the identifier that refers to a macro.
647 const IdentifierInfo *Macro;
650 /// \brief The priority of this particular code-completion result.
653 /// \brief Specifies which parameter (of a function, Objective-C method,
654 /// macro, etc.) we should start with when formatting the result.
655 unsigned StartParameter;
657 /// \brief The kind of result stored here.
660 /// \brief The cursor kind that describes this result.
661 CXCursorKind CursorKind;
663 /// \brief The availability of this result.
664 CXAvailabilityKind Availability;
666 /// \brief Whether this result is hidden by another name.
669 /// \brief Whether this result was found via lookup into a base class.
670 bool QualifierIsInformative : 1;
672 /// \brief Whether this declaration is the beginning of a
673 /// nested-name-specifier and, therefore, should be followed by '::'.
674 bool StartsNestedNameSpecifier : 1;
676 /// \brief Whether all parameters (of a function, Objective-C
677 /// method, etc.) should be considered "informative".
678 bool AllParametersAreInformative : 1;
680 /// \brief Whether we're completing a declaration of the given entity,
681 /// rather than a use of that entity.
682 bool DeclaringEntity : 1;
684 /// \brief If the result should have a nested-name-specifier, this is it.
685 /// When \c QualifierIsInformative, the nested-name-specifier is
686 /// informative rather than required.
687 NestedNameSpecifier *Qualifier;
689 /// \brief Build a result that refers to a declaration.
690 CodeCompletionResult(const NamedDecl *Declaration,
692 NestedNameSpecifier *Qualifier = nullptr,
693 bool QualifierIsInformative = false,
694 bool Accessible = true)
695 : Declaration(Declaration), Priority(Priority),
696 StartParameter(0), Kind(RK_Declaration),
697 Availability(CXAvailability_Available), Hidden(false),
698 QualifierIsInformative(QualifierIsInformative),
699 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
700 DeclaringEntity(false), Qualifier(Qualifier) {
701 computeCursorKindAndAvailability(Accessible);
704 /// \brief Build a result that refers to a keyword or symbol.
705 CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
706 : Declaration(nullptr), Keyword(Keyword), Priority(Priority),
707 StartParameter(0), Kind(RK_Keyword), CursorKind(CXCursor_NotImplemented),
708 Availability(CXAvailability_Available), Hidden(false),
709 QualifierIsInformative(0), StartsNestedNameSpecifier(false),
710 AllParametersAreInformative(false), DeclaringEntity(false),
711 Qualifier(nullptr) {}
713 /// \brief Build a result that refers to a macro.
714 CodeCompletionResult(const IdentifierInfo *Macro,
715 unsigned Priority = CCP_Macro)
716 : Declaration(nullptr), Macro(Macro), Priority(Priority), StartParameter(0),
717 Kind(RK_Macro), CursorKind(CXCursor_MacroDefinition),
718 Availability(CXAvailability_Available), Hidden(false),
719 QualifierIsInformative(0), StartsNestedNameSpecifier(false),
720 AllParametersAreInformative(false), DeclaringEntity(false),
721 Qualifier(nullptr) {}
723 /// \brief Build a result that refers to a pattern.
724 CodeCompletionResult(CodeCompletionString *Pattern,
725 unsigned Priority = CCP_CodePattern,
726 CXCursorKind CursorKind = CXCursor_NotImplemented,
727 CXAvailabilityKind Availability = CXAvailability_Available,
728 const NamedDecl *D = nullptr)
729 : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
730 Kind(RK_Pattern), CursorKind(CursorKind), Availability(Availability),
731 Hidden(false), QualifierIsInformative(0),
732 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
733 DeclaringEntity(false), Qualifier(nullptr)
737 /// \brief Build a result that refers to a pattern with an associated
739 CodeCompletionResult(CodeCompletionString *Pattern, const NamedDecl *D,
741 : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
742 Kind(RK_Pattern), Availability(CXAvailability_Available), Hidden(false),
743 QualifierIsInformative(false), StartsNestedNameSpecifier(false),
744 AllParametersAreInformative(false), DeclaringEntity(false),
746 computeCursorKindAndAvailability();
749 /// \brief Retrieve the declaration stored in this result.
750 const NamedDecl *getDeclaration() const {
751 assert(Kind == RK_Declaration && "Not a declaration result");
755 /// \brief Retrieve the keyword stored in this result.
756 const char *getKeyword() const {
757 assert(Kind == RK_Keyword && "Not a keyword result");
761 /// \brief Create a new code-completion string that describes how to insert
762 /// this result into a program.
764 /// \param S The semantic analysis that created the result.
766 /// \param Allocator The allocator that will be used to allocate the
768 CodeCompletionString *CreateCodeCompletionString(Sema &S,
769 const CodeCompletionContext &CCContext,
770 CodeCompletionAllocator &Allocator,
771 CodeCompletionTUInfo &CCTUInfo,
772 bool IncludeBriefComments);
773 CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
775 const CodeCompletionContext &CCContext,
776 CodeCompletionAllocator &Allocator,
777 CodeCompletionTUInfo &CCTUInfo,
778 bool IncludeBriefComments);
781 void computeCursorKindAndAvailability(bool Accessible = true);
784 bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
786 inline bool operator>(const CodeCompletionResult &X,
787 const CodeCompletionResult &Y) {
791 inline bool operator<=(const CodeCompletionResult &X,
792 const CodeCompletionResult &Y) {
796 inline bool operator>=(const CodeCompletionResult &X,
797 const CodeCompletionResult &Y) {
802 raw_ostream &operator<<(raw_ostream &OS,
803 const CodeCompletionString &CCS);
805 /// \brief Abstract interface for a consumer of code-completion
807 class CodeCompleteConsumer {
809 const CodeCompleteOptions CodeCompleteOpts;
811 /// \brief Whether the output format for the code-completion consumer is
816 class OverloadCandidate {
818 /// \brief Describes the type of overload candidate.
820 /// \brief The candidate is a function declaration.
822 /// \brief The candidate is a function template.
824 /// \brief The "candidate" is actually a variable, expression, or block
825 /// for which we only have a function prototype.
830 /// \brief The kind of overload candidate.
834 /// \brief The function overload candidate, available when
835 /// Kind == CK_Function.
836 FunctionDecl *Function;
838 /// \brief The function template overload candidate, available when
839 /// Kind == CK_FunctionTemplate.
840 FunctionTemplateDecl *FunctionTemplate;
842 /// \brief The function type that describes the entity being called,
843 /// when Kind == CK_FunctionType.
844 const FunctionType *Type;
848 OverloadCandidate(FunctionDecl *Function)
849 : Kind(CK_Function), Function(Function) { }
851 OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
852 : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) { }
854 OverloadCandidate(const FunctionType *Type)
855 : Kind(CK_FunctionType), Type(Type) { }
857 /// \brief Determine the kind of overload candidate.
858 CandidateKind getKind() const { return Kind; }
860 /// \brief Retrieve the function overload candidate or the templated
861 /// function declaration for a function template.
862 FunctionDecl *getFunction() const;
864 /// \brief Retrieve the function template overload candidate.
865 FunctionTemplateDecl *getFunctionTemplate() const {
866 assert(getKind() == CK_FunctionTemplate && "Not a function template");
867 return FunctionTemplate;
870 /// \brief Retrieve the function type of the entity, regardless of how the
871 /// function is stored.
872 const FunctionType *getFunctionType() const;
874 /// \brief Create a new code-completion string that describes the function
875 /// signature of this overload candidate.
876 CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
878 CodeCompletionAllocator &Allocator,
879 CodeCompletionTUInfo &CCTUInfo,
880 bool IncludeBriefComments) const;
883 CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
885 : CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary)
888 /// \brief Whether the code-completion consumer wants to see macros.
889 bool includeMacros() const {
890 return CodeCompleteOpts.IncludeMacros;
893 /// \brief Whether the code-completion consumer wants to see code patterns.
894 bool includeCodePatterns() const {
895 return CodeCompleteOpts.IncludeCodePatterns;
898 /// \brief Whether to include global (top-level) declaration results.
899 bool includeGlobals() const {
900 return CodeCompleteOpts.IncludeGlobals;
903 /// \brief Whether to include brief documentation comments within the set of
904 /// code completions returned.
905 bool includeBriefComments() const {
906 return CodeCompleteOpts.IncludeBriefComments;
909 /// \brief Determine whether the output of this consumer is binary.
910 bool isOutputBinary() const { return OutputIsBinary; }
912 /// \brief Deregisters and destroys this code-completion consumer.
913 virtual ~CodeCompleteConsumer();
915 /// \name Code-completion filtering
916 /// \brief Check if the result should be filtered out.
917 virtual bool isResultFilteredOut(StringRef Filter,
918 CodeCompletionResult Results) {
922 /// \name Code-completion callbacks
924 /// \brief Process the finalized code-completion results.
925 virtual void ProcessCodeCompleteResults(Sema &S,
926 CodeCompletionContext Context,
927 CodeCompletionResult *Results,
928 unsigned NumResults) { }
930 /// \param S the semantic-analyzer object for which code-completion is being
933 /// \param CurrentArg the index of the current argument.
935 /// \param Candidates an array of overload candidates.
937 /// \param NumCandidates the number of overload candidates
938 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
939 OverloadCandidate *Candidates,
940 unsigned NumCandidates) { }
943 /// \brief Retrieve the allocator that will be used to allocate
944 /// code completion strings.
945 virtual CodeCompletionAllocator &getAllocator() = 0;
947 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
950 /// \brief A simple code-completion consumer that prints the results it
951 /// receives in a simple format.
952 class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
953 /// \brief The raw output stream.
956 CodeCompletionTUInfo CCTUInfo;
959 /// \brief Create a new printing code-completion consumer that prints its
960 /// results to the given raw output stream.
961 PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
963 : CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS),
964 CCTUInfo(std::make_shared<GlobalCodeCompletionAllocator>()) {}
966 /// \brief Prints the finalized code-completion results.
967 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
968 CodeCompletionResult *Results,
969 unsigned NumResults) override;
971 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
972 OverloadCandidate *Candidates,
973 unsigned NumCandidates) override;
975 bool isResultFilteredOut(StringRef Filter, CodeCompletionResult Results) override;
977 CodeCompletionAllocator &getAllocator() override {
978 return CCTUInfo.getAllocator();
981 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
984 } // end namespace clang
986 #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H