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