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 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
15 #define LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
17 #include "clang-c/Index.h"
18 #include "clang/AST/Type.h"
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Lex/MacroInfo.h"
21 #include "clang/Sema/CodeCompleteOptions.h"
22 #include "clang/Sema/DeclSpec.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/None.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/type_traits.h"
43 class FunctionTemplateDecl;
47 class NestedNameSpecifier;
51 class UsingShadowDecl;
53 /// Default priority values for code-completion results based
56 /// Priority for the next initialization in a constructor initializer
58 CCP_NextInitializer = 7,
60 /// Priority for an enumeration constant inside a switch whose
61 /// condition is of the enumeration type.
64 /// Priority for a send-to-super completion.
65 CCP_SuperCompletion = 20,
67 /// Priority for a declaration that is in the local scope.
68 CCP_LocalDeclaration = 34,
70 /// Priority for a member declaration found from the current
71 /// method or member function.
72 CCP_MemberDeclaration = 35,
74 /// Priority for a language keyword (that isn't any of the other
78 /// Priority for a code pattern.
81 /// Priority for a non-type declaration.
84 /// Priority for a type.
85 CCP_Type = CCP_Declaration,
87 /// Priority for a constant value (e.g., enumerator).
90 /// Priority for a preprocessor macro.
93 /// Priority for a nested-name-specifier.
94 CCP_NestedNameSpecifier = 75,
96 /// Priority for a result that isn't likely to be what the user wants,
97 /// but is included for completeness.
100 /// Priority for the Objective-C "_cmd" implicit parameter.
101 CCP_ObjC_cmd = CCP_Unlikely
104 /// Priority value deltas that are added to code-completion results
105 /// based on the context of the result.
107 /// The result is in a base class.
110 /// The result is a C++ non-static member function whose qualifiers
111 /// exactly match the object type on which the member function can be called.
112 CCD_ObjectQualifierMatch = -1,
114 /// The selector of the given message exactly matches the selector
115 /// of the current method, which might imply that some kind of delegation
117 CCD_SelectorMatch = -3,
119 /// Adjustment to the "bool" type in Objective-C, where the typedef
120 /// "BOOL" is preferred.
121 CCD_bool_in_ObjC = 1,
123 /// Adjustment for KVC code pattern priorities when it doesn't look
125 CCD_ProbablyNotObjCCollection = 15,
127 /// An Objective-C method being used as a property.
128 CCD_MethodAsProperty = 2,
130 /// An Objective-C block property completed as a setter with a
131 /// block placeholder.
132 CCD_BlockPropertySetter = 3
135 /// Priority value factors by which we will divide or multiply the
136 /// priority of a code-completion result.
138 /// Divide by this factor when a code-completion result's type exactly
139 /// matches the type we expect.
140 CCF_ExactTypeMatch = 4,
142 /// Divide by this factor when a code-completion result's type is
143 /// similar to the type we expect (e.g., both arithmetic types, both
144 /// Objective-C object pointer types).
145 CCF_SimilarTypeMatch = 2
148 /// A simplified classification of types used when determining
149 /// "similar" types for code completion.
150 enum SimplifiedTypeClass {
162 /// Determine the simplified type class of the given canonical type.
163 SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
165 /// Determine the type that this declaration will have if it is used
166 /// as a type or in an expression.
167 QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND);
169 /// Determine the priority to be given to a macro code completion result
170 /// with the given name.
172 /// \param MacroName The name of the macro.
174 /// \param LangOpts Options describing the current language dialect.
176 /// \param PreferredTypeIsPointer Whether the preferred type for the context
177 /// of this macro is a pointer type.
178 unsigned getMacroUsagePriority(StringRef MacroName,
179 const LangOptions &LangOpts,
180 bool PreferredTypeIsPointer = false);
182 /// Determine the libclang cursor kind associated with the given
184 CXCursorKind getCursorKindForDecl(const Decl *D);
186 /// The context in which code completion occurred, so that the
187 /// code-completion consumer can process the results accordingly.
188 class CodeCompletionContext {
191 /// An unspecified code-completion context.
194 /// An unspecified code-completion context where we should also add
195 /// macro completions.
198 /// Code completion occurred within a "top-level" completion context,
199 /// e.g., at namespace or global scope.
202 /// Code completion occurred within an Objective-C interface,
203 /// protocol, or category interface.
206 /// Code completion occurred within an Objective-C implementation
207 /// or category implementation.
208 CCC_ObjCImplementation,
210 /// Code completion occurred within the instance variable list of
211 /// an Objective-C interface, implementation, or category implementation.
214 /// Code completion occurred within a class, struct, or union.
215 CCC_ClassStructUnion,
217 /// Code completion occurred where a statement (or declaration) is
218 /// expected in a function, method, or block.
221 /// Code completion occurred where an expression is expected.
224 /// Code completion occurred where an Objective-C message receiver
226 CCC_ObjCMessageReceiver,
228 /// Code completion occurred on the right-hand side of a member
229 /// access expression using the dot operator.
231 /// The results of this completion are the members of the type being
232 /// accessed. The type itself is available via
233 /// \c CodeCompletionContext::getType().
236 /// Code completion occurred on the right-hand side of a member
237 /// access expression using the arrow operator.
239 /// The results of this completion are the members of the type being
240 /// accessed. The type itself is available via
241 /// \c CodeCompletionContext::getType().
242 CCC_ArrowMemberAccess,
244 /// Code completion occurred on the right-hand side of an Objective-C
245 /// property access expression.
247 /// The results of this completion are the members of the type being
248 /// accessed. The type itself is available via
249 /// \c CodeCompletionContext::getType().
250 CCC_ObjCPropertyAccess,
252 /// Code completion occurred after the "enum" keyword, to indicate
253 /// an enumeration name.
256 /// Code completion occurred after the "union" keyword, to indicate
260 /// Code completion occurred after the "struct" or "class" keyword,
261 /// to indicate a struct or class name.
262 CCC_ClassOrStructTag,
264 /// Code completion occurred where a protocol name is expected.
265 CCC_ObjCProtocolName,
267 /// Code completion occurred where a namespace or namespace alias
271 /// Code completion occurred where a type name is expected.
274 /// Code completion occurred where a new name is expected.
277 /// Code completion occurred where both a new name and an existing symbol is
281 /// Code completion occurred where an existing name(such as type, function
282 /// or variable) is expected.
285 /// Code completion occurred where an macro is being defined.
288 /// Code completion occurred where a macro name is expected
289 /// (without any arguments, in the case of a function-like macro).
292 /// Code completion occurred within a preprocessor expression.
293 CCC_PreprocessorExpression,
295 /// Code completion occurred where a preprocessor directive is
297 CCC_PreprocessorDirective,
299 /// Code completion occurred in a context where natural language is
300 /// expected, e.g., a comment or string literal.
302 /// This context usually implies that no completions should be added,
303 /// unless they come from an appropriate natural-language dictionary.
306 /// Code completion for a selector, as in an \@selector expression.
309 /// Code completion within a type-qualifier list.
312 /// Code completion in a parenthesized expression, which means that
313 /// we may also have types here in C and Objective-C (as well as in C++).
314 CCC_ParenthesizedExpression,
316 /// Code completion where an Objective-C instance message is
318 CCC_ObjCInstanceMessage,
320 /// Code completion where an Objective-C class message is expected.
321 CCC_ObjCClassMessage,
323 /// Code completion where the name of an Objective-C class is
325 CCC_ObjCInterfaceName,
327 /// Code completion where an Objective-C category name is expected.
328 CCC_ObjCCategoryName,
330 /// Code completion inside the filename part of a #include directive.
333 /// An unknown context, in which we are recovering from a parsing
334 /// error and don't know which completions we should give.
338 using VisitedContextSet = llvm::SmallPtrSet<DeclContext *, 8>;
343 /// The type that would prefer to see at this point (e.g., the type
344 /// of an initializer or function parameter).
345 QualType PreferredType;
347 /// The type of the base object in a member access expression.
350 /// The identifiers for Objective-C selector parts.
351 ArrayRef<IdentifierInfo *> SelIdents;
353 /// The scope specifier that comes before the completion token e.g.
355 llvm::Optional<CXXScopeSpec> ScopeSpecifier;
357 /// A set of declaration contexts visited by Sema when doing lookup for
359 VisitedContextSet VisitedContexts;
362 /// Construct a new code-completion context of the given kind.
363 CodeCompletionContext(Kind CCKind) : CCKind(CCKind), SelIdents(None) {}
365 /// Construct a new code-completion context of the given kind.
366 CodeCompletionContext(Kind CCKind, QualType T,
367 ArrayRef<IdentifierInfo *> SelIdents = None)
368 : CCKind(CCKind), SelIdents(SelIdents) {
369 if (CCKind == CCC_DotMemberAccess || CCKind == CCC_ArrowMemberAccess ||
370 CCKind == CCC_ObjCPropertyAccess || CCKind == CCC_ObjCClassMessage ||
371 CCKind == CCC_ObjCInstanceMessage)
377 /// Retrieve the kind of code-completion context.
378 Kind getKind() const { return CCKind; }
380 /// Retrieve the type that this expression would prefer to have, e.g.,
381 /// if the expression is a variable initializer or a function argument, the
382 /// type of the corresponding variable or function parameter.
383 QualType getPreferredType() const { return PreferredType; }
385 /// Retrieve the type of the base object in a member-access
387 QualType getBaseType() const { return BaseType; }
389 /// Retrieve the Objective-C selector identifiers.
390 ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; }
392 /// Determines whether we want C++ constructors as results within this
394 bool wantConstructorResults() const;
396 /// Sets the scope specifier that comes before the completion token.
397 /// This is expected to be set in code completions on qualfied specifiers
399 void setCXXScopeSpecifier(CXXScopeSpec SS) {
400 this->ScopeSpecifier = std::move(SS);
403 /// Adds a visited context.
404 void addVisitedContext(DeclContext *Ctx) {
405 VisitedContexts.insert(Ctx);
408 /// Retrieves all visited contexts.
409 const VisitedContextSet &getVisitedContexts() const {
410 return VisitedContexts;
413 llvm::Optional<const CXXScopeSpec *> getCXXScopeSpecifier() {
415 return ScopeSpecifier.getPointer();
420 /// Get string representation of \p Kind, useful for for debugging.
421 llvm::StringRef getCompletionKindString(CodeCompletionContext::Kind Kind);
423 /// A "string" used to describe how code completion can
424 /// be performed for an entity.
426 /// A code completion string typically shows how a particular entity can be
427 /// used. For example, the code completion string for a function would show
428 /// the syntax to call it, including the parentheses, placeholders for the
430 class CodeCompletionString {
432 /// The different kinds of "chunks" that can occur within a code
433 /// completion string.
435 /// The piece of text that the user is expected to type to
436 /// match the code-completion string, typically a keyword or the name of a
437 /// declarator or macro.
440 /// A piece of text that should be placed in the buffer, e.g.,
441 /// parentheses or a comma in a function call.
444 /// A code completion string that is entirely optional. For example,
445 /// an optional code completion string that describes the default arguments
446 /// in a function call.
449 /// A string that acts as a placeholder for, e.g., a function
453 /// A piece of text that describes something about the result but
454 /// should not be inserted into the buffer.
456 /// A piece of text that describes the type of an entity or, for
457 /// functions and methods, the return type.
460 /// A piece of text that describes the parameter that corresponds
461 /// to the code-completion location within a function call, message send,
462 /// macro invocation, etc.
465 /// A left parenthesis ('(').
468 /// A right parenthesis (')').
471 /// A left bracket ('[').
474 /// A right bracket (']').
477 /// A left brace ('{').
480 /// A right brace ('}').
483 /// A left angle bracket ('<').
486 /// A right angle bracket ('>').
489 /// A comma separator (',').
495 /// A semicolon (';').
501 /// Horizontal whitespace (' ').
504 /// Vertical whitespace ('\\n' or '\\r\\n', depending on the
509 /// One piece of the code completion string.
511 /// The kind of data stored in this piece of the code completion
513 ChunkKind Kind = CK_Text;
516 /// The text string associated with a CK_Text, CK_Placeholder,
517 /// CK_Informative, or CK_Comma chunk.
518 /// The string is owned by the chunk and will be deallocated
519 /// (with delete[]) when the chunk is destroyed.
522 /// The code completion string associated with a CK_Optional chunk.
523 /// The optional code completion string is owned by the chunk, and will
524 /// be deallocated (with delete) when the chunk is destroyed.
525 CodeCompletionString *Optional;
528 Chunk() : Text(nullptr) {}
530 explicit Chunk(ChunkKind Kind, const char *Text = "");
532 /// Create a new text chunk.
533 static Chunk CreateText(const char *Text);
535 /// Create a new optional chunk.
536 static Chunk CreateOptional(CodeCompletionString *Optional);
538 /// Create a new placeholder chunk.
539 static Chunk CreatePlaceholder(const char *Placeholder);
541 /// Create a new informative chunk.
542 static Chunk CreateInformative(const char *Informative);
544 /// Create a new result type chunk.
545 static Chunk CreateResultType(const char *ResultType);
547 /// Create a new current-parameter chunk.
548 static Chunk CreateCurrentParameter(const char *CurrentParameter);
552 friend class CodeCompletionBuilder;
553 friend class CodeCompletionResult;
555 /// The number of chunks stored in this string.
556 unsigned NumChunks : 16;
558 /// The number of annotations for this code-completion result.
559 unsigned NumAnnotations : 16;
561 /// The priority of this code-completion string.
562 unsigned Priority : 16;
564 /// The availability of this code-completion result.
565 unsigned Availability : 2;
567 /// The name of the parent context.
568 StringRef ParentName;
570 /// A brief documentation comment attached to the declaration of
571 /// entity being completed by this result.
572 const char *BriefComment;
574 CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
575 unsigned Priority, CXAvailabilityKind Availability,
576 const char **Annotations, unsigned NumAnnotations,
577 StringRef ParentName,
578 const char *BriefComment);
579 ~CodeCompletionString() = default;
582 CodeCompletionString(const CodeCompletionString &) = delete;
583 CodeCompletionString &operator=(const CodeCompletionString &) = delete;
585 using iterator = const Chunk *;
587 iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
588 iterator end() const { return begin() + NumChunks; }
589 bool empty() const { return NumChunks == 0; }
590 unsigned size() const { return NumChunks; }
592 const Chunk &operator[](unsigned I) const {
593 assert(I < size() && "Chunk index out-of-range");
597 /// Returns the text in the TypedText chunk.
598 const char *getTypedText() const;
600 /// Retrieve the priority of this code completion result.
601 unsigned getPriority() const { return Priority; }
603 /// Retrieve the availability of this code completion result.
604 unsigned getAvailability() const { return Availability; }
606 /// Retrieve the number of annotations for this code completion result.
607 unsigned getAnnotationCount() const;
609 /// Retrieve the annotation string specified by \c AnnotationNr.
610 const char *getAnnotation(unsigned AnnotationNr) const;
612 /// Retrieve the name of the parent context.
613 StringRef getParentContextName() const {
617 const char *getBriefComment() const {
621 /// Retrieve a string representation of the code completion string,
622 /// which is mainly useful for debugging.
623 std::string getAsString() const;
626 /// An allocator used specifically for the purpose of code completion.
627 class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
629 /// Copy the given string into this allocator.
630 const char *CopyString(const Twine &String);
633 /// Allocator for a cached set of global code completions.
634 class GlobalCodeCompletionAllocator : public CodeCompletionAllocator {};
636 class CodeCompletionTUInfo {
637 llvm::DenseMap<const DeclContext *, StringRef> ParentNames;
638 std::shared_ptr<GlobalCodeCompletionAllocator> AllocatorRef;
641 explicit CodeCompletionTUInfo(
642 std::shared_ptr<GlobalCodeCompletionAllocator> Allocator)
643 : AllocatorRef(std::move(Allocator)) {}
645 std::shared_ptr<GlobalCodeCompletionAllocator> getAllocatorRef() const {
649 CodeCompletionAllocator &getAllocator() const {
650 assert(AllocatorRef);
651 return *AllocatorRef;
654 StringRef getParentName(const DeclContext *DC);
661 template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
662 static const bool value = true;
669 /// A builder class used to construct new code-completion strings.
670 class CodeCompletionBuilder {
672 using Chunk = CodeCompletionString::Chunk;
675 CodeCompletionAllocator &Allocator;
676 CodeCompletionTUInfo &CCTUInfo;
677 unsigned Priority = 0;
678 CXAvailabilityKind Availability = CXAvailability_Available;
679 StringRef ParentName;
680 const char *BriefComment = nullptr;
682 /// The chunks stored in this string.
683 SmallVector<Chunk, 4> Chunks;
685 SmallVector<const char *, 2> Annotations;
688 CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
689 CodeCompletionTUInfo &CCTUInfo)
690 : Allocator(Allocator), CCTUInfo(CCTUInfo) {}
692 CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
693 CodeCompletionTUInfo &CCTUInfo,
694 unsigned Priority, CXAvailabilityKind Availability)
695 : Allocator(Allocator), CCTUInfo(CCTUInfo), Priority(Priority),
696 Availability(Availability) {}
698 /// Retrieve the allocator into which the code completion
699 /// strings should be allocated.
700 CodeCompletionAllocator &getAllocator() const { return Allocator; }
702 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
704 /// Take the resulting completion string.
706 /// This operation can only be performed once.
707 CodeCompletionString *TakeString();
709 /// Add a new typed-text chunk.
710 void AddTypedTextChunk(const char *Text);
712 /// Add a new text chunk.
713 void AddTextChunk(const char *Text);
715 /// Add a new optional chunk.
716 void AddOptionalChunk(CodeCompletionString *Optional);
718 /// Add a new placeholder chunk.
719 void AddPlaceholderChunk(const char *Placeholder);
721 /// Add a new informative chunk.
722 void AddInformativeChunk(const char *Text);
724 /// Add a new result-type chunk.
725 void AddResultTypeChunk(const char *ResultType);
727 /// Add a new current-parameter chunk.
728 void AddCurrentParameterChunk(const char *CurrentParameter);
731 void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = "");
733 void AddAnnotation(const char *A) { Annotations.push_back(A); }
735 /// Add the parent context information to this code completion.
736 void addParentContext(const DeclContext *DC);
738 const char *getBriefComment() const { return BriefComment; }
739 void addBriefComment(StringRef Comment);
741 StringRef getParentName() const { return ParentName; }
744 /// Captures a result of code completion.
745 class CodeCompletionResult {
747 /// Describes the kind of result generated.
749 /// Refers to a declaration.
752 /// Refers to a keyword or symbol.
755 /// Refers to a macro.
758 /// Refers to a precomputed pattern.
762 /// When Kind == RK_Declaration or RK_Pattern, the declaration we are
763 /// referring to. In the latter case, the declaration might be NULL.
764 const NamedDecl *Declaration = nullptr;
767 /// When Kind == RK_Keyword, the string representing the keyword
768 /// or symbol's spelling.
771 /// When Kind == RK_Pattern, the code-completion string that
772 /// describes the completion text to insert.
773 CodeCompletionString *Pattern;
775 /// When Kind == RK_Macro, the identifier that refers to a macro.
776 const IdentifierInfo *Macro;
779 /// The priority of this particular code-completion result.
782 /// Specifies which parameter (of a function, Objective-C method,
783 /// macro, etc.) we should start with when formatting the result.
784 unsigned StartParameter = 0;
786 /// The kind of result stored here.
789 /// The cursor kind that describes this result.
790 CXCursorKind CursorKind;
792 /// The availability of this result.
793 CXAvailabilityKind Availability = CXAvailability_Available;
795 /// Fix-its that *must* be applied before inserting the text for the
796 /// corresponding completion.
798 /// By default, CodeCompletionBuilder only returns completions with empty
799 /// fix-its. Extra completions with non-empty fix-its should be explicitly
800 /// requested by setting CompletionOptions::IncludeFixIts.
802 /// For the clients to be able to compute position of the cursor after
803 /// applying fix-its, the following conditions are guaranteed to hold for
804 /// RemoveRange of the stored fix-its:
805 /// - Ranges in the fix-its are guaranteed to never contain the completion
806 /// point (or identifier under completion point, if any) inside them, except
807 /// at the start or at the end of the range.
808 /// - If a fix-it range starts or ends with completion point (or starts or
809 /// ends after the identifier under completion point), it will contain at
810 /// least one character. It allows to unambiguously recompute completion
811 /// point after applying the fix-it.
813 /// The intuition is that provided fix-its change code around the identifier
814 /// we complete, but are not allowed to touch the identifier itself or the
815 /// completion point. One example of completions with corrections are the ones
816 /// replacing '.' with '->' and vice versa:
818 /// std::unique_ptr<std::vector<int>> vec_ptr;
819 /// In 'vec_ptr.^', one of the completions is 'push_back', it requires
820 /// replacing '.' with '->'.
821 /// In 'vec_ptr->^', one of the completions is 'release', it requires
822 /// replacing '->' with '.'.
823 std::vector<FixItHint> FixIts;
825 /// Whether this result is hidden by another name.
828 /// Whether this is a class member from base class.
829 bool InBaseClass : 1;
831 /// Whether this result was found via lookup into a base class.
832 bool QualifierIsInformative : 1;
834 /// Whether this declaration is the beginning of a
835 /// nested-name-specifier and, therefore, should be followed by '::'.
836 bool StartsNestedNameSpecifier : 1;
838 /// Whether all parameters (of a function, Objective-C
839 /// method, etc.) should be considered "informative".
840 bool AllParametersAreInformative : 1;
842 /// Whether we're completing a declaration of the given entity,
843 /// rather than a use of that entity.
844 bool DeclaringEntity : 1;
846 /// If the result should have a nested-name-specifier, this is it.
847 /// When \c QualifierIsInformative, the nested-name-specifier is
848 /// informative rather than required.
849 NestedNameSpecifier *Qualifier = nullptr;
851 /// If this Decl was unshadowed by using declaration, this can store a
852 /// pointer to the UsingShadowDecl which was used in the unshadowing process.
853 /// This information can be used to uprank CodeCompletionResults / which have
854 /// corresponding `using decl::qualified::name;` nearby.
855 const UsingShadowDecl *ShadowDecl = nullptr;
857 /// If the result is RK_Macro, this can store the information about the macro
858 /// definition. This should be set in most cases but can be missing when
859 /// the macro has been undefined.
860 const MacroInfo *MacroDefInfo = nullptr;
862 /// Build a result that refers to a declaration.
863 CodeCompletionResult(const NamedDecl *Declaration, unsigned Priority,
864 NestedNameSpecifier *Qualifier = nullptr,
865 bool QualifierIsInformative = false,
866 bool Accessible = true,
867 std::vector<FixItHint> FixIts = std::vector<FixItHint>())
868 : Declaration(Declaration), Priority(Priority), Kind(RK_Declaration),
869 FixIts(std::move(FixIts)), Hidden(false), InBaseClass(false),
870 QualifierIsInformative(QualifierIsInformative),
871 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
872 DeclaringEntity(false), Qualifier(Qualifier) {
873 // FIXME: Add assert to check FixIts range requirements.
874 computeCursorKindAndAvailability(Accessible);
877 /// Build a result that refers to a keyword or symbol.
878 CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
879 : Keyword(Keyword), Priority(Priority), Kind(RK_Keyword),
880 CursorKind(CXCursor_NotImplemented), Hidden(false), InBaseClass(false),
881 QualifierIsInformative(false), StartsNestedNameSpecifier(false),
882 AllParametersAreInformative(false), DeclaringEntity(false) {}
884 /// Build a result that refers to a macro.
885 CodeCompletionResult(const IdentifierInfo *Macro,
886 const MacroInfo *MI = nullptr,
887 unsigned Priority = CCP_Macro)
888 : Macro(Macro), Priority(Priority), Kind(RK_Macro),
889 CursorKind(CXCursor_MacroDefinition), Hidden(false), InBaseClass(false),
890 QualifierIsInformative(false), StartsNestedNameSpecifier(false),
891 AllParametersAreInformative(false), DeclaringEntity(false),
894 /// Build a result that refers to a pattern.
895 CodeCompletionResult(
896 CodeCompletionString *Pattern, unsigned Priority = CCP_CodePattern,
897 CXCursorKind CursorKind = CXCursor_NotImplemented,
898 CXAvailabilityKind Availability = CXAvailability_Available,
899 const NamedDecl *D = nullptr)
900 : Declaration(D), Pattern(Pattern), Priority(Priority), Kind(RK_Pattern),
901 CursorKind(CursorKind), Availability(Availability), Hidden(false),
902 InBaseClass(false), QualifierIsInformative(false),
903 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
904 DeclaringEntity(false) {}
906 /// Build a result that refers to a pattern with an associated
908 CodeCompletionResult(CodeCompletionString *Pattern, const NamedDecl *D,
910 : Declaration(D), Pattern(Pattern), Priority(Priority), Kind(RK_Pattern),
911 Hidden(false), InBaseClass(false), QualifierIsInformative(false),
912 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
913 DeclaringEntity(false) {
914 computeCursorKindAndAvailability();
917 /// Retrieve the declaration stored in this result. This might be nullptr if
918 /// Kind is RK_Pattern.
919 const NamedDecl *getDeclaration() const {
920 assert(((Kind == RK_Declaration) || (Kind == RK_Pattern)) &&
921 "Not a declaration or pattern result");
925 /// Retrieve the keyword stored in this result.
926 const char *getKeyword() const {
927 assert(Kind == RK_Keyword && "Not a keyword result");
931 /// Create a new code-completion string that describes how to insert
932 /// this result into a program.
934 /// \param S The semantic analysis that created the result.
936 /// \param Allocator The allocator that will be used to allocate the
938 CodeCompletionString *CreateCodeCompletionString(Sema &S,
939 const CodeCompletionContext &CCContext,
940 CodeCompletionAllocator &Allocator,
941 CodeCompletionTUInfo &CCTUInfo,
942 bool IncludeBriefComments);
943 CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
945 const CodeCompletionContext &CCContext,
946 CodeCompletionAllocator &Allocator,
947 CodeCompletionTUInfo &CCTUInfo,
948 bool IncludeBriefComments);
949 /// Creates a new code-completion string for the macro result. Similar to the
950 /// above overloads, except this only requires preprocessor information.
951 /// The result kind must be `RK_Macro`.
952 CodeCompletionString *
953 CreateCodeCompletionStringForMacro(Preprocessor &PP,
954 CodeCompletionAllocator &Allocator,
955 CodeCompletionTUInfo &CCTUInfo);
957 CodeCompletionString *createCodeCompletionStringForDecl(
958 Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
959 bool IncludeBriefComments, const CodeCompletionContext &CCContext,
960 PrintingPolicy &Policy);
962 CodeCompletionString *createCodeCompletionStringForOverride(
963 Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
964 bool IncludeBriefComments, const CodeCompletionContext &CCContext,
965 PrintingPolicy &Policy);
967 /// Retrieve the name that should be used to order a result.
969 /// If the name needs to be constructed as a string, that string will be
970 /// saved into Saved and the returned StringRef will refer to it.
971 StringRef getOrderedName(std::string &Saved) const;
974 void computeCursorKindAndAvailability(bool Accessible = true);
977 bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
979 inline bool operator>(const CodeCompletionResult &X,
980 const CodeCompletionResult &Y) {
984 inline bool operator<=(const CodeCompletionResult &X,
985 const CodeCompletionResult &Y) {
989 inline bool operator>=(const CodeCompletionResult &X,
990 const CodeCompletionResult &Y) {
994 raw_ostream &operator<<(raw_ostream &OS,
995 const CodeCompletionString &CCS);
997 /// Abstract interface for a consumer of code-completion
999 class CodeCompleteConsumer {
1001 const CodeCompleteOptions CodeCompleteOpts;
1003 /// Whether the output format for the code-completion consumer is
1005 bool OutputIsBinary;
1008 class OverloadCandidate {
1010 /// Describes the type of overload candidate.
1011 enum CandidateKind {
1012 /// The candidate is a function declaration.
1015 /// The candidate is a function template.
1016 CK_FunctionTemplate,
1018 /// The "candidate" is actually a variable, expression, or block
1019 /// for which we only have a function prototype.
1024 /// The kind of overload candidate.
1028 /// The function overload candidate, available when
1029 /// Kind == CK_Function.
1030 FunctionDecl *Function;
1032 /// The function template overload candidate, available when
1033 /// Kind == CK_FunctionTemplate.
1034 FunctionTemplateDecl *FunctionTemplate;
1036 /// The function type that describes the entity being called,
1037 /// when Kind == CK_FunctionType.
1038 const FunctionType *Type;
1042 OverloadCandidate(FunctionDecl *Function)
1043 : Kind(CK_Function), Function(Function) {}
1045 OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
1046 : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) {}
1048 OverloadCandidate(const FunctionType *Type)
1049 : Kind(CK_FunctionType), Type(Type) {}
1051 /// Determine the kind of overload candidate.
1052 CandidateKind getKind() const { return Kind; }
1054 /// Retrieve the function overload candidate or the templated
1055 /// function declaration for a function template.
1056 FunctionDecl *getFunction() const;
1058 /// Retrieve the function template overload candidate.
1059 FunctionTemplateDecl *getFunctionTemplate() const {
1060 assert(getKind() == CK_FunctionTemplate && "Not a function template");
1061 return FunctionTemplate;
1064 /// Retrieve the function type of the entity, regardless of how the
1065 /// function is stored.
1066 const FunctionType *getFunctionType() const;
1068 /// Create a new code-completion string that describes the function
1069 /// signature of this overload candidate.
1070 CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
1072 CodeCompletionAllocator &Allocator,
1073 CodeCompletionTUInfo &CCTUInfo,
1074 bool IncludeBriefComments) const;
1077 CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
1078 bool OutputIsBinary)
1079 : CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary) {}
1081 /// Whether the code-completion consumer wants to see macros.
1082 bool includeMacros() const {
1083 return CodeCompleteOpts.IncludeMacros;
1086 /// Whether the code-completion consumer wants to see code patterns.
1087 bool includeCodePatterns() const {
1088 return CodeCompleteOpts.IncludeCodePatterns;
1091 /// Whether to include global (top-level) declaration results.
1092 bool includeGlobals() const { return CodeCompleteOpts.IncludeGlobals; }
1094 /// Whether to include declarations in namespace contexts (including
1095 /// the global namespace). If this is false, `includeGlobals()` will be
1097 bool includeNamespaceLevelDecls() const {
1098 return CodeCompleteOpts.IncludeNamespaceLevelDecls;
1101 /// Whether to include brief documentation comments within the set of
1102 /// code completions returned.
1103 bool includeBriefComments() const {
1104 return CodeCompleteOpts.IncludeBriefComments;
1107 /// Whether to include completion items with small fix-its, e.g. change
1108 /// '.' to '->' on member access, etc.
1109 bool includeFixIts() const { return CodeCompleteOpts.IncludeFixIts; }
1111 /// Hint whether to load data from the external AST in order to provide
1112 /// full results. If false, declarations from the preamble may be omitted.
1113 bool loadExternal() const {
1114 return CodeCompleteOpts.LoadExternal;
1117 /// Determine whether the output of this consumer is binary.
1118 bool isOutputBinary() const { return OutputIsBinary; }
1120 /// Deregisters and destroys this code-completion consumer.
1121 virtual ~CodeCompleteConsumer();
1123 /// \name Code-completion filtering
1124 /// Check if the result should be filtered out.
1125 virtual bool isResultFilteredOut(StringRef Filter,
1126 CodeCompletionResult Results) {
1130 /// \name Code-completion callbacks
1132 /// Process the finalized code-completion results.
1133 virtual void ProcessCodeCompleteResults(Sema &S,
1134 CodeCompletionContext Context,
1135 CodeCompletionResult *Results,
1136 unsigned NumResults) {}
1138 /// \param S the semantic-analyzer object for which code-completion is being
1141 /// \param CurrentArg the index of the current argument.
1143 /// \param Candidates an array of overload candidates.
1145 /// \param NumCandidates the number of overload candidates
1147 /// \param OpenParLoc location of the opening parenthesis of the argument
1149 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1150 OverloadCandidate *Candidates,
1151 unsigned NumCandidates,
1152 SourceLocation OpenParLoc) {}
1155 /// Retrieve the allocator that will be used to allocate
1156 /// code completion strings.
1157 virtual CodeCompletionAllocator &getAllocator() = 0;
1159 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
1162 /// Get the documentation comment used to produce
1163 /// CodeCompletionString::BriefComment for RK_Declaration.
1164 const RawComment *getCompletionComment(const ASTContext &Ctx,
1165 const NamedDecl *Decl);
1167 /// Get the documentation comment used to produce
1168 /// CodeCompletionString::BriefComment for RK_Pattern.
1169 const RawComment *getPatternCompletionComment(const ASTContext &Ctx,
1170 const NamedDecl *Decl);
1172 /// Get the documentation comment used to produce
1173 /// CodeCompletionString::BriefComment for OverloadCandidate.
1175 getParameterComment(const ASTContext &Ctx,
1176 const CodeCompleteConsumer::OverloadCandidate &Result,
1179 /// A simple code-completion consumer that prints the results it
1180 /// receives in a simple format.
1181 class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
1182 /// The raw output stream.
1185 CodeCompletionTUInfo CCTUInfo;
1188 /// Create a new printing code-completion consumer that prints its
1189 /// results to the given raw output stream.
1190 PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
1192 : CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS),
1193 CCTUInfo(std::make_shared<GlobalCodeCompletionAllocator>()) {}
1195 /// Prints the finalized code-completion results.
1196 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1197 CodeCompletionResult *Results,
1198 unsigned NumResults) override;
1200 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1201 OverloadCandidate *Candidates,
1202 unsigned NumCandidates,
1203 SourceLocation OpenParLoc) override;
1205 bool isResultFilteredOut(StringRef Filter, CodeCompletionResult Results) override;
1207 CodeCompletionAllocator &getAllocator() override {
1208 return CCTUInfo.getAllocator();
1211 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
1214 } // namespace clang
1216 #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H