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