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