Home | History | Annotate | Download | only in Sema
      1 //===---- CodeCompleteConsumer.h - Code Completion Interface ----*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file defines the CodeCompleteConsumer class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 #ifndef LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
     14 #define LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
     15 
     16 #include "clang-c/Index.h"
     17 #include "clang/AST/CanonicalType.h"
     18 #include "clang/AST/Type.h"
     19 #include "clang/Sema/CodeCompleteOptions.h"
     20 #include "llvm/ADT/DenseMap.h"
     21 #include "llvm/ADT/SmallVector.h"
     22 #include "llvm/ADT/StringRef.h"
     23 #include "llvm/Support/Allocator.h"
     24 #include <string>
     25 
     26 namespace clang {
     27 
     28 class Decl;
     29 
     30 /// \brief Default priority values for code-completion results based
     31 /// on their kind.
     32 enum {
     33   /// \brief Priority for the next initialization in a constructor initializer
     34   /// list.
     35   CCP_NextInitializer = 7,
     36   /// \brief Priority for an enumeration constant inside a switch whose
     37   /// condition is of the enumeration type.
     38   CCP_EnumInCase = 7,
     39   /// \brief Priority for a send-to-super completion.
     40   CCP_SuperCompletion = 20,
     41   /// \brief Priority for a declaration that is in the local scope.
     42   CCP_LocalDeclaration = 34,
     43   /// \brief Priority for a member declaration found from the current
     44   /// method or member function.
     45   CCP_MemberDeclaration = 35,
     46   /// \brief Priority for a language keyword (that isn't any of the other
     47   /// categories).
     48   CCP_Keyword = 40,
     49   /// \brief Priority for a code pattern.
     50   CCP_CodePattern = 40,
     51   /// \brief Priority for a non-type declaration.
     52   CCP_Declaration = 50,
     53   /// \brief Priority for a type.
     54   CCP_Type = CCP_Declaration,
     55   /// \brief Priority for a constant value (e.g., enumerator).
     56   CCP_Constant = 65,
     57   /// \brief Priority for a preprocessor macro.
     58   CCP_Macro = 70,
     59   /// \brief Priority for a nested-name-specifier.
     60   CCP_NestedNameSpecifier = 75,
     61   /// \brief Priority for a result that isn't likely to be what the user wants,
     62   /// but is included for completeness.
     63   CCP_Unlikely = 80,
     64 
     65   /// \brief Priority for the Objective-C "_cmd" implicit parameter.
     66   CCP_ObjC_cmd = CCP_Unlikely
     67 };
     68 
     69 /// \brief Priority value deltas that are added to code-completion results
     70 /// based on the context of the result.
     71 enum {
     72   /// \brief The result is in a base class.
     73   CCD_InBaseClass = 2,
     74   /// \brief The result is a C++ non-static member function whose qualifiers
     75   /// exactly match the object type on which the member function can be called.
     76   CCD_ObjectQualifierMatch = -1,
     77   /// \brief The selector of the given message exactly matches the selector
     78   /// of the current method, which might imply that some kind of delegation
     79   /// is occurring.
     80   CCD_SelectorMatch = -3,
     81 
     82   /// \brief Adjustment to the "bool" type in Objective-C, where the typedef
     83   /// "BOOL" is preferred.
     84   CCD_bool_in_ObjC = 1,
     85 
     86   /// \brief Adjustment for KVC code pattern priorities when it doesn't look
     87   /// like the
     88   CCD_ProbablyNotObjCCollection = 15,
     89 
     90   /// \brief An Objective-C method being used as a property.
     91   CCD_MethodAsProperty = 2
     92 };
     93 
     94 /// \brief Priority value factors by which we will divide or multiply the
     95 /// priority of a code-completion result.
     96 enum {
     97   /// \brief Divide by this factor when a code-completion result's type exactly
     98   /// matches the type we expect.
     99   CCF_ExactTypeMatch = 4,
    100   /// \brief Divide by this factor when a code-completion result's type is
    101   /// similar to the type we expect (e.g., both arithmetic types, both
    102   /// Objective-C object pointer types).
    103   CCF_SimilarTypeMatch = 2
    104 };
    105 
    106 /// \brief A simplified classification of types used when determining
    107 /// "similar" types for code completion.
    108 enum SimplifiedTypeClass {
    109   STC_Arithmetic,
    110   STC_Array,
    111   STC_Block,
    112   STC_Function,
    113   STC_ObjectiveC,
    114   STC_Other,
    115   STC_Pointer,
    116   STC_Record,
    117   STC_Void
    118 };
    119 
    120 /// \brief Determine the simplified type class of the given canonical type.
    121 SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
    122 
    123 /// \brief Determine the type that this declaration will have if it is used
    124 /// as a type or in an expression.
    125 QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND);
    126 
    127 /// \brief Determine the priority to be given to a macro code completion result
    128 /// with the given name.
    129 ///
    130 /// \param MacroName The name of the macro.
    131 ///
    132 /// \param LangOpts Options describing the current language dialect.
    133 ///
    134 /// \param PreferredTypeIsPointer Whether the preferred type for the context
    135 /// of this macro is a pointer type.
    136 unsigned getMacroUsagePriority(StringRef MacroName,
    137                                const LangOptions &LangOpts,
    138                                bool PreferredTypeIsPointer = false);
    139 
    140 /// \brief Determine the libclang cursor kind associated with the given
    141 /// declaration.
    142 CXCursorKind getCursorKindForDecl(const Decl *D);
    143 
    144 class FunctionDecl;
    145 class FunctionType;
    146 class FunctionTemplateDecl;
    147 class IdentifierInfo;
    148 class NamedDecl;
    149 class NestedNameSpecifier;
    150 class Sema;
    151 
    152 /// \brief The context in which code completion occurred, so that the
    153 /// code-completion consumer can process the results accordingly.
    154 class CodeCompletionContext {
    155 public:
    156   enum Kind {
    157     /// \brief An unspecified code-completion context.
    158     CCC_Other,
    159     /// \brief An unspecified code-completion context where we should also add
    160     /// macro completions.
    161     CCC_OtherWithMacros,
    162     /// \brief Code completion occurred within a "top-level" completion context,
    163     /// e.g., at namespace or global scope.
    164     CCC_TopLevel,
    165     /// \brief Code completion occurred within an Objective-C interface,
    166     /// protocol, or category interface.
    167     CCC_ObjCInterface,
    168     /// \brief Code completion occurred within an Objective-C implementation
    169     /// or category implementation.
    170     CCC_ObjCImplementation,
    171     /// \brief Code completion occurred within the instance variable list of
    172     /// an Objective-C interface, implementation, or category implementation.
    173     CCC_ObjCIvarList,
    174     /// \brief Code completion occurred within a class, struct, or union.
    175     CCC_ClassStructUnion,
    176     /// \brief Code completion occurred where a statement (or declaration) is
    177     /// expected in a function, method, or block.
    178     CCC_Statement,
    179     /// \brief Code completion occurred where an expression is expected.
    180     CCC_Expression,
    181     /// \brief Code completion occurred where an Objective-C message receiver
    182     /// is expected.
    183     CCC_ObjCMessageReceiver,
    184     /// \brief Code completion occurred on the right-hand side of a member
    185     /// access expression using the dot operator.
    186     ///
    187     /// The results of this completion are the members of the type being
    188     /// accessed. The type itself is available via
    189     /// \c CodeCompletionContext::getType().
    190     CCC_DotMemberAccess,
    191     /// \brief Code completion occurred on the right-hand side of a member
    192     /// access expression using the arrow operator.
    193     ///
    194     /// The results of this completion are the members of the type being
    195     /// accessed. The type itself is available via
    196     /// \c CodeCompletionContext::getType().
    197     CCC_ArrowMemberAccess,
    198     /// \brief Code completion occurred on the right-hand side of an Objective-C
    199     /// property access expression.
    200     ///
    201     /// The results of this completion are the members of the type being
    202     /// accessed. The type itself is available via
    203     /// \c CodeCompletionContext::getType().
    204     CCC_ObjCPropertyAccess,
    205     /// \brief Code completion occurred after the "enum" keyword, to indicate
    206     /// an enumeration name.
    207     CCC_EnumTag,
    208     /// \brief Code completion occurred after the "union" keyword, to indicate
    209     /// a union name.
    210     CCC_UnionTag,
    211     /// \brief Code completion occurred after the "struct" or "class" keyword,
    212     /// to indicate a struct or class name.
    213     CCC_ClassOrStructTag,
    214     /// \brief Code completion occurred where a protocol name is expected.
    215     CCC_ObjCProtocolName,
    216     /// \brief Code completion occurred where a namespace or namespace alias
    217     /// is expected.
    218     CCC_Namespace,
    219     /// \brief Code completion occurred where a type name is expected.
    220     CCC_Type,
    221     /// \brief Code completion occurred where a new name is expected.
    222     CCC_Name,
    223     /// \brief Code completion occurred where a new name is expected and a
    224     /// qualified name is permissible.
    225     CCC_PotentiallyQualifiedName,
    226     /// \brief Code completion occurred where an macro is being defined.
    227     CCC_MacroName,
    228     /// \brief Code completion occurred where a macro name is expected
    229     /// (without any arguments, in the case of a function-like macro).
    230     CCC_MacroNameUse,
    231     /// \brief Code completion occurred within a preprocessor expression.
    232     CCC_PreprocessorExpression,
    233     /// \brief Code completion occurred where a preprocessor directive is
    234     /// expected.
    235     CCC_PreprocessorDirective,
    236     /// \brief Code completion occurred in a context where natural language is
    237     /// expected, e.g., a comment or string literal.
    238     ///
    239     /// This context usually implies that no completions should be added,
    240     /// unless they come from an appropriate natural-language dictionary.
    241     CCC_NaturalLanguage,
    242     /// \brief Code completion for a selector, as in an \@selector expression.
    243     CCC_SelectorName,
    244     /// \brief Code completion within a type-qualifier list.
    245     CCC_TypeQualifiers,
    246     /// \brief Code completion in a parenthesized expression, which means that
    247     /// we may also have types here in C and Objective-C (as well as in C++).
    248     CCC_ParenthesizedExpression,
    249     /// \brief Code completion where an Objective-C instance message is
    250     /// expected.
    251     CCC_ObjCInstanceMessage,
    252     /// \brief Code completion where an Objective-C class message is expected.
    253     CCC_ObjCClassMessage,
    254     /// \brief Code completion where the name of an Objective-C class is
    255     /// expected.
    256     CCC_ObjCInterfaceName,
    257     /// \brief Code completion where an Objective-C category name is expected.
    258     CCC_ObjCCategoryName,
    259     /// \brief An unknown context, in which we are recovering from a parsing
    260     /// error and don't know which completions we should give.
    261     CCC_Recovery
    262   };
    263 
    264 private:
    265   enum Kind Kind;
    266 
    267   /// \brief The type that would prefer to see at this point (e.g., the type
    268   /// of an initializer or function parameter).
    269   QualType PreferredType;
    270 
    271   /// \brief The type of the base object in a member access expression.
    272   QualType BaseType;
    273 
    274   /// \brief The identifiers for Objective-C selector parts.
    275   ArrayRef<IdentifierInfo *> SelIdents;
    276 
    277 public:
    278   /// \brief Construct a new code-completion context of the given kind.
    279   CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(None) { }
    280 
    281   /// \brief Construct a new code-completion context of the given kind.
    282   CodeCompletionContext(enum Kind Kind, QualType T,
    283                         ArrayRef<IdentifierInfo *> SelIdents = None)
    284                         : Kind(Kind),
    285                           SelIdents(SelIdents) {
    286     if (Kind == CCC_DotMemberAccess || Kind == CCC_ArrowMemberAccess ||
    287         Kind == CCC_ObjCPropertyAccess || Kind == CCC_ObjCClassMessage ||
    288         Kind == CCC_ObjCInstanceMessage)
    289       BaseType = T;
    290     else
    291       PreferredType = T;
    292   }
    293 
    294   /// \brief Retrieve the kind of code-completion context.
    295   enum Kind getKind() const { return Kind; }
    296 
    297   /// \brief Retrieve the type that this expression would prefer to have, e.g.,
    298   /// if the expression is a variable initializer or a function argument, the
    299   /// type of the corresponding variable or function parameter.
    300   QualType getPreferredType() const { return PreferredType; }
    301 
    302   /// \brief Retrieve the type of the base object in a member-access
    303   /// expression.
    304   QualType getBaseType() const { return BaseType; }
    305 
    306   /// \brief Retrieve the Objective-C selector identifiers.
    307   ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; }
    308 
    309   /// \brief Determines whether we want C++ constructors as results within this
    310   /// context.
    311   bool wantConstructorResults() const;
    312 };
    313 
    314 
    315 /// \brief A "string" used to describe how code completion can
    316 /// be performed for an entity.
    317 ///
    318 /// A code completion string typically shows how a particular entity can be
    319 /// used. For example, the code completion string for a function would show
    320 /// the syntax to call it, including the parentheses, placeholders for the
    321 /// arguments, etc.
    322 class CodeCompletionString {
    323 public:
    324   /// \brief The different kinds of "chunks" that can occur within a code
    325   /// completion string.
    326   enum ChunkKind {
    327     /// \brief The piece of text that the user is expected to type to
    328     /// match the code-completion string, typically a keyword or the name of a
    329     /// declarator or macro.
    330     CK_TypedText,
    331     /// \brief A piece of text that should be placed in the buffer, e.g.,
    332     /// parentheses or a comma in a function call.
    333     CK_Text,
    334     /// \brief A code completion string that is entirely optional. For example,
    335     /// an optional code completion string that describes the default arguments
    336     /// in a function call.
    337     CK_Optional,
    338     /// \brief A string that acts as a placeholder for, e.g., a function
    339     /// call argument.
    340     CK_Placeholder,
    341     /// \brief A piece of text that describes something about the result but
    342     /// should not be inserted into the buffer.
    343     CK_Informative,
    344     /// \brief A piece of text that describes the type of an entity or, for
    345     /// functions and methods, the return type.
    346     CK_ResultType,
    347     /// \brief A piece of text that describes the parameter that corresponds
    348     /// to the code-completion location within a function call, message send,
    349     /// macro invocation, etc.
    350     CK_CurrentParameter,
    351     /// \brief A left parenthesis ('(').
    352     CK_LeftParen,
    353     /// \brief A right parenthesis (')').
    354     CK_RightParen,
    355     /// \brief A left bracket ('[').
    356     CK_LeftBracket,
    357     /// \brief A right bracket (']').
    358     CK_RightBracket,
    359     /// \brief A left brace ('{').
    360     CK_LeftBrace,
    361     /// \brief A right brace ('}').
    362     CK_RightBrace,
    363     /// \brief A left angle bracket ('<').
    364     CK_LeftAngle,
    365     /// \brief A right angle bracket ('>').
    366     CK_RightAngle,
    367     /// \brief A comma separator (',').
    368     CK_Comma,
    369     /// \brief A colon (':').
    370     CK_Colon,
    371     /// \brief A semicolon (';').
    372     CK_SemiColon,
    373     /// \brief An '=' sign.
    374     CK_Equal,
    375     /// \brief Horizontal whitespace (' ').
    376     CK_HorizontalSpace,
    377     /// \brief Vertical whitespace ('\\n' or '\\r\\n', depending on the
    378     /// platform).
    379     CK_VerticalSpace
    380   };
    381 
    382   /// \brief One piece of the code completion string.
    383   struct Chunk {
    384     /// \brief The kind of data stored in this piece of the code completion
    385     /// string.
    386     ChunkKind Kind;
    387 
    388     union {
    389       /// \brief The text string associated with a CK_Text, CK_Placeholder,
    390       /// CK_Informative, or CK_Comma chunk.
    391       /// The string is owned by the chunk and will be deallocated
    392       /// (with delete[]) when the chunk is destroyed.
    393       const char *Text;
    394 
    395       /// \brief The code completion string associated with a CK_Optional chunk.
    396       /// The optional code completion string is owned by the chunk, and will
    397       /// be deallocated (with delete) when the chunk is destroyed.
    398       CodeCompletionString *Optional;
    399     };
    400 
    401     Chunk() : Kind(CK_Text), Text(nullptr) { }
    402 
    403     explicit Chunk(ChunkKind Kind, const char *Text = "");
    404 
    405     /// \brief Create a new text chunk.
    406     static Chunk CreateText(const char *Text);
    407 
    408     /// \brief Create a new optional chunk.
    409     static Chunk CreateOptional(CodeCompletionString *Optional);
    410 
    411     /// \brief Create a new placeholder chunk.
    412     static Chunk CreatePlaceholder(const char *Placeholder);
    413 
    414     /// \brief Create a new informative chunk.
    415     static Chunk CreateInformative(const char *Informative);
    416 
    417     /// \brief Create a new result type chunk.
    418     static Chunk CreateResultType(const char *ResultType);
    419 
    420     /// \brief Create a new current-parameter chunk.
    421     static Chunk CreateCurrentParameter(const char *CurrentParameter);
    422   };
    423 
    424 private:
    425   /// \brief The number of chunks stored in this string.
    426   unsigned NumChunks : 16;
    427 
    428   /// \brief The number of annotations for this code-completion result.
    429   unsigned NumAnnotations : 16;
    430 
    431   /// \brief The priority of this code-completion string.
    432   unsigned Priority : 16;
    433 
    434   /// \brief The availability of this code-completion result.
    435   unsigned Availability : 2;
    436 
    437   /// \brief The name of the parent context.
    438   StringRef ParentName;
    439 
    440   /// \brief A brief documentation comment attached to the declaration of
    441   /// entity being completed by this result.
    442   const char *BriefComment;
    443 
    444   CodeCompletionString(const CodeCompletionString &) = delete;
    445   void operator=(const CodeCompletionString &) = delete;
    446 
    447   CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
    448                        unsigned Priority, CXAvailabilityKind Availability,
    449                        const char **Annotations, unsigned NumAnnotations,
    450                        StringRef ParentName,
    451                        const char *BriefComment);
    452   ~CodeCompletionString() = default;
    453 
    454   friend class CodeCompletionBuilder;
    455   friend class CodeCompletionResult;
    456 
    457 public:
    458   typedef const Chunk *iterator;
    459   iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
    460   iterator end() const { return begin() + NumChunks; }
    461   bool empty() const { return NumChunks == 0; }
    462   unsigned size() const { return NumChunks; }
    463 
    464   const Chunk &operator[](unsigned I) const {
    465     assert(I < size() && "Chunk index out-of-range");
    466     return begin()[I];
    467   }
    468 
    469   /// \brief Returns the text in the TypedText chunk.
    470   const char *getTypedText() const;
    471 
    472   /// \brief Retrieve the priority of this code completion result.
    473   unsigned getPriority() const { return Priority; }
    474 
    475   /// \brief Retrieve the availability of this code completion result.
    476   unsigned getAvailability() const { return Availability; }
    477 
    478   /// \brief Retrieve the number of annotations for this code completion result.
    479   unsigned getAnnotationCount() const;
    480 
    481   /// \brief Retrieve the annotation string specified by \c AnnotationNr.
    482   const char *getAnnotation(unsigned AnnotationNr) const;
    483 
    484   /// \brief Retrieve the name of the parent context.
    485   StringRef getParentContextName() const {
    486     return ParentName;
    487   }
    488 
    489   const char *getBriefComment() const {
    490     return BriefComment;
    491   }
    492 
    493   /// \brief Retrieve a string representation of the code completion string,
    494   /// which is mainly useful for debugging.
    495   std::string getAsString() const;
    496 };
    497 
    498 /// \brief An allocator used specifically for the purpose of code completion.
    499 class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
    500 public:
    501   /// \brief Copy the given string into this allocator.
    502   const char *CopyString(const Twine &String);
    503 };
    504 
    505 /// \brief Allocator for a cached set of global code completions.
    506 class GlobalCodeCompletionAllocator
    507   : public CodeCompletionAllocator,
    508     public RefCountedBase<GlobalCodeCompletionAllocator>
    509 {
    510 
    511 };
    512 
    513 class CodeCompletionTUInfo {
    514   llvm::DenseMap<const DeclContext *, StringRef> ParentNames;
    515   IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> AllocatorRef;
    516 
    517 public:
    518   explicit CodeCompletionTUInfo(
    519                     IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> Allocator)
    520     : AllocatorRef(Allocator) { }
    521 
    522   IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> getAllocatorRef() const {
    523     return AllocatorRef;
    524   }
    525   CodeCompletionAllocator &getAllocator() const {
    526     assert(AllocatorRef);
    527     return *AllocatorRef;
    528   }
    529 
    530   StringRef getParentName(const DeclContext *DC);
    531 };
    532 
    533 } // end namespace clang
    534 
    535 namespace llvm {
    536   template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
    537     static const bool value = true;
    538   };
    539 }
    540 
    541 namespace clang {
    542 
    543 /// \brief A builder class used to construct new code-completion strings.
    544 class CodeCompletionBuilder {
    545 public:
    546   typedef CodeCompletionString::Chunk Chunk;
    547 
    548 private:
    549   CodeCompletionAllocator &Allocator;
    550   CodeCompletionTUInfo &CCTUInfo;
    551   unsigned Priority;
    552   CXAvailabilityKind Availability;
    553   StringRef ParentName;
    554   const char *BriefComment;
    555 
    556   /// \brief The chunks stored in this string.
    557   SmallVector<Chunk, 4> Chunks;
    558 
    559   SmallVector<const char *, 2> Annotations;
    560 
    561 public:
    562   CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
    563                         CodeCompletionTUInfo &CCTUInfo)
    564     : Allocator(Allocator), CCTUInfo(CCTUInfo),
    565       Priority(0), Availability(CXAvailability_Available),
    566       BriefComment(nullptr) { }
    567 
    568   CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
    569                         CodeCompletionTUInfo &CCTUInfo,
    570                         unsigned Priority, CXAvailabilityKind Availability)
    571     : Allocator(Allocator), CCTUInfo(CCTUInfo),
    572       Priority(Priority), Availability(Availability),
    573       BriefComment(nullptr) { }
    574 
    575   /// \brief Retrieve the allocator into which the code completion
    576   /// strings should be allocated.
    577   CodeCompletionAllocator &getAllocator() const { return Allocator; }
    578 
    579   CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
    580 
    581   /// \brief Take the resulting completion string.
    582   ///
    583   /// This operation can only be performed once.
    584   CodeCompletionString *TakeString();
    585 
    586   /// \brief Add a new typed-text chunk.
    587   void AddTypedTextChunk(const char *Text);
    588 
    589   /// \brief Add a new text chunk.
    590   void AddTextChunk(const char *Text);
    591 
    592   /// \brief Add a new optional chunk.
    593   void AddOptionalChunk(CodeCompletionString *Optional);
    594 
    595   /// \brief Add a new placeholder chunk.
    596   void AddPlaceholderChunk(const char *Placeholder);
    597 
    598   /// \brief Add a new informative chunk.
    599   void AddInformativeChunk(const char *Text);
    600 
    601   /// \brief Add a new result-type chunk.
    602   void AddResultTypeChunk(const char *ResultType);
    603 
    604   /// \brief Add a new current-parameter chunk.
    605   void AddCurrentParameterChunk(const char *CurrentParameter);
    606 
    607   /// \brief Add a new chunk.
    608   void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = "");
    609 
    610   void AddAnnotation(const char *A) { Annotations.push_back(A); }
    611 
    612   /// \brief Add the parent context information to this code completion.
    613   void addParentContext(const DeclContext *DC);
    614 
    615   const char *getBriefComment() const { return BriefComment; }
    616   void addBriefComment(StringRef Comment);
    617 
    618   StringRef getParentName() const { return ParentName; }
    619 };
    620 
    621 /// \brief Captures a result of code completion.
    622 class CodeCompletionResult {
    623 public:
    624   /// \brief Describes the kind of result generated.
    625   enum ResultKind {
    626     RK_Declaration = 0, ///< Refers to a declaration
    627     RK_Keyword,         ///< Refers to a keyword or symbol.
    628     RK_Macro,           ///< Refers to a macro
    629     RK_Pattern          ///< Refers to a precomputed pattern.
    630   };
    631 
    632   /// \brief When Kind == RK_Declaration or RK_Pattern, the declaration we are
    633   /// referring to. In the latter case, the declaration might be NULL.
    634   const NamedDecl *Declaration;
    635 
    636   union {
    637     /// \brief When Kind == RK_Keyword, the string representing the keyword
    638     /// or symbol's spelling.
    639     const char *Keyword;
    640 
    641     /// \brief When Kind == RK_Pattern, the code-completion string that
    642     /// describes the completion text to insert.
    643     CodeCompletionString *Pattern;
    644 
    645     /// \brief When Kind == RK_Macro, the identifier that refers to a macro.
    646     const IdentifierInfo *Macro;
    647   };
    648 
    649   /// \brief The priority of this particular code-completion result.
    650   unsigned Priority;
    651 
    652   /// \brief Specifies which parameter (of a function, Objective-C method,
    653   /// macro, etc.) we should start with when formatting the result.
    654   unsigned StartParameter;
    655 
    656   /// \brief The kind of result stored here.
    657   ResultKind Kind;
    658 
    659   /// \brief The cursor kind that describes this result.
    660   CXCursorKind CursorKind;
    661 
    662   /// \brief The availability of this result.
    663   CXAvailabilityKind Availability;
    664 
    665   /// \brief Whether this result is hidden by another name.
    666   bool Hidden : 1;
    667 
    668   /// \brief Whether this result was found via lookup into a base class.
    669   bool QualifierIsInformative : 1;
    670 
    671   /// \brief Whether this declaration is the beginning of a
    672   /// nested-name-specifier and, therefore, should be followed by '::'.
    673   bool StartsNestedNameSpecifier : 1;
    674 
    675   /// \brief Whether all parameters (of a function, Objective-C
    676   /// method, etc.) should be considered "informative".
    677   bool AllParametersAreInformative : 1;
    678 
    679   /// \brief Whether we're completing a declaration of the given entity,
    680   /// rather than a use of that entity.
    681   bool DeclaringEntity : 1;
    682 
    683   /// \brief If the result should have a nested-name-specifier, this is it.
    684   /// When \c QualifierIsInformative, the nested-name-specifier is
    685   /// informative rather than required.
    686   NestedNameSpecifier *Qualifier;
    687 
    688   /// \brief Build a result that refers to a declaration.
    689   CodeCompletionResult(const NamedDecl *Declaration,
    690                        unsigned Priority,
    691                        NestedNameSpecifier *Qualifier = nullptr,
    692                        bool QualifierIsInformative = false,
    693                        bool Accessible = true)
    694     : Declaration(Declaration), Priority(Priority),
    695       StartParameter(0), Kind(RK_Declaration),
    696       Availability(CXAvailability_Available), Hidden(false),
    697       QualifierIsInformative(QualifierIsInformative),
    698       StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
    699       DeclaringEntity(false), Qualifier(Qualifier) {
    700     computeCursorKindAndAvailability(Accessible);
    701   }
    702 
    703   /// \brief Build a result that refers to a keyword or symbol.
    704   CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
    705     : Declaration(nullptr), Keyword(Keyword), Priority(Priority),
    706       StartParameter(0), Kind(RK_Keyword), CursorKind(CXCursor_NotImplemented),
    707       Availability(CXAvailability_Available), Hidden(false),
    708       QualifierIsInformative(0), StartsNestedNameSpecifier(false),
    709       AllParametersAreInformative(false), DeclaringEntity(false),
    710       Qualifier(nullptr) {}
    711 
    712   /// \brief Build a result that refers to a macro.
    713   CodeCompletionResult(const IdentifierInfo *Macro,
    714                        unsigned Priority = CCP_Macro)
    715     : Declaration(nullptr), Macro(Macro), Priority(Priority), StartParameter(0),
    716       Kind(RK_Macro), CursorKind(CXCursor_MacroDefinition),
    717       Availability(CXAvailability_Available), Hidden(false),
    718       QualifierIsInformative(0), StartsNestedNameSpecifier(false),
    719       AllParametersAreInformative(false), DeclaringEntity(false),
    720       Qualifier(nullptr) {}
    721 
    722   /// \brief Build a result that refers to a pattern.
    723   CodeCompletionResult(CodeCompletionString *Pattern,
    724                        unsigned Priority = CCP_CodePattern,
    725                        CXCursorKind CursorKind = CXCursor_NotImplemented,
    726                    CXAvailabilityKind Availability = CXAvailability_Available,
    727                        const NamedDecl *D = nullptr)
    728     : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
    729       Kind(RK_Pattern), CursorKind(CursorKind), Availability(Availability),
    730       Hidden(false), QualifierIsInformative(0),
    731       StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
    732       DeclaringEntity(false), Qualifier(nullptr)
    733   {
    734   }
    735 
    736   /// \brief Build a result that refers to a pattern with an associated
    737   /// declaration.
    738   CodeCompletionResult(CodeCompletionString *Pattern, NamedDecl *D,
    739                        unsigned Priority)
    740     : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
    741       Kind(RK_Pattern), Availability(CXAvailability_Available), Hidden(false),
    742       QualifierIsInformative(false), StartsNestedNameSpecifier(false),
    743       AllParametersAreInformative(false), DeclaringEntity(false),
    744       Qualifier(nullptr) {
    745     computeCursorKindAndAvailability();
    746   }
    747 
    748   /// \brief Retrieve the declaration stored in this result.
    749   const NamedDecl *getDeclaration() const {
    750     assert(Kind == RK_Declaration && "Not a declaration result");
    751     return Declaration;
    752   }
    753 
    754   /// \brief Retrieve the keyword stored in this result.
    755   const char *getKeyword() const {
    756     assert(Kind == RK_Keyword && "Not a keyword result");
    757     return Keyword;
    758   }
    759 
    760   /// \brief Create a new code-completion string that describes how to insert
    761   /// this result into a program.
    762   ///
    763   /// \param S The semantic analysis that created the result.
    764   ///
    765   /// \param Allocator The allocator that will be used to allocate the
    766   /// string itself.
    767   CodeCompletionString *CreateCodeCompletionString(Sema &S,
    768                                            CodeCompletionAllocator &Allocator,
    769                                            CodeCompletionTUInfo &CCTUInfo,
    770                                            bool IncludeBriefComments);
    771   CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
    772                                                    Preprocessor &PP,
    773                                            CodeCompletionAllocator &Allocator,
    774                                            CodeCompletionTUInfo &CCTUInfo,
    775                                            bool IncludeBriefComments);
    776 
    777 private:
    778   void computeCursorKindAndAvailability(bool Accessible = true);
    779 };
    780 
    781 bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
    782 
    783 inline bool operator>(const CodeCompletionResult &X,
    784                       const CodeCompletionResult &Y) {
    785   return Y < X;
    786 }
    787 
    788 inline bool operator<=(const CodeCompletionResult &X,
    789                       const CodeCompletionResult &Y) {
    790   return !(Y < X);
    791 }
    792 
    793 inline bool operator>=(const CodeCompletionResult &X,
    794                        const CodeCompletionResult &Y) {
    795   return !(X < Y);
    796 }
    797 
    798 
    799 raw_ostream &operator<<(raw_ostream &OS,
    800                               const CodeCompletionString &CCS);
    801 
    802 /// \brief Abstract interface for a consumer of code-completion
    803 /// information.
    804 class CodeCompleteConsumer {
    805 protected:
    806   const CodeCompleteOptions CodeCompleteOpts;
    807 
    808   /// \brief Whether the output format for the code-completion consumer is
    809   /// binary.
    810   bool OutputIsBinary;
    811 
    812 public:
    813   class OverloadCandidate {
    814   public:
    815     /// \brief Describes the type of overload candidate.
    816     enum CandidateKind {
    817       /// \brief The candidate is a function declaration.
    818       CK_Function,
    819       /// \brief The candidate is a function template.
    820       CK_FunctionTemplate,
    821       /// \brief The "candidate" is actually a variable, expression, or block
    822       /// for which we only have a function prototype.
    823       CK_FunctionType
    824     };
    825 
    826   private:
    827     /// \brief The kind of overload candidate.
    828     CandidateKind Kind;
    829 
    830     union {
    831       /// \brief The function overload candidate, available when
    832       /// Kind == CK_Function.
    833       FunctionDecl *Function;
    834 
    835       /// \brief The function template overload candidate, available when
    836       /// Kind == CK_FunctionTemplate.
    837       FunctionTemplateDecl *FunctionTemplate;
    838 
    839       /// \brief The function type that describes the entity being called,
    840       /// when Kind == CK_FunctionType.
    841       const FunctionType *Type;
    842     };
    843 
    844   public:
    845     OverloadCandidate(FunctionDecl *Function)
    846       : Kind(CK_Function), Function(Function) { }
    847 
    848     OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
    849       : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) { }
    850 
    851     OverloadCandidate(const FunctionType *Type)
    852       : Kind(CK_FunctionType), Type(Type) { }
    853 
    854     /// \brief Determine the kind of overload candidate.
    855     CandidateKind getKind() const { return Kind; }
    856 
    857     /// \brief Retrieve the function overload candidate or the templated
    858     /// function declaration for a function template.
    859     FunctionDecl *getFunction() const;
    860 
    861     /// \brief Retrieve the function template overload candidate.
    862     FunctionTemplateDecl *getFunctionTemplate() const {
    863       assert(getKind() == CK_FunctionTemplate && "Not a function template");
    864       return FunctionTemplate;
    865     }
    866 
    867     /// \brief Retrieve the function type of the entity, regardless of how the
    868     /// function is stored.
    869     const FunctionType *getFunctionType() const;
    870 
    871     /// \brief Create a new code-completion string that describes the function
    872     /// signature of this overload candidate.
    873     CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
    874                                                 Sema &S,
    875                                       CodeCompletionAllocator &Allocator,
    876                                       CodeCompletionTUInfo &CCTUInfo,
    877                                       bool IncludeBriefComments) const;
    878   };
    879 
    880   CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
    881                        bool OutputIsBinary)
    882     : CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary)
    883   { }
    884 
    885   /// \brief Whether the code-completion consumer wants to see macros.
    886   bool includeMacros() const {
    887     return CodeCompleteOpts.IncludeMacros;
    888   }
    889 
    890   /// \brief Whether the code-completion consumer wants to see code patterns.
    891   bool includeCodePatterns() const {
    892     return CodeCompleteOpts.IncludeCodePatterns;
    893   }
    894 
    895   /// \brief Whether to include global (top-level) declaration results.
    896   bool includeGlobals() const {
    897     return CodeCompleteOpts.IncludeGlobals;
    898   }
    899 
    900   /// \brief Whether to include brief documentation comments within the set of
    901   /// code completions returned.
    902   bool includeBriefComments() const {
    903     return CodeCompleteOpts.IncludeBriefComments;
    904   }
    905 
    906   /// \brief Determine whether the output of this consumer is binary.
    907   bool isOutputBinary() const { return OutputIsBinary; }
    908 
    909   /// \brief Deregisters and destroys this code-completion consumer.
    910   virtual ~CodeCompleteConsumer();
    911 
    912   /// \name Code-completion callbacks
    913   //@{
    914   /// \brief Process the finalized code-completion results.
    915   virtual void ProcessCodeCompleteResults(Sema &S,
    916                                           CodeCompletionContext Context,
    917                                           CodeCompletionResult *Results,
    918                                           unsigned NumResults) { }
    919 
    920   /// \param S the semantic-analyzer object for which code-completion is being
    921   /// done.
    922   ///
    923   /// \param CurrentArg the index of the current argument.
    924   ///
    925   /// \param Candidates an array of overload candidates.
    926   ///
    927   /// \param NumCandidates the number of overload candidates
    928   virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
    929                                          OverloadCandidate *Candidates,
    930                                          unsigned NumCandidates) { }
    931   //@}
    932 
    933   /// \brief Retrieve the allocator that will be used to allocate
    934   /// code completion strings.
    935   virtual CodeCompletionAllocator &getAllocator() = 0;
    936 
    937   virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
    938 };
    939 
    940 /// \brief A simple code-completion consumer that prints the results it
    941 /// receives in a simple format.
    942 class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
    943   /// \brief The raw output stream.
    944   raw_ostream &OS;
    945 
    946   CodeCompletionTUInfo CCTUInfo;
    947 
    948 public:
    949   /// \brief Create a new printing code-completion consumer that prints its
    950   /// results to the given raw output stream.
    951   PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
    952                                raw_ostream &OS)
    953     : CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS),
    954       CCTUInfo(new GlobalCodeCompletionAllocator) {}
    955 
    956   /// \brief Prints the finalized code-completion results.
    957   void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
    958                                   CodeCompletionResult *Results,
    959                                   unsigned NumResults) override;
    960 
    961   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
    962                                  OverloadCandidate *Candidates,
    963                                  unsigned NumCandidates) override;
    964 
    965   CodeCompletionAllocator &getAllocator() override {
    966     return CCTUInfo.getAllocator();
    967   }
    968 
    969   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
    970 };
    971 
    972 } // end namespace clang
    973 
    974 #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
    975