clang API Documentation

CodeCompleteConsumer.h
Go to the documentation of this file.
00001 //===---- CodeCompleteConsumer.h - Code Completion Interface ----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the CodeCompleteConsumer class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 #ifndef LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
00014 #define LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
00015 
00016 #include "clang-c/Index.h"
00017 #include "clang/AST/CanonicalType.h"
00018 #include "clang/AST/Type.h"
00019 #include "clang/Sema/CodeCompleteOptions.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include "llvm/ADT/StringRef.h"
00022 #include "llvm/Support/Allocator.h"
00023 #include <string>
00024 
00025 namespace clang {
00026 
00027 class Decl;
00028 
00029 /// \brief Default priority values for code-completion results based
00030 /// on their kind.
00031 enum {
00032   /// \brief Priority for the next initialization in a constructor initializer
00033   /// list.
00034   CCP_NextInitializer = 7,
00035   /// \brief Priority for an enumeration constant inside a switch whose
00036   /// condition is of the enumeration type.
00037   CCP_EnumInCase = 7,
00038   /// \brief Priority for a send-to-super completion.
00039   CCP_SuperCompletion = 20,
00040   /// \brief Priority for a declaration that is in the local scope.
00041   CCP_LocalDeclaration = 34,
00042   /// \brief Priority for a member declaration found from the current
00043   /// method or member function.
00044   CCP_MemberDeclaration = 35,
00045   /// \brief Priority for a language keyword (that isn't any of the other
00046   /// categories).
00047   CCP_Keyword = 40,
00048   /// \brief Priority for a code pattern.
00049   CCP_CodePattern = 40,
00050   /// \brief Priority for a non-type declaration.
00051   CCP_Declaration = 50,
00052   /// \brief Priority for a type.
00053   CCP_Type = CCP_Declaration,
00054   /// \brief Priority for a constant value (e.g., enumerator).
00055   CCP_Constant = 65,
00056   /// \brief Priority for a preprocessor macro.
00057   CCP_Macro = 70,
00058   /// \brief Priority for a nested-name-specifier.
00059   CCP_NestedNameSpecifier = 75,
00060   /// \brief Priority for a result that isn't likely to be what the user wants,
00061   /// but is included for completeness.
00062   CCP_Unlikely = 80,
00063 
00064   /// \brief Priority for the Objective-C "_cmd" implicit parameter.
00065   CCP_ObjC_cmd = CCP_Unlikely
00066 };
00067 
00068 /// \brief Priority value deltas that are added to code-completion results
00069 /// based on the context of the result.
00070 enum {
00071   /// \brief The result is in a base class.
00072   CCD_InBaseClass = 2,
00073   /// \brief The result is a C++ non-static member function whose qualifiers
00074   /// exactly match the object type on which the member function can be called.
00075   CCD_ObjectQualifierMatch = -1,
00076   /// \brief The selector of the given message exactly matches the selector
00077   /// of the current method, which might imply that some kind of delegation
00078   /// is occurring.
00079   CCD_SelectorMatch = -3,
00080 
00081   /// \brief Adjustment to the "bool" type in Objective-C, where the typedef
00082   /// "BOOL" is preferred.
00083   CCD_bool_in_ObjC = 1,
00084 
00085   /// \brief Adjustment for KVC code pattern priorities when it doesn't look
00086   /// like the
00087   CCD_ProbablyNotObjCCollection = 15,
00088 
00089   /// \brief An Objective-C method being used as a property.
00090   CCD_MethodAsProperty = 2
00091 };
00092 
00093 /// \brief Priority value factors by which we will divide or multiply the
00094 /// priority of a code-completion result.
00095 enum {
00096   /// \brief Divide by this factor when a code-completion result's type exactly
00097   /// matches the type we expect.
00098   CCF_ExactTypeMatch = 4,
00099   /// \brief Divide by this factor when a code-completion result's type is
00100   /// similar to the type we expect (e.g., both arithmetic types, both
00101   /// Objective-C object pointer types).
00102   CCF_SimilarTypeMatch = 2
00103 };
00104 
00105 /// \brief A simplified classification of types used when determining
00106 /// "similar" types for code completion.
00107 enum SimplifiedTypeClass {
00108   STC_Arithmetic,
00109   STC_Array,
00110   STC_Block,
00111   STC_Function,
00112   STC_ObjectiveC,
00113   STC_Other,
00114   STC_Pointer,
00115   STC_Record,
00116   STC_Void
00117 };
00118 
00119 /// \brief Determine the simplified type class of the given canonical type.
00120 SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
00121 
00122 /// \brief Determine the type that this declaration will have if it is used
00123 /// as a type or in an expression.
00124 QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND);
00125 
00126 /// \brief Determine the priority to be given to a macro code completion result
00127 /// with the given name.
00128 ///
00129 /// \param MacroName The name of the macro.
00130 ///
00131 /// \param LangOpts Options describing the current language dialect.
00132 ///
00133 /// \param PreferredTypeIsPointer Whether the preferred type for the context
00134 /// of this macro is a pointer type.
00135 unsigned getMacroUsagePriority(StringRef MacroName,
00136                                const LangOptions &LangOpts,
00137                                bool PreferredTypeIsPointer = false);
00138 
00139 /// \brief Determine the libclang cursor kind associated with the given
00140 /// declaration.
00141 CXCursorKind getCursorKindForDecl(const Decl *D);
00142 
00143 class FunctionDecl;
00144 class FunctionType;
00145 class FunctionTemplateDecl;
00146 class IdentifierInfo;
00147 class NamedDecl;
00148 class NestedNameSpecifier;
00149 class Sema;
00150 
00151 /// \brief The context in which code completion occurred, so that the
00152 /// code-completion consumer can process the results accordingly.
00153 class CodeCompletionContext {
00154 public:
00155   enum Kind {
00156     /// \brief An unspecified code-completion context.
00157     CCC_Other,
00158     /// \brief An unspecified code-completion context where we should also add
00159     /// macro completions.
00160     CCC_OtherWithMacros,
00161     /// \brief Code completion occurred within a "top-level" completion context,
00162     /// e.g., at namespace or global scope.
00163     CCC_TopLevel,
00164     /// \brief Code completion occurred within an Objective-C interface,
00165     /// protocol, or category interface.
00166     CCC_ObjCInterface,
00167     /// \brief Code completion occurred within an Objective-C implementation
00168     /// or category implementation.
00169     CCC_ObjCImplementation,
00170     /// \brief Code completion occurred within the instance variable list of
00171     /// an Objective-C interface, implementation, or category implementation.
00172     CCC_ObjCIvarList,
00173     /// \brief Code completion occurred within a class, struct, or union.
00174     CCC_ClassStructUnion,
00175     /// \brief Code completion occurred where a statement (or declaration) is
00176     /// expected in a function, method, or block.
00177     CCC_Statement,
00178     /// \brief Code completion occurred where an expression is expected.
00179     CCC_Expression,
00180     /// \brief Code completion occurred where an Objective-C message receiver
00181     /// is expected.
00182     CCC_ObjCMessageReceiver,
00183     /// \brief Code completion occurred on the right-hand side of a member
00184     /// access expression using the dot operator.
00185     ///
00186     /// The results of this completion are the members of the type being
00187     /// accessed. The type itself is available via
00188     /// \c CodeCompletionContext::getType().
00189     CCC_DotMemberAccess,
00190     /// \brief Code completion occurred on the right-hand side of a member
00191     /// access expression using the arrow operator.
00192     ///
00193     /// The results of this completion are the members of the type being
00194     /// accessed. The type itself is available via
00195     /// \c CodeCompletionContext::getType().
00196     CCC_ArrowMemberAccess,
00197     /// \brief Code completion occurred on the right-hand side of an Objective-C
00198     /// property access expression.
00199     ///
00200     /// The results of this completion are the members of the type being
00201     /// accessed. The type itself is available via
00202     /// \c CodeCompletionContext::getType().
00203     CCC_ObjCPropertyAccess,
00204     /// \brief Code completion occurred after the "enum" keyword, to indicate
00205     /// an enumeration name.
00206     CCC_EnumTag,
00207     /// \brief Code completion occurred after the "union" keyword, to indicate
00208     /// a union name.
00209     CCC_UnionTag,
00210     /// \brief Code completion occurred after the "struct" or "class" keyword,
00211     /// to indicate a struct or class name.
00212     CCC_ClassOrStructTag,
00213     /// \brief Code completion occurred where a protocol name is expected.
00214     CCC_ObjCProtocolName,
00215     /// \brief Code completion occurred where a namespace or namespace alias
00216     /// is expected.
00217     CCC_Namespace,
00218     /// \brief Code completion occurred where a type name is expected.
00219     CCC_Type,
00220     /// \brief Code completion occurred where a new name is expected.
00221     CCC_Name,
00222     /// \brief Code completion occurred where a new name is expected and a
00223     /// qualified name is permissible.
00224     CCC_PotentiallyQualifiedName,
00225     /// \brief Code completion occurred where an macro is being defined.
00226     CCC_MacroName,
00227     /// \brief Code completion occurred where a macro name is expected
00228     /// (without any arguments, in the case of a function-like macro).
00229     CCC_MacroNameUse,
00230     /// \brief Code completion occurred within a preprocessor expression.
00231     CCC_PreprocessorExpression,
00232     /// \brief Code completion occurred where a preprocessor directive is
00233     /// expected.
00234     CCC_PreprocessorDirective,
00235     /// \brief Code completion occurred in a context where natural language is
00236     /// expected, e.g., a comment or string literal.
00237     ///
00238     /// This context usually implies that no completions should be added,
00239     /// unless they come from an appropriate natural-language dictionary.
00240     CCC_NaturalLanguage,
00241     /// \brief Code completion for a selector, as in an \@selector expression.
00242     CCC_SelectorName,
00243     /// \brief Code completion within a type-qualifier list.
00244     CCC_TypeQualifiers,
00245     /// \brief Code completion in a parenthesized expression, which means that
00246     /// we may also have types here in C and Objective-C (as well as in C++).
00247     CCC_ParenthesizedExpression,
00248     /// \brief Code completion where an Objective-C instance message is
00249     /// expected.
00250     CCC_ObjCInstanceMessage,
00251     /// \brief Code completion where an Objective-C class message is expected.
00252     CCC_ObjCClassMessage,
00253     /// \brief Code completion where the name of an Objective-C class is
00254     /// expected.
00255     CCC_ObjCInterfaceName,
00256     /// \brief Code completion where an Objective-C category name is expected.
00257     CCC_ObjCCategoryName,
00258     /// \brief An unknown context, in which we are recovering from a parsing
00259     /// error and don't know which completions we should give.
00260     CCC_Recovery
00261   };
00262 
00263 private:
00264   enum Kind Kind;
00265 
00266   /// \brief The type that would prefer to see at this point (e.g., the type
00267   /// of an initializer or function parameter).
00268   QualType PreferredType;
00269 
00270   /// \brief The type of the base object in a member access expression.
00271   QualType BaseType;
00272 
00273   /// \brief The identifiers for Objective-C selector parts.
00274   ArrayRef<IdentifierInfo *> SelIdents;
00275 
00276 public:
00277   /// \brief Construct a new code-completion context of the given kind.
00278   CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(None) { }
00279 
00280   /// \brief Construct a new code-completion context of the given kind.
00281   CodeCompletionContext(enum Kind Kind, QualType T,
00282                         ArrayRef<IdentifierInfo *> SelIdents = None)
00283                         : Kind(Kind),
00284                           SelIdents(SelIdents) {
00285     if (Kind == CCC_DotMemberAccess || Kind == CCC_ArrowMemberAccess ||
00286         Kind == CCC_ObjCPropertyAccess || Kind == CCC_ObjCClassMessage ||
00287         Kind == CCC_ObjCInstanceMessage)
00288       BaseType = T;
00289     else
00290       PreferredType = T;
00291   }
00292 
00293   /// \brief Retrieve the kind of code-completion context.
00294   enum Kind getKind() const { return Kind; }
00295 
00296   /// \brief Retrieve the type that this expression would prefer to have, e.g.,
00297   /// if the expression is a variable initializer or a function argument, the
00298   /// type of the corresponding variable or function parameter.
00299   QualType getPreferredType() const { return PreferredType; }
00300 
00301   /// \brief Retrieve the type of the base object in a member-access
00302   /// expression.
00303   QualType getBaseType() const { return BaseType; }
00304 
00305   /// \brief Retrieve the Objective-C selector identifiers.
00306   ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; }
00307 
00308   /// \brief Determines whether we want C++ constructors as results within this
00309   /// context.
00310   bool wantConstructorResults() const;
00311 };
00312 
00313 
00314 /// \brief A "string" used to describe how code completion can
00315 /// be performed for an entity.
00316 ///
00317 /// A code completion string typically shows how a particular entity can be
00318 /// used. For example, the code completion string for a function would show
00319 /// the syntax to call it, including the parentheses, placeholders for the
00320 /// arguments, etc.
00321 class CodeCompletionString {
00322 public:
00323   /// \brief The different kinds of "chunks" that can occur within a code
00324   /// completion string.
00325   enum ChunkKind {
00326     /// \brief The piece of text that the user is expected to type to
00327     /// match the code-completion string, typically a keyword or the name of a
00328     /// declarator or macro.
00329     CK_TypedText,
00330     /// \brief A piece of text that should be placed in the buffer, e.g.,
00331     /// parentheses or a comma in a function call.
00332     CK_Text,
00333     /// \brief A code completion string that is entirely optional. For example,
00334     /// an optional code completion string that describes the default arguments
00335     /// in a function call.
00336     CK_Optional,
00337     /// \brief A string that acts as a placeholder for, e.g., a function
00338     /// call argument.
00339     CK_Placeholder,
00340     /// \brief A piece of text that describes something about the result but
00341     /// should not be inserted into the buffer.
00342     CK_Informative,
00343     /// \brief A piece of text that describes the type of an entity or, for
00344     /// functions and methods, the return type.
00345     CK_ResultType,
00346     /// \brief A piece of text that describes the parameter that corresponds
00347     /// to the code-completion location within a function call, message send,
00348     /// macro invocation, etc.
00349     CK_CurrentParameter,
00350     /// \brief A left parenthesis ('(').
00351     CK_LeftParen,
00352     /// \brief A right parenthesis (')').
00353     CK_RightParen,
00354     /// \brief A left bracket ('[').
00355     CK_LeftBracket,
00356     /// \brief A right bracket (']').
00357     CK_RightBracket,
00358     /// \brief A left brace ('{').
00359     CK_LeftBrace,
00360     /// \brief A right brace ('}').
00361     CK_RightBrace,
00362     /// \brief A left angle bracket ('<').
00363     CK_LeftAngle,
00364     /// \brief A right angle bracket ('>').
00365     CK_RightAngle,
00366     /// \brief A comma separator (',').
00367     CK_Comma,
00368     /// \brief A colon (':').
00369     CK_Colon,
00370     /// \brief A semicolon (';').
00371     CK_SemiColon,
00372     /// \brief An '=' sign.
00373     CK_Equal,
00374     /// \brief Horizontal whitespace (' ').
00375     CK_HorizontalSpace,
00376     /// \brief Vertical whitespace ('\\n' or '\\r\\n', depending on the
00377     /// platform).
00378     CK_VerticalSpace
00379   };
00380 
00381   /// \brief One piece of the code completion string.
00382   struct Chunk {
00383     /// \brief The kind of data stored in this piece of the code completion
00384     /// string.
00385     ChunkKind Kind;
00386 
00387     union {
00388       /// \brief The text string associated with a CK_Text, CK_Placeholder,
00389       /// CK_Informative, or CK_Comma chunk.
00390       /// The string is owned by the chunk and will be deallocated
00391       /// (with delete[]) when the chunk is destroyed.
00392       const char *Text;
00393 
00394       /// \brief The code completion string associated with a CK_Optional chunk.
00395       /// The optional code completion string is owned by the chunk, and will
00396       /// be deallocated (with delete) when the chunk is destroyed.
00397       CodeCompletionString *Optional;
00398     };
00399 
00400     Chunk() : Kind(CK_Text), Text(nullptr) { }
00401 
00402     explicit Chunk(ChunkKind Kind, const char *Text = "");
00403 
00404     /// \brief Create a new text chunk.
00405     static Chunk CreateText(const char *Text);
00406 
00407     /// \brief Create a new optional chunk.
00408     static Chunk CreateOptional(CodeCompletionString *Optional);
00409 
00410     /// \brief Create a new placeholder chunk.
00411     static Chunk CreatePlaceholder(const char *Placeholder);
00412 
00413     /// \brief Create a new informative chunk.
00414     static Chunk CreateInformative(const char *Informative);
00415 
00416     /// \brief Create a new result type chunk.
00417     static Chunk CreateResultType(const char *ResultType);
00418 
00419     /// \brief Create a new current-parameter chunk.
00420     static Chunk CreateCurrentParameter(const char *CurrentParameter);
00421   };
00422 
00423 private:
00424   /// \brief The number of chunks stored in this string.
00425   unsigned NumChunks : 16;
00426 
00427   /// \brief The number of annotations for this code-completion result.
00428   unsigned NumAnnotations : 16;
00429 
00430   /// \brief The priority of this code-completion string.
00431   unsigned Priority : 16;
00432 
00433   /// \brief The availability of this code-completion result.
00434   unsigned Availability : 2;
00435   
00436   /// \brief The name of the parent context.
00437   StringRef ParentName;
00438 
00439   /// \brief A brief documentation comment attached to the declaration of
00440   /// entity being completed by this result.
00441   const char *BriefComment;
00442   
00443   CodeCompletionString(const CodeCompletionString &) LLVM_DELETED_FUNCTION;
00444   void operator=(const CodeCompletionString &) LLVM_DELETED_FUNCTION;
00445 
00446   CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
00447                        unsigned Priority, CXAvailabilityKind Availability,
00448                        const char **Annotations, unsigned NumAnnotations,
00449                        StringRef ParentName,
00450                        const char *BriefComment);
00451   ~CodeCompletionString() { }
00452 
00453   friend class CodeCompletionBuilder;
00454   friend class CodeCompletionResult;
00455 
00456 public:
00457   typedef const Chunk *iterator;
00458   iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
00459   iterator end() const { return begin() + NumChunks; }
00460   bool empty() const { return NumChunks == 0; }
00461   unsigned size() const { return NumChunks; }
00462 
00463   const Chunk &operator[](unsigned I) const {
00464     assert(I < size() && "Chunk index out-of-range");
00465     return begin()[I];
00466   }
00467 
00468   /// \brief Returns the text in the TypedText chunk.
00469   const char *getTypedText() const;
00470 
00471   /// \brief Retrieve the priority of this code completion result.
00472   unsigned getPriority() const { return Priority; }
00473 
00474   /// \brief Retrieve the availability of this code completion result.
00475   unsigned getAvailability() const { return Availability; }
00476 
00477   /// \brief Retrieve the number of annotations for this code completion result.
00478   unsigned getAnnotationCount() const;
00479 
00480   /// \brief Retrieve the annotation string specified by \c AnnotationNr.
00481   const char *getAnnotation(unsigned AnnotationNr) const;
00482   
00483   /// \brief Retrieve the name of the parent context.
00484   StringRef getParentContextName() const {
00485     return ParentName;
00486   }
00487 
00488   const char *getBriefComment() const {
00489     return BriefComment;
00490   }
00491   
00492   /// \brief Retrieve a string representation of the code completion string,
00493   /// which is mainly useful for debugging.
00494   std::string getAsString() const;
00495 };
00496 
00497 /// \brief An allocator used specifically for the purpose of code completion.
00498 class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
00499 public:
00500   /// \brief Copy the given string into this allocator.
00501   const char *CopyString(StringRef String);
00502 
00503   /// \brief Copy the given string into this allocator.
00504   const char *CopyString(Twine String);
00505 
00506   // \brief Copy the given string into this allocator.
00507   const char *CopyString(const char *String) {
00508     return CopyString(StringRef(String));
00509   }
00510 
00511   /// \brief Copy the given string into this allocator.
00512   const char *CopyString(const std::string &String) {
00513     return CopyString(StringRef(String));
00514   }
00515 };
00516 
00517 /// \brief Allocator for a cached set of global code completions.
00518 class GlobalCodeCompletionAllocator 
00519   : public CodeCompletionAllocator,
00520     public RefCountedBase<GlobalCodeCompletionAllocator>
00521 {
00522 
00523 };
00524 
00525 class CodeCompletionTUInfo {
00526   llvm::DenseMap<const DeclContext *, StringRef> ParentNames;
00527   IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> AllocatorRef;
00528 
00529 public:
00530   explicit CodeCompletionTUInfo(
00531                     IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> Allocator)
00532     : AllocatorRef(Allocator) { }
00533 
00534   IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> getAllocatorRef() const {
00535     return AllocatorRef;
00536   }
00537   CodeCompletionAllocator &getAllocator() const {
00538     assert(AllocatorRef);
00539     return *AllocatorRef;
00540   }
00541 
00542   StringRef getParentName(const DeclContext *DC);
00543 };
00544 
00545 } // end namespace clang
00546 
00547 namespace llvm {
00548   template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
00549     static const bool value = true;
00550   };
00551 }
00552 
00553 namespace clang {
00554 
00555 /// \brief A builder class used to construct new code-completion strings.
00556 class CodeCompletionBuilder {
00557 public:
00558   typedef CodeCompletionString::Chunk Chunk;
00559 
00560 private:
00561   CodeCompletionAllocator &Allocator;
00562   CodeCompletionTUInfo &CCTUInfo;
00563   unsigned Priority;
00564   CXAvailabilityKind Availability;
00565   StringRef ParentName;
00566   const char *BriefComment;
00567   
00568   /// \brief The chunks stored in this string.
00569   SmallVector<Chunk, 4> Chunks;
00570 
00571   SmallVector<const char *, 2> Annotations;
00572 
00573 public:
00574   CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
00575                         CodeCompletionTUInfo &CCTUInfo)
00576     : Allocator(Allocator), CCTUInfo(CCTUInfo),
00577       Priority(0), Availability(CXAvailability_Available),
00578       BriefComment(nullptr) { }
00579 
00580   CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
00581                         CodeCompletionTUInfo &CCTUInfo,
00582                         unsigned Priority, CXAvailabilityKind Availability)
00583     : Allocator(Allocator), CCTUInfo(CCTUInfo),
00584       Priority(Priority), Availability(Availability),
00585       BriefComment(nullptr) { }
00586 
00587   /// \brief Retrieve the allocator into which the code completion
00588   /// strings should be allocated.
00589   CodeCompletionAllocator &getAllocator() const { return Allocator; }
00590 
00591   CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
00592 
00593   /// \brief Take the resulting completion string.
00594   ///
00595   /// This operation can only be performed once.
00596   CodeCompletionString *TakeString();
00597 
00598   /// \brief Add a new typed-text chunk.
00599   void AddTypedTextChunk(const char *Text);
00600 
00601   /// \brief Add a new text chunk.
00602   void AddTextChunk(const char *Text);
00603 
00604   /// \brief Add a new optional chunk.
00605   void AddOptionalChunk(CodeCompletionString *Optional);
00606 
00607   /// \brief Add a new placeholder chunk.
00608   void AddPlaceholderChunk(const char *Placeholder);
00609 
00610   /// \brief Add a new informative chunk.
00611   void AddInformativeChunk(const char *Text);
00612 
00613   /// \brief Add a new result-type chunk.
00614   void AddResultTypeChunk(const char *ResultType);
00615 
00616   /// \brief Add a new current-parameter chunk.
00617   void AddCurrentParameterChunk(const char *CurrentParameter);
00618 
00619   /// \brief Add a new chunk.
00620   void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = "");
00621 
00622   void AddAnnotation(const char *A) { Annotations.push_back(A); }
00623 
00624   /// \brief Add the parent context information to this code completion.
00625   void addParentContext(const DeclContext *DC);
00626 
00627   const char *getBriefComment() const { return BriefComment; }
00628   void addBriefComment(StringRef Comment);
00629   
00630   StringRef getParentName() const { return ParentName; }
00631 };
00632 
00633 /// \brief Captures a result of code completion.
00634 class CodeCompletionResult {
00635 public:
00636   /// \brief Describes the kind of result generated.
00637   enum ResultKind {
00638     RK_Declaration = 0, ///< Refers to a declaration
00639     RK_Keyword,         ///< Refers to a keyword or symbol.
00640     RK_Macro,           ///< Refers to a macro
00641     RK_Pattern          ///< Refers to a precomputed pattern.
00642   };
00643 
00644   /// \brief When Kind == RK_Declaration or RK_Pattern, the declaration we are
00645   /// referring to. In the latter case, the declaration might be NULL.
00646   const NamedDecl *Declaration;
00647 
00648   union {
00649     /// \brief When Kind == RK_Keyword, the string representing the keyword
00650     /// or symbol's spelling.
00651     const char *Keyword;
00652 
00653     /// \brief When Kind == RK_Pattern, the code-completion string that
00654     /// describes the completion text to insert.
00655     CodeCompletionString *Pattern;
00656 
00657     /// \brief When Kind == RK_Macro, the identifier that refers to a macro.
00658     const IdentifierInfo *Macro;
00659   };
00660 
00661   /// \brief The priority of this particular code-completion result.
00662   unsigned Priority;
00663 
00664   /// \brief Specifies which parameter (of a function, Objective-C method,
00665   /// macro, etc.) we should start with when formatting the result.
00666   unsigned StartParameter;
00667 
00668   /// \brief The kind of result stored here.
00669   ResultKind Kind;
00670 
00671   /// \brief The cursor kind that describes this result.
00672   CXCursorKind CursorKind;
00673 
00674   /// \brief The availability of this result.
00675   CXAvailabilityKind Availability;
00676 
00677   /// \brief Whether this result is hidden by another name.
00678   bool Hidden : 1;
00679 
00680   /// \brief Whether this result was found via lookup into a base class.
00681   bool QualifierIsInformative : 1;
00682 
00683   /// \brief Whether this declaration is the beginning of a
00684   /// nested-name-specifier and, therefore, should be followed by '::'.
00685   bool StartsNestedNameSpecifier : 1;
00686 
00687   /// \brief Whether all parameters (of a function, Objective-C
00688   /// method, etc.) should be considered "informative".
00689   bool AllParametersAreInformative : 1;
00690 
00691   /// \brief Whether we're completing a declaration of the given entity,
00692   /// rather than a use of that entity.
00693   bool DeclaringEntity : 1;
00694 
00695   /// \brief If the result should have a nested-name-specifier, this is it.
00696   /// When \c QualifierIsInformative, the nested-name-specifier is
00697   /// informative rather than required.
00698   NestedNameSpecifier *Qualifier;
00699 
00700   /// \brief Build a result that refers to a declaration.
00701   CodeCompletionResult(const NamedDecl *Declaration,
00702                        unsigned Priority,
00703                        NestedNameSpecifier *Qualifier = nullptr,
00704                        bool QualifierIsInformative = false,
00705                        bool Accessible = true)
00706     : Declaration(Declaration), Priority(Priority),
00707       StartParameter(0), Kind(RK_Declaration),
00708       Availability(CXAvailability_Available), Hidden(false),
00709       QualifierIsInformative(QualifierIsInformative),
00710       StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
00711       DeclaringEntity(false), Qualifier(Qualifier) {
00712     computeCursorKindAndAvailability(Accessible);
00713   }
00714 
00715   /// \brief Build a result that refers to a keyword or symbol.
00716   CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
00717     : Declaration(nullptr), Keyword(Keyword), Priority(Priority),
00718       StartParameter(0), Kind(RK_Keyword), CursorKind(CXCursor_NotImplemented),
00719       Availability(CXAvailability_Available), Hidden(false),
00720       QualifierIsInformative(0), StartsNestedNameSpecifier(false),
00721       AllParametersAreInformative(false), DeclaringEntity(false),
00722       Qualifier(nullptr) {}
00723 
00724   /// \brief Build a result that refers to a macro.
00725   CodeCompletionResult(const IdentifierInfo *Macro,
00726                        unsigned Priority = CCP_Macro)
00727     : Declaration(nullptr), Macro(Macro), Priority(Priority), StartParameter(0),
00728       Kind(RK_Macro), CursorKind(CXCursor_MacroDefinition),
00729       Availability(CXAvailability_Available), Hidden(false),
00730       QualifierIsInformative(0), StartsNestedNameSpecifier(false),
00731       AllParametersAreInformative(false), DeclaringEntity(false),
00732       Qualifier(nullptr) {}
00733 
00734   /// \brief Build a result that refers to a pattern.
00735   CodeCompletionResult(CodeCompletionString *Pattern,
00736                        unsigned Priority = CCP_CodePattern,
00737                        CXCursorKind CursorKind = CXCursor_NotImplemented,
00738                    CXAvailabilityKind Availability = CXAvailability_Available,
00739                        const NamedDecl *D = nullptr)
00740     : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
00741       Kind(RK_Pattern), CursorKind(CursorKind), Availability(Availability),
00742       Hidden(false), QualifierIsInformative(0),
00743       StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
00744       DeclaringEntity(false), Qualifier(nullptr)
00745   {
00746   }
00747 
00748   /// \brief Build a result that refers to a pattern with an associated
00749   /// declaration.
00750   CodeCompletionResult(CodeCompletionString *Pattern, NamedDecl *D,
00751                        unsigned Priority)
00752     : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
00753       Kind(RK_Pattern), Availability(CXAvailability_Available), Hidden(false),
00754       QualifierIsInformative(false), StartsNestedNameSpecifier(false),
00755       AllParametersAreInformative(false), DeclaringEntity(false),
00756       Qualifier(nullptr) {
00757     computeCursorKindAndAvailability();
00758   }  
00759   
00760   /// \brief Retrieve the declaration stored in this result.
00761   const NamedDecl *getDeclaration() const {
00762     assert(Kind == RK_Declaration && "Not a declaration result");
00763     return Declaration;
00764   }
00765 
00766   /// \brief Retrieve the keyword stored in this result.
00767   const char *getKeyword() const {
00768     assert(Kind == RK_Keyword && "Not a keyword result");
00769     return Keyword;
00770   }
00771 
00772   /// \brief Create a new code-completion string that describes how to insert
00773   /// this result into a program.
00774   ///
00775   /// \param S The semantic analysis that created the result.
00776   ///
00777   /// \param Allocator The allocator that will be used to allocate the
00778   /// string itself.
00779   CodeCompletionString *CreateCodeCompletionString(Sema &S,
00780                                            CodeCompletionAllocator &Allocator,
00781                                            CodeCompletionTUInfo &CCTUInfo,
00782                                            bool IncludeBriefComments);
00783   CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
00784                                                    Preprocessor &PP,
00785                                            CodeCompletionAllocator &Allocator,
00786                                            CodeCompletionTUInfo &CCTUInfo,
00787                                            bool IncludeBriefComments);
00788 
00789 private:
00790   void computeCursorKindAndAvailability(bool Accessible = true);
00791 };
00792 
00793 bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
00794 
00795 inline bool operator>(const CodeCompletionResult &X,
00796                       const CodeCompletionResult &Y) {
00797   return Y < X;
00798 }
00799 
00800 inline bool operator<=(const CodeCompletionResult &X,
00801                       const CodeCompletionResult &Y) {
00802   return !(Y < X);
00803 }
00804 
00805 inline bool operator>=(const CodeCompletionResult &X,
00806                        const CodeCompletionResult &Y) {
00807   return !(X < Y);
00808 }
00809 
00810 
00811 raw_ostream &operator<<(raw_ostream &OS,
00812                               const CodeCompletionString &CCS);
00813 
00814 /// \brief Abstract interface for a consumer of code-completion
00815 /// information.
00816 class CodeCompleteConsumer {
00817 protected:
00818   const CodeCompleteOptions CodeCompleteOpts;
00819 
00820   /// \brief Whether the output format for the code-completion consumer is
00821   /// binary.
00822   bool OutputIsBinary;
00823 
00824 public:
00825   class OverloadCandidate {
00826   public:
00827     /// \brief Describes the type of overload candidate.
00828     enum CandidateKind {
00829       /// \brief The candidate is a function declaration.
00830       CK_Function,
00831       /// \brief The candidate is a function template.
00832       CK_FunctionTemplate,
00833       /// \brief The "candidate" is actually a variable, expression, or block
00834       /// for which we only have a function prototype.
00835       CK_FunctionType
00836     };
00837 
00838   private:
00839     /// \brief The kind of overload candidate.
00840     CandidateKind Kind;
00841 
00842     union {
00843       /// \brief The function overload candidate, available when
00844       /// Kind == CK_Function.
00845       FunctionDecl *Function;
00846 
00847       /// \brief The function template overload candidate, available when
00848       /// Kind == CK_FunctionTemplate.
00849       FunctionTemplateDecl *FunctionTemplate;
00850 
00851       /// \brief The function type that describes the entity being called,
00852       /// when Kind == CK_FunctionType.
00853       const FunctionType *Type;
00854     };
00855 
00856   public:
00857     OverloadCandidate(FunctionDecl *Function)
00858       : Kind(CK_Function), Function(Function) { }
00859 
00860     OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
00861       : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) { }
00862 
00863     OverloadCandidate(const FunctionType *Type)
00864       : Kind(CK_FunctionType), Type(Type) { }
00865 
00866     /// \brief Determine the kind of overload candidate.
00867     CandidateKind getKind() const { return Kind; }
00868 
00869     /// \brief Retrieve the function overload candidate or the templated
00870     /// function declaration for a function template.
00871     FunctionDecl *getFunction() const;
00872 
00873     /// \brief Retrieve the function template overload candidate.
00874     FunctionTemplateDecl *getFunctionTemplate() const {
00875       assert(getKind() == CK_FunctionTemplate && "Not a function template");
00876       return FunctionTemplate;
00877     }
00878 
00879     /// \brief Retrieve the function type of the entity, regardless of how the
00880     /// function is stored.
00881     const FunctionType *getFunctionType() const;
00882 
00883     /// \brief Create a new code-completion string that describes the function
00884     /// signature of this overload candidate.
00885     CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
00886                                                 Sema &S,
00887                                       CodeCompletionAllocator &Allocator,
00888                                       CodeCompletionTUInfo &CCTUInfo) const;
00889   };
00890 
00891   CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
00892                        bool OutputIsBinary)
00893     : CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary)
00894   { }
00895 
00896   /// \brief Whether the code-completion consumer wants to see macros.
00897   bool includeMacros() const {
00898     return CodeCompleteOpts.IncludeMacros;
00899   }
00900 
00901   /// \brief Whether the code-completion consumer wants to see code patterns.
00902   bool includeCodePatterns() const {
00903     return CodeCompleteOpts.IncludeCodePatterns;
00904   }
00905 
00906   /// \brief Whether to include global (top-level) declaration results.
00907   bool includeGlobals() const {
00908     return CodeCompleteOpts.IncludeGlobals;
00909   }
00910 
00911   /// \brief Whether to include brief documentation comments within the set of
00912   /// code completions returned.
00913   bool includeBriefComments() const {
00914     return CodeCompleteOpts.IncludeBriefComments;
00915   }
00916 
00917   /// \brief Determine whether the output of this consumer is binary.
00918   bool isOutputBinary() const { return OutputIsBinary; }
00919 
00920   /// \brief Deregisters and destroys this code-completion consumer.
00921   virtual ~CodeCompleteConsumer();
00922 
00923   /// \name Code-completion callbacks
00924   //@{
00925   /// \brief Process the finalized code-completion results.
00926   virtual void ProcessCodeCompleteResults(Sema &S,
00927                                           CodeCompletionContext Context,
00928                                           CodeCompletionResult *Results,
00929                                           unsigned NumResults) { }
00930 
00931   /// \param S the semantic-analyzer object for which code-completion is being
00932   /// done.
00933   ///
00934   /// \param CurrentArg the index of the current argument.
00935   ///
00936   /// \param Candidates an array of overload candidates.
00937   ///
00938   /// \param NumCandidates the number of overload candidates
00939   virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
00940                                          OverloadCandidate *Candidates,
00941                                          unsigned NumCandidates) { }
00942   //@}
00943 
00944   /// \brief Retrieve the allocator that will be used to allocate
00945   /// code completion strings.
00946   virtual CodeCompletionAllocator &getAllocator() = 0;
00947 
00948   virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
00949 };
00950 
00951 /// \brief A simple code-completion consumer that prints the results it
00952 /// receives in a simple format.
00953 class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
00954   /// \brief The raw output stream.
00955   raw_ostream &OS;
00956 
00957   CodeCompletionTUInfo CCTUInfo;
00958 
00959 public:
00960   /// \brief Create a new printing code-completion consumer that prints its
00961   /// results to the given raw output stream.
00962   PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
00963                                raw_ostream &OS)
00964     : CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS),
00965       CCTUInfo(new GlobalCodeCompletionAllocator) {}
00966 
00967   /// \brief Prints the finalized code-completion results.
00968   void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
00969                                   CodeCompletionResult *Results,
00970                                   unsigned NumResults) override;
00971 
00972   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
00973                                  OverloadCandidate *Candidates,
00974                                  unsigned NumCandidates) override;
00975 
00976   CodeCompletionAllocator &getAllocator() override {
00977     return CCTUInfo.getAllocator();
00978   }
00979 
00980   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
00981 };
00982 
00983 } // end namespace clang
00984 
00985 #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H