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 "clang/Sema/DeclSpec.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/Support/Allocator.h"
33 /// \brief Default priority values for code-completion results based
36 /// \brief Priority for the next initialization in a constructor initializer
38 CCP_NextInitializer = 7,
39 /// \brief Priority for an enumeration constant inside a switch whose
40 /// condition is of the enumeration type.
42 /// \brief Priority for a send-to-super completion.
43 CCP_SuperCompletion = 20,
44 /// \brief Priority for a declaration that is in the local scope.
45 CCP_LocalDeclaration = 34,
46 /// \brief Priority for a member declaration found from the current
47 /// method or member function.
48 CCP_MemberDeclaration = 35,
49 /// \brief Priority for a language keyword (that isn't any of the other
52 /// \brief Priority for a code pattern.
54 /// \brief Priority for a non-type declaration.
56 /// \brief Priority for a type.
57 CCP_Type = CCP_Declaration,
58 /// \brief Priority for a constant value (e.g., enumerator).
60 /// \brief Priority for a preprocessor macro.
62 /// \brief Priority for a nested-name-specifier.
63 CCP_NestedNameSpecifier = 75,
64 /// \brief Priority for a result that isn't likely to be what the user wants,
65 /// but is included for completeness.
68 /// \brief Priority for the Objective-C "_cmd" implicit parameter.
69 CCP_ObjC_cmd = CCP_Unlikely
72 /// \brief Priority value deltas that are added to code-completion results
73 /// based on the context of the result.
75 /// \brief The result is in a base class.
77 /// \brief The result is a C++ non-static member function whose qualifiers
78 /// exactly match the object type on which the member function can be called.
79 CCD_ObjectQualifierMatch = -1,
80 /// \brief The selector of the given message exactly matches the selector
81 /// of the current method, which might imply that some kind of delegation
83 CCD_SelectorMatch = -3,
85 /// \brief Adjustment to the "bool" type in Objective-C, where the typedef
86 /// "BOOL" is preferred.
89 /// \brief Adjustment for KVC code pattern priorities when it doesn't look
91 CCD_ProbablyNotObjCCollection = 15,
93 /// \brief An Objective-C method being used as a property.
94 CCD_MethodAsProperty = 2,
96 /// \brief An Objective-C block property completed as a setter with a
97 /// block placeholder.
98 CCD_BlockPropertySetter = 3
101 /// \brief Priority value factors by which we will divide or multiply the
102 /// priority of a code-completion result.
104 /// \brief Divide by this factor when a code-completion result's type exactly
105 /// matches the type we expect.
106 CCF_ExactTypeMatch = 4,
107 /// \brief Divide by this factor when a code-completion result's type is
108 /// similar to the type we expect (e.g., both arithmetic types, both
109 /// Objective-C object pointer types).
110 CCF_SimilarTypeMatch = 2
113 /// \brief A simplified classification of types used when determining
114 /// "similar" types for code completion.
115 enum SimplifiedTypeClass {
127 /// \brief Determine the simplified type class of the given canonical type.
128 SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
130 /// \brief Determine the type that this declaration will have if it is used
131 /// as a type or in an expression.
132 QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND);
134 /// \brief Determine the priority to be given to a macro code completion result
135 /// with the given name.
137 /// \param MacroName The name of the macro.
139 /// \param LangOpts Options describing the current language dialect.
141 /// \param PreferredTypeIsPointer Whether the preferred type for the context
142 /// of this macro is a pointer type.
143 unsigned getMacroUsagePriority(StringRef MacroName,
144 const LangOptions &LangOpts,
145 bool PreferredTypeIsPointer = false);
147 /// \brief Determine the libclang cursor kind associated with the given
149 CXCursorKind getCursorKindForDecl(const Decl *D);
153 class FunctionTemplateDecl;
154 class IdentifierInfo;
156 class NestedNameSpecifier;
159 /// \brief The context in which code completion occurred, so that the
160 /// code-completion consumer can process the results accordingly.
161 class CodeCompletionContext {
164 /// \brief An unspecified code-completion context.
166 /// \brief An unspecified code-completion context where we should also add
167 /// macro completions.
169 /// \brief Code completion occurred within a "top-level" completion context,
170 /// e.g., at namespace or global scope.
172 /// \brief Code completion occurred within an Objective-C interface,
173 /// protocol, or category interface.
175 /// \brief Code completion occurred within an Objective-C implementation
176 /// or category implementation.
177 CCC_ObjCImplementation,
178 /// \brief Code completion occurred within the instance variable list of
179 /// an Objective-C interface, implementation, or category implementation.
181 /// \brief Code completion occurred within a class, struct, or union.
182 CCC_ClassStructUnion,
183 /// \brief Code completion occurred where a statement (or declaration) is
184 /// expected in a function, method, or block.
186 /// \brief Code completion occurred where an expression is expected.
188 /// \brief Code completion occurred where an Objective-C message receiver
190 CCC_ObjCMessageReceiver,
191 /// \brief Code completion occurred on the right-hand side of a member
192 /// access expression using the dot 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().
198 /// \brief Code completion occurred on the right-hand side of a member
199 /// access expression using the arrow operator.
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_ArrowMemberAccess,
205 /// \brief Code completion occurred on the right-hand side of an Objective-C
206 /// property access expression.
208 /// The results of this completion are the members of the type being
209 /// accessed. The type itself is available via
210 /// \c CodeCompletionContext::getType().
211 CCC_ObjCPropertyAccess,
212 /// \brief Code completion occurred after the "enum" keyword, to indicate
213 /// an enumeration name.
215 /// \brief Code completion occurred after the "union" keyword, to indicate
218 /// \brief Code completion occurred after the "struct" or "class" keyword,
219 /// to indicate a struct or class name.
220 CCC_ClassOrStructTag,
221 /// \brief Code completion occurred where a protocol name is expected.
222 CCC_ObjCProtocolName,
223 /// \brief Code completion occurred where a namespace or namespace alias
226 /// \brief Code completion occurred where a type name is expected.
228 /// \brief Code completion occurred where a new name is expected.
230 /// \brief Code completion occurred where a new name is expected and a
231 /// qualified name is permissible.
232 CCC_PotentiallyQualifiedName,
233 /// \brief Code completion occurred where an macro is being defined.
235 /// \brief Code completion occurred where a macro name is expected
236 /// (without any arguments, in the case of a function-like macro).
238 /// \brief Code completion occurred within a preprocessor expression.
239 CCC_PreprocessorExpression,
240 /// \brief Code completion occurred where a preprocessor directive is
242 CCC_PreprocessorDirective,
243 /// \brief Code completion occurred in a context where natural language is
244 /// expected, e.g., a comment or string literal.
246 /// This context usually implies that no completions should be added,
247 /// unless they come from an appropriate natural-language dictionary.
249 /// \brief Code completion for a selector, as in an \@selector expression.
251 /// \brief Code completion within a type-qualifier list.
253 /// \brief Code completion in a parenthesized expression, which means that
254 /// we may also have types here in C and Objective-C (as well as in C++).
255 CCC_ParenthesizedExpression,
256 /// \brief Code completion where an Objective-C instance message is
258 CCC_ObjCInstanceMessage,
259 /// \brief Code completion where an Objective-C class message is expected.
260 CCC_ObjCClassMessage,
261 /// \brief Code completion where the name of an Objective-C class is
263 CCC_ObjCInterfaceName,
264 /// \brief Code completion where an Objective-C category name is expected.
265 CCC_ObjCCategoryName,
266 /// \brief An unknown context, in which we are recovering from a parsing
267 /// error and don't know which completions we should give.
274 /// \brief The type that would prefer to see at this point (e.g., the type
275 /// of an initializer or function parameter).
276 QualType PreferredType;
278 /// \brief The type of the base object in a member access expression.
281 /// \brief The identifiers for Objective-C selector parts.
282 ArrayRef<IdentifierInfo *> SelIdents;
284 /// \brief The scope specifier that comes before the completion token e.g.
286 llvm::Optional<CXXScopeSpec> ScopeSpecifier;
289 /// \brief Construct a new code-completion context of the given kind.
290 CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(None) { }
292 /// \brief Construct a new code-completion context of the given kind.
293 CodeCompletionContext(enum Kind Kind, QualType T,
294 ArrayRef<IdentifierInfo *> SelIdents = None)
296 SelIdents(SelIdents) {
297 if (Kind == CCC_DotMemberAccess || Kind == CCC_ArrowMemberAccess ||
298 Kind == CCC_ObjCPropertyAccess || Kind == CCC_ObjCClassMessage ||
299 Kind == CCC_ObjCInstanceMessage)
305 /// \brief Retrieve the kind of code-completion context.
306 enum Kind getKind() const { return Kind; }
308 /// \brief Retrieve the type that this expression would prefer to have, e.g.,
309 /// if the expression is a variable initializer or a function argument, the
310 /// type of the corresponding variable or function parameter.
311 QualType getPreferredType() const { return PreferredType; }
313 /// \brief Retrieve the type of the base object in a member-access
315 QualType getBaseType() const { return BaseType; }
317 /// \brief Retrieve the Objective-C selector identifiers.
318 ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; }
320 /// \brief Determines whether we want C++ constructors as results within this
322 bool wantConstructorResults() const;
324 /// \brief Sets the scope specifier that comes before the completion token.
325 /// This is expected to be set in code completions on qualfied specifiers
327 void setCXXScopeSpecifier(CXXScopeSpec SS) {
328 this->ScopeSpecifier = std::move(SS);
331 llvm::Optional<const CXXScopeSpec *> getCXXScopeSpecifier() {
333 return ScopeSpecifier.getPointer();
338 /// \brief A "string" used to describe how code completion can
339 /// be performed for an entity.
341 /// A code completion string typically shows how a particular entity can be
342 /// used. For example, the code completion string for a function would show
343 /// the syntax to call it, including the parentheses, placeholders for the
345 class CodeCompletionString {
347 /// \brief The different kinds of "chunks" that can occur within a code
348 /// completion string.
350 /// \brief The piece of text that the user is expected to type to
351 /// match the code-completion string, typically a keyword or the name of a
352 /// declarator or macro.
354 /// \brief A piece of text that should be placed in the buffer, e.g.,
355 /// parentheses or a comma in a function call.
357 /// \brief A code completion string that is entirely optional. For example,
358 /// an optional code completion string that describes the default arguments
359 /// in a function call.
361 /// \brief A string that acts as a placeholder for, e.g., a function
364 /// \brief A piece of text that describes something about the result but
365 /// should not be inserted into the buffer.
367 /// \brief A piece of text that describes the type of an entity or, for
368 /// functions and methods, the return type.
370 /// \brief A piece of text that describes the parameter that corresponds
371 /// to the code-completion location within a function call, message send,
372 /// macro invocation, etc.
374 /// \brief A left parenthesis ('(').
376 /// \brief A right parenthesis (')').
378 /// \brief A left bracket ('[').
380 /// \brief A right bracket (']').
382 /// \brief A left brace ('{').
384 /// \brief A right brace ('}').
386 /// \brief A left angle bracket ('<').
388 /// \brief A right angle bracket ('>').
390 /// \brief A comma separator (',').
392 /// \brief A colon (':').
394 /// \brief A semicolon (';').
396 /// \brief An '=' sign.
398 /// \brief Horizontal whitespace (' ').
400 /// \brief Vertical whitespace ('\\n' or '\\r\\n', depending on the
405 /// \brief One piece of the code completion string.
407 /// \brief The kind of data stored in this piece of the code completion
412 /// \brief The text string associated with a CK_Text, CK_Placeholder,
413 /// CK_Informative, or CK_Comma chunk.
414 /// The string is owned by the chunk and will be deallocated
415 /// (with delete[]) when the chunk is destroyed.
418 /// \brief The code completion string associated with a CK_Optional chunk.
419 /// The optional code completion string is owned by the chunk, and will
420 /// be deallocated (with delete) when the chunk is destroyed.
421 CodeCompletionString *Optional;
424 Chunk() : Kind(CK_Text), Text(nullptr) { }
426 explicit Chunk(ChunkKind Kind, const char *Text = "");
428 /// \brief Create a new text chunk.
429 static Chunk CreateText(const char *Text);
431 /// \brief Create a new optional chunk.
432 static Chunk CreateOptional(CodeCompletionString *Optional);
434 /// \brief Create a new placeholder chunk.
435 static Chunk CreatePlaceholder(const char *Placeholder);
437 /// \brief Create a new informative chunk.
438 static Chunk CreateInformative(const char *Informative);
440 /// \brief Create a new result type chunk.
441 static Chunk CreateResultType(const char *ResultType);
443 /// \brief Create a new current-parameter chunk.
444 static Chunk CreateCurrentParameter(const char *CurrentParameter);
448 /// \brief The number of chunks stored in this string.
449 unsigned NumChunks : 16;
451 /// \brief The number of annotations for this code-completion result.
452 unsigned NumAnnotations : 16;
454 /// \brief The priority of this code-completion string.
455 unsigned Priority : 16;
457 /// \brief The availability of this code-completion result.
458 unsigned Availability : 2;
460 /// \brief The name of the parent context.
461 StringRef ParentName;
463 /// \brief A brief documentation comment attached to the declaration of
464 /// entity being completed by this result.
465 const char *BriefComment;
467 CodeCompletionString(const CodeCompletionString &) = delete;
468 void operator=(const CodeCompletionString &) = delete;
470 CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
471 unsigned Priority, CXAvailabilityKind Availability,
472 const char **Annotations, unsigned NumAnnotations,
473 StringRef ParentName,
474 const char *BriefComment);
475 ~CodeCompletionString() = default;
477 friend class CodeCompletionBuilder;
478 friend class CodeCompletionResult;
481 typedef const Chunk *iterator;
482 iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
483 iterator end() const { return begin() + NumChunks; }
484 bool empty() const { return NumChunks == 0; }
485 unsigned size() const { return NumChunks; }
487 const Chunk &operator[](unsigned I) const {
488 assert(I < size() && "Chunk index out-of-range");
492 /// \brief Returns the text in the TypedText chunk.
493 const char *getTypedText() const;
495 /// \brief Retrieve the priority of this code completion result.
496 unsigned getPriority() const { return Priority; }
498 /// \brief Retrieve the availability of this code completion result.
499 unsigned getAvailability() const { return Availability; }
501 /// \brief Retrieve the number of annotations for this code completion result.
502 unsigned getAnnotationCount() const;
504 /// \brief Retrieve the annotation string specified by \c AnnotationNr.
505 const char *getAnnotation(unsigned AnnotationNr) const;
507 /// \brief Retrieve the name of the parent context.
508 StringRef getParentContextName() const {
512 const char *getBriefComment() const {
516 /// \brief Retrieve a string representation of the code completion string,
517 /// which is mainly useful for debugging.
518 std::string getAsString() const;
521 /// \brief An allocator used specifically for the purpose of code completion.
522 class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
524 /// \brief Copy the given string into this allocator.
525 const char *CopyString(const Twine &String);
528 /// \brief Allocator for a cached set of global code completions.
529 class GlobalCodeCompletionAllocator : public CodeCompletionAllocator {};
531 class CodeCompletionTUInfo {
532 llvm::DenseMap<const DeclContext *, StringRef> ParentNames;
533 std::shared_ptr<GlobalCodeCompletionAllocator> AllocatorRef;
536 explicit CodeCompletionTUInfo(
537 std::shared_ptr<GlobalCodeCompletionAllocator> Allocator)
538 : AllocatorRef(std::move(Allocator)) {}
540 std::shared_ptr<GlobalCodeCompletionAllocator> getAllocatorRef() const {
543 CodeCompletionAllocator &getAllocator() const {
544 assert(AllocatorRef);
545 return *AllocatorRef;
548 StringRef getParentName(const DeclContext *DC);
551 } // end namespace clang
554 template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
555 static const bool value = true;
561 /// \brief A builder class used to construct new code-completion strings.
562 class CodeCompletionBuilder {
564 typedef CodeCompletionString::Chunk Chunk;
567 CodeCompletionAllocator &Allocator;
568 CodeCompletionTUInfo &CCTUInfo;
570 CXAvailabilityKind Availability;
571 StringRef ParentName;
572 const char *BriefComment;
574 /// \brief The chunks stored in this string.
575 SmallVector<Chunk, 4> Chunks;
577 SmallVector<const char *, 2> Annotations;
580 CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
581 CodeCompletionTUInfo &CCTUInfo)
582 : Allocator(Allocator), CCTUInfo(CCTUInfo),
583 Priority(0), Availability(CXAvailability_Available),
584 BriefComment(nullptr) { }
586 CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
587 CodeCompletionTUInfo &CCTUInfo,
588 unsigned Priority, CXAvailabilityKind Availability)
589 : Allocator(Allocator), CCTUInfo(CCTUInfo),
590 Priority(Priority), Availability(Availability),
591 BriefComment(nullptr) { }
593 /// \brief Retrieve the allocator into which the code completion
594 /// strings should be allocated.
595 CodeCompletionAllocator &getAllocator() const { return Allocator; }
597 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
599 /// \brief Take the resulting completion string.
601 /// This operation can only be performed once.
602 CodeCompletionString *TakeString();
604 /// \brief Add a new typed-text chunk.
605 void AddTypedTextChunk(const char *Text);
607 /// \brief Add a new text chunk.
608 void AddTextChunk(const char *Text);
610 /// \brief Add a new optional chunk.
611 void AddOptionalChunk(CodeCompletionString *Optional);
613 /// \brief Add a new placeholder chunk.
614 void AddPlaceholderChunk(const char *Placeholder);
616 /// \brief Add a new informative chunk.
617 void AddInformativeChunk(const char *Text);
619 /// \brief Add a new result-type chunk.
620 void AddResultTypeChunk(const char *ResultType);
622 /// \brief Add a new current-parameter chunk.
623 void AddCurrentParameterChunk(const char *CurrentParameter);
625 /// \brief Add a new chunk.
626 void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = "");
628 void AddAnnotation(const char *A) { Annotations.push_back(A); }
630 /// \brief Add the parent context information to this code completion.
631 void addParentContext(const DeclContext *DC);
633 const char *getBriefComment() const { return BriefComment; }
634 void addBriefComment(StringRef Comment);
636 StringRef getParentName() const { return ParentName; }
639 /// \brief Captures a result of code completion.
640 class CodeCompletionResult {
642 /// \brief Describes the kind of result generated.
644 RK_Declaration = 0, ///< Refers to a declaration
645 RK_Keyword, ///< Refers to a keyword or symbol.
646 RK_Macro, ///< Refers to a macro
647 RK_Pattern ///< Refers to a precomputed pattern.
650 /// \brief When Kind == RK_Declaration or RK_Pattern, the declaration we are
651 /// referring to. In the latter case, the declaration might be NULL.
652 const NamedDecl *Declaration;
655 /// \brief When Kind == RK_Keyword, the string representing the keyword
656 /// or symbol's spelling.
659 /// \brief When Kind == RK_Pattern, the code-completion string that
660 /// describes the completion text to insert.
661 CodeCompletionString *Pattern;
663 /// \brief When Kind == RK_Macro, the identifier that refers to a macro.
664 const IdentifierInfo *Macro;
667 /// \brief The priority of this particular code-completion result.
670 /// \brief Specifies which parameter (of a function, Objective-C method,
671 /// macro, etc.) we should start with when formatting the result.
672 unsigned StartParameter;
674 /// \brief The kind of result stored here.
677 /// \brief The cursor kind that describes this result.
678 CXCursorKind CursorKind;
680 /// \brief The availability of this result.
681 CXAvailabilityKind Availability;
683 /// \brief Whether this result is hidden by another name.
686 /// \brief Whether this result was found via lookup into a base class.
687 bool QualifierIsInformative : 1;
689 /// \brief Whether this declaration is the beginning of a
690 /// nested-name-specifier and, therefore, should be followed by '::'.
691 bool StartsNestedNameSpecifier : 1;
693 /// \brief Whether all parameters (of a function, Objective-C
694 /// method, etc.) should be considered "informative".
695 bool AllParametersAreInformative : 1;
697 /// \brief Whether we're completing a declaration of the given entity,
698 /// rather than a use of that entity.
699 bool DeclaringEntity : 1;
701 /// \brief If the result should have a nested-name-specifier, this is it.
702 /// When \c QualifierIsInformative, the nested-name-specifier is
703 /// informative rather than required.
704 NestedNameSpecifier *Qualifier;
706 /// \brief Build a result that refers to a declaration.
707 CodeCompletionResult(const NamedDecl *Declaration,
709 NestedNameSpecifier *Qualifier = nullptr,
710 bool QualifierIsInformative = false,
711 bool Accessible = true)
712 : Declaration(Declaration), Priority(Priority),
713 StartParameter(0), Kind(RK_Declaration),
714 Availability(CXAvailability_Available), Hidden(false),
715 QualifierIsInformative(QualifierIsInformative),
716 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
717 DeclaringEntity(false), Qualifier(Qualifier) {
718 computeCursorKindAndAvailability(Accessible);
721 /// \brief Build a result that refers to a keyword or symbol.
722 CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
723 : Declaration(nullptr), Keyword(Keyword), Priority(Priority),
724 StartParameter(0), Kind(RK_Keyword), CursorKind(CXCursor_NotImplemented),
725 Availability(CXAvailability_Available), Hidden(false),
726 QualifierIsInformative(0), StartsNestedNameSpecifier(false),
727 AllParametersAreInformative(false), DeclaringEntity(false),
728 Qualifier(nullptr) {}
730 /// \brief Build a result that refers to a macro.
731 CodeCompletionResult(const IdentifierInfo *Macro,
732 unsigned Priority = CCP_Macro)
733 : Declaration(nullptr), Macro(Macro), Priority(Priority), StartParameter(0),
734 Kind(RK_Macro), CursorKind(CXCursor_MacroDefinition),
735 Availability(CXAvailability_Available), Hidden(false),
736 QualifierIsInformative(0), StartsNestedNameSpecifier(false),
737 AllParametersAreInformative(false), DeclaringEntity(false),
738 Qualifier(nullptr) {}
740 /// \brief Build a result that refers to a pattern.
741 CodeCompletionResult(CodeCompletionString *Pattern,
742 unsigned Priority = CCP_CodePattern,
743 CXCursorKind CursorKind = CXCursor_NotImplemented,
744 CXAvailabilityKind Availability = CXAvailability_Available,
745 const NamedDecl *D = nullptr)
746 : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
747 Kind(RK_Pattern), CursorKind(CursorKind), Availability(Availability),
748 Hidden(false), QualifierIsInformative(0),
749 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
750 DeclaringEntity(false), Qualifier(nullptr)
754 /// \brief Build a result that refers to a pattern with an associated
756 CodeCompletionResult(CodeCompletionString *Pattern, const NamedDecl *D,
758 : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
759 Kind(RK_Pattern), Availability(CXAvailability_Available), Hidden(false),
760 QualifierIsInformative(false), StartsNestedNameSpecifier(false),
761 AllParametersAreInformative(false), DeclaringEntity(false),
763 computeCursorKindAndAvailability();
766 /// \brief Retrieve the declaration stored in this result.
767 const NamedDecl *getDeclaration() const {
768 assert(Kind == RK_Declaration && "Not a declaration result");
772 /// \brief Retrieve the keyword stored in this result.
773 const char *getKeyword() const {
774 assert(Kind == RK_Keyword && "Not a keyword result");
778 /// \brief Create a new code-completion string that describes how to insert
779 /// this result into a program.
781 /// \param S The semantic analysis that created the result.
783 /// \param Allocator The allocator that will be used to allocate the
785 CodeCompletionString *CreateCodeCompletionString(Sema &S,
786 const CodeCompletionContext &CCContext,
787 CodeCompletionAllocator &Allocator,
788 CodeCompletionTUInfo &CCTUInfo,
789 bool IncludeBriefComments);
790 CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
792 const CodeCompletionContext &CCContext,
793 CodeCompletionAllocator &Allocator,
794 CodeCompletionTUInfo &CCTUInfo,
795 bool IncludeBriefComments);
797 /// \brief Retrieve the name that should be used to order a result.
799 /// If the name needs to be constructed as a string, that string will be
800 /// saved into Saved and the returned StringRef will refer to it.
801 StringRef getOrderedName(std::string &Saved) const;
804 void computeCursorKindAndAvailability(bool Accessible = true);
807 bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
809 inline bool operator>(const CodeCompletionResult &X,
810 const CodeCompletionResult &Y) {
814 inline bool operator<=(const CodeCompletionResult &X,
815 const CodeCompletionResult &Y) {
819 inline bool operator>=(const CodeCompletionResult &X,
820 const CodeCompletionResult &Y) {
825 raw_ostream &operator<<(raw_ostream &OS,
826 const CodeCompletionString &CCS);
828 /// \brief Abstract interface for a consumer of code-completion
830 class CodeCompleteConsumer {
832 const CodeCompleteOptions CodeCompleteOpts;
834 /// \brief Whether the output format for the code-completion consumer is
839 class OverloadCandidate {
841 /// \brief Describes the type of overload candidate.
843 /// \brief The candidate is a function declaration.
845 /// \brief The candidate is a function template.
847 /// \brief The "candidate" is actually a variable, expression, or block
848 /// for which we only have a function prototype.
853 /// \brief The kind of overload candidate.
857 /// \brief The function overload candidate, available when
858 /// Kind == CK_Function.
859 FunctionDecl *Function;
861 /// \brief The function template overload candidate, available when
862 /// Kind == CK_FunctionTemplate.
863 FunctionTemplateDecl *FunctionTemplate;
865 /// \brief The function type that describes the entity being called,
866 /// when Kind == CK_FunctionType.
867 const FunctionType *Type;
871 OverloadCandidate(FunctionDecl *Function)
872 : Kind(CK_Function), Function(Function) { }
874 OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
875 : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) { }
877 OverloadCandidate(const FunctionType *Type)
878 : Kind(CK_FunctionType), Type(Type) { }
880 /// \brief Determine the kind of overload candidate.
881 CandidateKind getKind() const { return Kind; }
883 /// \brief Retrieve the function overload candidate or the templated
884 /// function declaration for a function template.
885 FunctionDecl *getFunction() const;
887 /// \brief Retrieve the function template overload candidate.
888 FunctionTemplateDecl *getFunctionTemplate() const {
889 assert(getKind() == CK_FunctionTemplate && "Not a function template");
890 return FunctionTemplate;
893 /// \brief Retrieve the function type of the entity, regardless of how the
894 /// function is stored.
895 const FunctionType *getFunctionType() const;
897 /// \brief Create a new code-completion string that describes the function
898 /// signature of this overload candidate.
899 CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
901 CodeCompletionAllocator &Allocator,
902 CodeCompletionTUInfo &CCTUInfo,
903 bool IncludeBriefComments) const;
906 CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
908 : CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary)
911 /// \brief Whether the code-completion consumer wants to see macros.
912 bool includeMacros() const {
913 return CodeCompleteOpts.IncludeMacros;
916 /// \brief Whether the code-completion consumer wants to see code patterns.
917 bool includeCodePatterns() const {
918 return CodeCompleteOpts.IncludeCodePatterns;
921 /// \brief Whether to include global (top-level) declaration results.
922 bool includeGlobals() const { return CodeCompleteOpts.IncludeGlobals; }
924 /// \brief Whether to include declarations in namespace contexts (including
925 /// the global namespace). If this is false, `includeGlobals()` will be
927 bool includeNamespaceLevelDecls() const {
928 return CodeCompleteOpts.IncludeNamespaceLevelDecls;
931 /// \brief Whether to include brief documentation comments within the set of
932 /// code completions returned.
933 bool includeBriefComments() const {
934 return CodeCompleteOpts.IncludeBriefComments;
937 /// \brief Determine whether the output of this consumer is binary.
938 bool isOutputBinary() const { return OutputIsBinary; }
940 /// \brief Deregisters and destroys this code-completion consumer.
941 virtual ~CodeCompleteConsumer();
943 /// \name Code-completion filtering
944 /// \brief Check if the result should be filtered out.
945 virtual bool isResultFilteredOut(StringRef Filter,
946 CodeCompletionResult Results) {
950 /// \name Code-completion callbacks
952 /// \brief Process the finalized code-completion results.
953 virtual void ProcessCodeCompleteResults(Sema &S,
954 CodeCompletionContext Context,
955 CodeCompletionResult *Results,
956 unsigned NumResults) { }
958 /// \param S the semantic-analyzer object for which code-completion is being
961 /// \param CurrentArg the index of the current argument.
963 /// \param Candidates an array of overload candidates.
965 /// \param NumCandidates the number of overload candidates
966 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
967 OverloadCandidate *Candidates,
968 unsigned NumCandidates) { }
971 /// \brief Retrieve the allocator that will be used to allocate
972 /// code completion strings.
973 virtual CodeCompletionAllocator &getAllocator() = 0;
975 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
978 /// \brief A simple code-completion consumer that prints the results it
979 /// receives in a simple format.
980 class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
981 /// \brief The raw output stream.
984 CodeCompletionTUInfo CCTUInfo;
987 /// \brief Create a new printing code-completion consumer that prints its
988 /// results to the given raw output stream.
989 PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
991 : CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS),
992 CCTUInfo(std::make_shared<GlobalCodeCompletionAllocator>()) {}
994 /// \brief Prints the finalized code-completion results.
995 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
996 CodeCompletionResult *Results,
997 unsigned NumResults) override;
999 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1000 OverloadCandidate *Candidates,
1001 unsigned NumCandidates) override;
1003 bool isResultFilteredOut(StringRef Filter, CodeCompletionResult Results) override;
1005 CodeCompletionAllocator &getAllocator() override {
1006 return CCTUInfo.getAllocator();
1009 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
1012 } // end namespace clang
1014 #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H