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/AST/Type.h" 17 #include "clang/AST/CanonicalType.h" 18 #include "clang/Sema/CodeCompleteOptions.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/StringRef.h" 21 #include "llvm/Support/Allocator.h" 22 #include "clang-c/Index.h" 23 #include <string> 24 25 namespace clang { 26 27 class Decl; 28 29 /// \brief Default priority values for code-completion results based 30 /// on their kind. 31 enum { 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. 70 enum { 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. 95 enum { 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. 107 enum 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. 120 SimplifiedTypeClass 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. 124 QualType getDeclUsageType(ASTContext &C, 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. 135 unsigned 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. 141 CXCursorKind getCursorKindForDecl(Decl *D); 142 143 class FunctionDecl; 144 class FunctionType; 145 class FunctionTemplateDecl; 146 class IdentifierInfo; 147 class NamedDecl; 148 class NestedNameSpecifier; 149 class Sema; 150 151 /// \brief The context in which code completion occurred, so that the 152 /// code-completion consumer can process the results accordingly. 153 class CodeCompletionContext { 154 public: 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 expcted. 249 CCC_ObjCInstanceMessage, 250 /// \brief Code completion where an Objective-C class message is expected. 251 CCC_ObjCClassMessage, 252 /// \brief Code completion where the name of an Objective-C class is 253 /// expected. 254 CCC_ObjCInterfaceName, 255 /// \brief Code completion where an Objective-C category name is expected. 256 CCC_ObjCCategoryName, 257 /// \brief An unknown context, in which we are recovering from a parsing 258 /// error and don't know which completions we should give. 259 CCC_Recovery 260 }; 261 262 private: 263 enum Kind Kind; 264 265 /// \brief The type that would prefer to see at this point (e.g., the type 266 /// of an initializer or function parameter). 267 QualType PreferredType; 268 269 /// \brief The type of the base object in a member access expression. 270 QualType BaseType; 271 272 /// \brief The identifiers for Objective-C selector parts. 273 IdentifierInfo **SelIdents; 274 275 /// \brief The number of Objective-C selector parts. 276 unsigned NumSelIdents; 277 278 public: 279 /// \brief Construct a new code-completion context of the given kind. CodeCompletionContext(enum Kind Kind)280 CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(NULL), 281 NumSelIdents(0) { } 282 283 /// \brief Construct a new code-completion context of the given kind. 284 CodeCompletionContext(enum Kind Kind, QualType T, 285 IdentifierInfo **SelIdents = NULL, Kind(Kind)286 unsigned NumSelIdents = 0) : Kind(Kind), 287 SelIdents(SelIdents), 288 NumSelIdents(NumSelIdents) { 289 if (Kind == CCC_DotMemberAccess || Kind == CCC_ArrowMemberAccess || 290 Kind == CCC_ObjCPropertyAccess || Kind == CCC_ObjCClassMessage || 291 Kind == CCC_ObjCInstanceMessage) 292 BaseType = T; 293 else 294 PreferredType = T; 295 } 296 297 /// \brief Retrieve the kind of code-completion context. getKind()298 enum Kind getKind() const { return Kind; } 299 300 /// \brief Retrieve the type that this expression would prefer to have, e.g., 301 /// if the expression is a variable initializer or a function argument, the 302 /// type of the corresponding variable or function parameter. getPreferredType()303 QualType getPreferredType() const { return PreferredType; } 304 305 /// \brief Retrieve the type of the base object in a member-access 306 /// expression. getBaseType()307 QualType getBaseType() const { return BaseType; } 308 309 /// \brief Retrieve the Objective-C selector identifiers. getSelIdents()310 IdentifierInfo **getSelIdents() const { return SelIdents; } 311 312 /// \brief Retrieve the number of Objective-C selector identifiers. getNumSelIdents()313 unsigned getNumSelIdents() const { return NumSelIdents; } 314 315 /// \brief Determines whether we want C++ constructors as results within this 316 /// context. 317 bool wantConstructorResults() const; 318 }; 319 320 321 /// \brief A "string" used to describe how code completion can 322 /// be performed for an entity. 323 /// 324 /// A code completion string typically shows how a particular entity can be 325 /// used. For example, the code completion string for a function would show 326 /// the syntax to call it, including the parentheses, placeholders for the 327 /// arguments, etc. 328 class CodeCompletionString { 329 public: 330 /// \brief The different kinds of "chunks" that can occur within a code 331 /// completion string. 332 enum ChunkKind { 333 /// \brief The piece of text that the user is expected to type to 334 /// match the code-completion string, typically a keyword or the name of a 335 /// declarator or macro. 336 CK_TypedText, 337 /// \brief A piece of text that should be placed in the buffer, e.g., 338 /// parentheses or a comma in a function call. 339 CK_Text, 340 /// \brief A code completion string that is entirely optional. For example, 341 /// an optional code completion string that describes the default arguments 342 /// in a function call. 343 CK_Optional, 344 /// \brief A string that acts as a placeholder for, e.g., a function 345 /// call argument. 346 CK_Placeholder, 347 /// \brief A piece of text that describes something about the result but 348 /// should not be inserted into the buffer. 349 CK_Informative, 350 /// \brief A piece of text that describes the type of an entity or, for 351 /// functions and methods, the return type. 352 CK_ResultType, 353 /// \brief A piece of text that describes the parameter that corresponds 354 /// to the code-completion location within a function call, message send, 355 /// macro invocation, etc. 356 CK_CurrentParameter, 357 /// \brief A left parenthesis ('('). 358 CK_LeftParen, 359 /// \brief A right parenthesis (')'). 360 CK_RightParen, 361 /// \brief A left bracket ('['). 362 CK_LeftBracket, 363 /// \brief A right bracket (']'). 364 CK_RightBracket, 365 /// \brief A left brace ('{'). 366 CK_LeftBrace, 367 /// \brief A right brace ('}'). 368 CK_RightBrace, 369 /// \brief A left angle bracket ('<'). 370 CK_LeftAngle, 371 /// \brief A right angle bracket ('>'). 372 CK_RightAngle, 373 /// \brief A comma separator (','). 374 CK_Comma, 375 /// \brief A colon (':'). 376 CK_Colon, 377 /// \brief A semicolon (';'). 378 CK_SemiColon, 379 /// \brief An '=' sign. 380 CK_Equal, 381 /// \brief Horizontal whitespace (' '). 382 CK_HorizontalSpace, 383 /// \brief Vertical whitespace ('\\n' or '\\r\\n', depending on the 384 /// platform). 385 CK_VerticalSpace 386 }; 387 388 /// \brief One piece of the code completion string. 389 struct Chunk { 390 /// \brief The kind of data stored in this piece of the code completion 391 /// string. 392 ChunkKind Kind; 393 394 union { 395 /// \brief The text string associated with a CK_Text, CK_Placeholder, 396 /// CK_Informative, or CK_Comma chunk. 397 /// The string is owned by the chunk and will be deallocated 398 /// (with delete[]) when the chunk is destroyed. 399 const char *Text; 400 401 /// \brief The code completion string associated with a CK_Optional chunk. 402 /// The optional code completion string is owned by the chunk, and will 403 /// be deallocated (with delete) when the chunk is destroyed. 404 CodeCompletionString *Optional; 405 }; 406 ChunkChunk407 Chunk() : Kind(CK_Text), Text(0) { } 408 409 explicit Chunk(ChunkKind Kind, const char *Text = ""); 410 411 /// \brief Create a new text chunk. 412 static Chunk CreateText(const char *Text); 413 414 /// \brief Create a new optional chunk. 415 static Chunk CreateOptional(CodeCompletionString *Optional); 416 417 /// \brief Create a new placeholder chunk. 418 static Chunk CreatePlaceholder(const char *Placeholder); 419 420 /// \brief Create a new informative chunk. 421 static Chunk CreateInformative(const char *Informative); 422 423 /// \brief Create a new result type chunk. 424 static Chunk CreateResultType(const char *ResultType); 425 426 /// \brief Create a new current-parameter chunk. 427 static Chunk CreateCurrentParameter(const char *CurrentParameter); 428 }; 429 430 private: 431 /// \brief The number of chunks stored in this string. 432 unsigned NumChunks : 16; 433 434 /// \brief The number of annotations for this code-completion result. 435 unsigned NumAnnotations : 16; 436 437 /// \brief The priority of this code-completion string. 438 unsigned Priority : 16; 439 440 /// \brief The availability of this code-completion result. 441 unsigned Availability : 2; 442 443 /// \brief The kind of the parent context. 444 unsigned ParentKind : 14; 445 446 /// \brief The name of the parent context. 447 StringRef ParentName; 448 449 /// \brief A brief documentation comment attached to the declaration of 450 /// entity being completed by this result. 451 const char *BriefComment; 452 453 CodeCompletionString(const CodeCompletionString &); // DO NOT IMPLEMENT 454 CodeCompletionString &operator=(const CodeCompletionString &); // DITTO 455 456 CodeCompletionString(const Chunk *Chunks, unsigned NumChunks, 457 unsigned Priority, CXAvailabilityKind Availability, 458 const char **Annotations, unsigned NumAnnotations, 459 CXCursorKind ParentKind, StringRef ParentName, 460 const char *BriefComment); ~CodeCompletionString()461 ~CodeCompletionString() { } 462 463 friend class CodeCompletionBuilder; 464 friend class CodeCompletionResult; 465 466 public: 467 typedef const Chunk *iterator; begin()468 iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); } end()469 iterator end() const { return begin() + NumChunks; } empty()470 bool empty() const { return NumChunks == 0; } size()471 unsigned size() const { return NumChunks; } 472 473 const Chunk &operator[](unsigned I) const { 474 assert(I < size() && "Chunk index out-of-range"); 475 return begin()[I]; 476 } 477 478 /// \brief Returns the text in the TypedText chunk. 479 const char *getTypedText() const; 480 481 /// \brief Retrieve the priority of this code completion result. getPriority()482 unsigned getPriority() const { return Priority; } 483 484 /// \brief Retrieve the availability of this code completion result. getAvailability()485 unsigned getAvailability() const { return Availability; } 486 487 /// \brief Retrieve the number of annotations for this code completion result. 488 unsigned getAnnotationCount() const; 489 490 /// \brief Retrieve the annotation string specified by \c AnnotationNr. 491 const char *getAnnotation(unsigned AnnotationNr) const; 492 493 /// \brief Retrieve parent context's cursor kind. getParentContextKind()494 CXCursorKind getParentContextKind() const { 495 return (CXCursorKind)ParentKind; 496 } 497 498 /// \brief Retrieve the name of the parent context. getParentContextName()499 StringRef getParentContextName() const { 500 return ParentName; 501 } 502 getBriefComment()503 const char *getBriefComment() const { 504 return BriefComment; 505 } 506 507 /// \brief Retrieve a string representation of the code completion string, 508 /// which is mainly useful for debugging. 509 std::string getAsString() const; 510 }; 511 512 /// \brief An allocator used specifically for the purpose of code completion. 513 class CodeCompletionAllocator : public llvm::BumpPtrAllocator { 514 public: 515 /// \brief Copy the given string into this allocator. 516 const char *CopyString(StringRef String); 517 518 /// \brief Copy the given string into this allocator. 519 const char *CopyString(Twine String); 520 521 // \brief Copy the given string into this allocator. CopyString(const char * String)522 const char *CopyString(const char *String) { 523 return CopyString(StringRef(String)); 524 } 525 526 /// \brief Copy the given string into this allocator. CopyString(const std::string & String)527 const char *CopyString(const std::string &String) { 528 return CopyString(StringRef(String)); 529 } 530 }; 531 532 /// \brief Allocator for a cached set of global code completions. 533 class GlobalCodeCompletionAllocator 534 : public CodeCompletionAllocator, 535 public RefCountedBase<GlobalCodeCompletionAllocator> 536 { 537 538 }; 539 540 class CodeCompletionTUInfo { 541 llvm::DenseMap<DeclContext *, StringRef> ParentNames; 542 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> AllocatorRef; 543 544 public: CodeCompletionTUInfo(IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> Allocator)545 explicit CodeCompletionTUInfo( 546 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> Allocator) 547 : AllocatorRef(Allocator) { } 548 getAllocatorRef()549 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> getAllocatorRef() const { 550 return AllocatorRef; 551 } getAllocator()552 CodeCompletionAllocator &getAllocator() const { 553 assert(AllocatorRef); 554 return *AllocatorRef; 555 } 556 557 StringRef getParentName(DeclContext *DC); 558 }; 559 560 } // end namespace clang 561 562 namespace llvm { 563 template <> struct isPodLike<clang::CodeCompletionString::Chunk> { 564 static const bool value = true; 565 }; 566 } 567 568 namespace clang { 569 570 /// \brief A builder class used to construct new code-completion strings. 571 class CodeCompletionBuilder { 572 public: 573 typedef CodeCompletionString::Chunk Chunk; 574 575 private: 576 CodeCompletionAllocator &Allocator; 577 CodeCompletionTUInfo &CCTUInfo; 578 unsigned Priority; 579 CXAvailabilityKind Availability; 580 CXCursorKind ParentKind; 581 StringRef ParentName; 582 const char *BriefComment; 583 584 /// \brief The chunks stored in this string. 585 SmallVector<Chunk, 4> Chunks; 586 587 SmallVector<const char *, 2> Annotations; 588 589 public: 590 CodeCompletionBuilder(CodeCompletionAllocator &Allocator, 591 CodeCompletionTUInfo &CCTUInfo) 592 : Allocator(Allocator), CCTUInfo(CCTUInfo), 593 Priority(0), Availability(CXAvailability_Available), 594 ParentKind(CXCursor_NotImplemented), BriefComment(NULL) { } 595 596 CodeCompletionBuilder(CodeCompletionAllocator &Allocator, 597 CodeCompletionTUInfo &CCTUInfo, 598 unsigned Priority, CXAvailabilityKind Availability) 599 : Allocator(Allocator), CCTUInfo(CCTUInfo), 600 Priority(Priority), Availability(Availability), 601 ParentKind(CXCursor_NotImplemented), BriefComment(NULL) { } 602 603 /// \brief Retrieve the allocator into which the code completion 604 /// strings should be allocated. 605 CodeCompletionAllocator &getAllocator() const { return Allocator; } 606 607 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; } 608 609 /// \brief Take the resulting completion string. 610 /// 611 /// This operation can only be performed once. 612 CodeCompletionString *TakeString(); 613 614 /// \brief Add a new typed-text chunk. 615 void AddTypedTextChunk(const char *Text); 616 617 /// \brief Add a new text chunk. 618 void AddTextChunk(const char *Text); 619 620 /// \brief Add a new optional chunk. 621 void AddOptionalChunk(CodeCompletionString *Optional); 622 623 /// \brief Add a new placeholder chunk. 624 void AddPlaceholderChunk(const char *Placeholder); 625 626 /// \brief Add a new informative chunk. 627 void AddInformativeChunk(const char *Text); 628 629 /// \brief Add a new result-type chunk. 630 void AddResultTypeChunk(const char *ResultType); 631 632 /// \brief Add a new current-parameter chunk. 633 void AddCurrentParameterChunk(const char *CurrentParameter); 634 635 /// \brief Add a new chunk. 636 void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = ""); 637 638 void AddAnnotation(const char *A) { Annotations.push_back(A); } 639 640 /// \brief Add the parent context information to this code completion. 641 void addParentContext(DeclContext *DC); 642 643 void addBriefComment(StringRef Comment); 644 645 CXCursorKind getParentKind() const { return ParentKind; } 646 StringRef getParentName() const { return ParentName; } 647 }; 648 649 /// \brief Captures a result of code completion. 650 class CodeCompletionResult { 651 public: 652 /// \brief Describes the kind of result generated. 653 enum ResultKind { 654 RK_Declaration = 0, ///< Refers to a declaration 655 RK_Keyword, ///< Refers to a keyword or symbol. 656 RK_Macro, ///< Refers to a macro 657 RK_Pattern ///< Refers to a precomputed pattern. 658 }; 659 660 /// \brief When Kind == RK_Declaration or RK_Pattern, the declaration we are 661 /// referring to. In the latter case, the declaration might be NULL. 662 NamedDecl *Declaration; 663 664 union { 665 /// \brief When Kind == RK_Keyword, the string representing the keyword 666 /// or symbol's spelling. 667 const char *Keyword; 668 669 /// \brief When Kind == RK_Pattern, the code-completion string that 670 /// describes the completion text to insert. 671 CodeCompletionString *Pattern; 672 673 /// \brief When Kind == RK_Macro, the identifier that refers to a macro. 674 IdentifierInfo *Macro; 675 }; 676 677 /// \brief The priority of this particular code-completion result. 678 unsigned Priority; 679 680 /// \brief Specifies which parameter (of a function, Objective-C method, 681 /// macro, etc.) we should start with when formatting the result. 682 unsigned StartParameter; 683 684 /// \brief The kind of result stored here. 685 ResultKind Kind; 686 687 /// \brief The cursor kind that describes this result. 688 CXCursorKind CursorKind; 689 690 /// \brief The availability of this result. 691 CXAvailabilityKind Availability; 692 693 /// \brief Whether this result is hidden by another name. 694 bool Hidden : 1; 695 696 /// \brief Whether this result was found via lookup into a base class. 697 bool QualifierIsInformative : 1; 698 699 /// \brief Whether this declaration is the beginning of a 700 /// nested-name-specifier and, therefore, should be followed by '::'. 701 bool StartsNestedNameSpecifier : 1; 702 703 /// \brief Whether all parameters (of a function, Objective-C 704 /// method, etc.) should be considered "informative". 705 bool AllParametersAreInformative : 1; 706 707 /// \brief Whether we're completing a declaration of the given entity, 708 /// rather than a use of that entity. 709 bool DeclaringEntity : 1; 710 711 /// \brief If the result should have a nested-name-specifier, this is it. 712 /// When \c QualifierIsInformative, the nested-name-specifier is 713 /// informative rather than required. 714 NestedNameSpecifier *Qualifier; 715 716 /// \brief Build a result that refers to a declaration. 717 CodeCompletionResult(NamedDecl *Declaration, 718 NestedNameSpecifier *Qualifier = 0, 719 bool QualifierIsInformative = false, 720 bool Accessible = true) 721 : Declaration(Declaration), Priority(getPriorityFromDecl(Declaration)), 722 StartParameter(0), Kind(RK_Declaration), 723 Availability(CXAvailability_Available), Hidden(false), 724 QualifierIsInformative(QualifierIsInformative), 725 StartsNestedNameSpecifier(false), AllParametersAreInformative(false), 726 DeclaringEntity(false), Qualifier(Qualifier) { 727 computeCursorKindAndAvailability(Accessible); 728 } 729 730 /// \brief Build a result that refers to a keyword or symbol. 731 CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword) 732 : Declaration(0), Keyword(Keyword), Priority(Priority), StartParameter(0), 733 Kind(RK_Keyword), CursorKind(CXCursor_NotImplemented), 734 Availability(CXAvailability_Available), Hidden(false), 735 QualifierIsInformative(0), StartsNestedNameSpecifier(false), 736 AllParametersAreInformative(false), DeclaringEntity(false), Qualifier(0) 737 { 738 } 739 740 /// \brief Build a result that refers to a macro. 741 CodeCompletionResult(IdentifierInfo *Macro, unsigned Priority = CCP_Macro) 742 : Declaration(0), Macro(Macro), Priority(Priority), StartParameter(0), 743 Kind(RK_Macro), CursorKind(CXCursor_MacroDefinition), 744 Availability(CXAvailability_Available), Hidden(false), 745 QualifierIsInformative(0), StartsNestedNameSpecifier(false), 746 AllParametersAreInformative(false), DeclaringEntity(false), Qualifier(0) 747 { 748 } 749 750 /// \brief Build a result that refers to a pattern. 751 CodeCompletionResult(CodeCompletionString *Pattern, 752 unsigned Priority = CCP_CodePattern, 753 CXCursorKind CursorKind = CXCursor_NotImplemented, 754 CXAvailabilityKind Availability = CXAvailability_Available, 755 NamedDecl *D = 0) 756 : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0), 757 Kind(RK_Pattern), CursorKind(CursorKind), Availability(Availability), 758 Hidden(false), QualifierIsInformative(0), 759 StartsNestedNameSpecifier(false), AllParametersAreInformative(false), 760 DeclaringEntity(false), Qualifier(0) 761 { 762 } 763 764 /// \brief Build a result that refers to a pattern with an associated 765 /// declaration. 766 CodeCompletionResult(CodeCompletionString *Pattern, NamedDecl *D, 767 unsigned Priority) 768 : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0), 769 Kind(RK_Pattern), Availability(CXAvailability_Available), Hidden(false), 770 QualifierIsInformative(false), StartsNestedNameSpecifier(false), 771 AllParametersAreInformative(false), DeclaringEntity(false), Qualifier(0) { 772 computeCursorKindAndAvailability(); 773 } 774 775 /// \brief Retrieve the declaration stored in this result. 776 NamedDecl *getDeclaration() const { 777 assert(Kind == RK_Declaration && "Not a declaration result"); 778 return Declaration; 779 } 780 781 /// \brief Retrieve the keyword stored in this result. 782 const char *getKeyword() const { 783 assert(Kind == RK_Keyword && "Not a keyword result"); 784 return Keyword; 785 } 786 787 /// \brief Create a new code-completion string that describes how to insert 788 /// this result into a program. 789 /// 790 /// \param S The semantic analysis that created the result. 791 /// 792 /// \param Allocator The allocator that will be used to allocate the 793 /// string itself. 794 CodeCompletionString *CreateCodeCompletionString(Sema &S, 795 CodeCompletionAllocator &Allocator, 796 CodeCompletionTUInfo &CCTUInfo, 797 bool IncludeBriefComments); 798 CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx, 799 Preprocessor &PP, 800 CodeCompletionAllocator &Allocator, 801 CodeCompletionTUInfo &CCTUInfo, 802 bool IncludeBriefComments); 803 804 /// \brief Determine a base priority for the given declaration. 805 static unsigned getPriorityFromDecl(NamedDecl *ND); 806 807 private: 808 void computeCursorKindAndAvailability(bool Accessible = true); 809 }; 810 811 bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y); 812 813 inline bool operator>(const CodeCompletionResult &X, 814 const CodeCompletionResult &Y) { 815 return Y < X; 816 } 817 818 inline bool operator<=(const CodeCompletionResult &X, 819 const CodeCompletionResult &Y) { 820 return !(Y < X); 821 } 822 823 inline bool operator>=(const CodeCompletionResult &X, 824 const CodeCompletionResult &Y) { 825 return !(X < Y); 826 } 827 828 829 raw_ostream &operator<<(raw_ostream &OS, 830 const CodeCompletionString &CCS); 831 832 /// \brief Abstract interface for a consumer of code-completion 833 /// information. 834 class CodeCompleteConsumer { 835 protected: 836 const CodeCompleteOptions CodeCompleteOpts; 837 838 /// \brief Whether the output format for the code-completion consumer is 839 /// binary. 840 bool OutputIsBinary; 841 842 public: 843 class OverloadCandidate { 844 public: 845 /// \brief Describes the type of overload candidate. 846 enum CandidateKind { 847 /// \brief The candidate is a function declaration. 848 CK_Function, 849 /// \brief The candidate is a function template. 850 CK_FunctionTemplate, 851 /// \brief The "candidate" is actually a variable, expression, or block 852 /// for which we only have a function prototype. 853 CK_FunctionType 854 }; 855 856 private: 857 /// \brief The kind of overload candidate. 858 CandidateKind Kind; 859 860 union { 861 /// \brief The function overload candidate, available when 862 /// Kind == CK_Function. 863 FunctionDecl *Function; 864 865 /// \brief The function template overload candidate, available when 866 /// Kind == CK_FunctionTemplate. 867 FunctionTemplateDecl *FunctionTemplate; 868 869 /// \brief The function type that describes the entity being called, 870 /// when Kind == CK_FunctionType. 871 const FunctionType *Type; 872 }; 873 874 public: 875 OverloadCandidate(FunctionDecl *Function) 876 : Kind(CK_Function), Function(Function) { } 877 878 OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl) 879 : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) { } 880 881 OverloadCandidate(const FunctionType *Type) 882 : Kind(CK_FunctionType), Type(Type) { } 883 884 /// \brief Determine the kind of overload candidate. 885 CandidateKind getKind() const { return Kind; } 886 887 /// \brief Retrieve the function overload candidate or the templated 888 /// function declaration for a function template. 889 FunctionDecl *getFunction() const; 890 891 /// \brief Retrieve the function template overload candidate. 892 FunctionTemplateDecl *getFunctionTemplate() const { 893 assert(getKind() == CK_FunctionTemplate && "Not a function template"); 894 return FunctionTemplate; 895 } 896 897 /// \brief Retrieve the function type of the entity, regardless of how the 898 /// function is stored. 899 const FunctionType *getFunctionType() const; 900 901 /// \brief Create a new code-completion string that describes the function 902 /// signature of this overload candidate. 903 CodeCompletionString *CreateSignatureString(unsigned CurrentArg, 904 Sema &S, 905 CodeCompletionAllocator &Allocator, 906 CodeCompletionTUInfo &CCTUInfo) const; 907 }; 908 909 CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts, 910 bool OutputIsBinary) 911 : CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary) 912 { } 913 914 /// \brief Whether the code-completion consumer wants to see macros. 915 bool includeMacros() const { 916 return CodeCompleteOpts.IncludeMacros; 917 } 918 919 /// \brief Whether the code-completion consumer wants to see code patterns. 920 bool includeCodePatterns() const { 921 return CodeCompleteOpts.IncludeCodePatterns; 922 } 923 924 /// \brief Whether to include global (top-level) declaration results. 925 bool includeGlobals() const { 926 return CodeCompleteOpts.IncludeGlobals; 927 } 928 929 /// \brief Whether to include brief documentation comments within the set of 930 /// code completions returned. 931 bool includeBriefComments() const { 932 return CodeCompleteOpts.IncludeBriefComments; 933 } 934 935 /// \brief Determine whether the output of this consumer is binary. 936 bool isOutputBinary() const { return OutputIsBinary; } 937 938 /// \brief Deregisters and destroys this code-completion consumer. 939 virtual ~CodeCompleteConsumer(); 940 941 /// \name Code-completion callbacks 942 //@{ 943 /// \brief Process the finalized code-completion results. 944 virtual void ProcessCodeCompleteResults(Sema &S, 945 CodeCompletionContext Context, 946 CodeCompletionResult *Results, 947 unsigned NumResults) { } 948 949 /// \param S the semantic-analyzer object for which code-completion is being 950 /// done. 951 /// 952 /// \param CurrentArg the index of the current argument. 953 /// 954 /// \param Candidates an array of overload candidates. 955 /// 956 /// \param NumCandidates the number of overload candidates 957 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, 958 OverloadCandidate *Candidates, 959 unsigned NumCandidates) { } 960 //@} 961 962 /// \brief Retrieve the allocator that will be used to allocate 963 /// code completion strings. 964 virtual CodeCompletionAllocator &getAllocator() = 0; 965 966 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0; 967 }; 968 969 /// \brief A simple code-completion consumer that prints the results it 970 /// receives in a simple format. 971 class PrintingCodeCompleteConsumer : public CodeCompleteConsumer { 972 /// \brief The raw output stream. 973 raw_ostream &OS; 974 975 CodeCompletionTUInfo CCTUInfo; 976 977 public: 978 /// \brief Create a new printing code-completion consumer that prints its 979 /// results to the given raw output stream. 980 PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts, 981 raw_ostream &OS) 982 : CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS), 983 CCTUInfo(new GlobalCodeCompletionAllocator) {} 984 985 /// \brief Prints the finalized code-completion results. 986 virtual void ProcessCodeCompleteResults(Sema &S, 987 CodeCompletionContext Context, 988 CodeCompletionResult *Results, 989 unsigned NumResults); 990 991 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, 992 OverloadCandidate *Candidates, 993 unsigned NumCandidates); 994 995 virtual CodeCompletionAllocator &getAllocator() { 996 return CCTUInfo.getAllocator(); 997 } 998 999 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() { return CCTUInfo; } 1000 }; 1001 1002 } // end namespace clang 1003 1004 #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H 1005