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