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