1 //===---------------- SemaCodeComplete.cpp - Code Completion ----*- 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 code-completion semantic actions. 11 // 12 //===----------------------------------------------------------------------===// 13 #include "clang/Sema/SemaInternal.h" 14 #include "clang/AST/DeclObjC.h" 15 #include "clang/AST/ExprCXX.h" 16 #include "clang/AST/ExprObjC.h" 17 #include "clang/Basic/CharInfo.h" 18 #include "clang/Lex/HeaderSearch.h" 19 #include "clang/Lex/MacroInfo.h" 20 #include "clang/Lex/Preprocessor.h" 21 #include "clang/Sema/CodeCompleteConsumer.h" 22 #include "clang/Sema/Lookup.h" 23 #include "clang/Sema/Overload.h" 24 #include "clang/Sema/Scope.h" 25 #include "clang/Sema/ScopeInfo.h" 26 #include "llvm/ADT/DenseSet.h" 27 #include "llvm/ADT/SmallBitVector.h" 28 #include "llvm/ADT/SmallPtrSet.h" 29 #include "llvm/ADT/SmallString.h" 30 #include "llvm/ADT/StringExtras.h" 31 #include "llvm/ADT/StringSwitch.h" 32 #include "llvm/ADT/Twine.h" 33 #include <list> 34 #include <map> 35 #include <vector> 36 37 using namespace clang; 38 using namespace sema; 39 40 namespace { 41 /// \brief A container of code-completion results. 42 class ResultBuilder { 43 public: 44 /// \brief The type of a name-lookup filter, which can be provided to the 45 /// name-lookup routines to specify which declarations should be included in 46 /// the result set (when it returns true) and which declarations should be 47 /// filtered out (returns false). 48 typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const; 49 50 typedef CodeCompletionResult Result; 51 52 private: 53 /// \brief The actual results we have found. 54 std::vector<Result> Results; 55 56 /// \brief A record of all of the declarations we have found and placed 57 /// into the result set, used to ensure that no declaration ever gets into 58 /// the result set twice. 59 llvm::SmallPtrSet<const Decl*, 16> AllDeclsFound; 60 61 typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair; 62 63 /// \brief An entry in the shadow map, which is optimized to store 64 /// a single (declaration, index) mapping (the common case) but 65 /// can also store a list of (declaration, index) mappings. 66 class ShadowMapEntry { 67 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector; 68 69 /// \brief Contains either the solitary NamedDecl * or a vector 70 /// of (declaration, index) pairs. 71 llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector*> DeclOrVector; 72 73 /// \brief When the entry contains a single declaration, this is 74 /// the index associated with that entry. 75 unsigned SingleDeclIndex; 76 77 public: 78 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { } 79 80 void Add(const NamedDecl *ND, unsigned Index) { 81 if (DeclOrVector.isNull()) { 82 // 0 - > 1 elements: just set the single element information. 83 DeclOrVector = ND; 84 SingleDeclIndex = Index; 85 return; 86 } 87 88 if (const NamedDecl *PrevND = 89 DeclOrVector.dyn_cast<const NamedDecl *>()) { 90 // 1 -> 2 elements: create the vector of results and push in the 91 // existing declaration. 92 DeclIndexPairVector *Vec = new DeclIndexPairVector; 93 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex)); 94 DeclOrVector = Vec; 95 } 96 97 // Add the new element to the end of the vector. 98 DeclOrVector.get<DeclIndexPairVector*>()->push_back( 99 DeclIndexPair(ND, Index)); 100 } 101 102 void Destroy() { 103 if (DeclIndexPairVector *Vec 104 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) { 105 delete Vec; 106 DeclOrVector = ((NamedDecl *)nullptr); 107 } 108 } 109 110 // Iteration. 111 class iterator; 112 iterator begin() const; 113 iterator end() const; 114 }; 115 116 /// \brief A mapping from declaration names to the declarations that have 117 /// this name within a particular scope and their index within the list of 118 /// results. 119 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; 120 121 /// \brief The semantic analysis object for which results are being 122 /// produced. 123 Sema &SemaRef; 124 125 /// \brief The allocator used to allocate new code-completion strings. 126 CodeCompletionAllocator &Allocator; 127 128 CodeCompletionTUInfo &CCTUInfo; 129 130 /// \brief If non-NULL, a filter function used to remove any code-completion 131 /// results that are not desirable. 132 LookupFilter Filter; 133 134 /// \brief Whether we should allow declarations as 135 /// nested-name-specifiers that would otherwise be filtered out. 136 bool AllowNestedNameSpecifiers; 137 138 /// \brief If set, the type that we would prefer our resulting value 139 /// declarations to have. 140 /// 141 /// Closely matching the preferred type gives a boost to a result's 142 /// priority. 143 CanQualType PreferredType; 144 145 /// \brief A list of shadow maps, which is used to model name hiding at 146 /// different levels of, e.g., the inheritance hierarchy. 147 std::list<ShadowMap> ShadowMaps; 148 149 /// \brief If we're potentially referring to a C++ member function, the set 150 /// of qualifiers applied to the object type. 151 Qualifiers ObjectTypeQualifiers; 152 153 /// \brief Whether the \p ObjectTypeQualifiers field is active. 154 bool HasObjectTypeQualifiers; 155 156 /// \brief The selector that we prefer. 157 Selector PreferredSelector; 158 159 /// \brief The completion context in which we are gathering results. 160 CodeCompletionContext CompletionContext; 161 162 /// \brief If we are in an instance method definition, the \@implementation 163 /// object. 164 ObjCImplementationDecl *ObjCImplementation; 165 166 void AdjustResultPriorityForDecl(Result &R); 167 168 void MaybeAddConstructorResults(Result R); 169 170 public: 171 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator, 172 CodeCompletionTUInfo &CCTUInfo, 173 const CodeCompletionContext &CompletionContext, 174 LookupFilter Filter = nullptr) 175 : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo), 176 Filter(Filter), 177 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false), 178 CompletionContext(CompletionContext), 179 ObjCImplementation(nullptr) 180 { 181 // If this is an Objective-C instance method definition, dig out the 182 // corresponding implementation. 183 switch (CompletionContext.getKind()) { 184 case CodeCompletionContext::CCC_Expression: 185 case CodeCompletionContext::CCC_ObjCMessageReceiver: 186 case CodeCompletionContext::CCC_ParenthesizedExpression: 187 case CodeCompletionContext::CCC_Statement: 188 case CodeCompletionContext::CCC_Recovery: 189 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) 190 if (Method->isInstanceMethod()) 191 if (ObjCInterfaceDecl *Interface = Method->getClassInterface()) 192 ObjCImplementation = Interface->getImplementation(); 193 break; 194 195 default: 196 break; 197 } 198 } 199 200 /// \brief Determine the priority for a reference to the given declaration. 201 unsigned getBasePriority(const NamedDecl *D); 202 203 /// \brief Whether we should include code patterns in the completion 204 /// results. 205 bool includeCodePatterns() const { 206 return SemaRef.CodeCompleter && 207 SemaRef.CodeCompleter->includeCodePatterns(); 208 } 209 210 /// \brief Set the filter used for code-completion results. 211 void setFilter(LookupFilter Filter) { 212 this->Filter = Filter; 213 } 214 215 Result *data() { return Results.empty()? nullptr : &Results.front(); } 216 unsigned size() const { return Results.size(); } 217 bool empty() const { return Results.empty(); } 218 219 /// \brief Specify the preferred type. 220 void setPreferredType(QualType T) { 221 PreferredType = SemaRef.Context.getCanonicalType(T); 222 } 223 224 /// \brief Set the cv-qualifiers on the object type, for us in filtering 225 /// calls to member functions. 226 /// 227 /// When there are qualifiers in this set, they will be used to filter 228 /// out member functions that aren't available (because there will be a 229 /// cv-qualifier mismatch) or prefer functions with an exact qualifier 230 /// match. 231 void setObjectTypeQualifiers(Qualifiers Quals) { 232 ObjectTypeQualifiers = Quals; 233 HasObjectTypeQualifiers = true; 234 } 235 236 /// \brief Set the preferred selector. 237 /// 238 /// When an Objective-C method declaration result is added, and that 239 /// method's selector matches this preferred selector, we give that method 240 /// a slight priority boost. 241 void setPreferredSelector(Selector Sel) { 242 PreferredSelector = Sel; 243 } 244 245 /// \brief Retrieve the code-completion context for which results are 246 /// being collected. 247 const CodeCompletionContext &getCompletionContext() const { 248 return CompletionContext; 249 } 250 251 /// \brief Specify whether nested-name-specifiers are allowed. 252 void allowNestedNameSpecifiers(bool Allow = true) { 253 AllowNestedNameSpecifiers = Allow; 254 } 255 256 /// \brief Return the semantic analysis object for which we are collecting 257 /// code completion results. 258 Sema &getSema() const { return SemaRef; } 259 260 /// \brief Retrieve the allocator used to allocate code completion strings. 261 CodeCompletionAllocator &getAllocator() const { return Allocator; } 262 263 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; } 264 265 /// \brief Determine whether the given declaration is at all interesting 266 /// as a code-completion result. 267 /// 268 /// \param ND the declaration that we are inspecting. 269 /// 270 /// \param AsNestedNameSpecifier will be set true if this declaration is 271 /// only interesting when it is a nested-name-specifier. 272 bool isInterestingDecl(const NamedDecl *ND, 273 bool &AsNestedNameSpecifier) const; 274 275 /// \brief Check whether the result is hidden by the Hiding declaration. 276 /// 277 /// \returns true if the result is hidden and cannot be found, false if 278 /// the hidden result could still be found. When false, \p R may be 279 /// modified to describe how the result can be found (e.g., via extra 280 /// qualification). 281 bool CheckHiddenResult(Result &R, DeclContext *CurContext, 282 const NamedDecl *Hiding); 283 284 /// \brief Add a new result to this result set (if it isn't already in one 285 /// of the shadow maps), or replace an existing result (for, e.g., a 286 /// redeclaration). 287 /// 288 /// \param R the result to add (if it is unique). 289 /// 290 /// \param CurContext the context in which this result will be named. 291 void MaybeAddResult(Result R, DeclContext *CurContext = nullptr); 292 293 /// \brief Add a new result to this result set, where we already know 294 /// the hiding declaration (if any). 295 /// 296 /// \param R the result to add (if it is unique). 297 /// 298 /// \param CurContext the context in which this result will be named. 299 /// 300 /// \param Hiding the declaration that hides the result. 301 /// 302 /// \param InBaseClass whether the result was found in a base 303 /// class of the searched context. 304 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding, 305 bool InBaseClass); 306 307 /// \brief Add a new non-declaration result to this result set. 308 void AddResult(Result R); 309 310 /// \brief Enter into a new scope. 311 void EnterNewScope(); 312 313 /// \brief Exit from the current scope. 314 void ExitScope(); 315 316 /// \brief Ignore this declaration, if it is seen again. 317 void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); } 318 319 /// \name Name lookup predicates 320 /// 321 /// These predicates can be passed to the name lookup functions to filter the 322 /// results of name lookup. All of the predicates have the same type, so that 323 /// 324 //@{ 325 bool IsOrdinaryName(const NamedDecl *ND) const; 326 bool IsOrdinaryNonTypeName(const NamedDecl *ND) const; 327 bool IsIntegralConstantValue(const NamedDecl *ND) const; 328 bool IsOrdinaryNonValueName(const NamedDecl *ND) const; 329 bool IsNestedNameSpecifier(const NamedDecl *ND) const; 330 bool IsEnum(const NamedDecl *ND) const; 331 bool IsClassOrStruct(const NamedDecl *ND) const; 332 bool IsUnion(const NamedDecl *ND) const; 333 bool IsNamespace(const NamedDecl *ND) const; 334 bool IsNamespaceOrAlias(const NamedDecl *ND) const; 335 bool IsType(const NamedDecl *ND) const; 336 bool IsMember(const NamedDecl *ND) const; 337 bool IsObjCIvar(const NamedDecl *ND) const; 338 bool IsObjCMessageReceiver(const NamedDecl *ND) const; 339 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const; 340 bool IsObjCCollection(const NamedDecl *ND) const; 341 bool IsImpossibleToSatisfy(const NamedDecl *ND) const; 342 //@} 343 }; 344 } 345 346 class ResultBuilder::ShadowMapEntry::iterator { 347 llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator; 348 unsigned SingleDeclIndex; 349 350 public: 351 typedef DeclIndexPair value_type; 352 typedef value_type reference; 353 typedef std::ptrdiff_t difference_type; 354 typedef std::input_iterator_tag iterator_category; 355 356 class pointer { 357 DeclIndexPair Value; 358 359 public: 360 pointer(const DeclIndexPair &Value) : Value(Value) { } 361 362 const DeclIndexPair *operator->() const { 363 return &Value; 364 } 365 }; 366 367 iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {} 368 369 iterator(const NamedDecl *SingleDecl, unsigned Index) 370 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { } 371 372 iterator(const DeclIndexPair *Iterator) 373 : DeclOrIterator(Iterator), SingleDeclIndex(0) { } 374 375 iterator &operator++() { 376 if (DeclOrIterator.is<const NamedDecl *>()) { 377 DeclOrIterator = (NamedDecl *)nullptr; 378 SingleDeclIndex = 0; 379 return *this; 380 } 381 382 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>(); 383 ++I; 384 DeclOrIterator = I; 385 return *this; 386 } 387 388 /*iterator operator++(int) { 389 iterator tmp(*this); 390 ++(*this); 391 return tmp; 392 }*/ 393 394 reference operator*() const { 395 if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>()) 396 return reference(ND, SingleDeclIndex); 397 398 return *DeclOrIterator.get<const DeclIndexPair*>(); 399 } 400 401 pointer operator->() const { 402 return pointer(**this); 403 } 404 405 friend bool operator==(const iterator &X, const iterator &Y) { 406 return X.DeclOrIterator.getOpaqueValue() 407 == Y.DeclOrIterator.getOpaqueValue() && 408 X.SingleDeclIndex == Y.SingleDeclIndex; 409 } 410 411 friend bool operator!=(const iterator &X, const iterator &Y) { 412 return !(X == Y); 413 } 414 }; 415 416 ResultBuilder::ShadowMapEntry::iterator 417 ResultBuilder::ShadowMapEntry::begin() const { 418 if (DeclOrVector.isNull()) 419 return iterator(); 420 421 if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>()) 422 return iterator(ND, SingleDeclIndex); 423 424 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin()); 425 } 426 427 ResultBuilder::ShadowMapEntry::iterator 428 ResultBuilder::ShadowMapEntry::end() const { 429 if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull()) 430 return iterator(); 431 432 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end()); 433 } 434 435 /// \brief Compute the qualification required to get from the current context 436 /// (\p CurContext) to the target context (\p TargetContext). 437 /// 438 /// \param Context the AST context in which the qualification will be used. 439 /// 440 /// \param CurContext the context where an entity is being named, which is 441 /// typically based on the current scope. 442 /// 443 /// \param TargetContext the context in which the named entity actually 444 /// resides. 445 /// 446 /// \returns a nested name specifier that refers into the target context, or 447 /// NULL if no qualification is needed. 448 static NestedNameSpecifier * 449 getRequiredQualification(ASTContext &Context, 450 const DeclContext *CurContext, 451 const DeclContext *TargetContext) { 452 SmallVector<const DeclContext *, 4> TargetParents; 453 454 for (const DeclContext *CommonAncestor = TargetContext; 455 CommonAncestor && !CommonAncestor->Encloses(CurContext); 456 CommonAncestor = CommonAncestor->getLookupParent()) { 457 if (CommonAncestor->isTransparentContext() || 458 CommonAncestor->isFunctionOrMethod()) 459 continue; 460 461 TargetParents.push_back(CommonAncestor); 462 } 463 464 NestedNameSpecifier *Result = nullptr; 465 while (!TargetParents.empty()) { 466 const DeclContext *Parent = TargetParents.pop_back_val(); 467 468 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) { 469 if (!Namespace->getIdentifier()) 470 continue; 471 472 Result = NestedNameSpecifier::Create(Context, Result, Namespace); 473 } 474 else if (const TagDecl *TD = dyn_cast<TagDecl>(Parent)) 475 Result = NestedNameSpecifier::Create(Context, Result, 476 false, 477 Context.getTypeDeclType(TD).getTypePtr()); 478 } 479 return Result; 480 } 481 482 /// Determine whether \p Id is a name reserved for the implementation (C99 483 /// 7.1.3, C++ [lib.global.names]). 484 static bool isReservedName(const IdentifierInfo *Id, 485 bool doubleUnderscoreOnly = false) { 486 if (Id->getLength() < 2) 487 return false; 488 const char *Name = Id->getNameStart(); 489 return Name[0] == '_' && 490 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z' && 491 !doubleUnderscoreOnly)); 492 } 493 494 // Some declarations have reserved names that we don't want to ever show. 495 // Filter out names reserved for the implementation if they come from a 496 // system header. 497 static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) { 498 const IdentifierInfo *Id = ND->getIdentifier(); 499 if (!Id) 500 return false; 501 502 // Ignore reserved names for compiler provided decls. 503 if (isReservedName(Id) && ND->getLocation().isInvalid()) 504 return true; 505 506 // For system headers ignore only double-underscore names. 507 // This allows for system headers providing private symbols with a single 508 // underscore. 509 if (isReservedName(Id, /*doubleUnderscoreOnly=*/true) && 510 SemaRef.SourceMgr.isInSystemHeader( 511 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))) 512 return true; 513 514 return false; 515 } 516 517 bool ResultBuilder::isInterestingDecl(const NamedDecl *ND, 518 bool &AsNestedNameSpecifier) const { 519 AsNestedNameSpecifier = false; 520 521 auto *Named = ND; 522 ND = ND->getUnderlyingDecl(); 523 524 // Skip unnamed entities. 525 if (!ND->getDeclName()) 526 return false; 527 528 // Friend declarations and declarations introduced due to friends are never 529 // added as results. 530 if (ND->getFriendObjectKind() == Decl::FOK_Undeclared) 531 return false; 532 533 // Class template (partial) specializations are never added as results. 534 if (isa<ClassTemplateSpecializationDecl>(ND) || 535 isa<ClassTemplatePartialSpecializationDecl>(ND)) 536 return false; 537 538 // Using declarations themselves are never added as results. 539 if (isa<UsingDecl>(ND)) 540 return false; 541 542 if (shouldIgnoreDueToReservedName(ND, SemaRef)) 543 return false; 544 545 if (Filter == &ResultBuilder::IsNestedNameSpecifier || 546 (isa<NamespaceDecl>(ND) && 547 Filter != &ResultBuilder::IsNamespace && 548 Filter != &ResultBuilder::IsNamespaceOrAlias && 549 Filter != nullptr)) 550 AsNestedNameSpecifier = true; 551 552 // Filter out any unwanted results. 553 if (Filter && !(this->*Filter)(Named)) { 554 // Check whether it is interesting as a nested-name-specifier. 555 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus && 556 IsNestedNameSpecifier(ND) && 557 (Filter != &ResultBuilder::IsMember || 558 (isa<CXXRecordDecl>(ND) && 559 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) { 560 AsNestedNameSpecifier = true; 561 return true; 562 } 563 564 return false; 565 } 566 // ... then it must be interesting! 567 return true; 568 } 569 570 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext, 571 const NamedDecl *Hiding) { 572 // In C, there is no way to refer to a hidden name. 573 // FIXME: This isn't true; we can find a tag name hidden by an ordinary 574 // name if we introduce the tag type. 575 if (!SemaRef.getLangOpts().CPlusPlus) 576 return true; 577 578 const DeclContext *HiddenCtx = 579 R.Declaration->getDeclContext()->getRedeclContext(); 580 581 // There is no way to qualify a name declared in a function or method. 582 if (HiddenCtx->isFunctionOrMethod()) 583 return true; 584 585 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext()) 586 return true; 587 588 // We can refer to the result with the appropriate qualification. Do it. 589 R.Hidden = true; 590 R.QualifierIsInformative = false; 591 592 if (!R.Qualifier) 593 R.Qualifier = getRequiredQualification(SemaRef.Context, 594 CurContext, 595 R.Declaration->getDeclContext()); 596 return false; 597 } 598 599 /// \brief A simplified classification of types used to determine whether two 600 /// types are "similar enough" when adjusting priorities. 601 SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) { 602 switch (T->getTypeClass()) { 603 case Type::Builtin: 604 switch (cast<BuiltinType>(T)->getKind()) { 605 case BuiltinType::Void: 606 return STC_Void; 607 608 case BuiltinType::NullPtr: 609 return STC_Pointer; 610 611 case BuiltinType::Overload: 612 case BuiltinType::Dependent: 613 return STC_Other; 614 615 case BuiltinType::ObjCId: 616 case BuiltinType::ObjCClass: 617 case BuiltinType::ObjCSel: 618 return STC_ObjectiveC; 619 620 default: 621 return STC_Arithmetic; 622 } 623 624 case Type::Complex: 625 return STC_Arithmetic; 626 627 case Type::Pointer: 628 return STC_Pointer; 629 630 case Type::BlockPointer: 631 return STC_Block; 632 633 case Type::LValueReference: 634 case Type::RValueReference: 635 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType()); 636 637 case Type::ConstantArray: 638 case Type::IncompleteArray: 639 case Type::VariableArray: 640 case Type::DependentSizedArray: 641 return STC_Array; 642 643 case Type::DependentSizedExtVector: 644 case Type::Vector: 645 case Type::ExtVector: 646 return STC_Arithmetic; 647 648 case Type::FunctionProto: 649 case Type::FunctionNoProto: 650 return STC_Function; 651 652 case Type::Record: 653 return STC_Record; 654 655 case Type::Enum: 656 return STC_Arithmetic; 657 658 case Type::ObjCObject: 659 case Type::ObjCInterface: 660 case Type::ObjCObjectPointer: 661 return STC_ObjectiveC; 662 663 default: 664 return STC_Other; 665 } 666 } 667 668 /// \brief Get the type that a given expression will have if this declaration 669 /// is used as an expression in its "typical" code-completion form. 670 QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) { 671 ND = cast<NamedDecl>(ND->getUnderlyingDecl()); 672 673 if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND)) 674 return C.getTypeDeclType(Type); 675 if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND)) 676 return C.getObjCInterfaceType(Iface); 677 678 QualType T; 679 if (const FunctionDecl *Function = ND->getAsFunction()) 680 T = Function->getCallResultType(); 681 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) 682 T = Method->getSendResultType(); 683 else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND)) 684 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext())); 685 else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) 686 T = Property->getType(); 687 else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) 688 T = Value->getType(); 689 else 690 return QualType(); 691 692 // Dig through references, function pointers, and block pointers to 693 // get down to the likely type of an expression when the entity is 694 // used. 695 do { 696 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) { 697 T = Ref->getPointeeType(); 698 continue; 699 } 700 701 if (const PointerType *Pointer = T->getAs<PointerType>()) { 702 if (Pointer->getPointeeType()->isFunctionType()) { 703 T = Pointer->getPointeeType(); 704 continue; 705 } 706 707 break; 708 } 709 710 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) { 711 T = Block->getPointeeType(); 712 continue; 713 } 714 715 if (const FunctionType *Function = T->getAs<FunctionType>()) { 716 T = Function->getReturnType(); 717 continue; 718 } 719 720 break; 721 } while (true); 722 723 return T; 724 } 725 726 unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) { 727 if (!ND) 728 return CCP_Unlikely; 729 730 // Context-based decisions. 731 const DeclContext *LexicalDC = ND->getLexicalDeclContext(); 732 if (LexicalDC->isFunctionOrMethod()) { 733 // _cmd is relatively rare 734 if (const ImplicitParamDecl *ImplicitParam = 735 dyn_cast<ImplicitParamDecl>(ND)) 736 if (ImplicitParam->getIdentifier() && 737 ImplicitParam->getIdentifier()->isStr("_cmd")) 738 return CCP_ObjC_cmd; 739 740 return CCP_LocalDeclaration; 741 } 742 743 const DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 744 if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) 745 return CCP_MemberDeclaration; 746 747 // Content-based decisions. 748 if (isa<EnumConstantDecl>(ND)) 749 return CCP_Constant; 750 751 // Use CCP_Type for type declarations unless we're in a statement, Objective-C 752 // message receiver, or parenthesized expression context. There, it's as 753 // likely that the user will want to write a type as other declarations. 754 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) && 755 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement || 756 CompletionContext.getKind() 757 == CodeCompletionContext::CCC_ObjCMessageReceiver || 758 CompletionContext.getKind() 759 == CodeCompletionContext::CCC_ParenthesizedExpression)) 760 return CCP_Type; 761 762 return CCP_Declaration; 763 } 764 765 void ResultBuilder::AdjustResultPriorityForDecl(Result &R) { 766 // If this is an Objective-C method declaration whose selector matches our 767 // preferred selector, give it a priority boost. 768 if (!PreferredSelector.isNull()) 769 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration)) 770 if (PreferredSelector == Method->getSelector()) 771 R.Priority += CCD_SelectorMatch; 772 773 // If we have a preferred type, adjust the priority for results with exactly- 774 // matching or nearly-matching types. 775 if (!PreferredType.isNull()) { 776 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration); 777 if (!T.isNull()) { 778 CanQualType TC = SemaRef.Context.getCanonicalType(T); 779 // Check for exactly-matching types (modulo qualifiers). 780 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC)) 781 R.Priority /= CCF_ExactTypeMatch; 782 // Check for nearly-matching types, based on classification of each. 783 else if ((getSimplifiedTypeClass(PreferredType) 784 == getSimplifiedTypeClass(TC)) && 785 !(PreferredType->isEnumeralType() && TC->isEnumeralType())) 786 R.Priority /= CCF_SimilarTypeMatch; 787 } 788 } 789 } 790 791 void ResultBuilder::MaybeAddConstructorResults(Result R) { 792 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration || 793 !CompletionContext.wantConstructorResults()) 794 return; 795 796 ASTContext &Context = SemaRef.Context; 797 const NamedDecl *D = R.Declaration; 798 const CXXRecordDecl *Record = nullptr; 799 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) 800 Record = ClassTemplate->getTemplatedDecl(); 801 else if ((Record = dyn_cast<CXXRecordDecl>(D))) { 802 // Skip specializations and partial specializations. 803 if (isa<ClassTemplateSpecializationDecl>(Record)) 804 return; 805 } else { 806 // There are no constructors here. 807 return; 808 } 809 810 Record = Record->getDefinition(); 811 if (!Record) 812 return; 813 814 815 QualType RecordTy = Context.getTypeDeclType(Record); 816 DeclarationName ConstructorName 817 = Context.DeclarationNames.getCXXConstructorName( 818 Context.getCanonicalType(RecordTy)); 819 DeclContext::lookup_result Ctors = Record->lookup(ConstructorName); 820 for (DeclContext::lookup_iterator I = Ctors.begin(), 821 E = Ctors.end(); 822 I != E; ++I) { 823 R.Declaration = *I; 824 R.CursorKind = getCursorKindForDecl(R.Declaration); 825 Results.push_back(R); 826 } 827 } 828 829 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) { 830 assert(!ShadowMaps.empty() && "Must enter into a results scope"); 831 832 if (R.Kind != Result::RK_Declaration) { 833 // For non-declaration results, just add the result. 834 Results.push_back(R); 835 return; 836 } 837 838 // Look through using declarations. 839 if (const UsingShadowDecl *Using = 840 dyn_cast<UsingShadowDecl>(R.Declaration)) { 841 MaybeAddResult(Result(Using->getTargetDecl(), 842 getBasePriority(Using->getTargetDecl()), 843 R.Qualifier), 844 CurContext); 845 return; 846 } 847 848 const Decl *CanonDecl = R.Declaration->getCanonicalDecl(); 849 unsigned IDNS = CanonDecl->getIdentifierNamespace(); 850 851 bool AsNestedNameSpecifier = false; 852 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier)) 853 return; 854 855 // C++ constructors are never found by name lookup. 856 if (isa<CXXConstructorDecl>(R.Declaration)) 857 return; 858 859 ShadowMap &SMap = ShadowMaps.back(); 860 ShadowMapEntry::iterator I, IEnd; 861 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName()); 862 if (NamePos != SMap.end()) { 863 I = NamePos->second.begin(); 864 IEnd = NamePos->second.end(); 865 } 866 867 for (; I != IEnd; ++I) { 868 const NamedDecl *ND = I->first; 869 unsigned Index = I->second; 870 if (ND->getCanonicalDecl() == CanonDecl) { 871 // This is a redeclaration. Always pick the newer declaration. 872 Results[Index].Declaration = R.Declaration; 873 874 // We're done. 875 return; 876 } 877 } 878 879 // This is a new declaration in this scope. However, check whether this 880 // declaration name is hidden by a similarly-named declaration in an outer 881 // scope. 882 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end(); 883 --SMEnd; 884 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) { 885 ShadowMapEntry::iterator I, IEnd; 886 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName()); 887 if (NamePos != SM->end()) { 888 I = NamePos->second.begin(); 889 IEnd = NamePos->second.end(); 890 } 891 for (; I != IEnd; ++I) { 892 // A tag declaration does not hide a non-tag declaration. 893 if (I->first->hasTagIdentifierNamespace() && 894 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | 895 Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol))) 896 continue; 897 898 // Protocols are in distinct namespaces from everything else. 899 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) 900 || (IDNS & Decl::IDNS_ObjCProtocol)) && 901 I->first->getIdentifierNamespace() != IDNS) 902 continue; 903 904 // The newly-added result is hidden by an entry in the shadow map. 905 if (CheckHiddenResult(R, CurContext, I->first)) 906 return; 907 908 break; 909 } 910 } 911 912 // Make sure that any given declaration only shows up in the result set once. 913 if (!AllDeclsFound.insert(CanonDecl).second) 914 return; 915 916 // If the filter is for nested-name-specifiers, then this result starts a 917 // nested-name-specifier. 918 if (AsNestedNameSpecifier) { 919 R.StartsNestedNameSpecifier = true; 920 R.Priority = CCP_NestedNameSpecifier; 921 } else 922 AdjustResultPriorityForDecl(R); 923 924 // If this result is supposed to have an informative qualifier, add one. 925 if (R.QualifierIsInformative && !R.Qualifier && 926 !R.StartsNestedNameSpecifier) { 927 const DeclContext *Ctx = R.Declaration->getDeclContext(); 928 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx)) 929 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, 930 Namespace); 931 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx)) 932 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, 933 false, SemaRef.Context.getTypeDeclType(Tag).getTypePtr()); 934 else 935 R.QualifierIsInformative = false; 936 } 937 938 // Insert this result into the set of results and into the current shadow 939 // map. 940 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size()); 941 Results.push_back(R); 942 943 if (!AsNestedNameSpecifier) 944 MaybeAddConstructorResults(R); 945 } 946 947 void ResultBuilder::AddResult(Result R, DeclContext *CurContext, 948 NamedDecl *Hiding, bool InBaseClass = false) { 949 if (R.Kind != Result::RK_Declaration) { 950 // For non-declaration results, just add the result. 951 Results.push_back(R); 952 return; 953 } 954 955 // Look through using declarations. 956 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) { 957 AddResult(Result(Using->getTargetDecl(), 958 getBasePriority(Using->getTargetDecl()), 959 R.Qualifier), 960 CurContext, Hiding); 961 return; 962 } 963 964 bool AsNestedNameSpecifier = false; 965 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier)) 966 return; 967 968 // C++ constructors are never found by name lookup. 969 if (isa<CXXConstructorDecl>(R.Declaration)) 970 return; 971 972 if (Hiding && CheckHiddenResult(R, CurContext, Hiding)) 973 return; 974 975 // Make sure that any given declaration only shows up in the result set once. 976 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second) 977 return; 978 979 // If the filter is for nested-name-specifiers, then this result starts a 980 // nested-name-specifier. 981 if (AsNestedNameSpecifier) { 982 R.StartsNestedNameSpecifier = true; 983 R.Priority = CCP_NestedNameSpecifier; 984 } 985 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass && 986 isa<CXXRecordDecl>(R.Declaration->getDeclContext() 987 ->getRedeclContext())) 988 R.QualifierIsInformative = true; 989 990 // If this result is supposed to have an informative qualifier, add one. 991 if (R.QualifierIsInformative && !R.Qualifier && 992 !R.StartsNestedNameSpecifier) { 993 const DeclContext *Ctx = R.Declaration->getDeclContext(); 994 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx)) 995 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, 996 Namespace); 997 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx)) 998 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, false, 999 SemaRef.Context.getTypeDeclType(Tag).getTypePtr()); 1000 else 1001 R.QualifierIsInformative = false; 1002 } 1003 1004 // Adjust the priority if this result comes from a base class. 1005 if (InBaseClass) 1006 R.Priority += CCD_InBaseClass; 1007 1008 AdjustResultPriorityForDecl(R); 1009 1010 if (HasObjectTypeQualifiers) 1011 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration)) 1012 if (Method->isInstance()) { 1013 Qualifiers MethodQuals 1014 = Qualifiers::fromCVRMask(Method->getTypeQualifiers()); 1015 if (ObjectTypeQualifiers == MethodQuals) 1016 R.Priority += CCD_ObjectQualifierMatch; 1017 else if (ObjectTypeQualifiers - MethodQuals) { 1018 // The method cannot be invoked, because doing so would drop 1019 // qualifiers. 1020 return; 1021 } 1022 } 1023 1024 // Insert this result into the set of results. 1025 Results.push_back(R); 1026 1027 if (!AsNestedNameSpecifier) 1028 MaybeAddConstructorResults(R); 1029 } 1030 1031 void ResultBuilder::AddResult(Result R) { 1032 assert(R.Kind != Result::RK_Declaration && 1033 "Declaration results need more context"); 1034 Results.push_back(R); 1035 } 1036 1037 /// \brief Enter into a new scope. 1038 void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); } 1039 1040 /// \brief Exit from the current scope. 1041 void ResultBuilder::ExitScope() { 1042 for (ShadowMap::iterator E = ShadowMaps.back().begin(), 1043 EEnd = ShadowMaps.back().end(); 1044 E != EEnd; 1045 ++E) 1046 E->second.Destroy(); 1047 1048 ShadowMaps.pop_back(); 1049 } 1050 1051 /// \brief Determines whether this given declaration will be found by 1052 /// ordinary name lookup. 1053 bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const { 1054 ND = cast<NamedDecl>(ND->getUnderlyingDecl()); 1055 1056 // If name lookup finds a local extern declaration, then we are in a 1057 // context where it behaves like an ordinary name. 1058 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern; 1059 if (SemaRef.getLangOpts().CPlusPlus) 1060 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member; 1061 else if (SemaRef.getLangOpts().ObjC1) { 1062 if (isa<ObjCIvarDecl>(ND)) 1063 return true; 1064 } 1065 1066 return ND->getIdentifierNamespace() & IDNS; 1067 } 1068 1069 /// \brief Determines whether this given declaration will be found by 1070 /// ordinary name lookup but is not a type name. 1071 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const { 1072 ND = cast<NamedDecl>(ND->getUnderlyingDecl()); 1073 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) 1074 return false; 1075 1076 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern; 1077 if (SemaRef.getLangOpts().CPlusPlus) 1078 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member; 1079 else if (SemaRef.getLangOpts().ObjC1) { 1080 if (isa<ObjCIvarDecl>(ND)) 1081 return true; 1082 } 1083 1084 return ND->getIdentifierNamespace() & IDNS; 1085 } 1086 1087 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const { 1088 if (!IsOrdinaryNonTypeName(ND)) 1089 return 0; 1090 1091 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl())) 1092 if (VD->getType()->isIntegralOrEnumerationType()) 1093 return true; 1094 1095 return false; 1096 } 1097 1098 /// \brief Determines whether this given declaration will be found by 1099 /// ordinary name lookup. 1100 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const { 1101 ND = cast<NamedDecl>(ND->getUnderlyingDecl()); 1102 1103 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern; 1104 if (SemaRef.getLangOpts().CPlusPlus) 1105 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace; 1106 1107 return (ND->getIdentifierNamespace() & IDNS) && 1108 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) && 1109 !isa<ObjCPropertyDecl>(ND); 1110 } 1111 1112 /// \brief Determines whether the given declaration is suitable as the 1113 /// start of a C++ nested-name-specifier, e.g., a class or namespace. 1114 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const { 1115 // Allow us to find class templates, too. 1116 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) 1117 ND = ClassTemplate->getTemplatedDecl(); 1118 1119 return SemaRef.isAcceptableNestedNameSpecifier(ND); 1120 } 1121 1122 /// \brief Determines whether the given declaration is an enumeration. 1123 bool ResultBuilder::IsEnum(const NamedDecl *ND) const { 1124 return isa<EnumDecl>(ND); 1125 } 1126 1127 /// \brief Determines whether the given declaration is a class or struct. 1128 bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const { 1129 // Allow us to find class templates, too. 1130 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) 1131 ND = ClassTemplate->getTemplatedDecl(); 1132 1133 // For purposes of this check, interfaces match too. 1134 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND)) 1135 return RD->getTagKind() == TTK_Class || 1136 RD->getTagKind() == TTK_Struct || 1137 RD->getTagKind() == TTK_Interface; 1138 1139 return false; 1140 } 1141 1142 /// \brief Determines whether the given declaration is a union. 1143 bool ResultBuilder::IsUnion(const NamedDecl *ND) const { 1144 // Allow us to find class templates, too. 1145 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) 1146 ND = ClassTemplate->getTemplatedDecl(); 1147 1148 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND)) 1149 return RD->getTagKind() == TTK_Union; 1150 1151 return false; 1152 } 1153 1154 /// \brief Determines whether the given declaration is a namespace. 1155 bool ResultBuilder::IsNamespace(const NamedDecl *ND) const { 1156 return isa<NamespaceDecl>(ND); 1157 } 1158 1159 /// \brief Determines whether the given declaration is a namespace or 1160 /// namespace alias. 1161 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const { 1162 return isa<NamespaceDecl>(ND->getUnderlyingDecl()); 1163 } 1164 1165 /// \brief Determines whether the given declaration is a type. 1166 bool ResultBuilder::IsType(const NamedDecl *ND) const { 1167 ND = ND->getUnderlyingDecl(); 1168 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1169 } 1170 1171 /// \brief Determines which members of a class should be visible via 1172 /// "." or "->". Only value declarations, nested name specifiers, and 1173 /// using declarations thereof should show up. 1174 bool ResultBuilder::IsMember(const NamedDecl *ND) const { 1175 ND = ND->getUnderlyingDecl(); 1176 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) || 1177 isa<ObjCPropertyDecl>(ND); 1178 } 1179 1180 static bool isObjCReceiverType(ASTContext &C, QualType T) { 1181 T = C.getCanonicalType(T); 1182 switch (T->getTypeClass()) { 1183 case Type::ObjCObject: 1184 case Type::ObjCInterface: 1185 case Type::ObjCObjectPointer: 1186 return true; 1187 1188 case Type::Builtin: 1189 switch (cast<BuiltinType>(T)->getKind()) { 1190 case BuiltinType::ObjCId: 1191 case BuiltinType::ObjCClass: 1192 case BuiltinType::ObjCSel: 1193 return true; 1194 1195 default: 1196 break; 1197 } 1198 return false; 1199 1200 default: 1201 break; 1202 } 1203 1204 if (!C.getLangOpts().CPlusPlus) 1205 return false; 1206 1207 // FIXME: We could perform more analysis here to determine whether a 1208 // particular class type has any conversions to Objective-C types. For now, 1209 // just accept all class types. 1210 return T->isDependentType() || T->isRecordType(); 1211 } 1212 1213 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const { 1214 QualType T = getDeclUsageType(SemaRef.Context, ND); 1215 if (T.isNull()) 1216 return false; 1217 1218 T = SemaRef.Context.getBaseElementType(T); 1219 return isObjCReceiverType(SemaRef.Context, T); 1220 } 1221 1222 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const { 1223 if (IsObjCMessageReceiver(ND)) 1224 return true; 1225 1226 const VarDecl *Var = dyn_cast<VarDecl>(ND); 1227 if (!Var) 1228 return false; 1229 1230 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>(); 1231 } 1232 1233 bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const { 1234 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) || 1235 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND))) 1236 return false; 1237 1238 QualType T = getDeclUsageType(SemaRef.Context, ND); 1239 if (T.isNull()) 1240 return false; 1241 1242 T = SemaRef.Context.getBaseElementType(T); 1243 return T->isObjCObjectType() || T->isObjCObjectPointerType() || 1244 T->isObjCIdType() || 1245 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType()); 1246 } 1247 1248 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const { 1249 return false; 1250 } 1251 1252 /// \brief Determines whether the given declaration is an Objective-C 1253 /// instance variable. 1254 bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const { 1255 return isa<ObjCIvarDecl>(ND); 1256 } 1257 1258 namespace { 1259 /// \brief Visible declaration consumer that adds a code-completion result 1260 /// for each visible declaration. 1261 class CodeCompletionDeclConsumer : public VisibleDeclConsumer { 1262 ResultBuilder &Results; 1263 DeclContext *CurContext; 1264 1265 public: 1266 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext) 1267 : Results(Results), CurContext(CurContext) { } 1268 1269 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, 1270 bool InBaseClass) override { 1271 bool Accessible = true; 1272 if (Ctx) 1273 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx); 1274 1275 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr, 1276 false, Accessible); 1277 Results.AddResult(Result, CurContext, Hiding, InBaseClass); 1278 } 1279 }; 1280 } 1281 1282 /// \brief Add type specifiers for the current language as keyword results. 1283 static void AddTypeSpecifierResults(const LangOptions &LangOpts, 1284 ResultBuilder &Results) { 1285 typedef CodeCompletionResult Result; 1286 Results.AddResult(Result("short", CCP_Type)); 1287 Results.AddResult(Result("long", CCP_Type)); 1288 Results.AddResult(Result("signed", CCP_Type)); 1289 Results.AddResult(Result("unsigned", CCP_Type)); 1290 Results.AddResult(Result("void", CCP_Type)); 1291 Results.AddResult(Result("char", CCP_Type)); 1292 Results.AddResult(Result("int", CCP_Type)); 1293 Results.AddResult(Result("float", CCP_Type)); 1294 Results.AddResult(Result("double", CCP_Type)); 1295 Results.AddResult(Result("enum", CCP_Type)); 1296 Results.AddResult(Result("struct", CCP_Type)); 1297 Results.AddResult(Result("union", CCP_Type)); 1298 Results.AddResult(Result("const", CCP_Type)); 1299 Results.AddResult(Result("volatile", CCP_Type)); 1300 1301 if (LangOpts.C99) { 1302 // C99-specific 1303 Results.AddResult(Result("_Complex", CCP_Type)); 1304 Results.AddResult(Result("_Imaginary", CCP_Type)); 1305 Results.AddResult(Result("_Bool", CCP_Type)); 1306 Results.AddResult(Result("restrict", CCP_Type)); 1307 } 1308 1309 CodeCompletionBuilder Builder(Results.getAllocator(), 1310 Results.getCodeCompletionTUInfo()); 1311 if (LangOpts.CPlusPlus) { 1312 // C++-specific 1313 Results.AddResult(Result("bool", CCP_Type + 1314 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0))); 1315 Results.AddResult(Result("class", CCP_Type)); 1316 Results.AddResult(Result("wchar_t", CCP_Type)); 1317 1318 // typename qualified-id 1319 Builder.AddTypedTextChunk("typename"); 1320 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1321 Builder.AddPlaceholderChunk("qualifier"); 1322 Builder.AddTextChunk("::"); 1323 Builder.AddPlaceholderChunk("name"); 1324 Results.AddResult(Result(Builder.TakeString())); 1325 1326 if (LangOpts.CPlusPlus11) { 1327 Results.AddResult(Result("auto", CCP_Type)); 1328 Results.AddResult(Result("char16_t", CCP_Type)); 1329 Results.AddResult(Result("char32_t", CCP_Type)); 1330 1331 Builder.AddTypedTextChunk("decltype"); 1332 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1333 Builder.AddPlaceholderChunk("expression"); 1334 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1335 Results.AddResult(Result(Builder.TakeString())); 1336 } 1337 } 1338 1339 // GNU extensions 1340 if (LangOpts.GNUMode) { 1341 // FIXME: Enable when we actually support decimal floating point. 1342 // Results.AddResult(Result("_Decimal32")); 1343 // Results.AddResult(Result("_Decimal64")); 1344 // Results.AddResult(Result("_Decimal128")); 1345 1346 Builder.AddTypedTextChunk("typeof"); 1347 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1348 Builder.AddPlaceholderChunk("expression"); 1349 Results.AddResult(Result(Builder.TakeString())); 1350 1351 Builder.AddTypedTextChunk("typeof"); 1352 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1353 Builder.AddPlaceholderChunk("type"); 1354 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1355 Results.AddResult(Result(Builder.TakeString())); 1356 } 1357 1358 // Nullability 1359 Results.AddResult(Result("_Nonnull", CCP_Type)); 1360 Results.AddResult(Result("_Null_unspecified", CCP_Type)); 1361 Results.AddResult(Result("_Nullable", CCP_Type)); 1362 } 1363 1364 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC, 1365 const LangOptions &LangOpts, 1366 ResultBuilder &Results) { 1367 typedef CodeCompletionResult Result; 1368 // Note: we don't suggest either "auto" or "register", because both 1369 // are pointless as storage specifiers. Elsewhere, we suggest "auto" 1370 // in C++0x as a type specifier. 1371 Results.AddResult(Result("extern")); 1372 Results.AddResult(Result("static")); 1373 } 1374 1375 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC, 1376 const LangOptions &LangOpts, 1377 ResultBuilder &Results) { 1378 typedef CodeCompletionResult Result; 1379 switch (CCC) { 1380 case Sema::PCC_Class: 1381 case Sema::PCC_MemberTemplate: 1382 if (LangOpts.CPlusPlus) { 1383 Results.AddResult(Result("explicit")); 1384 Results.AddResult(Result("friend")); 1385 Results.AddResult(Result("mutable")); 1386 Results.AddResult(Result("virtual")); 1387 } 1388 // Fall through 1389 1390 case Sema::PCC_ObjCInterface: 1391 case Sema::PCC_ObjCImplementation: 1392 case Sema::PCC_Namespace: 1393 case Sema::PCC_Template: 1394 if (LangOpts.CPlusPlus || LangOpts.C99) 1395 Results.AddResult(Result("inline")); 1396 break; 1397 1398 case Sema::PCC_ObjCInstanceVariableList: 1399 case Sema::PCC_Expression: 1400 case Sema::PCC_Statement: 1401 case Sema::PCC_ForInit: 1402 case Sema::PCC_Condition: 1403 case Sema::PCC_RecoveryInFunction: 1404 case Sema::PCC_Type: 1405 case Sema::PCC_ParenthesizedExpression: 1406 case Sema::PCC_LocalDeclarationSpecifiers: 1407 break; 1408 } 1409 } 1410 1411 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt); 1412 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt); 1413 static void AddObjCVisibilityResults(const LangOptions &LangOpts, 1414 ResultBuilder &Results, 1415 bool NeedAt); 1416 static void AddObjCImplementationResults(const LangOptions &LangOpts, 1417 ResultBuilder &Results, 1418 bool NeedAt); 1419 static void AddObjCInterfaceResults(const LangOptions &LangOpts, 1420 ResultBuilder &Results, 1421 bool NeedAt); 1422 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt); 1423 1424 static void AddTypedefResult(ResultBuilder &Results) { 1425 CodeCompletionBuilder Builder(Results.getAllocator(), 1426 Results.getCodeCompletionTUInfo()); 1427 Builder.AddTypedTextChunk("typedef"); 1428 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1429 Builder.AddPlaceholderChunk("type"); 1430 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1431 Builder.AddPlaceholderChunk("name"); 1432 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 1433 } 1434 1435 static bool WantTypesInContext(Sema::ParserCompletionContext CCC, 1436 const LangOptions &LangOpts) { 1437 switch (CCC) { 1438 case Sema::PCC_Namespace: 1439 case Sema::PCC_Class: 1440 case Sema::PCC_ObjCInstanceVariableList: 1441 case Sema::PCC_Template: 1442 case Sema::PCC_MemberTemplate: 1443 case Sema::PCC_Statement: 1444 case Sema::PCC_RecoveryInFunction: 1445 case Sema::PCC_Type: 1446 case Sema::PCC_ParenthesizedExpression: 1447 case Sema::PCC_LocalDeclarationSpecifiers: 1448 return true; 1449 1450 case Sema::PCC_Expression: 1451 case Sema::PCC_Condition: 1452 return LangOpts.CPlusPlus; 1453 1454 case Sema::PCC_ObjCInterface: 1455 case Sema::PCC_ObjCImplementation: 1456 return false; 1457 1458 case Sema::PCC_ForInit: 1459 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99; 1460 } 1461 1462 llvm_unreachable("Invalid ParserCompletionContext!"); 1463 } 1464 1465 static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context, 1466 const Preprocessor &PP) { 1467 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP); 1468 Policy.AnonymousTagLocations = false; 1469 Policy.SuppressStrongLifetime = true; 1470 Policy.SuppressUnwrittenScope = true; 1471 return Policy; 1472 } 1473 1474 /// \brief Retrieve a printing policy suitable for code completion. 1475 static PrintingPolicy getCompletionPrintingPolicy(Sema &S) { 1476 return getCompletionPrintingPolicy(S.Context, S.PP); 1477 } 1478 1479 /// \brief Retrieve the string representation of the given type as a string 1480 /// that has the appropriate lifetime for code completion. 1481 /// 1482 /// This routine provides a fast path where we provide constant strings for 1483 /// common type names. 1484 static const char *GetCompletionTypeString(QualType T, 1485 ASTContext &Context, 1486 const PrintingPolicy &Policy, 1487 CodeCompletionAllocator &Allocator) { 1488 if (!T.getLocalQualifiers()) { 1489 // Built-in type names are constant strings. 1490 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) 1491 return BT->getNameAsCString(Policy); 1492 1493 // Anonymous tag types are constant strings. 1494 if (const TagType *TagT = dyn_cast<TagType>(T)) 1495 if (TagDecl *Tag = TagT->getDecl()) 1496 if (!Tag->hasNameForLinkage()) { 1497 switch (Tag->getTagKind()) { 1498 case TTK_Struct: return "struct <anonymous>"; 1499 case TTK_Interface: return "__interface <anonymous>"; 1500 case TTK_Class: return "class <anonymous>"; 1501 case TTK_Union: return "union <anonymous>"; 1502 case TTK_Enum: return "enum <anonymous>"; 1503 } 1504 } 1505 } 1506 1507 // Slow path: format the type as a string. 1508 std::string Result; 1509 T.getAsStringInternal(Result, Policy); 1510 return Allocator.CopyString(Result); 1511 } 1512 1513 /// \brief Add a completion for "this", if we're in a member function. 1514 static void addThisCompletion(Sema &S, ResultBuilder &Results) { 1515 QualType ThisTy = S.getCurrentThisType(); 1516 if (ThisTy.isNull()) 1517 return; 1518 1519 CodeCompletionAllocator &Allocator = Results.getAllocator(); 1520 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 1521 PrintingPolicy Policy = getCompletionPrintingPolicy(S); 1522 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy, 1523 S.Context, 1524 Policy, 1525 Allocator)); 1526 Builder.AddTypedTextChunk("this"); 1527 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 1528 } 1529 1530 /// \brief Add language constructs that show up for "ordinary" names. 1531 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, 1532 Scope *S, 1533 Sema &SemaRef, 1534 ResultBuilder &Results) { 1535 CodeCompletionAllocator &Allocator = Results.getAllocator(); 1536 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 1537 1538 typedef CodeCompletionResult Result; 1539 switch (CCC) { 1540 case Sema::PCC_Namespace: 1541 if (SemaRef.getLangOpts().CPlusPlus) { 1542 if (Results.includeCodePatterns()) { 1543 // namespace <identifier> { declarations } 1544 Builder.AddTypedTextChunk("namespace"); 1545 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1546 Builder.AddPlaceholderChunk("identifier"); 1547 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1548 Builder.AddPlaceholderChunk("declarations"); 1549 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1550 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1551 Results.AddResult(Result(Builder.TakeString())); 1552 } 1553 1554 // namespace identifier = identifier ; 1555 Builder.AddTypedTextChunk("namespace"); 1556 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1557 Builder.AddPlaceholderChunk("name"); 1558 Builder.AddChunk(CodeCompletionString::CK_Equal); 1559 Builder.AddPlaceholderChunk("namespace"); 1560 Results.AddResult(Result(Builder.TakeString())); 1561 1562 // Using directives 1563 Builder.AddTypedTextChunk("using"); 1564 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1565 Builder.AddTextChunk("namespace"); 1566 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1567 Builder.AddPlaceholderChunk("identifier"); 1568 Results.AddResult(Result(Builder.TakeString())); 1569 1570 // asm(string-literal) 1571 Builder.AddTypedTextChunk("asm"); 1572 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1573 Builder.AddPlaceholderChunk("string-literal"); 1574 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1575 Results.AddResult(Result(Builder.TakeString())); 1576 1577 if (Results.includeCodePatterns()) { 1578 // Explicit template instantiation 1579 Builder.AddTypedTextChunk("template"); 1580 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1581 Builder.AddPlaceholderChunk("declaration"); 1582 Results.AddResult(Result(Builder.TakeString())); 1583 } 1584 } 1585 1586 if (SemaRef.getLangOpts().ObjC1) 1587 AddObjCTopLevelResults(Results, true); 1588 1589 AddTypedefResult(Results); 1590 // Fall through 1591 1592 case Sema::PCC_Class: 1593 if (SemaRef.getLangOpts().CPlusPlus) { 1594 // Using declaration 1595 Builder.AddTypedTextChunk("using"); 1596 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1597 Builder.AddPlaceholderChunk("qualifier"); 1598 Builder.AddTextChunk("::"); 1599 Builder.AddPlaceholderChunk("name"); 1600 Results.AddResult(Result(Builder.TakeString())); 1601 1602 // using typename qualifier::name (only in a dependent context) 1603 if (SemaRef.CurContext->isDependentContext()) { 1604 Builder.AddTypedTextChunk("using"); 1605 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1606 Builder.AddTextChunk("typename"); 1607 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1608 Builder.AddPlaceholderChunk("qualifier"); 1609 Builder.AddTextChunk("::"); 1610 Builder.AddPlaceholderChunk("name"); 1611 Results.AddResult(Result(Builder.TakeString())); 1612 } 1613 1614 if (CCC == Sema::PCC_Class) { 1615 AddTypedefResult(Results); 1616 1617 // public: 1618 Builder.AddTypedTextChunk("public"); 1619 if (Results.includeCodePatterns()) 1620 Builder.AddChunk(CodeCompletionString::CK_Colon); 1621 Results.AddResult(Result(Builder.TakeString())); 1622 1623 // protected: 1624 Builder.AddTypedTextChunk("protected"); 1625 if (Results.includeCodePatterns()) 1626 Builder.AddChunk(CodeCompletionString::CK_Colon); 1627 Results.AddResult(Result(Builder.TakeString())); 1628 1629 // private: 1630 Builder.AddTypedTextChunk("private"); 1631 if (Results.includeCodePatterns()) 1632 Builder.AddChunk(CodeCompletionString::CK_Colon); 1633 Results.AddResult(Result(Builder.TakeString())); 1634 } 1635 } 1636 // Fall through 1637 1638 case Sema::PCC_Template: 1639 case Sema::PCC_MemberTemplate: 1640 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) { 1641 // template < parameters > 1642 Builder.AddTypedTextChunk("template"); 1643 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 1644 Builder.AddPlaceholderChunk("parameters"); 1645 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 1646 Results.AddResult(Result(Builder.TakeString())); 1647 } 1648 1649 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); 1650 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results); 1651 break; 1652 1653 case Sema::PCC_ObjCInterface: 1654 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true); 1655 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); 1656 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results); 1657 break; 1658 1659 case Sema::PCC_ObjCImplementation: 1660 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true); 1661 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); 1662 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results); 1663 break; 1664 1665 case Sema::PCC_ObjCInstanceVariableList: 1666 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true); 1667 break; 1668 1669 case Sema::PCC_RecoveryInFunction: 1670 case Sema::PCC_Statement: { 1671 AddTypedefResult(Results); 1672 1673 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() && 1674 SemaRef.getLangOpts().CXXExceptions) { 1675 Builder.AddTypedTextChunk("try"); 1676 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1677 Builder.AddPlaceholderChunk("statements"); 1678 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1679 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1680 Builder.AddTextChunk("catch"); 1681 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1682 Builder.AddPlaceholderChunk("declaration"); 1683 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1684 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1685 Builder.AddPlaceholderChunk("statements"); 1686 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1687 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1688 Results.AddResult(Result(Builder.TakeString())); 1689 } 1690 if (SemaRef.getLangOpts().ObjC1) 1691 AddObjCStatementResults(Results, true); 1692 1693 if (Results.includeCodePatterns()) { 1694 // if (condition) { statements } 1695 Builder.AddTypedTextChunk("if"); 1696 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1697 if (SemaRef.getLangOpts().CPlusPlus) 1698 Builder.AddPlaceholderChunk("condition"); 1699 else 1700 Builder.AddPlaceholderChunk("expression"); 1701 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1702 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1703 Builder.AddPlaceholderChunk("statements"); 1704 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1705 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1706 Results.AddResult(Result(Builder.TakeString())); 1707 1708 // switch (condition) { } 1709 Builder.AddTypedTextChunk("switch"); 1710 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1711 if (SemaRef.getLangOpts().CPlusPlus) 1712 Builder.AddPlaceholderChunk("condition"); 1713 else 1714 Builder.AddPlaceholderChunk("expression"); 1715 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1716 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1717 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1718 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1719 Results.AddResult(Result(Builder.TakeString())); 1720 } 1721 1722 // Switch-specific statements. 1723 if (!SemaRef.getCurFunction()->SwitchStack.empty()) { 1724 // case expression: 1725 Builder.AddTypedTextChunk("case"); 1726 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1727 Builder.AddPlaceholderChunk("expression"); 1728 Builder.AddChunk(CodeCompletionString::CK_Colon); 1729 Results.AddResult(Result(Builder.TakeString())); 1730 1731 // default: 1732 Builder.AddTypedTextChunk("default"); 1733 Builder.AddChunk(CodeCompletionString::CK_Colon); 1734 Results.AddResult(Result(Builder.TakeString())); 1735 } 1736 1737 if (Results.includeCodePatterns()) { 1738 /// while (condition) { statements } 1739 Builder.AddTypedTextChunk("while"); 1740 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1741 if (SemaRef.getLangOpts().CPlusPlus) 1742 Builder.AddPlaceholderChunk("condition"); 1743 else 1744 Builder.AddPlaceholderChunk("expression"); 1745 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1746 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1747 Builder.AddPlaceholderChunk("statements"); 1748 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1749 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1750 Results.AddResult(Result(Builder.TakeString())); 1751 1752 // do { statements } while ( expression ); 1753 Builder.AddTypedTextChunk("do"); 1754 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1755 Builder.AddPlaceholderChunk("statements"); 1756 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1757 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1758 Builder.AddTextChunk("while"); 1759 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1760 Builder.AddPlaceholderChunk("expression"); 1761 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1762 Results.AddResult(Result(Builder.TakeString())); 1763 1764 // for ( for-init-statement ; condition ; expression ) { statements } 1765 Builder.AddTypedTextChunk("for"); 1766 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1767 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99) 1768 Builder.AddPlaceholderChunk("init-statement"); 1769 else 1770 Builder.AddPlaceholderChunk("init-expression"); 1771 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 1772 Builder.AddPlaceholderChunk("condition"); 1773 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 1774 Builder.AddPlaceholderChunk("inc-expression"); 1775 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1776 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1777 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1778 Builder.AddPlaceholderChunk("statements"); 1779 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1780 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1781 Results.AddResult(Result(Builder.TakeString())); 1782 } 1783 1784 if (S->getContinueParent()) { 1785 // continue ; 1786 Builder.AddTypedTextChunk("continue"); 1787 Results.AddResult(Result(Builder.TakeString())); 1788 } 1789 1790 if (S->getBreakParent()) { 1791 // break ; 1792 Builder.AddTypedTextChunk("break"); 1793 Results.AddResult(Result(Builder.TakeString())); 1794 } 1795 1796 // "return expression ;" or "return ;", depending on whether we 1797 // know the function is void or not. 1798 bool isVoid = false; 1799 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext)) 1800 isVoid = Function->getReturnType()->isVoidType(); 1801 else if (ObjCMethodDecl *Method 1802 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext)) 1803 isVoid = Method->getReturnType()->isVoidType(); 1804 else if (SemaRef.getCurBlock() && 1805 !SemaRef.getCurBlock()->ReturnType.isNull()) 1806 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType(); 1807 Builder.AddTypedTextChunk("return"); 1808 if (!isVoid) { 1809 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1810 Builder.AddPlaceholderChunk("expression"); 1811 } 1812 Results.AddResult(Result(Builder.TakeString())); 1813 1814 // goto identifier ; 1815 Builder.AddTypedTextChunk("goto"); 1816 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1817 Builder.AddPlaceholderChunk("label"); 1818 Results.AddResult(Result(Builder.TakeString())); 1819 1820 // Using directives 1821 Builder.AddTypedTextChunk("using"); 1822 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1823 Builder.AddTextChunk("namespace"); 1824 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1825 Builder.AddPlaceholderChunk("identifier"); 1826 Results.AddResult(Result(Builder.TakeString())); 1827 } 1828 1829 // Fall through (for statement expressions). 1830 case Sema::PCC_ForInit: 1831 case Sema::PCC_Condition: 1832 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); 1833 // Fall through: conditions and statements can have expressions. 1834 1835 case Sema::PCC_ParenthesizedExpression: 1836 if (SemaRef.getLangOpts().ObjCAutoRefCount && 1837 CCC == Sema::PCC_ParenthesizedExpression) { 1838 // (__bridge <type>)<expression> 1839 Builder.AddTypedTextChunk("__bridge"); 1840 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1841 Builder.AddPlaceholderChunk("type"); 1842 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1843 Builder.AddPlaceholderChunk("expression"); 1844 Results.AddResult(Result(Builder.TakeString())); 1845 1846 // (__bridge_transfer <Objective-C type>)<expression> 1847 Builder.AddTypedTextChunk("__bridge_transfer"); 1848 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1849 Builder.AddPlaceholderChunk("Objective-C type"); 1850 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1851 Builder.AddPlaceholderChunk("expression"); 1852 Results.AddResult(Result(Builder.TakeString())); 1853 1854 // (__bridge_retained <CF type>)<expression> 1855 Builder.AddTypedTextChunk("__bridge_retained"); 1856 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1857 Builder.AddPlaceholderChunk("CF type"); 1858 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1859 Builder.AddPlaceholderChunk("expression"); 1860 Results.AddResult(Result(Builder.TakeString())); 1861 } 1862 // Fall through 1863 1864 case Sema::PCC_Expression: { 1865 if (SemaRef.getLangOpts().CPlusPlus) { 1866 // 'this', if we're in a non-static member function. 1867 addThisCompletion(SemaRef, Results); 1868 1869 // true 1870 Builder.AddResultTypeChunk("bool"); 1871 Builder.AddTypedTextChunk("true"); 1872 Results.AddResult(Result(Builder.TakeString())); 1873 1874 // false 1875 Builder.AddResultTypeChunk("bool"); 1876 Builder.AddTypedTextChunk("false"); 1877 Results.AddResult(Result(Builder.TakeString())); 1878 1879 if (SemaRef.getLangOpts().RTTI) { 1880 // dynamic_cast < type-id > ( expression ) 1881 Builder.AddTypedTextChunk("dynamic_cast"); 1882 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 1883 Builder.AddPlaceholderChunk("type"); 1884 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 1885 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1886 Builder.AddPlaceholderChunk("expression"); 1887 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1888 Results.AddResult(Result(Builder.TakeString())); 1889 } 1890 1891 // static_cast < type-id > ( expression ) 1892 Builder.AddTypedTextChunk("static_cast"); 1893 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 1894 Builder.AddPlaceholderChunk("type"); 1895 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 1896 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1897 Builder.AddPlaceholderChunk("expression"); 1898 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1899 Results.AddResult(Result(Builder.TakeString())); 1900 1901 // reinterpret_cast < type-id > ( expression ) 1902 Builder.AddTypedTextChunk("reinterpret_cast"); 1903 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 1904 Builder.AddPlaceholderChunk("type"); 1905 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 1906 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1907 Builder.AddPlaceholderChunk("expression"); 1908 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1909 Results.AddResult(Result(Builder.TakeString())); 1910 1911 // const_cast < type-id > ( expression ) 1912 Builder.AddTypedTextChunk("const_cast"); 1913 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 1914 Builder.AddPlaceholderChunk("type"); 1915 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 1916 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1917 Builder.AddPlaceholderChunk("expression"); 1918 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1919 Results.AddResult(Result(Builder.TakeString())); 1920 1921 if (SemaRef.getLangOpts().RTTI) { 1922 // typeid ( expression-or-type ) 1923 Builder.AddResultTypeChunk("std::type_info"); 1924 Builder.AddTypedTextChunk("typeid"); 1925 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1926 Builder.AddPlaceholderChunk("expression-or-type"); 1927 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1928 Results.AddResult(Result(Builder.TakeString())); 1929 } 1930 1931 // new T ( ... ) 1932 Builder.AddTypedTextChunk("new"); 1933 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1934 Builder.AddPlaceholderChunk("type"); 1935 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1936 Builder.AddPlaceholderChunk("expressions"); 1937 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1938 Results.AddResult(Result(Builder.TakeString())); 1939 1940 // new T [ ] ( ... ) 1941 Builder.AddTypedTextChunk("new"); 1942 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1943 Builder.AddPlaceholderChunk("type"); 1944 Builder.AddChunk(CodeCompletionString::CK_LeftBracket); 1945 Builder.AddPlaceholderChunk("size"); 1946 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 1947 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1948 Builder.AddPlaceholderChunk("expressions"); 1949 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1950 Results.AddResult(Result(Builder.TakeString())); 1951 1952 // delete expression 1953 Builder.AddResultTypeChunk("void"); 1954 Builder.AddTypedTextChunk("delete"); 1955 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1956 Builder.AddPlaceholderChunk("expression"); 1957 Results.AddResult(Result(Builder.TakeString())); 1958 1959 // delete [] expression 1960 Builder.AddResultTypeChunk("void"); 1961 Builder.AddTypedTextChunk("delete"); 1962 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1963 Builder.AddChunk(CodeCompletionString::CK_LeftBracket); 1964 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 1965 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1966 Builder.AddPlaceholderChunk("expression"); 1967 Results.AddResult(Result(Builder.TakeString())); 1968 1969 if (SemaRef.getLangOpts().CXXExceptions) { 1970 // throw expression 1971 Builder.AddResultTypeChunk("void"); 1972 Builder.AddTypedTextChunk("throw"); 1973 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1974 Builder.AddPlaceholderChunk("expression"); 1975 Results.AddResult(Result(Builder.TakeString())); 1976 } 1977 1978 // FIXME: Rethrow? 1979 1980 if (SemaRef.getLangOpts().CPlusPlus11) { 1981 // nullptr 1982 Builder.AddResultTypeChunk("std::nullptr_t"); 1983 Builder.AddTypedTextChunk("nullptr"); 1984 Results.AddResult(Result(Builder.TakeString())); 1985 1986 // alignof 1987 Builder.AddResultTypeChunk("size_t"); 1988 Builder.AddTypedTextChunk("alignof"); 1989 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1990 Builder.AddPlaceholderChunk("type"); 1991 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1992 Results.AddResult(Result(Builder.TakeString())); 1993 1994 // noexcept 1995 Builder.AddResultTypeChunk("bool"); 1996 Builder.AddTypedTextChunk("noexcept"); 1997 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1998 Builder.AddPlaceholderChunk("expression"); 1999 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2000 Results.AddResult(Result(Builder.TakeString())); 2001 2002 // sizeof... expression 2003 Builder.AddResultTypeChunk("size_t"); 2004 Builder.AddTypedTextChunk("sizeof..."); 2005 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2006 Builder.AddPlaceholderChunk("parameter-pack"); 2007 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2008 Results.AddResult(Result(Builder.TakeString())); 2009 } 2010 } 2011 2012 if (SemaRef.getLangOpts().ObjC1) { 2013 // Add "super", if we're in an Objective-C class with a superclass. 2014 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { 2015 // The interface can be NULL. 2016 if (ObjCInterfaceDecl *ID = Method->getClassInterface()) 2017 if (ID->getSuperClass()) { 2018 std::string SuperType; 2019 SuperType = ID->getSuperClass()->getNameAsString(); 2020 if (Method->isInstanceMethod()) 2021 SuperType += " *"; 2022 2023 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType)); 2024 Builder.AddTypedTextChunk("super"); 2025 Results.AddResult(Result(Builder.TakeString())); 2026 } 2027 } 2028 2029 AddObjCExpressionResults(Results, true); 2030 } 2031 2032 if (SemaRef.getLangOpts().C11) { 2033 // _Alignof 2034 Builder.AddResultTypeChunk("size_t"); 2035 if (SemaRef.PP.isMacroDefined("alignof")) 2036 Builder.AddTypedTextChunk("alignof"); 2037 else 2038 Builder.AddTypedTextChunk("_Alignof"); 2039 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2040 Builder.AddPlaceholderChunk("type"); 2041 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2042 Results.AddResult(Result(Builder.TakeString())); 2043 } 2044 2045 // sizeof expression 2046 Builder.AddResultTypeChunk("size_t"); 2047 Builder.AddTypedTextChunk("sizeof"); 2048 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2049 Builder.AddPlaceholderChunk("expression-or-type"); 2050 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2051 Results.AddResult(Result(Builder.TakeString())); 2052 break; 2053 } 2054 2055 case Sema::PCC_Type: 2056 case Sema::PCC_LocalDeclarationSpecifiers: 2057 break; 2058 } 2059 2060 if (WantTypesInContext(CCC, SemaRef.getLangOpts())) 2061 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results); 2062 2063 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type) 2064 Results.AddResult(Result("operator")); 2065 } 2066 2067 /// \brief If the given declaration has an associated type, add it as a result 2068 /// type chunk. 2069 static void AddResultTypeChunk(ASTContext &Context, 2070 const PrintingPolicy &Policy, 2071 const NamedDecl *ND, 2072 QualType BaseType, 2073 CodeCompletionBuilder &Result) { 2074 if (!ND) 2075 return; 2076 2077 // Skip constructors and conversion functions, which have their return types 2078 // built into their names. 2079 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND)) 2080 return; 2081 2082 // Determine the type of the declaration (if it has a type). 2083 QualType T; 2084 if (const FunctionDecl *Function = ND->getAsFunction()) 2085 T = Function->getReturnType(); 2086 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) { 2087 if (!BaseType.isNull()) 2088 T = Method->getSendResultType(BaseType); 2089 else 2090 T = Method->getReturnType(); 2091 } else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND)) 2092 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext())); 2093 else if (isa<UnresolvedUsingValueDecl>(ND)) { 2094 /* Do nothing: ignore unresolved using declarations*/ 2095 } else if (const ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { 2096 if (!BaseType.isNull()) 2097 T = Ivar->getUsageType(BaseType); 2098 else 2099 T = Ivar->getType(); 2100 } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) { 2101 T = Value->getType(); 2102 } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) { 2103 if (!BaseType.isNull()) 2104 T = Property->getUsageType(BaseType); 2105 else 2106 T = Property->getType(); 2107 } 2108 2109 if (T.isNull() || Context.hasSameType(T, Context.DependentTy)) 2110 return; 2111 2112 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy, 2113 Result.getAllocator())); 2114 } 2115 2116 static void MaybeAddSentinel(Preprocessor &PP, 2117 const NamedDecl *FunctionOrMethod, 2118 CodeCompletionBuilder &Result) { 2119 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>()) 2120 if (Sentinel->getSentinel() == 0) { 2121 if (PP.getLangOpts().ObjC1 && PP.isMacroDefined("nil")) 2122 Result.AddTextChunk(", nil"); 2123 else if (PP.isMacroDefined("NULL")) 2124 Result.AddTextChunk(", NULL"); 2125 else 2126 Result.AddTextChunk(", (void*)0"); 2127 } 2128 } 2129 2130 static std::string formatObjCParamQualifiers(unsigned ObjCQuals, 2131 QualType &Type) { 2132 std::string Result; 2133 if (ObjCQuals & Decl::OBJC_TQ_In) 2134 Result += "in "; 2135 else if (ObjCQuals & Decl::OBJC_TQ_Inout) 2136 Result += "inout "; 2137 else if (ObjCQuals & Decl::OBJC_TQ_Out) 2138 Result += "out "; 2139 if (ObjCQuals & Decl::OBJC_TQ_Bycopy) 2140 Result += "bycopy "; 2141 else if (ObjCQuals & Decl::OBJC_TQ_Byref) 2142 Result += "byref "; 2143 if (ObjCQuals & Decl::OBJC_TQ_Oneway) 2144 Result += "oneway "; 2145 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) { 2146 if (auto nullability = AttributedType::stripOuterNullability(Type)) { 2147 switch (*nullability) { 2148 case NullabilityKind::NonNull: 2149 Result += "nonnull "; 2150 break; 2151 2152 case NullabilityKind::Nullable: 2153 Result += "nullable "; 2154 break; 2155 2156 case NullabilityKind::Unspecified: 2157 Result += "null_unspecified "; 2158 break; 2159 } 2160 } 2161 } 2162 return Result; 2163 } 2164 2165 /// \brief Tries to find the most appropriate type location for an Objective-C 2166 /// block placeholder. 2167 /// 2168 /// This function ignores things like typedefs and qualifiers in order to 2169 /// present the most relevant and accurate block placeholders in code completion 2170 /// results. 2171 static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo, 2172 FunctionTypeLoc &Block, 2173 FunctionProtoTypeLoc &BlockProto, 2174 bool SuppressBlock = false) { 2175 if (!TSInfo) 2176 return; 2177 TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc(); 2178 while (true) { 2179 // Look through typedefs. 2180 if (!SuppressBlock) { 2181 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) { 2182 if (TypeSourceInfo *InnerTSInfo = 2183 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) { 2184 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc(); 2185 continue; 2186 } 2187 } 2188 2189 // Look through qualified types 2190 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) { 2191 TL = QualifiedTL.getUnqualifiedLoc(); 2192 continue; 2193 } 2194 2195 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) { 2196 TL = AttrTL.getModifiedLoc(); 2197 continue; 2198 } 2199 } 2200 2201 // Try to get the function prototype behind the block pointer type, 2202 // then we're done. 2203 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) { 2204 TL = BlockPtr.getPointeeLoc().IgnoreParens(); 2205 Block = TL.getAs<FunctionTypeLoc>(); 2206 BlockProto = TL.getAs<FunctionProtoTypeLoc>(); 2207 } 2208 break; 2209 } 2210 } 2211 2212 static std::string 2213 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl, 2214 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, 2215 bool SuppressBlockName = false, 2216 bool SuppressBlock = false, 2217 Optional<ArrayRef<QualType>> ObjCSubsts = None); 2218 2219 static std::string FormatFunctionParameter(const PrintingPolicy &Policy, 2220 const ParmVarDecl *Param, 2221 bool SuppressName = false, 2222 bool SuppressBlock = false, 2223 Optional<ArrayRef<QualType>> ObjCSubsts = None) { 2224 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext()); 2225 if (Param->getType()->isDependentType() || 2226 !Param->getType()->isBlockPointerType()) { 2227 // The argument for a dependent or non-block parameter is a placeholder 2228 // containing that parameter's type. 2229 std::string Result; 2230 2231 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName) 2232 Result = Param->getIdentifier()->getName(); 2233 2234 QualType Type = Param->getType(); 2235 if (ObjCSubsts) 2236 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts, 2237 ObjCSubstitutionContext::Parameter); 2238 if (ObjCMethodParam) { 2239 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(), 2240 Type); 2241 Result += Type.getAsString(Policy) + ")"; 2242 if (Param->getIdentifier() && !SuppressName) 2243 Result += Param->getIdentifier()->getName(); 2244 } else { 2245 Type.getAsStringInternal(Result, Policy); 2246 } 2247 return Result; 2248 } 2249 2250 // The argument for a block pointer parameter is a block literal with 2251 // the appropriate type. 2252 FunctionTypeLoc Block; 2253 FunctionProtoTypeLoc BlockProto; 2254 findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto, 2255 SuppressBlock); 2256 2257 if (!Block) { 2258 // We were unable to find a FunctionProtoTypeLoc with parameter names 2259 // for the block; just use the parameter type as a placeholder. 2260 std::string Result; 2261 if (!ObjCMethodParam && Param->getIdentifier()) 2262 Result = Param->getIdentifier()->getName(); 2263 2264 QualType Type = Param->getType().getUnqualifiedType(); 2265 2266 if (ObjCMethodParam) { 2267 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(), 2268 Type); 2269 Result += Type.getAsString(Policy) + Result + ")"; 2270 if (Param->getIdentifier()) 2271 Result += Param->getIdentifier()->getName(); 2272 } else { 2273 Type.getAsStringInternal(Result, Policy); 2274 } 2275 2276 return Result; 2277 } 2278 2279 // We have the function prototype behind the block pointer type, as it was 2280 // written in the source. 2281 return formatBlockPlaceholder(Policy, Param, Block, BlockProto, 2282 /*SuppressBlockName=*/false, SuppressBlock, 2283 ObjCSubsts); 2284 } 2285 2286 /// \brief Returns a placeholder string that corresponds to an Objective-C block 2287 /// declaration. 2288 /// 2289 /// \param BlockDecl A declaration with an Objective-C block type. 2290 /// 2291 /// \param Block The most relevant type location for that block type. 2292 /// 2293 /// \param SuppressBlockName Determines wether or not the name of the block 2294 /// declaration is included in the resulting string. 2295 static std::string 2296 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl, 2297 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, 2298 bool SuppressBlockName, bool SuppressBlock, 2299 Optional<ArrayRef<QualType>> ObjCSubsts) { 2300 std::string Result; 2301 QualType ResultType = Block.getTypePtr()->getReturnType(); 2302 if (ObjCSubsts) 2303 ResultType = 2304 ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts, 2305 ObjCSubstitutionContext::Result); 2306 if (!ResultType->isVoidType() || SuppressBlock) 2307 ResultType.getAsStringInternal(Result, Policy); 2308 2309 // Format the parameter list. 2310 std::string Params; 2311 if (!BlockProto || Block.getNumParams() == 0) { 2312 if (BlockProto && BlockProto.getTypePtr()->isVariadic()) 2313 Params = "(...)"; 2314 else 2315 Params = "(void)"; 2316 } else { 2317 Params += "("; 2318 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) { 2319 if (I) 2320 Params += ", "; 2321 Params += FormatFunctionParameter(Policy, Block.getParam(I), 2322 /*SuppressName=*/false, 2323 /*SuppressBlock=*/true, ObjCSubsts); 2324 2325 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic()) 2326 Params += ", ..."; 2327 } 2328 Params += ")"; 2329 } 2330 2331 if (SuppressBlock) { 2332 // Format as a parameter. 2333 Result = Result + " (^"; 2334 if (!SuppressBlockName && BlockDecl->getIdentifier()) 2335 Result += BlockDecl->getIdentifier()->getName(); 2336 Result += ")"; 2337 Result += Params; 2338 } else { 2339 // Format as a block literal argument. 2340 Result = '^' + Result; 2341 Result += Params; 2342 2343 if (!SuppressBlockName && BlockDecl->getIdentifier()) 2344 Result += BlockDecl->getIdentifier()->getName(); 2345 } 2346 2347 return Result; 2348 } 2349 2350 /// \brief Add function parameter chunks to the given code completion string. 2351 static void AddFunctionParameterChunks(Preprocessor &PP, 2352 const PrintingPolicy &Policy, 2353 const FunctionDecl *Function, 2354 CodeCompletionBuilder &Result, 2355 unsigned Start = 0, 2356 bool InOptional = false) { 2357 bool FirstParameter = true; 2358 2359 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) { 2360 const ParmVarDecl *Param = Function->getParamDecl(P); 2361 2362 if (Param->hasDefaultArg() && !InOptional) { 2363 // When we see an optional default argument, put that argument and 2364 // the remaining default arguments into a new, optional string. 2365 CodeCompletionBuilder Opt(Result.getAllocator(), 2366 Result.getCodeCompletionTUInfo()); 2367 if (!FirstParameter) 2368 Opt.AddChunk(CodeCompletionString::CK_Comma); 2369 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true); 2370 Result.AddOptionalChunk(Opt.TakeString()); 2371 break; 2372 } 2373 2374 if (FirstParameter) 2375 FirstParameter = false; 2376 else 2377 Result.AddChunk(CodeCompletionString::CK_Comma); 2378 2379 InOptional = false; 2380 2381 // Format the placeholder string. 2382 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param); 2383 2384 if (Function->isVariadic() && P == N - 1) 2385 PlaceholderStr += ", ..."; 2386 2387 // Add the placeholder string. 2388 Result.AddPlaceholderChunk( 2389 Result.getAllocator().CopyString(PlaceholderStr)); 2390 } 2391 2392 if (const FunctionProtoType *Proto 2393 = Function->getType()->getAs<FunctionProtoType>()) 2394 if (Proto->isVariadic()) { 2395 if (Proto->getNumParams() == 0) 2396 Result.AddPlaceholderChunk("..."); 2397 2398 MaybeAddSentinel(PP, Function, Result); 2399 } 2400 } 2401 2402 /// \brief Add template parameter chunks to the given code completion string. 2403 static void AddTemplateParameterChunks(ASTContext &Context, 2404 const PrintingPolicy &Policy, 2405 const TemplateDecl *Template, 2406 CodeCompletionBuilder &Result, 2407 unsigned MaxParameters = 0, 2408 unsigned Start = 0, 2409 bool InDefaultArg = false) { 2410 bool FirstParameter = true; 2411 2412 // Prefer to take the template parameter names from the first declaration of 2413 // the template. 2414 Template = cast<TemplateDecl>(Template->getCanonicalDecl()); 2415 2416 TemplateParameterList *Params = Template->getTemplateParameters(); 2417 TemplateParameterList::iterator PEnd = Params->end(); 2418 if (MaxParameters) 2419 PEnd = Params->begin() + MaxParameters; 2420 for (TemplateParameterList::iterator P = Params->begin() + Start; 2421 P != PEnd; ++P) { 2422 bool HasDefaultArg = false; 2423 std::string PlaceholderStr; 2424 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 2425 if (TTP->wasDeclaredWithTypename()) 2426 PlaceholderStr = "typename"; 2427 else 2428 PlaceholderStr = "class"; 2429 2430 if (TTP->getIdentifier()) { 2431 PlaceholderStr += ' '; 2432 PlaceholderStr += TTP->getIdentifier()->getName(); 2433 } 2434 2435 HasDefaultArg = TTP->hasDefaultArgument(); 2436 } else if (NonTypeTemplateParmDecl *NTTP 2437 = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 2438 if (NTTP->getIdentifier()) 2439 PlaceholderStr = NTTP->getIdentifier()->getName(); 2440 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy); 2441 HasDefaultArg = NTTP->hasDefaultArgument(); 2442 } else { 2443 assert(isa<TemplateTemplateParmDecl>(*P)); 2444 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 2445 2446 // Since putting the template argument list into the placeholder would 2447 // be very, very long, we just use an abbreviation. 2448 PlaceholderStr = "template<...> class"; 2449 if (TTP->getIdentifier()) { 2450 PlaceholderStr += ' '; 2451 PlaceholderStr += TTP->getIdentifier()->getName(); 2452 } 2453 2454 HasDefaultArg = TTP->hasDefaultArgument(); 2455 } 2456 2457 if (HasDefaultArg && !InDefaultArg) { 2458 // When we see an optional default argument, put that argument and 2459 // the remaining default arguments into a new, optional string. 2460 CodeCompletionBuilder Opt(Result.getAllocator(), 2461 Result.getCodeCompletionTUInfo()); 2462 if (!FirstParameter) 2463 Opt.AddChunk(CodeCompletionString::CK_Comma); 2464 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters, 2465 P - Params->begin(), true); 2466 Result.AddOptionalChunk(Opt.TakeString()); 2467 break; 2468 } 2469 2470 InDefaultArg = false; 2471 2472 if (FirstParameter) 2473 FirstParameter = false; 2474 else 2475 Result.AddChunk(CodeCompletionString::CK_Comma); 2476 2477 // Add the placeholder string. 2478 Result.AddPlaceholderChunk( 2479 Result.getAllocator().CopyString(PlaceholderStr)); 2480 } 2481 } 2482 2483 /// \brief Add a qualifier to the given code-completion string, if the 2484 /// provided nested-name-specifier is non-NULL. 2485 static void 2486 AddQualifierToCompletionString(CodeCompletionBuilder &Result, 2487 NestedNameSpecifier *Qualifier, 2488 bool QualifierIsInformative, 2489 ASTContext &Context, 2490 const PrintingPolicy &Policy) { 2491 if (!Qualifier) 2492 return; 2493 2494 std::string PrintedNNS; 2495 { 2496 llvm::raw_string_ostream OS(PrintedNNS); 2497 Qualifier->print(OS, Policy); 2498 } 2499 if (QualifierIsInformative) 2500 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS)); 2501 else 2502 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS)); 2503 } 2504 2505 static void 2506 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result, 2507 const FunctionDecl *Function) { 2508 const FunctionProtoType *Proto 2509 = Function->getType()->getAs<FunctionProtoType>(); 2510 if (!Proto || !Proto->getTypeQuals()) 2511 return; 2512 2513 // FIXME: Add ref-qualifier! 2514 2515 // Handle single qualifiers without copying 2516 if (Proto->getTypeQuals() == Qualifiers::Const) { 2517 Result.AddInformativeChunk(" const"); 2518 return; 2519 } 2520 2521 if (Proto->getTypeQuals() == Qualifiers::Volatile) { 2522 Result.AddInformativeChunk(" volatile"); 2523 return; 2524 } 2525 2526 if (Proto->getTypeQuals() == Qualifiers::Restrict) { 2527 Result.AddInformativeChunk(" restrict"); 2528 return; 2529 } 2530 2531 // Handle multiple qualifiers. 2532 std::string QualsStr; 2533 if (Proto->isConst()) 2534 QualsStr += " const"; 2535 if (Proto->isVolatile()) 2536 QualsStr += " volatile"; 2537 if (Proto->isRestrict()) 2538 QualsStr += " restrict"; 2539 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr)); 2540 } 2541 2542 /// \brief Add the name of the given declaration 2543 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy, 2544 const NamedDecl *ND, 2545 CodeCompletionBuilder &Result) { 2546 DeclarationName Name = ND->getDeclName(); 2547 if (!Name) 2548 return; 2549 2550 switch (Name.getNameKind()) { 2551 case DeclarationName::CXXOperatorName: { 2552 const char *OperatorName = nullptr; 2553 switch (Name.getCXXOverloadedOperator()) { 2554 case OO_None: 2555 case OO_Conditional: 2556 case NUM_OVERLOADED_OPERATORS: 2557 OperatorName = "operator"; 2558 break; 2559 2560 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 2561 case OO_##Name: OperatorName = "operator" Spelling; break; 2562 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) 2563 #include "clang/Basic/OperatorKinds.def" 2564 2565 case OO_New: OperatorName = "operator new"; break; 2566 case OO_Delete: OperatorName = "operator delete"; break; 2567 case OO_Array_New: OperatorName = "operator new[]"; break; 2568 case OO_Array_Delete: OperatorName = "operator delete[]"; break; 2569 case OO_Call: OperatorName = "operator()"; break; 2570 case OO_Subscript: OperatorName = "operator[]"; break; 2571 } 2572 Result.AddTypedTextChunk(OperatorName); 2573 break; 2574 } 2575 2576 case DeclarationName::Identifier: 2577 case DeclarationName::CXXConversionFunctionName: 2578 case DeclarationName::CXXDestructorName: 2579 case DeclarationName::CXXLiteralOperatorName: 2580 Result.AddTypedTextChunk( 2581 Result.getAllocator().CopyString(ND->getNameAsString())); 2582 break; 2583 2584 case DeclarationName::CXXUsingDirective: 2585 case DeclarationName::ObjCZeroArgSelector: 2586 case DeclarationName::ObjCOneArgSelector: 2587 case DeclarationName::ObjCMultiArgSelector: 2588 break; 2589 2590 case DeclarationName::CXXConstructorName: { 2591 CXXRecordDecl *Record = nullptr; 2592 QualType Ty = Name.getCXXNameType(); 2593 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) 2594 Record = cast<CXXRecordDecl>(RecordTy->getDecl()); 2595 else if (const InjectedClassNameType *InjectedTy 2596 = Ty->getAs<InjectedClassNameType>()) 2597 Record = InjectedTy->getDecl(); 2598 else { 2599 Result.AddTypedTextChunk( 2600 Result.getAllocator().CopyString(ND->getNameAsString())); 2601 break; 2602 } 2603 2604 Result.AddTypedTextChunk( 2605 Result.getAllocator().CopyString(Record->getNameAsString())); 2606 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) { 2607 Result.AddChunk(CodeCompletionString::CK_LeftAngle); 2608 AddTemplateParameterChunks(Context, Policy, Template, Result); 2609 Result.AddChunk(CodeCompletionString::CK_RightAngle); 2610 } 2611 break; 2612 } 2613 } 2614 } 2615 2616 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S, 2617 const CodeCompletionContext &CCContext, 2618 CodeCompletionAllocator &Allocator, 2619 CodeCompletionTUInfo &CCTUInfo, 2620 bool IncludeBriefComments) { 2621 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator, 2622 CCTUInfo, IncludeBriefComments); 2623 } 2624 2625 /// \brief If possible, create a new code completion string for the given 2626 /// result. 2627 /// 2628 /// \returns Either a new, heap-allocated code completion string describing 2629 /// how to use this result, or NULL to indicate that the string or name of the 2630 /// result is all that is needed. 2631 CodeCompletionString * 2632 CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx, 2633 Preprocessor &PP, 2634 const CodeCompletionContext &CCContext, 2635 CodeCompletionAllocator &Allocator, 2636 CodeCompletionTUInfo &CCTUInfo, 2637 bool IncludeBriefComments) { 2638 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability); 2639 2640 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP); 2641 if (Kind == RK_Pattern) { 2642 Pattern->Priority = Priority; 2643 Pattern->Availability = Availability; 2644 2645 if (Declaration) { 2646 Result.addParentContext(Declaration->getDeclContext()); 2647 Pattern->ParentName = Result.getParentName(); 2648 // Provide code completion comment for self.GetterName where 2649 // GetterName is the getter method for a property with name 2650 // different from the property name (declared via a property 2651 // getter attribute. 2652 const NamedDecl *ND = Declaration; 2653 if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND)) 2654 if (M->isPropertyAccessor()) 2655 if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl()) 2656 if (PDecl->getGetterName() == M->getSelector() && 2657 PDecl->getIdentifier() != M->getIdentifier()) { 2658 if (const RawComment *RC = 2659 Ctx.getRawCommentForAnyRedecl(M)) { 2660 Result.addBriefComment(RC->getBriefText(Ctx)); 2661 Pattern->BriefComment = Result.getBriefComment(); 2662 } 2663 else if (const RawComment *RC = 2664 Ctx.getRawCommentForAnyRedecl(PDecl)) { 2665 Result.addBriefComment(RC->getBriefText(Ctx)); 2666 Pattern->BriefComment = Result.getBriefComment(); 2667 } 2668 } 2669 } 2670 2671 return Pattern; 2672 } 2673 2674 if (Kind == RK_Keyword) { 2675 Result.AddTypedTextChunk(Keyword); 2676 return Result.TakeString(); 2677 } 2678 2679 if (Kind == RK_Macro) { 2680 const MacroInfo *MI = PP.getMacroInfo(Macro); 2681 Result.AddTypedTextChunk( 2682 Result.getAllocator().CopyString(Macro->getName())); 2683 2684 if (!MI || !MI->isFunctionLike()) 2685 return Result.TakeString(); 2686 2687 // Format a function-like macro with placeholders for the arguments. 2688 Result.AddChunk(CodeCompletionString::CK_LeftParen); 2689 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end(); 2690 2691 // C99 variadic macros add __VA_ARGS__ at the end. Skip it. 2692 if (MI->isC99Varargs()) { 2693 --AEnd; 2694 2695 if (A == AEnd) { 2696 Result.AddPlaceholderChunk("..."); 2697 } 2698 } 2699 2700 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) { 2701 if (A != MI->arg_begin()) 2702 Result.AddChunk(CodeCompletionString::CK_Comma); 2703 2704 if (MI->isVariadic() && (A+1) == AEnd) { 2705 SmallString<32> Arg = (*A)->getName(); 2706 if (MI->isC99Varargs()) 2707 Arg += ", ..."; 2708 else 2709 Arg += "..."; 2710 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg)); 2711 break; 2712 } 2713 2714 // Non-variadic macros are simple. 2715 Result.AddPlaceholderChunk( 2716 Result.getAllocator().CopyString((*A)->getName())); 2717 } 2718 Result.AddChunk(CodeCompletionString::CK_RightParen); 2719 return Result.TakeString(); 2720 } 2721 2722 assert(Kind == RK_Declaration && "Missed a result kind?"); 2723 const NamedDecl *ND = Declaration; 2724 Result.addParentContext(ND->getDeclContext()); 2725 2726 if (IncludeBriefComments) { 2727 // Add documentation comment, if it exists. 2728 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) { 2729 Result.addBriefComment(RC->getBriefText(Ctx)); 2730 } 2731 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 2732 if (OMD->isPropertyAccessor()) 2733 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) 2734 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl)) 2735 Result.addBriefComment(RC->getBriefText(Ctx)); 2736 } 2737 2738 if (StartsNestedNameSpecifier) { 2739 Result.AddTypedTextChunk( 2740 Result.getAllocator().CopyString(ND->getNameAsString())); 2741 Result.AddTextChunk("::"); 2742 return Result.TakeString(); 2743 } 2744 2745 for (const auto *I : ND->specific_attrs<AnnotateAttr>()) 2746 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation())); 2747 2748 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result); 2749 2750 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) { 2751 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 2752 Ctx, Policy); 2753 AddTypedNameChunk(Ctx, Policy, ND, Result); 2754 Result.AddChunk(CodeCompletionString::CK_LeftParen); 2755 AddFunctionParameterChunks(PP, Policy, Function, Result); 2756 Result.AddChunk(CodeCompletionString::CK_RightParen); 2757 AddFunctionTypeQualsToCompletionString(Result, Function); 2758 return Result.TakeString(); 2759 } 2760 2761 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) { 2762 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 2763 Ctx, Policy); 2764 FunctionDecl *Function = FunTmpl->getTemplatedDecl(); 2765 AddTypedNameChunk(Ctx, Policy, Function, Result); 2766 2767 // Figure out which template parameters are deduced (or have default 2768 // arguments). 2769 llvm::SmallBitVector Deduced; 2770 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced); 2771 unsigned LastDeducibleArgument; 2772 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0; 2773 --LastDeducibleArgument) { 2774 if (!Deduced[LastDeducibleArgument - 1]) { 2775 // C++0x: Figure out if the template argument has a default. If so, 2776 // the user doesn't need to type this argument. 2777 // FIXME: We need to abstract template parameters better! 2778 bool HasDefaultArg = false; 2779 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam( 2780 LastDeducibleArgument - 1); 2781 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 2782 HasDefaultArg = TTP->hasDefaultArgument(); 2783 else if (NonTypeTemplateParmDecl *NTTP 2784 = dyn_cast<NonTypeTemplateParmDecl>(Param)) 2785 HasDefaultArg = NTTP->hasDefaultArgument(); 2786 else { 2787 assert(isa<TemplateTemplateParmDecl>(Param)); 2788 HasDefaultArg 2789 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument(); 2790 } 2791 2792 if (!HasDefaultArg) 2793 break; 2794 } 2795 } 2796 2797 if (LastDeducibleArgument) { 2798 // Some of the function template arguments cannot be deduced from a 2799 // function call, so we introduce an explicit template argument list 2800 // containing all of the arguments up to the first deducible argument. 2801 Result.AddChunk(CodeCompletionString::CK_LeftAngle); 2802 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result, 2803 LastDeducibleArgument); 2804 Result.AddChunk(CodeCompletionString::CK_RightAngle); 2805 } 2806 2807 // Add the function parameters 2808 Result.AddChunk(CodeCompletionString::CK_LeftParen); 2809 AddFunctionParameterChunks(PP, Policy, Function, Result); 2810 Result.AddChunk(CodeCompletionString::CK_RightParen); 2811 AddFunctionTypeQualsToCompletionString(Result, Function); 2812 return Result.TakeString(); 2813 } 2814 2815 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) { 2816 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 2817 Ctx, Policy); 2818 Result.AddTypedTextChunk( 2819 Result.getAllocator().CopyString(Template->getNameAsString())); 2820 Result.AddChunk(CodeCompletionString::CK_LeftAngle); 2821 AddTemplateParameterChunks(Ctx, Policy, Template, Result); 2822 Result.AddChunk(CodeCompletionString::CK_RightAngle); 2823 return Result.TakeString(); 2824 } 2825 2826 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) { 2827 Selector Sel = Method->getSelector(); 2828 if (Sel.isUnarySelector()) { 2829 Result.AddTypedTextChunk(Result.getAllocator().CopyString( 2830 Sel.getNameForSlot(0))); 2831 return Result.TakeString(); 2832 } 2833 2834 std::string SelName = Sel.getNameForSlot(0).str(); 2835 SelName += ':'; 2836 if (StartParameter == 0) 2837 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName)); 2838 else { 2839 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName)); 2840 2841 // If there is only one parameter, and we're past it, add an empty 2842 // typed-text chunk since there is nothing to type. 2843 if (Method->param_size() == 1) 2844 Result.AddTypedTextChunk(""); 2845 } 2846 unsigned Idx = 0; 2847 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(), 2848 PEnd = Method->param_end(); 2849 P != PEnd; (void)++P, ++Idx) { 2850 if (Idx > 0) { 2851 std::string Keyword; 2852 if (Idx > StartParameter) 2853 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2854 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx)) 2855 Keyword += II->getName(); 2856 Keyword += ":"; 2857 if (Idx < StartParameter || AllParametersAreInformative) 2858 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword)); 2859 else 2860 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword)); 2861 } 2862 2863 // If we're before the starting parameter, skip the placeholder. 2864 if (Idx < StartParameter) 2865 continue; 2866 2867 std::string Arg; 2868 QualType ParamType = (*P)->getType(); 2869 Optional<ArrayRef<QualType>> ObjCSubsts; 2870 if (!CCContext.getBaseType().isNull()) 2871 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method); 2872 2873 if (ParamType->isBlockPointerType() && !DeclaringEntity) 2874 Arg = FormatFunctionParameter(Policy, *P, true, 2875 /*SuppressBlock=*/false, 2876 ObjCSubsts); 2877 else { 2878 if (ObjCSubsts) 2879 ParamType = ParamType.substObjCTypeArgs(Ctx, *ObjCSubsts, 2880 ObjCSubstitutionContext::Parameter); 2881 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(), 2882 ParamType); 2883 Arg += ParamType.getAsString(Policy) + ")"; 2884 if (IdentifierInfo *II = (*P)->getIdentifier()) 2885 if (DeclaringEntity || AllParametersAreInformative) 2886 Arg += II->getName(); 2887 } 2888 2889 if (Method->isVariadic() && (P + 1) == PEnd) 2890 Arg += ", ..."; 2891 2892 if (DeclaringEntity) 2893 Result.AddTextChunk(Result.getAllocator().CopyString(Arg)); 2894 else if (AllParametersAreInformative) 2895 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg)); 2896 else 2897 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg)); 2898 } 2899 2900 if (Method->isVariadic()) { 2901 if (Method->param_size() == 0) { 2902 if (DeclaringEntity) 2903 Result.AddTextChunk(", ..."); 2904 else if (AllParametersAreInformative) 2905 Result.AddInformativeChunk(", ..."); 2906 else 2907 Result.AddPlaceholderChunk(", ..."); 2908 } 2909 2910 MaybeAddSentinel(PP, Method, Result); 2911 } 2912 2913 return Result.TakeString(); 2914 } 2915 2916 if (Qualifier) 2917 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 2918 Ctx, Policy); 2919 2920 Result.AddTypedTextChunk( 2921 Result.getAllocator().CopyString(ND->getNameAsString())); 2922 return Result.TakeString(); 2923 } 2924 2925 /// \brief Add function overload parameter chunks to the given code completion 2926 /// string. 2927 static void AddOverloadParameterChunks(ASTContext &Context, 2928 const PrintingPolicy &Policy, 2929 const FunctionDecl *Function, 2930 const FunctionProtoType *Prototype, 2931 CodeCompletionBuilder &Result, 2932 unsigned CurrentArg, 2933 unsigned Start = 0, 2934 bool InOptional = false) { 2935 bool FirstParameter = true; 2936 unsigned NumParams = Function ? Function->getNumParams() 2937 : Prototype->getNumParams(); 2938 2939 for (unsigned P = Start; P != NumParams; ++P) { 2940 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) { 2941 // When we see an optional default argument, put that argument and 2942 // the remaining default arguments into a new, optional string. 2943 CodeCompletionBuilder Opt(Result.getAllocator(), 2944 Result.getCodeCompletionTUInfo()); 2945 if (!FirstParameter) 2946 Opt.AddChunk(CodeCompletionString::CK_Comma); 2947 // Optional sections are nested. 2948 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt, 2949 CurrentArg, P, /*InOptional=*/true); 2950 Result.AddOptionalChunk(Opt.TakeString()); 2951 return; 2952 } 2953 2954 if (FirstParameter) 2955 FirstParameter = false; 2956 else 2957 Result.AddChunk(CodeCompletionString::CK_Comma); 2958 2959 InOptional = false; 2960 2961 // Format the placeholder string. 2962 std::string Placeholder; 2963 if (Function) 2964 Placeholder = FormatFunctionParameter(Policy, Function->getParamDecl(P)); 2965 else 2966 Placeholder = Prototype->getParamType(P).getAsString(Policy); 2967 2968 if (P == CurrentArg) 2969 Result.AddCurrentParameterChunk( 2970 Result.getAllocator().CopyString(Placeholder)); 2971 else 2972 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder)); 2973 } 2974 2975 if (Prototype && Prototype->isVariadic()) { 2976 CodeCompletionBuilder Opt(Result.getAllocator(), 2977 Result.getCodeCompletionTUInfo()); 2978 if (!FirstParameter) 2979 Opt.AddChunk(CodeCompletionString::CK_Comma); 2980 2981 if (CurrentArg < NumParams) 2982 Opt.AddPlaceholderChunk("..."); 2983 else 2984 Opt.AddCurrentParameterChunk("..."); 2985 2986 Result.AddOptionalChunk(Opt.TakeString()); 2987 } 2988 } 2989 2990 CodeCompletionString * 2991 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString( 2992 unsigned CurrentArg, Sema &S, 2993 CodeCompletionAllocator &Allocator, 2994 CodeCompletionTUInfo &CCTUInfo, 2995 bool IncludeBriefComments) const { 2996 PrintingPolicy Policy = getCompletionPrintingPolicy(S); 2997 2998 // FIXME: Set priority, availability appropriately. 2999 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available); 3000 FunctionDecl *FDecl = getFunction(); 3001 const FunctionProtoType *Proto 3002 = dyn_cast<FunctionProtoType>(getFunctionType()); 3003 if (!FDecl && !Proto) { 3004 // Function without a prototype. Just give the return type and a 3005 // highlighted ellipsis. 3006 const FunctionType *FT = getFunctionType(); 3007 Result.AddResultTypeChunk(Result.getAllocator().CopyString( 3008 FT->getReturnType().getAsString(Policy))); 3009 Result.AddChunk(CodeCompletionString::CK_LeftParen); 3010 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "..."); 3011 Result.AddChunk(CodeCompletionString::CK_RightParen); 3012 return Result.TakeString(); 3013 } 3014 3015 if (FDecl) { 3016 if (IncludeBriefComments && CurrentArg < FDecl->getNumParams()) 3017 if (auto RC = S.getASTContext().getRawCommentForAnyRedecl( 3018 FDecl->getParamDecl(CurrentArg))) 3019 Result.addBriefComment(RC->getBriefText(S.getASTContext())); 3020 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result); 3021 Result.AddTextChunk( 3022 Result.getAllocator().CopyString(FDecl->getNameAsString())); 3023 } else { 3024 Result.AddResultTypeChunk( 3025 Result.getAllocator().CopyString( 3026 Proto->getReturnType().getAsString(Policy))); 3027 } 3028 3029 Result.AddChunk(CodeCompletionString::CK_LeftParen); 3030 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result, 3031 CurrentArg); 3032 Result.AddChunk(CodeCompletionString::CK_RightParen); 3033 3034 return Result.TakeString(); 3035 } 3036 3037 unsigned clang::getMacroUsagePriority(StringRef MacroName, 3038 const LangOptions &LangOpts, 3039 bool PreferredTypeIsPointer) { 3040 unsigned Priority = CCP_Macro; 3041 3042 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants. 3043 if (MacroName.equals("nil") || MacroName.equals("NULL") || 3044 MacroName.equals("Nil")) { 3045 Priority = CCP_Constant; 3046 if (PreferredTypeIsPointer) 3047 Priority = Priority / CCF_SimilarTypeMatch; 3048 } 3049 // Treat "YES", "NO", "true", and "false" as constants. 3050 else if (MacroName.equals("YES") || MacroName.equals("NO") || 3051 MacroName.equals("true") || MacroName.equals("false")) 3052 Priority = CCP_Constant; 3053 // Treat "bool" as a type. 3054 else if (MacroName.equals("bool")) 3055 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0); 3056 3057 3058 return Priority; 3059 } 3060 3061 CXCursorKind clang::getCursorKindForDecl(const Decl *D) { 3062 if (!D) 3063 return CXCursor_UnexposedDecl; 3064 3065 switch (D->getKind()) { 3066 case Decl::Enum: return CXCursor_EnumDecl; 3067 case Decl::EnumConstant: return CXCursor_EnumConstantDecl; 3068 case Decl::Field: return CXCursor_FieldDecl; 3069 case Decl::Function: 3070 return CXCursor_FunctionDecl; 3071 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl; 3072 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl; 3073 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl; 3074 3075 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl; 3076 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl; 3077 case Decl::ObjCMethod: 3078 return cast<ObjCMethodDecl>(D)->isInstanceMethod() 3079 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl; 3080 case Decl::CXXMethod: return CXCursor_CXXMethod; 3081 case Decl::CXXConstructor: return CXCursor_Constructor; 3082 case Decl::CXXDestructor: return CXCursor_Destructor; 3083 case Decl::CXXConversion: return CXCursor_ConversionFunction; 3084 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl; 3085 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl; 3086 case Decl::ParmVar: return CXCursor_ParmDecl; 3087 case Decl::Typedef: return CXCursor_TypedefDecl; 3088 case Decl::TypeAlias: return CXCursor_TypeAliasDecl; 3089 case Decl::TypeAliasTemplate: return CXCursor_TypeAliasTemplateDecl; 3090 case Decl::Var: return CXCursor_VarDecl; 3091 case Decl::Namespace: return CXCursor_Namespace; 3092 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias; 3093 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter; 3094 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter; 3095 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter; 3096 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate; 3097 case Decl::ClassTemplate: return CXCursor_ClassTemplate; 3098 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier; 3099 case Decl::ClassTemplatePartialSpecialization: 3100 return CXCursor_ClassTemplatePartialSpecialization; 3101 case Decl::UsingDirective: return CXCursor_UsingDirective; 3102 case Decl::StaticAssert: return CXCursor_StaticAssert; 3103 case Decl::Friend: return CXCursor_FriendDecl; 3104 case Decl::TranslationUnit: return CXCursor_TranslationUnit; 3105 3106 case Decl::Using: 3107 case Decl::UnresolvedUsingValue: 3108 case Decl::UnresolvedUsingTypename: 3109 return CXCursor_UsingDeclaration; 3110 3111 case Decl::ObjCPropertyImpl: 3112 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) { 3113 case ObjCPropertyImplDecl::Dynamic: 3114 return CXCursor_ObjCDynamicDecl; 3115 3116 case ObjCPropertyImplDecl::Synthesize: 3117 return CXCursor_ObjCSynthesizeDecl; 3118 } 3119 3120 case Decl::Import: 3121 return CXCursor_ModuleImportDecl; 3122 3123 case Decl::ObjCTypeParam: return CXCursor_TemplateTypeParameter; 3124 3125 default: 3126 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) { 3127 switch (TD->getTagKind()) { 3128 case TTK_Interface: // fall through 3129 case TTK_Struct: return CXCursor_StructDecl; 3130 case TTK_Class: return CXCursor_ClassDecl; 3131 case TTK_Union: return CXCursor_UnionDecl; 3132 case TTK_Enum: return CXCursor_EnumDecl; 3133 } 3134 } 3135 } 3136 3137 return CXCursor_UnexposedDecl; 3138 } 3139 3140 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results, 3141 bool IncludeUndefined, 3142 bool TargetTypeIsPointer = false) { 3143 typedef CodeCompletionResult Result; 3144 3145 Results.EnterNewScope(); 3146 3147 for (Preprocessor::macro_iterator M = PP.macro_begin(), 3148 MEnd = PP.macro_end(); 3149 M != MEnd; ++M) { 3150 auto MD = PP.getMacroDefinition(M->first); 3151 if (IncludeUndefined || MD) { 3152 if (MacroInfo *MI = MD.getMacroInfo()) 3153 if (MI->isUsedForHeaderGuard()) 3154 continue; 3155 3156 Results.AddResult(Result(M->first, 3157 getMacroUsagePriority(M->first->getName(), 3158 PP.getLangOpts(), 3159 TargetTypeIsPointer))); 3160 } 3161 } 3162 3163 Results.ExitScope(); 3164 3165 } 3166 3167 static void AddPrettyFunctionResults(const LangOptions &LangOpts, 3168 ResultBuilder &Results) { 3169 typedef CodeCompletionResult Result; 3170 3171 Results.EnterNewScope(); 3172 3173 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant)); 3174 Results.AddResult(Result("__FUNCTION__", CCP_Constant)); 3175 if (LangOpts.C99 || LangOpts.CPlusPlus11) 3176 Results.AddResult(Result("__func__", CCP_Constant)); 3177 Results.ExitScope(); 3178 } 3179 3180 static void HandleCodeCompleteResults(Sema *S, 3181 CodeCompleteConsumer *CodeCompleter, 3182 CodeCompletionContext Context, 3183 CodeCompletionResult *Results, 3184 unsigned NumResults) { 3185 if (CodeCompleter) 3186 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults); 3187 } 3188 3189 static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S, 3190 Sema::ParserCompletionContext PCC) { 3191 switch (PCC) { 3192 case Sema::PCC_Namespace: 3193 return CodeCompletionContext::CCC_TopLevel; 3194 3195 case Sema::PCC_Class: 3196 return CodeCompletionContext::CCC_ClassStructUnion; 3197 3198 case Sema::PCC_ObjCInterface: 3199 return CodeCompletionContext::CCC_ObjCInterface; 3200 3201 case Sema::PCC_ObjCImplementation: 3202 return CodeCompletionContext::CCC_ObjCImplementation; 3203 3204 case Sema::PCC_ObjCInstanceVariableList: 3205 return CodeCompletionContext::CCC_ObjCIvarList; 3206 3207 case Sema::PCC_Template: 3208 case Sema::PCC_MemberTemplate: 3209 if (S.CurContext->isFileContext()) 3210 return CodeCompletionContext::CCC_TopLevel; 3211 if (S.CurContext->isRecord()) 3212 return CodeCompletionContext::CCC_ClassStructUnion; 3213 return CodeCompletionContext::CCC_Other; 3214 3215 case Sema::PCC_RecoveryInFunction: 3216 return CodeCompletionContext::CCC_Recovery; 3217 3218 case Sema::PCC_ForInit: 3219 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 || 3220 S.getLangOpts().ObjC1) 3221 return CodeCompletionContext::CCC_ParenthesizedExpression; 3222 else 3223 return CodeCompletionContext::CCC_Expression; 3224 3225 case Sema::PCC_Expression: 3226 case Sema::PCC_Condition: 3227 return CodeCompletionContext::CCC_Expression; 3228 3229 case Sema::PCC_Statement: 3230 return CodeCompletionContext::CCC_Statement; 3231 3232 case Sema::PCC_Type: 3233 return CodeCompletionContext::CCC_Type; 3234 3235 case Sema::PCC_ParenthesizedExpression: 3236 return CodeCompletionContext::CCC_ParenthesizedExpression; 3237 3238 case Sema::PCC_LocalDeclarationSpecifiers: 3239 return CodeCompletionContext::CCC_Type; 3240 } 3241 3242 llvm_unreachable("Invalid ParserCompletionContext!"); 3243 } 3244 3245 /// \brief If we're in a C++ virtual member function, add completion results 3246 /// that invoke the functions we override, since it's common to invoke the 3247 /// overridden function as well as adding new functionality. 3248 /// 3249 /// \param S The semantic analysis object for which we are generating results. 3250 /// 3251 /// \param InContext This context in which the nested-name-specifier preceding 3252 /// the code-completion point 3253 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext, 3254 ResultBuilder &Results) { 3255 // Look through blocks. 3256 DeclContext *CurContext = S.CurContext; 3257 while (isa<BlockDecl>(CurContext)) 3258 CurContext = CurContext->getParent(); 3259 3260 3261 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext); 3262 if (!Method || !Method->isVirtual()) 3263 return; 3264 3265 // We need to have names for all of the parameters, if we're going to 3266 // generate a forwarding call. 3267 for (auto P : Method->parameters()) 3268 if (!P->getDeclName()) 3269 return; 3270 3271 PrintingPolicy Policy = getCompletionPrintingPolicy(S); 3272 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(), 3273 MEnd = Method->end_overridden_methods(); 3274 M != MEnd; ++M) { 3275 CodeCompletionBuilder Builder(Results.getAllocator(), 3276 Results.getCodeCompletionTUInfo()); 3277 const CXXMethodDecl *Overridden = *M; 3278 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl()) 3279 continue; 3280 3281 // If we need a nested-name-specifier, add one now. 3282 if (!InContext) { 3283 NestedNameSpecifier *NNS 3284 = getRequiredQualification(S.Context, CurContext, 3285 Overridden->getDeclContext()); 3286 if (NNS) { 3287 std::string Str; 3288 llvm::raw_string_ostream OS(Str); 3289 NNS->print(OS, Policy); 3290 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str())); 3291 } 3292 } else if (!InContext->Equals(Overridden->getDeclContext())) 3293 continue; 3294 3295 Builder.AddTypedTextChunk(Results.getAllocator().CopyString( 3296 Overridden->getNameAsString())); 3297 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3298 bool FirstParam = true; 3299 for (auto P : Method->parameters()) { 3300 if (FirstParam) 3301 FirstParam = false; 3302 else 3303 Builder.AddChunk(CodeCompletionString::CK_Comma); 3304 3305 Builder.AddPlaceholderChunk( 3306 Results.getAllocator().CopyString(P->getIdentifier()->getName())); 3307 } 3308 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3309 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 3310 CCP_SuperCompletion, 3311 CXCursor_CXXMethod, 3312 CXAvailability_Available, 3313 Overridden)); 3314 Results.Ignore(Overridden); 3315 } 3316 } 3317 3318 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc, 3319 ModuleIdPath Path) { 3320 typedef CodeCompletionResult Result; 3321 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3322 CodeCompleter->getCodeCompletionTUInfo(), 3323 CodeCompletionContext::CCC_Other); 3324 Results.EnterNewScope(); 3325 3326 CodeCompletionAllocator &Allocator = Results.getAllocator(); 3327 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 3328 typedef CodeCompletionResult Result; 3329 if (Path.empty()) { 3330 // Enumerate all top-level modules. 3331 SmallVector<Module *, 8> Modules; 3332 PP.getHeaderSearchInfo().collectAllModules(Modules); 3333 for (unsigned I = 0, N = Modules.size(); I != N; ++I) { 3334 Builder.AddTypedTextChunk( 3335 Builder.getAllocator().CopyString(Modules[I]->Name)); 3336 Results.AddResult(Result(Builder.TakeString(), 3337 CCP_Declaration, 3338 CXCursor_ModuleImportDecl, 3339 Modules[I]->isAvailable() 3340 ? CXAvailability_Available 3341 : CXAvailability_NotAvailable)); 3342 } 3343 } else if (getLangOpts().Modules) { 3344 // Load the named module. 3345 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 3346 Module::AllVisible, 3347 /*IsInclusionDirective=*/false); 3348 // Enumerate submodules. 3349 if (Mod) { 3350 for (Module::submodule_iterator Sub = Mod->submodule_begin(), 3351 SubEnd = Mod->submodule_end(); 3352 Sub != SubEnd; ++Sub) { 3353 3354 Builder.AddTypedTextChunk( 3355 Builder.getAllocator().CopyString((*Sub)->Name)); 3356 Results.AddResult(Result(Builder.TakeString(), 3357 CCP_Declaration, 3358 CXCursor_ModuleImportDecl, 3359 (*Sub)->isAvailable() 3360 ? CXAvailability_Available 3361 : CXAvailability_NotAvailable)); 3362 } 3363 } 3364 } 3365 Results.ExitScope(); 3366 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 3367 Results.data(),Results.size()); 3368 } 3369 3370 void Sema::CodeCompleteOrdinaryName(Scope *S, 3371 ParserCompletionContext CompletionContext) { 3372 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3373 CodeCompleter->getCodeCompletionTUInfo(), 3374 mapCodeCompletionContext(*this, CompletionContext)); 3375 Results.EnterNewScope(); 3376 3377 // Determine how to filter results, e.g., so that the names of 3378 // values (functions, enumerators, function templates, etc.) are 3379 // only allowed where we can have an expression. 3380 switch (CompletionContext) { 3381 case PCC_Namespace: 3382 case PCC_Class: 3383 case PCC_ObjCInterface: 3384 case PCC_ObjCImplementation: 3385 case PCC_ObjCInstanceVariableList: 3386 case PCC_Template: 3387 case PCC_MemberTemplate: 3388 case PCC_Type: 3389 case PCC_LocalDeclarationSpecifiers: 3390 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 3391 break; 3392 3393 case PCC_Statement: 3394 case PCC_ParenthesizedExpression: 3395 case PCC_Expression: 3396 case PCC_ForInit: 3397 case PCC_Condition: 3398 if (WantTypesInContext(CompletionContext, getLangOpts())) 3399 Results.setFilter(&ResultBuilder::IsOrdinaryName); 3400 else 3401 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); 3402 3403 if (getLangOpts().CPlusPlus) 3404 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results); 3405 break; 3406 3407 case PCC_RecoveryInFunction: 3408 // Unfiltered 3409 break; 3410 } 3411 3412 // If we are in a C++ non-static member function, check the qualifiers on 3413 // the member function to filter/prioritize the results list. 3414 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext)) 3415 if (CurMethod->isInstance()) 3416 Results.setObjectTypeQualifiers( 3417 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers())); 3418 3419 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3420 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3421 CodeCompleter->includeGlobals()); 3422 3423 AddOrdinaryNameResults(CompletionContext, S, *this, Results); 3424 Results.ExitScope(); 3425 3426 switch (CompletionContext) { 3427 case PCC_ParenthesizedExpression: 3428 case PCC_Expression: 3429 case PCC_Statement: 3430 case PCC_RecoveryInFunction: 3431 if (S->getFnParent()) 3432 AddPrettyFunctionResults(getLangOpts(), Results); 3433 break; 3434 3435 case PCC_Namespace: 3436 case PCC_Class: 3437 case PCC_ObjCInterface: 3438 case PCC_ObjCImplementation: 3439 case PCC_ObjCInstanceVariableList: 3440 case PCC_Template: 3441 case PCC_MemberTemplate: 3442 case PCC_ForInit: 3443 case PCC_Condition: 3444 case PCC_Type: 3445 case PCC_LocalDeclarationSpecifiers: 3446 break; 3447 } 3448 3449 if (CodeCompleter->includeMacros()) 3450 AddMacroResults(PP, Results, false); 3451 3452 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 3453 Results.data(),Results.size()); 3454 } 3455 3456 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 3457 ParsedType Receiver, 3458 ArrayRef<IdentifierInfo *> SelIdents, 3459 bool AtArgumentExpression, 3460 bool IsSuper, 3461 ResultBuilder &Results); 3462 3463 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 3464 bool AllowNonIdentifiers, 3465 bool AllowNestedNameSpecifiers) { 3466 typedef CodeCompletionResult Result; 3467 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3468 CodeCompleter->getCodeCompletionTUInfo(), 3469 AllowNestedNameSpecifiers 3470 ? CodeCompletionContext::CCC_PotentiallyQualifiedName 3471 : CodeCompletionContext::CCC_Name); 3472 Results.EnterNewScope(); 3473 3474 // Type qualifiers can come after names. 3475 Results.AddResult(Result("const")); 3476 Results.AddResult(Result("volatile")); 3477 if (getLangOpts().C99) 3478 Results.AddResult(Result("restrict")); 3479 3480 if (getLangOpts().CPlusPlus) { 3481 if (AllowNonIdentifiers) { 3482 Results.AddResult(Result("operator")); 3483 } 3484 3485 // Add nested-name-specifiers. 3486 if (AllowNestedNameSpecifiers) { 3487 Results.allowNestedNameSpecifiers(); 3488 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy); 3489 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3490 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, 3491 CodeCompleter->includeGlobals()); 3492 Results.setFilter(nullptr); 3493 } 3494 } 3495 Results.ExitScope(); 3496 3497 // If we're in a context where we might have an expression (rather than a 3498 // declaration), and what we've seen so far is an Objective-C type that could 3499 // be a receiver of a class message, this may be a class message send with 3500 // the initial opening bracket '[' missing. Add appropriate completions. 3501 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers && 3502 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && 3503 DS.getTypeSpecType() == DeclSpec::TST_typename && 3504 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified && 3505 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 3506 !DS.isTypeAltiVecVector() && 3507 S && 3508 (S->getFlags() & Scope::DeclScope) != 0 && 3509 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope | 3510 Scope::FunctionPrototypeScope | 3511 Scope::AtCatchScope)) == 0) { 3512 ParsedType T = DS.getRepAsType(); 3513 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType()) 3514 AddClassMessageCompletions(*this, S, T, None, false, false, Results); 3515 } 3516 3517 // Note that we intentionally suppress macro results here, since we do not 3518 // encourage using macros to produce the names of entities. 3519 3520 HandleCodeCompleteResults(this, CodeCompleter, 3521 Results.getCompletionContext(), 3522 Results.data(), Results.size()); 3523 } 3524 3525 struct Sema::CodeCompleteExpressionData { 3526 CodeCompleteExpressionData(QualType PreferredType = QualType()) 3527 : PreferredType(PreferredType), IntegralConstantExpression(false), 3528 ObjCCollection(false) { } 3529 3530 QualType PreferredType; 3531 bool IntegralConstantExpression; 3532 bool ObjCCollection; 3533 SmallVector<Decl *, 4> IgnoreDecls; 3534 }; 3535 3536 /// \brief Perform code-completion in an expression context when we know what 3537 /// type we're looking for. 3538 void Sema::CodeCompleteExpression(Scope *S, 3539 const CodeCompleteExpressionData &Data) { 3540 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3541 CodeCompleter->getCodeCompletionTUInfo(), 3542 CodeCompletionContext::CCC_Expression); 3543 if (Data.ObjCCollection) 3544 Results.setFilter(&ResultBuilder::IsObjCCollection); 3545 else if (Data.IntegralConstantExpression) 3546 Results.setFilter(&ResultBuilder::IsIntegralConstantValue); 3547 else if (WantTypesInContext(PCC_Expression, getLangOpts())) 3548 Results.setFilter(&ResultBuilder::IsOrdinaryName); 3549 else 3550 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); 3551 3552 if (!Data.PreferredType.isNull()) 3553 Results.setPreferredType(Data.PreferredType.getNonReferenceType()); 3554 3555 // Ignore any declarations that we were told that we don't care about. 3556 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I) 3557 Results.Ignore(Data.IgnoreDecls[I]); 3558 3559 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3560 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3561 CodeCompleter->includeGlobals()); 3562 3563 Results.EnterNewScope(); 3564 AddOrdinaryNameResults(PCC_Expression, S, *this, Results); 3565 Results.ExitScope(); 3566 3567 bool PreferredTypeIsPointer = false; 3568 if (!Data.PreferredType.isNull()) 3569 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() 3570 || Data.PreferredType->isMemberPointerType() 3571 || Data.PreferredType->isBlockPointerType(); 3572 3573 if (S->getFnParent() && 3574 !Data.ObjCCollection && 3575 !Data.IntegralConstantExpression) 3576 AddPrettyFunctionResults(getLangOpts(), Results); 3577 3578 if (CodeCompleter->includeMacros()) 3579 AddMacroResults(PP, Results, false, PreferredTypeIsPointer); 3580 HandleCodeCompleteResults(this, CodeCompleter, 3581 CodeCompletionContext(CodeCompletionContext::CCC_Expression, 3582 Data.PreferredType), 3583 Results.data(),Results.size()); 3584 } 3585 3586 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) { 3587 if (E.isInvalid()) 3588 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction); 3589 else if (getLangOpts().ObjC1) 3590 CodeCompleteObjCInstanceMessage(S, E.get(), None, false); 3591 } 3592 3593 /// \brief The set of properties that have already been added, referenced by 3594 /// property name. 3595 typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet; 3596 3597 /// \brief Retrieve the container definition, if any? 3598 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) { 3599 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 3600 if (Interface->hasDefinition()) 3601 return Interface->getDefinition(); 3602 3603 return Interface; 3604 } 3605 3606 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 3607 if (Protocol->hasDefinition()) 3608 return Protocol->getDefinition(); 3609 3610 return Protocol; 3611 } 3612 return Container; 3613 } 3614 3615 static void AddObjCProperties(const CodeCompletionContext &CCContext, 3616 ObjCContainerDecl *Container, 3617 bool AllowCategories, bool AllowNullaryMethods, 3618 DeclContext *CurContext, 3619 AddedPropertiesSet &AddedProperties, 3620 ResultBuilder &Results, 3621 bool IsBaseExprStatement = false) { 3622 typedef CodeCompletionResult Result; 3623 3624 // Retrieve the definition. 3625 Container = getContainerDef(Container); 3626 3627 // Add properties in this container. 3628 for (const auto *P : Container->instance_properties()) { 3629 if (!AddedProperties.insert(P->getIdentifier()).second) 3630 continue; 3631 3632 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr), 3633 CurContext); 3634 3635 // Provide additional block setter completion iff the base expression is a 3636 // statement. 3637 if (!P->isReadOnly() && IsBaseExprStatement && 3638 P->getType().getTypePtr()->isBlockPointerType()) { 3639 FunctionTypeLoc BlockLoc; 3640 FunctionProtoTypeLoc BlockProtoLoc; 3641 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc, 3642 BlockProtoLoc); 3643 3644 // Provide block setter completion only when we are able to find 3645 // the FunctionProtoTypeLoc with parameter names for the block. 3646 if (BlockLoc) { 3647 CodeCompletionBuilder Builder(Results.getAllocator(), 3648 Results.getCodeCompletionTUInfo()); 3649 AddResultTypeChunk(Container->getASTContext(), 3650 getCompletionPrintingPolicy(Results.getSema()), P, 3651 CCContext.getBaseType(), Builder); 3652 Builder.AddTypedTextChunk( 3653 Results.getAllocator().CopyString(P->getName())); 3654 Builder.AddChunk(CodeCompletionString::CK_Equal); 3655 3656 std::string PlaceholderStr = formatBlockPlaceholder( 3657 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc, 3658 BlockProtoLoc, /*SuppressBlockName=*/true); 3659 // Add the placeholder string. 3660 Builder.AddPlaceholderChunk( 3661 Builder.getAllocator().CopyString(PlaceholderStr)); 3662 3663 Results.MaybeAddResult( 3664 Result(Builder.TakeString(), P, 3665 Results.getBasePriority(P) + CCD_BlockPropertySetter), 3666 CurContext); 3667 } 3668 } 3669 } 3670 3671 // Add nullary methods 3672 if (AllowNullaryMethods) { 3673 ASTContext &Context = Container->getASTContext(); 3674 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 3675 for (auto *M : Container->methods()) { 3676 if (M->getSelector().isUnarySelector()) 3677 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0)) 3678 if (AddedProperties.insert(Name).second) { 3679 CodeCompletionBuilder Builder(Results.getAllocator(), 3680 Results.getCodeCompletionTUInfo()); 3681 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), 3682 Builder); 3683 Builder.AddTypedTextChunk( 3684 Results.getAllocator().CopyString(Name->getName())); 3685 3686 Results.MaybeAddResult(Result(Builder.TakeString(), M, 3687 CCP_MemberDeclaration + CCD_MethodAsProperty), 3688 CurContext); 3689 } 3690 } 3691 } 3692 3693 3694 // Add properties in referenced protocols. 3695 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 3696 for (auto *P : Protocol->protocols()) 3697 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, 3698 CurContext, AddedProperties, Results, 3699 IsBaseExprStatement); 3700 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){ 3701 if (AllowCategories) { 3702 // Look through categories. 3703 for (auto *Cat : IFace->known_categories()) 3704 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods, 3705 CurContext, AddedProperties, Results, 3706 IsBaseExprStatement); 3707 } 3708 3709 // Look through protocols. 3710 for (auto *I : IFace->all_referenced_protocols()) 3711 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods, 3712 CurContext, AddedProperties, Results, 3713 IsBaseExprStatement); 3714 3715 // Look in the superclass. 3716 if (IFace->getSuperClass()) 3717 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories, 3718 AllowNullaryMethods, CurContext, AddedProperties, 3719 Results, IsBaseExprStatement); 3720 } else if (const ObjCCategoryDecl *Category 3721 = dyn_cast<ObjCCategoryDecl>(Container)) { 3722 // Look through protocols. 3723 for (auto *P : Category->protocols()) 3724 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, 3725 CurContext, AddedProperties, Results, 3726 IsBaseExprStatement); 3727 } 3728 } 3729 3730 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 3731 SourceLocation OpLoc, bool IsArrow, 3732 bool IsBaseExprStatement) { 3733 if (!Base || !CodeCompleter) 3734 return; 3735 3736 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); 3737 if (ConvertedBase.isInvalid()) 3738 return; 3739 Base = ConvertedBase.get(); 3740 3741 typedef CodeCompletionResult Result; 3742 3743 QualType BaseType = Base->getType(); 3744 3745 if (IsArrow) { 3746 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 3747 BaseType = Ptr->getPointeeType(); 3748 else if (BaseType->isObjCObjectPointerType()) 3749 /*Do nothing*/ ; 3750 else 3751 return; 3752 } 3753 3754 enum CodeCompletionContext::Kind contextKind; 3755 3756 if (IsArrow) { 3757 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess; 3758 } 3759 else { 3760 if (BaseType->isObjCObjectPointerType() || 3761 BaseType->isObjCObjectOrInterfaceType()) { 3762 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess; 3763 } 3764 else { 3765 contextKind = CodeCompletionContext::CCC_DotMemberAccess; 3766 } 3767 } 3768 3769 CodeCompletionContext CCContext(contextKind, BaseType); 3770 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3771 CodeCompleter->getCodeCompletionTUInfo(), 3772 CCContext, 3773 &ResultBuilder::IsMember); 3774 Results.EnterNewScope(); 3775 if (const RecordType *Record = BaseType->getAs<RecordType>()) { 3776 // Indicate that we are performing a member access, and the cv-qualifiers 3777 // for the base object type. 3778 Results.setObjectTypeQualifiers(BaseType.getQualifiers()); 3779 3780 // Access to a C/C++ class, struct, or union. 3781 Results.allowNestedNameSpecifiers(); 3782 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3783 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer, 3784 CodeCompleter->includeGlobals()); 3785 3786 if (getLangOpts().CPlusPlus) { 3787 if (!Results.empty()) { 3788 // The "template" keyword can follow "->" or "." in the grammar. 3789 // However, we only want to suggest the template keyword if something 3790 // is dependent. 3791 bool IsDependent = BaseType->isDependentType(); 3792 if (!IsDependent) { 3793 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) 3794 if (DeclContext *Ctx = DepScope->getEntity()) { 3795 IsDependent = Ctx->isDependentContext(); 3796 break; 3797 } 3798 } 3799 3800 if (IsDependent) 3801 Results.AddResult(Result("template")); 3802 } 3803 } 3804 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) { 3805 // Objective-C property reference. 3806 AddedPropertiesSet AddedProperties; 3807 3808 if (const ObjCObjectPointerType *ObjCPtr = 3809 BaseType->getAsObjCInterfacePointerType()) { 3810 // Add property results based on our interface. 3811 assert(ObjCPtr && "Non-NULL pointer guaranteed above!"); 3812 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true, 3813 /*AllowNullaryMethods=*/true, CurContext, 3814 AddedProperties, Results, IsBaseExprStatement); 3815 } 3816 3817 // Add properties from the protocols in a qualified interface. 3818 for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals()) 3819 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true, 3820 CurContext, AddedProperties, Results, 3821 IsBaseExprStatement); 3822 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || 3823 (!IsArrow && BaseType->isObjCObjectType())) { 3824 // Objective-C instance variable access. 3825 ObjCInterfaceDecl *Class = nullptr; 3826 if (const ObjCObjectPointerType *ObjCPtr 3827 = BaseType->getAs<ObjCObjectPointerType>()) 3828 Class = ObjCPtr->getInterfaceDecl(); 3829 else 3830 Class = BaseType->getAs<ObjCObjectType>()->getInterface(); 3831 3832 // Add all ivars from this class and its superclasses. 3833 if (Class) { 3834 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3835 Results.setFilter(&ResultBuilder::IsObjCIvar); 3836 LookupVisibleDecls(Class, LookupMemberName, Consumer, 3837 CodeCompleter->includeGlobals()); 3838 } 3839 } 3840 3841 // FIXME: How do we cope with isa? 3842 3843 Results.ExitScope(); 3844 3845 // Hand off the results found for code completion. 3846 HandleCodeCompleteResults(this, CodeCompleter, 3847 Results.getCompletionContext(), 3848 Results.data(),Results.size()); 3849 } 3850 3851 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) { 3852 if (!CodeCompleter) 3853 return; 3854 3855 ResultBuilder::LookupFilter Filter = nullptr; 3856 enum CodeCompletionContext::Kind ContextKind 3857 = CodeCompletionContext::CCC_Other; 3858 switch ((DeclSpec::TST)TagSpec) { 3859 case DeclSpec::TST_enum: 3860 Filter = &ResultBuilder::IsEnum; 3861 ContextKind = CodeCompletionContext::CCC_EnumTag; 3862 break; 3863 3864 case DeclSpec::TST_union: 3865 Filter = &ResultBuilder::IsUnion; 3866 ContextKind = CodeCompletionContext::CCC_UnionTag; 3867 break; 3868 3869 case DeclSpec::TST_struct: 3870 case DeclSpec::TST_class: 3871 case DeclSpec::TST_interface: 3872 Filter = &ResultBuilder::IsClassOrStruct; 3873 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag; 3874 break; 3875 3876 default: 3877 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag"); 3878 } 3879 3880 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3881 CodeCompleter->getCodeCompletionTUInfo(), ContextKind); 3882 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3883 3884 // First pass: look for tags. 3885 Results.setFilter(Filter); 3886 LookupVisibleDecls(S, LookupTagName, Consumer, 3887 CodeCompleter->includeGlobals()); 3888 3889 if (CodeCompleter->includeGlobals()) { 3890 // Second pass: look for nested name specifiers. 3891 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); 3892 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer); 3893 } 3894 3895 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 3896 Results.data(),Results.size()); 3897 } 3898 3899 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) { 3900 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3901 CodeCompleter->getCodeCompletionTUInfo(), 3902 CodeCompletionContext::CCC_TypeQualifiers); 3903 Results.EnterNewScope(); 3904 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const)) 3905 Results.AddResult("const"); 3906 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile)) 3907 Results.AddResult("volatile"); 3908 if (getLangOpts().C99 && 3909 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict)) 3910 Results.AddResult("restrict"); 3911 if (getLangOpts().C11 && 3912 !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic)) 3913 Results.AddResult("_Atomic"); 3914 if (getLangOpts().MSVCCompat && 3915 !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)) 3916 Results.AddResult("__unaligned"); 3917 Results.ExitScope(); 3918 HandleCodeCompleteResults(this, CodeCompleter, 3919 Results.getCompletionContext(), 3920 Results.data(), Results.size()); 3921 } 3922 3923 void Sema::CodeCompleteBracketDeclarator(Scope *S) { 3924 CodeCompleteExpression(S, QualType(getASTContext().getSizeType())); 3925 } 3926 3927 void Sema::CodeCompleteCase(Scope *S) { 3928 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter) 3929 return; 3930 3931 SwitchStmt *Switch = getCurFunction()->SwitchStack.back(); 3932 QualType type = Switch->getCond()->IgnoreImplicit()->getType(); 3933 if (!type->isEnumeralType()) { 3934 CodeCompleteExpressionData Data(type); 3935 Data.IntegralConstantExpression = true; 3936 CodeCompleteExpression(S, Data); 3937 return; 3938 } 3939 3940 // Code-complete the cases of a switch statement over an enumeration type 3941 // by providing the list of 3942 EnumDecl *Enum = type->castAs<EnumType>()->getDecl(); 3943 if (EnumDecl *Def = Enum->getDefinition()) 3944 Enum = Def; 3945 3946 // Determine which enumerators we have already seen in the switch statement. 3947 // FIXME: Ideally, we would also be able to look *past* the code-completion 3948 // token, in case we are code-completing in the middle of the switch and not 3949 // at the end. However, we aren't able to do so at the moment. 3950 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen; 3951 NestedNameSpecifier *Qualifier = nullptr; 3952 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; 3953 SC = SC->getNextSwitchCase()) { 3954 CaseStmt *Case = dyn_cast<CaseStmt>(SC); 3955 if (!Case) 3956 continue; 3957 3958 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); 3959 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal)) 3960 if (EnumConstantDecl *Enumerator 3961 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 3962 // We look into the AST of the case statement to determine which 3963 // enumerator was named. Alternatively, we could compute the value of 3964 // the integral constant expression, then compare it against the 3965 // values of each enumerator. However, value-based approach would not 3966 // work as well with C++ templates where enumerators declared within a 3967 // template are type- and value-dependent. 3968 EnumeratorsSeen.insert(Enumerator); 3969 3970 // If this is a qualified-id, keep track of the nested-name-specifier 3971 // so that we can reproduce it as part of code completion, e.g., 3972 // 3973 // switch (TagD.getKind()) { 3974 // case TagDecl::TK_enum: 3975 // break; 3976 // case XXX 3977 // 3978 // At the XXX, our completions are TagDecl::TK_union, 3979 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union, 3980 // TK_struct, and TK_class. 3981 Qualifier = DRE->getQualifier(); 3982 } 3983 } 3984 3985 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) { 3986 // If there are no prior enumerators in C++, check whether we have to 3987 // qualify the names of the enumerators that we suggest, because they 3988 // may not be visible in this scope. 3989 Qualifier = getRequiredQualification(Context, CurContext, Enum); 3990 } 3991 3992 // Add any enumerators that have not yet been mentioned. 3993 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3994 CodeCompleter->getCodeCompletionTUInfo(), 3995 CodeCompletionContext::CCC_Expression); 3996 Results.EnterNewScope(); 3997 for (auto *E : Enum->enumerators()) { 3998 if (EnumeratorsSeen.count(E)) 3999 continue; 4000 4001 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier); 4002 Results.AddResult(R, CurContext, nullptr, false); 4003 } 4004 Results.ExitScope(); 4005 4006 //We need to make sure we're setting the right context, 4007 //so only say we include macros if the code completer says we do 4008 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other; 4009 if (CodeCompleter->includeMacros()) { 4010 AddMacroResults(PP, Results, false); 4011 kind = CodeCompletionContext::CCC_OtherWithMacros; 4012 } 4013 4014 HandleCodeCompleteResults(this, CodeCompleter, 4015 kind, 4016 Results.data(),Results.size()); 4017 } 4018 4019 static bool anyNullArguments(ArrayRef<Expr *> Args) { 4020 if (Args.size() && !Args.data()) 4021 return true; 4022 4023 for (unsigned I = 0; I != Args.size(); ++I) 4024 if (!Args[I]) 4025 return true; 4026 4027 return false; 4028 } 4029 4030 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate; 4031 4032 static void mergeCandidatesWithResults(Sema &SemaRef, 4033 SmallVectorImpl<ResultCandidate> &Results, 4034 OverloadCandidateSet &CandidateSet, 4035 SourceLocation Loc) { 4036 if (!CandidateSet.empty()) { 4037 // Sort the overload candidate set by placing the best overloads first. 4038 std::stable_sort( 4039 CandidateSet.begin(), CandidateSet.end(), 4040 [&](const OverloadCandidate &X, const OverloadCandidate &Y) { 4041 return isBetterOverloadCandidate(SemaRef, X, Y, Loc); 4042 }); 4043 4044 // Add the remaining viable overload candidates as code-completion results. 4045 for (auto &Candidate : CandidateSet) 4046 if (Candidate.Viable) 4047 Results.push_back(ResultCandidate(Candidate.Function)); 4048 } 4049 } 4050 4051 /// \brief Get the type of the Nth parameter from a given set of overload 4052 /// candidates. 4053 static QualType getParamType(Sema &SemaRef, 4054 ArrayRef<ResultCandidate> Candidates, 4055 unsigned N) { 4056 4057 // Given the overloads 'Candidates' for a function call matching all arguments 4058 // up to N, return the type of the Nth parameter if it is the same for all 4059 // overload candidates. 4060 QualType ParamType; 4061 for (auto &Candidate : Candidates) { 4062 if (auto FType = Candidate.getFunctionType()) 4063 if (auto Proto = dyn_cast<FunctionProtoType>(FType)) 4064 if (N < Proto->getNumParams()) { 4065 if (ParamType.isNull()) 4066 ParamType = Proto->getParamType(N); 4067 else if (!SemaRef.Context.hasSameUnqualifiedType( 4068 ParamType.getNonReferenceType(), 4069 Proto->getParamType(N).getNonReferenceType())) 4070 // Otherwise return a default-constructed QualType. 4071 return QualType(); 4072 } 4073 } 4074 4075 return ParamType; 4076 } 4077 4078 static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S, 4079 MutableArrayRef<ResultCandidate> Candidates, 4080 unsigned CurrentArg, 4081 bool CompleteExpressionWithCurrentArg = true) { 4082 QualType ParamType; 4083 if (CompleteExpressionWithCurrentArg) 4084 ParamType = getParamType(SemaRef, Candidates, CurrentArg); 4085 4086 if (ParamType.isNull()) 4087 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression); 4088 else 4089 SemaRef.CodeCompleteExpression(S, ParamType); 4090 4091 if (!Candidates.empty()) 4092 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg, 4093 Candidates.data(), 4094 Candidates.size()); 4095 } 4096 4097 void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) { 4098 if (!CodeCompleter) 4099 return; 4100 4101 // When we're code-completing for a call, we fall back to ordinary 4102 // name code-completion whenever we can't produce specific 4103 // results. We may want to revisit this strategy in the future, 4104 // e.g., by merging the two kinds of results. 4105 4106 // FIXME: Provide support for variadic template functions. 4107 4108 // Ignore type-dependent call expressions entirely. 4109 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) || 4110 Expr::hasAnyTypeDependentArguments(Args)) { 4111 CodeCompleteOrdinaryName(S, PCC_Expression); 4112 return; 4113 } 4114 4115 // Build an overload candidate set based on the functions we find. 4116 SourceLocation Loc = Fn->getExprLoc(); 4117 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 4118 4119 SmallVector<ResultCandidate, 8> Results; 4120 4121 Expr *NakedFn = Fn->IgnoreParenCasts(); 4122 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) 4123 AddOverloadedCallCandidates(ULE, Args, CandidateSet, 4124 /*PartialOverloading=*/true); 4125 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) { 4126 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 4127 if (UME->hasExplicitTemplateArgs()) { 4128 UME->copyTemplateArgumentsInto(TemplateArgsBuffer); 4129 TemplateArgs = &TemplateArgsBuffer; 4130 } 4131 SmallVector<Expr *, 12> ArgExprs(1, UME->getBase()); 4132 ArgExprs.append(Args.begin(), Args.end()); 4133 UnresolvedSet<8> Decls; 4134 Decls.append(UME->decls_begin(), UME->decls_end()); 4135 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs, 4136 /*SuppressUsedConversions=*/false, 4137 /*PartialOverloading=*/true); 4138 } else { 4139 FunctionDecl *FD = nullptr; 4140 if (auto MCE = dyn_cast<MemberExpr>(NakedFn)) 4141 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl()); 4142 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn)) 4143 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 4144 if (FD) { // We check whether it's a resolved function declaration. 4145 if (!getLangOpts().CPlusPlus || 4146 !FD->getType()->getAs<FunctionProtoType>()) 4147 Results.push_back(ResultCandidate(FD)); 4148 else 4149 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()), 4150 Args, CandidateSet, 4151 /*SuppressUsedConversions=*/false, 4152 /*PartialOverloading=*/true); 4153 4154 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) { 4155 // If expression's type is CXXRecordDecl, it may overload the function 4156 // call operator, so we check if it does and add them as candidates. 4157 // A complete type is needed to lookup for member function call operators. 4158 if (isCompleteType(Loc, NakedFn->getType())) { 4159 DeclarationName OpName = Context.DeclarationNames 4160 .getCXXOperatorName(OO_Call); 4161 LookupResult R(*this, OpName, Loc, LookupOrdinaryName); 4162 LookupQualifiedName(R, DC); 4163 R.suppressDiagnostics(); 4164 SmallVector<Expr *, 12> ArgExprs(1, NakedFn); 4165 ArgExprs.append(Args.begin(), Args.end()); 4166 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet, 4167 /*ExplicitArgs=*/nullptr, 4168 /*SuppressUsedConversions=*/false, 4169 /*PartialOverloading=*/true); 4170 } 4171 } else { 4172 // Lastly we check whether expression's type is function pointer or 4173 // function. 4174 QualType T = NakedFn->getType(); 4175 if (!T->getPointeeType().isNull()) 4176 T = T->getPointeeType(); 4177 4178 if (auto FP = T->getAs<FunctionProtoType>()) { 4179 if (!TooManyArguments(FP->getNumParams(), Args.size(), 4180 /*PartialOverloading=*/true) || 4181 FP->isVariadic()) 4182 Results.push_back(ResultCandidate(FP)); 4183 } else if (auto FT = T->getAs<FunctionType>()) 4184 // No prototype and declaration, it may be a K & R style function. 4185 Results.push_back(ResultCandidate(FT)); 4186 } 4187 } 4188 4189 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc); 4190 CodeCompleteOverloadResults(*this, S, Results, Args.size(), 4191 !CandidateSet.empty()); 4192 } 4193 4194 void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc, 4195 ArrayRef<Expr *> Args) { 4196 if (!CodeCompleter) 4197 return; 4198 4199 // A complete type is needed to lookup for constructors. 4200 if (!isCompleteType(Loc, Type)) 4201 return; 4202 4203 CXXRecordDecl *RD = Type->getAsCXXRecordDecl(); 4204 if (!RD) { 4205 CodeCompleteExpression(S, Type); 4206 return; 4207 } 4208 4209 // FIXME: Provide support for member initializers. 4210 // FIXME: Provide support for variadic template constructors. 4211 4212 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 4213 4214 for (auto C : LookupConstructors(RD)) { 4215 if (auto FD = dyn_cast<FunctionDecl>(C)) { 4216 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), 4217 Args, CandidateSet, 4218 /*SuppressUsedConversions=*/false, 4219 /*PartialOverloading=*/true); 4220 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) { 4221 AddTemplateOverloadCandidate(FTD, 4222 DeclAccessPair::make(FTD, C->getAccess()), 4223 /*ExplicitTemplateArgs=*/nullptr, 4224 Args, CandidateSet, 4225 /*SuppressUsedConversions=*/false, 4226 /*PartialOverloading=*/true); 4227 } 4228 } 4229 4230 SmallVector<ResultCandidate, 8> Results; 4231 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc); 4232 CodeCompleteOverloadResults(*this, S, Results, Args.size()); 4233 } 4234 4235 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) { 4236 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 4237 if (!VD) { 4238 CodeCompleteOrdinaryName(S, PCC_Expression); 4239 return; 4240 } 4241 4242 CodeCompleteExpression(S, VD->getType()); 4243 } 4244 4245 void Sema::CodeCompleteReturn(Scope *S) { 4246 QualType ResultType; 4247 if (isa<BlockDecl>(CurContext)) { 4248 if (BlockScopeInfo *BSI = getCurBlock()) 4249 ResultType = BSI->ReturnType; 4250 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext)) 4251 ResultType = Function->getReturnType(); 4252 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext)) 4253 ResultType = Method->getReturnType(); 4254 4255 if (ResultType.isNull()) 4256 CodeCompleteOrdinaryName(S, PCC_Expression); 4257 else 4258 CodeCompleteExpression(S, ResultType); 4259 } 4260 4261 void Sema::CodeCompleteAfterIf(Scope *S) { 4262 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4263 CodeCompleter->getCodeCompletionTUInfo(), 4264 mapCodeCompletionContext(*this, PCC_Statement)); 4265 Results.setFilter(&ResultBuilder::IsOrdinaryName); 4266 Results.EnterNewScope(); 4267 4268 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4269 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4270 CodeCompleter->includeGlobals()); 4271 4272 AddOrdinaryNameResults(PCC_Statement, S, *this, Results); 4273 4274 // "else" block 4275 CodeCompletionBuilder Builder(Results.getAllocator(), 4276 Results.getCodeCompletionTUInfo()); 4277 Builder.AddTypedTextChunk("else"); 4278 if (Results.includeCodePatterns()) { 4279 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4280 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 4281 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 4282 Builder.AddPlaceholderChunk("statements"); 4283 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 4284 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 4285 } 4286 Results.AddResult(Builder.TakeString()); 4287 4288 // "else if" block 4289 Builder.AddTypedTextChunk("else"); 4290 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4291 Builder.AddTextChunk("if"); 4292 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4293 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4294 if (getLangOpts().CPlusPlus) 4295 Builder.AddPlaceholderChunk("condition"); 4296 else 4297 Builder.AddPlaceholderChunk("expression"); 4298 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4299 if (Results.includeCodePatterns()) { 4300 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4301 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 4302 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 4303 Builder.AddPlaceholderChunk("statements"); 4304 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 4305 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 4306 } 4307 Results.AddResult(Builder.TakeString()); 4308 4309 Results.ExitScope(); 4310 4311 if (S->getFnParent()) 4312 AddPrettyFunctionResults(getLangOpts(), Results); 4313 4314 if (CodeCompleter->includeMacros()) 4315 AddMacroResults(PP, Results, false); 4316 4317 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4318 Results.data(),Results.size()); 4319 } 4320 4321 void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) { 4322 if (LHS) 4323 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType()); 4324 else 4325 CodeCompleteOrdinaryName(S, PCC_Expression); 4326 } 4327 4328 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 4329 bool EnteringContext) { 4330 if (!SS.getScopeRep() || !CodeCompleter) 4331 return; 4332 4333 DeclContext *Ctx = computeDeclContext(SS, EnteringContext); 4334 if (!Ctx) 4335 return; 4336 4337 // Try to instantiate any non-dependent declaration contexts before 4338 // we look in them. 4339 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx)) 4340 return; 4341 4342 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4343 CodeCompleter->getCodeCompletionTUInfo(), 4344 CodeCompletionContext::CCC_Name); 4345 Results.EnterNewScope(); 4346 4347 // The "template" keyword can follow "::" in the grammar, but only 4348 // put it into the grammar if the nested-name-specifier is dependent. 4349 NestedNameSpecifier *NNS = SS.getScopeRep(); 4350 if (!Results.empty() && NNS->isDependent()) 4351 Results.AddResult("template"); 4352 4353 // Add calls to overridden virtual functions, if there are any. 4354 // 4355 // FIXME: This isn't wonderful, because we don't know whether we're actually 4356 // in a context that permits expressions. This is a general issue with 4357 // qualified-id completions. 4358 if (!EnteringContext) 4359 MaybeAddOverrideCalls(*this, Ctx, Results); 4360 Results.ExitScope(); 4361 4362 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4363 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer); 4364 4365 HandleCodeCompleteResults(this, CodeCompleter, 4366 Results.getCompletionContext(), 4367 Results.data(),Results.size()); 4368 } 4369 4370 void Sema::CodeCompleteUsing(Scope *S) { 4371 if (!CodeCompleter) 4372 return; 4373 4374 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4375 CodeCompleter->getCodeCompletionTUInfo(), 4376 CodeCompletionContext::CCC_PotentiallyQualifiedName, 4377 &ResultBuilder::IsNestedNameSpecifier); 4378 Results.EnterNewScope(); 4379 4380 // If we aren't in class scope, we could see the "namespace" keyword. 4381 if (!S->isClassScope()) 4382 Results.AddResult(CodeCompletionResult("namespace")); 4383 4384 // After "using", we can see anything that would start a 4385 // nested-name-specifier. 4386 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4387 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4388 CodeCompleter->includeGlobals()); 4389 Results.ExitScope(); 4390 4391 HandleCodeCompleteResults(this, CodeCompleter, 4392 CodeCompletionContext::CCC_PotentiallyQualifiedName, 4393 Results.data(),Results.size()); 4394 } 4395 4396 void Sema::CodeCompleteUsingDirective(Scope *S) { 4397 if (!CodeCompleter) 4398 return; 4399 4400 // After "using namespace", we expect to see a namespace name or namespace 4401 // alias. 4402 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4403 CodeCompleter->getCodeCompletionTUInfo(), 4404 CodeCompletionContext::CCC_Namespace, 4405 &ResultBuilder::IsNamespaceOrAlias); 4406 Results.EnterNewScope(); 4407 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4408 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4409 CodeCompleter->includeGlobals()); 4410 Results.ExitScope(); 4411 HandleCodeCompleteResults(this, CodeCompleter, 4412 CodeCompletionContext::CCC_Namespace, 4413 Results.data(),Results.size()); 4414 } 4415 4416 void Sema::CodeCompleteNamespaceDecl(Scope *S) { 4417 if (!CodeCompleter) 4418 return; 4419 4420 DeclContext *Ctx = S->getEntity(); 4421 if (!S->getParent()) 4422 Ctx = Context.getTranslationUnitDecl(); 4423 4424 bool SuppressedGlobalResults 4425 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx); 4426 4427 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4428 CodeCompleter->getCodeCompletionTUInfo(), 4429 SuppressedGlobalResults 4430 ? CodeCompletionContext::CCC_Namespace 4431 : CodeCompletionContext::CCC_Other, 4432 &ResultBuilder::IsNamespace); 4433 4434 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { 4435 // We only want to see those namespaces that have already been defined 4436 // within this scope, because its likely that the user is creating an 4437 // extended namespace declaration. Keep track of the most recent 4438 // definition of each namespace. 4439 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; 4440 for (DeclContext::specific_decl_iterator<NamespaceDecl> 4441 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end()); 4442 NS != NSEnd; ++NS) 4443 OrigToLatest[NS->getOriginalNamespace()] = *NS; 4444 4445 // Add the most recent definition (or extended definition) of each 4446 // namespace to the list of results. 4447 Results.EnterNewScope(); 4448 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator 4449 NS = OrigToLatest.begin(), 4450 NSEnd = OrigToLatest.end(); 4451 NS != NSEnd; ++NS) 4452 Results.AddResult(CodeCompletionResult( 4453 NS->second, Results.getBasePriority(NS->second), 4454 nullptr), 4455 CurContext, nullptr, false); 4456 Results.ExitScope(); 4457 } 4458 4459 HandleCodeCompleteResults(this, CodeCompleter, 4460 Results.getCompletionContext(), 4461 Results.data(),Results.size()); 4462 } 4463 4464 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { 4465 if (!CodeCompleter) 4466 return; 4467 4468 // After "namespace", we expect to see a namespace or alias. 4469 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4470 CodeCompleter->getCodeCompletionTUInfo(), 4471 CodeCompletionContext::CCC_Namespace, 4472 &ResultBuilder::IsNamespaceOrAlias); 4473 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4474 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4475 CodeCompleter->includeGlobals()); 4476 HandleCodeCompleteResults(this, CodeCompleter, 4477 Results.getCompletionContext(), 4478 Results.data(),Results.size()); 4479 } 4480 4481 void Sema::CodeCompleteOperatorName(Scope *S) { 4482 if (!CodeCompleter) 4483 return; 4484 4485 typedef CodeCompletionResult Result; 4486 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4487 CodeCompleter->getCodeCompletionTUInfo(), 4488 CodeCompletionContext::CCC_Type, 4489 &ResultBuilder::IsType); 4490 Results.EnterNewScope(); 4491 4492 // Add the names of overloadable operators. 4493 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 4494 if (std::strcmp(Spelling, "?")) \ 4495 Results.AddResult(Result(Spelling)); 4496 #include "clang/Basic/OperatorKinds.def" 4497 4498 // Add any type names visible from the current scope 4499 Results.allowNestedNameSpecifiers(); 4500 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4501 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4502 CodeCompleter->includeGlobals()); 4503 4504 // Add any type specifiers 4505 AddTypeSpecifierResults(getLangOpts(), Results); 4506 Results.ExitScope(); 4507 4508 HandleCodeCompleteResults(this, CodeCompleter, 4509 CodeCompletionContext::CCC_Type, 4510 Results.data(),Results.size()); 4511 } 4512 4513 void Sema::CodeCompleteConstructorInitializer( 4514 Decl *ConstructorD, 4515 ArrayRef <CXXCtorInitializer *> Initializers) { 4516 if (!ConstructorD) 4517 return; 4518 4519 AdjustDeclIfTemplate(ConstructorD); 4520 4521 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD); 4522 if (!Constructor) 4523 return; 4524 4525 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4526 CodeCompleter->getCodeCompletionTUInfo(), 4527 CodeCompletionContext::CCC_PotentiallyQualifiedName); 4528 Results.EnterNewScope(); 4529 4530 // Fill in any already-initialized fields or base classes. 4531 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; 4532 llvm::SmallPtrSet<CanQualType, 4> InitializedBases; 4533 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) { 4534 if (Initializers[I]->isBaseInitializer()) 4535 InitializedBases.insert( 4536 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0))); 4537 else 4538 InitializedFields.insert(cast<FieldDecl>( 4539 Initializers[I]->getAnyMember())); 4540 } 4541 4542 // Add completions for base classes. 4543 CodeCompletionBuilder Builder(Results.getAllocator(), 4544 Results.getCodeCompletionTUInfo()); 4545 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 4546 bool SawLastInitializer = Initializers.empty(); 4547 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4548 for (const auto &Base : ClassDecl->bases()) { 4549 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 4550 .second) { 4551 SawLastInitializer 4552 = !Initializers.empty() && 4553 Initializers.back()->isBaseInitializer() && 4554 Context.hasSameUnqualifiedType(Base.getType(), 4555 QualType(Initializers.back()->getBaseClass(), 0)); 4556 continue; 4557 } 4558 4559 Builder.AddTypedTextChunk( 4560 Results.getAllocator().CopyString( 4561 Base.getType().getAsString(Policy))); 4562 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4563 Builder.AddPlaceholderChunk("args"); 4564 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4565 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 4566 SawLastInitializer? CCP_NextInitializer 4567 : CCP_MemberDeclaration)); 4568 SawLastInitializer = false; 4569 } 4570 4571 // Add completions for virtual base classes. 4572 for (const auto &Base : ClassDecl->vbases()) { 4573 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 4574 .second) { 4575 SawLastInitializer 4576 = !Initializers.empty() && 4577 Initializers.back()->isBaseInitializer() && 4578 Context.hasSameUnqualifiedType(Base.getType(), 4579 QualType(Initializers.back()->getBaseClass(), 0)); 4580 continue; 4581 } 4582 4583 Builder.AddTypedTextChunk( 4584 Builder.getAllocator().CopyString( 4585 Base.getType().getAsString(Policy))); 4586 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4587 Builder.AddPlaceholderChunk("args"); 4588 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4589 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 4590 SawLastInitializer? CCP_NextInitializer 4591 : CCP_MemberDeclaration)); 4592 SawLastInitializer = false; 4593 } 4594 4595 // Add completions for members. 4596 for (auto *Field : ClassDecl->fields()) { 4597 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl())) 4598 .second) { 4599 SawLastInitializer 4600 = !Initializers.empty() && 4601 Initializers.back()->isAnyMemberInitializer() && 4602 Initializers.back()->getAnyMember() == Field; 4603 continue; 4604 } 4605 4606 if (!Field->getDeclName()) 4607 continue; 4608 4609 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 4610 Field->getIdentifier()->getName())); 4611 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4612 Builder.AddPlaceholderChunk("args"); 4613 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4614 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 4615 SawLastInitializer? CCP_NextInitializer 4616 : CCP_MemberDeclaration, 4617 CXCursor_MemberRef, 4618 CXAvailability_Available, 4619 Field)); 4620 SawLastInitializer = false; 4621 } 4622 Results.ExitScope(); 4623 4624 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4625 Results.data(), Results.size()); 4626 } 4627 4628 /// \brief Determine whether this scope denotes a namespace. 4629 static bool isNamespaceScope(Scope *S) { 4630 DeclContext *DC = S->getEntity(); 4631 if (!DC) 4632 return false; 4633 4634 return DC->isFileContext(); 4635 } 4636 4637 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 4638 bool AfterAmpersand) { 4639 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4640 CodeCompleter->getCodeCompletionTUInfo(), 4641 CodeCompletionContext::CCC_Other); 4642 Results.EnterNewScope(); 4643 4644 // Note what has already been captured. 4645 llvm::SmallPtrSet<IdentifierInfo *, 4> Known; 4646 bool IncludedThis = false; 4647 for (const auto &C : Intro.Captures) { 4648 if (C.Kind == LCK_This) { 4649 IncludedThis = true; 4650 continue; 4651 } 4652 4653 Known.insert(C.Id); 4654 } 4655 4656 // Look for other capturable variables. 4657 for (; S && !isNamespaceScope(S); S = S->getParent()) { 4658 for (const auto *D : S->decls()) { 4659 const auto *Var = dyn_cast<VarDecl>(D); 4660 if (!Var || 4661 !Var->hasLocalStorage() || 4662 Var->hasAttr<BlocksAttr>()) 4663 continue; 4664 4665 if (Known.insert(Var->getIdentifier()).second) 4666 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration), 4667 CurContext, nullptr, false); 4668 } 4669 } 4670 4671 // Add 'this', if it would be valid. 4672 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy) 4673 addThisCompletion(*this, Results); 4674 4675 Results.ExitScope(); 4676 4677 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4678 Results.data(), Results.size()); 4679 } 4680 4681 /// Macro that optionally prepends an "@" to the string literal passed in via 4682 /// Keyword, depending on whether NeedAt is true or false. 4683 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword) 4684 4685 static void AddObjCImplementationResults(const LangOptions &LangOpts, 4686 ResultBuilder &Results, 4687 bool NeedAt) { 4688 typedef CodeCompletionResult Result; 4689 // Since we have an implementation, we can end it. 4690 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end"))); 4691 4692 CodeCompletionBuilder Builder(Results.getAllocator(), 4693 Results.getCodeCompletionTUInfo()); 4694 if (LangOpts.ObjC2) { 4695 // @dynamic 4696 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic")); 4697 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4698 Builder.AddPlaceholderChunk("property"); 4699 Results.AddResult(Result(Builder.TakeString())); 4700 4701 // @synthesize 4702 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize")); 4703 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4704 Builder.AddPlaceholderChunk("property"); 4705 Results.AddResult(Result(Builder.TakeString())); 4706 } 4707 } 4708 4709 static void AddObjCInterfaceResults(const LangOptions &LangOpts, 4710 ResultBuilder &Results, 4711 bool NeedAt) { 4712 typedef CodeCompletionResult Result; 4713 4714 // Since we have an interface or protocol, we can end it. 4715 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end"))); 4716 4717 if (LangOpts.ObjC2) { 4718 // @property 4719 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property"))); 4720 4721 // @required 4722 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required"))); 4723 4724 // @optional 4725 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional"))); 4726 } 4727 } 4728 4729 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { 4730 typedef CodeCompletionResult Result; 4731 CodeCompletionBuilder Builder(Results.getAllocator(), 4732 Results.getCodeCompletionTUInfo()); 4733 4734 // @class name ; 4735 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class")); 4736 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4737 Builder.AddPlaceholderChunk("name"); 4738 Results.AddResult(Result(Builder.TakeString())); 4739 4740 if (Results.includeCodePatterns()) { 4741 // @interface name 4742 // FIXME: Could introduce the whole pattern, including superclasses and 4743 // such. 4744 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface")); 4745 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4746 Builder.AddPlaceholderChunk("class"); 4747 Results.AddResult(Result(Builder.TakeString())); 4748 4749 // @protocol name 4750 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol")); 4751 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4752 Builder.AddPlaceholderChunk("protocol"); 4753 Results.AddResult(Result(Builder.TakeString())); 4754 4755 // @implementation name 4756 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation")); 4757 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4758 Builder.AddPlaceholderChunk("class"); 4759 Results.AddResult(Result(Builder.TakeString())); 4760 } 4761 4762 // @compatibility_alias name 4763 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias")); 4764 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4765 Builder.AddPlaceholderChunk("alias"); 4766 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4767 Builder.AddPlaceholderChunk("class"); 4768 Results.AddResult(Result(Builder.TakeString())); 4769 4770 if (Results.getSema().getLangOpts().Modules) { 4771 // @import name 4772 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import")); 4773 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4774 Builder.AddPlaceholderChunk("module"); 4775 Results.AddResult(Result(Builder.TakeString())); 4776 } 4777 } 4778 4779 void Sema::CodeCompleteObjCAtDirective(Scope *S) { 4780 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4781 CodeCompleter->getCodeCompletionTUInfo(), 4782 CodeCompletionContext::CCC_Other); 4783 Results.EnterNewScope(); 4784 if (isa<ObjCImplDecl>(CurContext)) 4785 AddObjCImplementationResults(getLangOpts(), Results, false); 4786 else if (CurContext->isObjCContainer()) 4787 AddObjCInterfaceResults(getLangOpts(), Results, false); 4788 else 4789 AddObjCTopLevelResults(Results, false); 4790 Results.ExitScope(); 4791 HandleCodeCompleteResults(this, CodeCompleter, 4792 CodeCompletionContext::CCC_Other, 4793 Results.data(),Results.size()); 4794 } 4795 4796 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { 4797 typedef CodeCompletionResult Result; 4798 CodeCompletionBuilder Builder(Results.getAllocator(), 4799 Results.getCodeCompletionTUInfo()); 4800 4801 // @encode ( type-name ) 4802 const char *EncodeType = "char[]"; 4803 if (Results.getSema().getLangOpts().CPlusPlus || 4804 Results.getSema().getLangOpts().ConstStrings) 4805 EncodeType = "const char[]"; 4806 Builder.AddResultTypeChunk(EncodeType); 4807 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode")); 4808 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4809 Builder.AddPlaceholderChunk("type-name"); 4810 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4811 Results.AddResult(Result(Builder.TakeString())); 4812 4813 // @protocol ( protocol-name ) 4814 Builder.AddResultTypeChunk("Protocol *"); 4815 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol")); 4816 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4817 Builder.AddPlaceholderChunk("protocol-name"); 4818 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4819 Results.AddResult(Result(Builder.TakeString())); 4820 4821 // @selector ( selector ) 4822 Builder.AddResultTypeChunk("SEL"); 4823 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector")); 4824 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4825 Builder.AddPlaceholderChunk("selector"); 4826 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4827 Results.AddResult(Result(Builder.TakeString())); 4828 4829 // @"string" 4830 Builder.AddResultTypeChunk("NSString *"); 4831 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\"")); 4832 Builder.AddPlaceholderChunk("string"); 4833 Builder.AddTextChunk("\""); 4834 Results.AddResult(Result(Builder.TakeString())); 4835 4836 // @[objects, ...] 4837 Builder.AddResultTypeChunk("NSArray *"); 4838 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"[")); 4839 Builder.AddPlaceholderChunk("objects, ..."); 4840 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 4841 Results.AddResult(Result(Builder.TakeString())); 4842 4843 // @{key : object, ...} 4844 Builder.AddResultTypeChunk("NSDictionary *"); 4845 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{")); 4846 Builder.AddPlaceholderChunk("key"); 4847 Builder.AddChunk(CodeCompletionString::CK_Colon); 4848 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4849 Builder.AddPlaceholderChunk("object, ..."); 4850 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 4851 Results.AddResult(Result(Builder.TakeString())); 4852 4853 // @(expression) 4854 Builder.AddResultTypeChunk("id"); 4855 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "(")); 4856 Builder.AddPlaceholderChunk("expression"); 4857 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4858 Results.AddResult(Result(Builder.TakeString())); 4859 } 4860 4861 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { 4862 typedef CodeCompletionResult Result; 4863 CodeCompletionBuilder Builder(Results.getAllocator(), 4864 Results.getCodeCompletionTUInfo()); 4865 4866 if (Results.includeCodePatterns()) { 4867 // @try { statements } @catch ( declaration ) { statements } @finally 4868 // { statements } 4869 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try")); 4870 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 4871 Builder.AddPlaceholderChunk("statements"); 4872 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 4873 Builder.AddTextChunk("@catch"); 4874 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4875 Builder.AddPlaceholderChunk("parameter"); 4876 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4877 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 4878 Builder.AddPlaceholderChunk("statements"); 4879 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 4880 Builder.AddTextChunk("@finally"); 4881 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 4882 Builder.AddPlaceholderChunk("statements"); 4883 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 4884 Results.AddResult(Result(Builder.TakeString())); 4885 } 4886 4887 // @throw 4888 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw")); 4889 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4890 Builder.AddPlaceholderChunk("expression"); 4891 Results.AddResult(Result(Builder.TakeString())); 4892 4893 if (Results.includeCodePatterns()) { 4894 // @synchronized ( expression ) { statements } 4895 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized")); 4896 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4897 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4898 Builder.AddPlaceholderChunk("expression"); 4899 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4900 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 4901 Builder.AddPlaceholderChunk("statements"); 4902 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 4903 Results.AddResult(Result(Builder.TakeString())); 4904 } 4905 } 4906 4907 static void AddObjCVisibilityResults(const LangOptions &LangOpts, 4908 ResultBuilder &Results, 4909 bool NeedAt) { 4910 typedef CodeCompletionResult Result; 4911 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private"))); 4912 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected"))); 4913 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public"))); 4914 if (LangOpts.ObjC2) 4915 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package"))); 4916 } 4917 4918 void Sema::CodeCompleteObjCAtVisibility(Scope *S) { 4919 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4920 CodeCompleter->getCodeCompletionTUInfo(), 4921 CodeCompletionContext::CCC_Other); 4922 Results.EnterNewScope(); 4923 AddObjCVisibilityResults(getLangOpts(), Results, false); 4924 Results.ExitScope(); 4925 HandleCodeCompleteResults(this, CodeCompleter, 4926 CodeCompletionContext::CCC_Other, 4927 Results.data(),Results.size()); 4928 } 4929 4930 void Sema::CodeCompleteObjCAtStatement(Scope *S) { 4931 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4932 CodeCompleter->getCodeCompletionTUInfo(), 4933 CodeCompletionContext::CCC_Other); 4934 Results.EnterNewScope(); 4935 AddObjCStatementResults(Results, false); 4936 AddObjCExpressionResults(Results, false); 4937 Results.ExitScope(); 4938 HandleCodeCompleteResults(this, CodeCompleter, 4939 CodeCompletionContext::CCC_Other, 4940 Results.data(),Results.size()); 4941 } 4942 4943 void Sema::CodeCompleteObjCAtExpression(Scope *S) { 4944 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4945 CodeCompleter->getCodeCompletionTUInfo(), 4946 CodeCompletionContext::CCC_Other); 4947 Results.EnterNewScope(); 4948 AddObjCExpressionResults(Results, false); 4949 Results.ExitScope(); 4950 HandleCodeCompleteResults(this, CodeCompleter, 4951 CodeCompletionContext::CCC_Other, 4952 Results.data(),Results.size()); 4953 } 4954 4955 /// \brief Determine whether the addition of the given flag to an Objective-C 4956 /// property's attributes will cause a conflict. 4957 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { 4958 // Check if we've already added this flag. 4959 if (Attributes & NewFlag) 4960 return true; 4961 4962 Attributes |= NewFlag; 4963 4964 // Check for collisions with "readonly". 4965 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && 4966 (Attributes & ObjCDeclSpec::DQ_PR_readwrite)) 4967 return true; 4968 4969 // Check for more than one of { assign, copy, retain, strong, weak }. 4970 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign | 4971 ObjCDeclSpec::DQ_PR_unsafe_unretained | 4972 ObjCDeclSpec::DQ_PR_copy | 4973 ObjCDeclSpec::DQ_PR_retain | 4974 ObjCDeclSpec::DQ_PR_strong | 4975 ObjCDeclSpec::DQ_PR_weak); 4976 if (AssignCopyRetMask && 4977 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign && 4978 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained && 4979 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy && 4980 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain && 4981 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong && 4982 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak) 4983 return true; 4984 4985 return false; 4986 } 4987 4988 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { 4989 if (!CodeCompleter) 4990 return; 4991 4992 unsigned Attributes = ODS.getPropertyAttributes(); 4993 4994 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4995 CodeCompleter->getCodeCompletionTUInfo(), 4996 CodeCompletionContext::CCC_Other); 4997 Results.EnterNewScope(); 4998 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly)) 4999 Results.AddResult(CodeCompletionResult("readonly")); 5000 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign)) 5001 Results.AddResult(CodeCompletionResult("assign")); 5002 if (!ObjCPropertyFlagConflicts(Attributes, 5003 ObjCDeclSpec::DQ_PR_unsafe_unretained)) 5004 Results.AddResult(CodeCompletionResult("unsafe_unretained")); 5005 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite)) 5006 Results.AddResult(CodeCompletionResult("readwrite")); 5007 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain)) 5008 Results.AddResult(CodeCompletionResult("retain")); 5009 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong)) 5010 Results.AddResult(CodeCompletionResult("strong")); 5011 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy)) 5012 Results.AddResult(CodeCompletionResult("copy")); 5013 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic)) 5014 Results.AddResult(CodeCompletionResult("nonatomic")); 5015 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic)) 5016 Results.AddResult(CodeCompletionResult("atomic")); 5017 5018 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC. 5019 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC) 5020 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak)) 5021 Results.AddResult(CodeCompletionResult("weak")); 5022 5023 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) { 5024 CodeCompletionBuilder Setter(Results.getAllocator(), 5025 Results.getCodeCompletionTUInfo()); 5026 Setter.AddTypedTextChunk("setter"); 5027 Setter.AddTextChunk("="); 5028 Setter.AddPlaceholderChunk("method"); 5029 Results.AddResult(CodeCompletionResult(Setter.TakeString())); 5030 } 5031 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) { 5032 CodeCompletionBuilder Getter(Results.getAllocator(), 5033 Results.getCodeCompletionTUInfo()); 5034 Getter.AddTypedTextChunk("getter"); 5035 Getter.AddTextChunk("="); 5036 Getter.AddPlaceholderChunk("method"); 5037 Results.AddResult(CodeCompletionResult(Getter.TakeString())); 5038 } 5039 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) { 5040 Results.AddResult(CodeCompletionResult("nonnull")); 5041 Results.AddResult(CodeCompletionResult("nullable")); 5042 Results.AddResult(CodeCompletionResult("null_unspecified")); 5043 Results.AddResult(CodeCompletionResult("null_resettable")); 5044 } 5045 Results.ExitScope(); 5046 HandleCodeCompleteResults(this, CodeCompleter, 5047 CodeCompletionContext::CCC_Other, 5048 Results.data(),Results.size()); 5049 } 5050 5051 /// \brief Describes the kind of Objective-C method that we want to find 5052 /// via code completion. 5053 enum ObjCMethodKind { 5054 MK_Any, ///< Any kind of method, provided it means other specified criteria. 5055 MK_ZeroArgSelector, ///< Zero-argument (unary) selector. 5056 MK_OneArgSelector ///< One-argument selector. 5057 }; 5058 5059 static bool isAcceptableObjCSelector(Selector Sel, 5060 ObjCMethodKind WantKind, 5061 ArrayRef<IdentifierInfo *> SelIdents, 5062 bool AllowSameLength = true) { 5063 unsigned NumSelIdents = SelIdents.size(); 5064 if (NumSelIdents > Sel.getNumArgs()) 5065 return false; 5066 5067 switch (WantKind) { 5068 case MK_Any: break; 5069 case MK_ZeroArgSelector: return Sel.isUnarySelector(); 5070 case MK_OneArgSelector: return Sel.getNumArgs() == 1; 5071 } 5072 5073 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) 5074 return false; 5075 5076 for (unsigned I = 0; I != NumSelIdents; ++I) 5077 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) 5078 return false; 5079 5080 return true; 5081 } 5082 5083 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, 5084 ObjCMethodKind WantKind, 5085 ArrayRef<IdentifierInfo *> SelIdents, 5086 bool AllowSameLength = true) { 5087 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents, 5088 AllowSameLength); 5089 } 5090 5091 namespace { 5092 /// \brief A set of selectors, which is used to avoid introducing multiple 5093 /// completions with the same selector into the result set. 5094 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; 5095 } 5096 5097 /// \brief Add all of the Objective-C methods in the given Objective-C 5098 /// container to the set of results. 5099 /// 5100 /// The container will be a class, protocol, category, or implementation of 5101 /// any of the above. This mether will recurse to include methods from 5102 /// the superclasses of classes along with their categories, protocols, and 5103 /// implementations. 5104 /// 5105 /// \param Container the container in which we'll look to find methods. 5106 /// 5107 /// \param WantInstanceMethods Whether to add instance methods (only); if 5108 /// false, this routine will add factory methods (only). 5109 /// 5110 /// \param CurContext the context in which we're performing the lookup that 5111 /// finds methods. 5112 /// 5113 /// \param AllowSameLength Whether we allow a method to be added to the list 5114 /// when it has the same number of parameters as we have selector identifiers. 5115 /// 5116 /// \param Results the structure into which we'll add results. 5117 static void AddObjCMethods(ObjCContainerDecl *Container, 5118 bool WantInstanceMethods, 5119 ObjCMethodKind WantKind, 5120 ArrayRef<IdentifierInfo *> SelIdents, 5121 DeclContext *CurContext, 5122 VisitedSelectorSet &Selectors, 5123 bool AllowSameLength, 5124 ResultBuilder &Results, 5125 bool InOriginalClass = true) { 5126 typedef CodeCompletionResult Result; 5127 Container = getContainerDef(Container); 5128 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container); 5129 bool isRootClass = IFace && !IFace->getSuperClass(); 5130 for (auto *M : Container->methods()) { 5131 // The instance methods on the root class can be messaged via the 5132 // metaclass. 5133 if (M->isInstanceMethod() == WantInstanceMethods || 5134 (isRootClass && !WantInstanceMethods)) { 5135 // Check whether the selector identifiers we've been given are a 5136 // subset of the identifiers for this particular method. 5137 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength)) 5138 continue; 5139 5140 if (!Selectors.insert(M->getSelector()).second) 5141 continue; 5142 5143 Result R = Result(M, Results.getBasePriority(M), nullptr); 5144 R.StartParameter = SelIdents.size(); 5145 R.AllParametersAreInformative = (WantKind != MK_Any); 5146 if (!InOriginalClass) 5147 R.Priority += CCD_InBaseClass; 5148 Results.MaybeAddResult(R, CurContext); 5149 } 5150 } 5151 5152 // Visit the protocols of protocols. 5153 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 5154 if (Protocol->hasDefinition()) { 5155 const ObjCList<ObjCProtocolDecl> &Protocols 5156 = Protocol->getReferencedProtocols(); 5157 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 5158 E = Protocols.end(); 5159 I != E; ++I) 5160 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, 5161 CurContext, Selectors, AllowSameLength, Results, false); 5162 } 5163 } 5164 5165 if (!IFace || !IFace->hasDefinition()) 5166 return; 5167 5168 // Add methods in protocols. 5169 for (auto *I : IFace->protocols()) 5170 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, 5171 CurContext, Selectors, AllowSameLength, Results, false); 5172 5173 // Add methods in categories. 5174 for (auto *CatDecl : IFace->known_categories()) { 5175 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, 5176 CurContext, Selectors, AllowSameLength, 5177 Results, InOriginalClass); 5178 5179 // Add a categories protocol methods. 5180 const ObjCList<ObjCProtocolDecl> &Protocols 5181 = CatDecl->getReferencedProtocols(); 5182 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 5183 E = Protocols.end(); 5184 I != E; ++I) 5185 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, 5186 CurContext, Selectors, AllowSameLength, 5187 Results, false); 5188 5189 // Add methods in category implementations. 5190 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) 5191 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, 5192 CurContext, Selectors, AllowSameLength, 5193 Results, InOriginalClass); 5194 } 5195 5196 // Add methods in superclass. 5197 if (IFace->getSuperClass()) 5198 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, 5199 SelIdents, CurContext, Selectors, 5200 AllowSameLength, Results, false); 5201 5202 // Add methods in our implementation, if any. 5203 if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 5204 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, 5205 CurContext, Selectors, AllowSameLength, 5206 Results, InOriginalClass); 5207 } 5208 5209 5210 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) { 5211 // Try to find the interface where getters might live. 5212 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 5213 if (!Class) { 5214 if (ObjCCategoryDecl *Category 5215 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 5216 Class = Category->getClassInterface(); 5217 5218 if (!Class) 5219 return; 5220 } 5221 5222 // Find all of the potential getters. 5223 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5224 CodeCompleter->getCodeCompletionTUInfo(), 5225 CodeCompletionContext::CCC_Other); 5226 Results.EnterNewScope(); 5227 5228 VisitedSelectorSet Selectors; 5229 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors, 5230 /*AllowSameLength=*/true, Results); 5231 Results.ExitScope(); 5232 HandleCodeCompleteResults(this, CodeCompleter, 5233 CodeCompletionContext::CCC_Other, 5234 Results.data(),Results.size()); 5235 } 5236 5237 void Sema::CodeCompleteObjCPropertySetter(Scope *S) { 5238 // Try to find the interface where setters might live. 5239 ObjCInterfaceDecl *Class 5240 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 5241 if (!Class) { 5242 if (ObjCCategoryDecl *Category 5243 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 5244 Class = Category->getClassInterface(); 5245 5246 if (!Class) 5247 return; 5248 } 5249 5250 // Find all of the potential getters. 5251 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5252 CodeCompleter->getCodeCompletionTUInfo(), 5253 CodeCompletionContext::CCC_Other); 5254 Results.EnterNewScope(); 5255 5256 VisitedSelectorSet Selectors; 5257 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext, 5258 Selectors, /*AllowSameLength=*/true, Results); 5259 5260 Results.ExitScope(); 5261 HandleCodeCompleteResults(this, CodeCompleter, 5262 CodeCompletionContext::CCC_Other, 5263 Results.data(),Results.size()); 5264 } 5265 5266 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 5267 bool IsParameter) { 5268 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5269 CodeCompleter->getCodeCompletionTUInfo(), 5270 CodeCompletionContext::CCC_Type); 5271 Results.EnterNewScope(); 5272 5273 // Add context-sensitive, Objective-C parameter-passing keywords. 5274 bool AddedInOut = false; 5275 if ((DS.getObjCDeclQualifier() & 5276 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { 5277 Results.AddResult("in"); 5278 Results.AddResult("inout"); 5279 AddedInOut = true; 5280 } 5281 if ((DS.getObjCDeclQualifier() & 5282 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { 5283 Results.AddResult("out"); 5284 if (!AddedInOut) 5285 Results.AddResult("inout"); 5286 } 5287 if ((DS.getObjCDeclQualifier() & 5288 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | 5289 ObjCDeclSpec::DQ_Oneway)) == 0) { 5290 Results.AddResult("bycopy"); 5291 Results.AddResult("byref"); 5292 Results.AddResult("oneway"); 5293 } 5294 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) { 5295 Results.AddResult("nonnull"); 5296 Results.AddResult("nullable"); 5297 Results.AddResult("null_unspecified"); 5298 } 5299 5300 // If we're completing the return type of an Objective-C method and the 5301 // identifier IBAction refers to a macro, provide a completion item for 5302 // an action, e.g., 5303 // IBAction)<#selector#>:(id)sender 5304 if (DS.getObjCDeclQualifier() == 0 && !IsParameter && 5305 PP.isMacroDefined("IBAction")) { 5306 CodeCompletionBuilder Builder(Results.getAllocator(), 5307 Results.getCodeCompletionTUInfo(), 5308 CCP_CodePattern, CXAvailability_Available); 5309 Builder.AddTypedTextChunk("IBAction"); 5310 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5311 Builder.AddPlaceholderChunk("selector"); 5312 Builder.AddChunk(CodeCompletionString::CK_Colon); 5313 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5314 Builder.AddTextChunk("id"); 5315 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5316 Builder.AddTextChunk("sender"); 5317 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 5318 } 5319 5320 // If we're completing the return type, provide 'instancetype'. 5321 if (!IsParameter) { 5322 Results.AddResult(CodeCompletionResult("instancetype")); 5323 } 5324 5325 // Add various builtin type names and specifiers. 5326 AddOrdinaryNameResults(PCC_Type, S, *this, Results); 5327 Results.ExitScope(); 5328 5329 // Add the various type names 5330 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 5331 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5332 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5333 CodeCompleter->includeGlobals()); 5334 5335 if (CodeCompleter->includeMacros()) 5336 AddMacroResults(PP, Results, false); 5337 5338 HandleCodeCompleteResults(this, CodeCompleter, 5339 CodeCompletionContext::CCC_Type, 5340 Results.data(), Results.size()); 5341 } 5342 5343 /// \brief When we have an expression with type "id", we may assume 5344 /// that it has some more-specific class type based on knowledge of 5345 /// common uses of Objective-C. This routine returns that class type, 5346 /// or NULL if no better result could be determined. 5347 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { 5348 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E); 5349 if (!Msg) 5350 return nullptr; 5351 5352 Selector Sel = Msg->getSelector(); 5353 if (Sel.isNull()) 5354 return nullptr; 5355 5356 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0); 5357 if (!Id) 5358 return nullptr; 5359 5360 ObjCMethodDecl *Method = Msg->getMethodDecl(); 5361 if (!Method) 5362 return nullptr; 5363 5364 // Determine the class that we're sending the message to. 5365 ObjCInterfaceDecl *IFace = nullptr; 5366 switch (Msg->getReceiverKind()) { 5367 case ObjCMessageExpr::Class: 5368 if (const ObjCObjectType *ObjType 5369 = Msg->getClassReceiver()->getAs<ObjCObjectType>()) 5370 IFace = ObjType->getInterface(); 5371 break; 5372 5373 case ObjCMessageExpr::Instance: { 5374 QualType T = Msg->getInstanceReceiver()->getType(); 5375 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) 5376 IFace = Ptr->getInterfaceDecl(); 5377 break; 5378 } 5379 5380 case ObjCMessageExpr::SuperInstance: 5381 case ObjCMessageExpr::SuperClass: 5382 break; 5383 } 5384 5385 if (!IFace) 5386 return nullptr; 5387 5388 ObjCInterfaceDecl *Super = IFace->getSuperClass(); 5389 if (Method->isInstanceMethod()) 5390 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 5391 .Case("retain", IFace) 5392 .Case("strong", IFace) 5393 .Case("autorelease", IFace) 5394 .Case("copy", IFace) 5395 .Case("copyWithZone", IFace) 5396 .Case("mutableCopy", IFace) 5397 .Case("mutableCopyWithZone", IFace) 5398 .Case("awakeFromCoder", IFace) 5399 .Case("replacementObjectFromCoder", IFace) 5400 .Case("class", IFace) 5401 .Case("classForCoder", IFace) 5402 .Case("superclass", Super) 5403 .Default(nullptr); 5404 5405 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 5406 .Case("new", IFace) 5407 .Case("alloc", IFace) 5408 .Case("allocWithZone", IFace) 5409 .Case("class", IFace) 5410 .Case("superclass", Super) 5411 .Default(nullptr); 5412 } 5413 5414 // Add a special completion for a message send to "super", which fills in the 5415 // most likely case of forwarding all of our arguments to the superclass 5416 // function. 5417 /// 5418 /// \param S The semantic analysis object. 5419 /// 5420 /// \param NeedSuperKeyword Whether we need to prefix this completion with 5421 /// the "super" keyword. Otherwise, we just need to provide the arguments. 5422 /// 5423 /// \param SelIdents The identifiers in the selector that have already been 5424 /// provided as arguments for a send to "super". 5425 /// 5426 /// \param Results The set of results to augment. 5427 /// 5428 /// \returns the Objective-C method declaration that would be invoked by 5429 /// this "super" completion. If NULL, no completion was added. 5430 static ObjCMethodDecl *AddSuperSendCompletion( 5431 Sema &S, bool NeedSuperKeyword, 5432 ArrayRef<IdentifierInfo *> SelIdents, 5433 ResultBuilder &Results) { 5434 ObjCMethodDecl *CurMethod = S.getCurMethodDecl(); 5435 if (!CurMethod) 5436 return nullptr; 5437 5438 ObjCInterfaceDecl *Class = CurMethod->getClassInterface(); 5439 if (!Class) 5440 return nullptr; 5441 5442 // Try to find a superclass method with the same selector. 5443 ObjCMethodDecl *SuperMethod = nullptr; 5444 while ((Class = Class->getSuperClass()) && !SuperMethod) { 5445 // Check in the class 5446 SuperMethod = Class->getMethod(CurMethod->getSelector(), 5447 CurMethod->isInstanceMethod()); 5448 5449 // Check in categories or class extensions. 5450 if (!SuperMethod) { 5451 for (const auto *Cat : Class->known_categories()) { 5452 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(), 5453 CurMethod->isInstanceMethod()))) 5454 break; 5455 } 5456 } 5457 } 5458 5459 if (!SuperMethod) 5460 return nullptr; 5461 5462 // Check whether the superclass method has the same signature. 5463 if (CurMethod->param_size() != SuperMethod->param_size() || 5464 CurMethod->isVariadic() != SuperMethod->isVariadic()) 5465 return nullptr; 5466 5467 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(), 5468 CurPEnd = CurMethod->param_end(), 5469 SuperP = SuperMethod->param_begin(); 5470 CurP != CurPEnd; ++CurP, ++SuperP) { 5471 // Make sure the parameter types are compatible. 5472 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), 5473 (*SuperP)->getType())) 5474 return nullptr; 5475 5476 // Make sure we have a parameter name to forward! 5477 if (!(*CurP)->getIdentifier()) 5478 return nullptr; 5479 } 5480 5481 // We have a superclass method. Now, form the send-to-super completion. 5482 CodeCompletionBuilder Builder(Results.getAllocator(), 5483 Results.getCodeCompletionTUInfo()); 5484 5485 // Give this completion a return type. 5486 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod, 5487 Results.getCompletionContext().getBaseType(), 5488 Builder); 5489 5490 // If we need the "super" keyword, add it (plus some spacing). 5491 if (NeedSuperKeyword) { 5492 Builder.AddTypedTextChunk("super"); 5493 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5494 } 5495 5496 Selector Sel = CurMethod->getSelector(); 5497 if (Sel.isUnarySelector()) { 5498 if (NeedSuperKeyword) 5499 Builder.AddTextChunk(Builder.getAllocator().CopyString( 5500 Sel.getNameForSlot(0))); 5501 else 5502 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 5503 Sel.getNameForSlot(0))); 5504 } else { 5505 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(); 5506 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { 5507 if (I > SelIdents.size()) 5508 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5509 5510 if (I < SelIdents.size()) 5511 Builder.AddInformativeChunk( 5512 Builder.getAllocator().CopyString( 5513 Sel.getNameForSlot(I) + ":")); 5514 else if (NeedSuperKeyword || I > SelIdents.size()) { 5515 Builder.AddTextChunk( 5516 Builder.getAllocator().CopyString( 5517 Sel.getNameForSlot(I) + ":")); 5518 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 5519 (*CurP)->getIdentifier()->getName())); 5520 } else { 5521 Builder.AddTypedTextChunk( 5522 Builder.getAllocator().CopyString( 5523 Sel.getNameForSlot(I) + ":")); 5524 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 5525 (*CurP)->getIdentifier()->getName())); 5526 } 5527 } 5528 } 5529 5530 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod, 5531 CCP_SuperCompletion)); 5532 return SuperMethod; 5533 } 5534 5535 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) { 5536 typedef CodeCompletionResult Result; 5537 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5538 CodeCompleter->getCodeCompletionTUInfo(), 5539 CodeCompletionContext::CCC_ObjCMessageReceiver, 5540 getLangOpts().CPlusPlus11 5541 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture 5542 : &ResultBuilder::IsObjCMessageReceiver); 5543 5544 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5545 Results.EnterNewScope(); 5546 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5547 CodeCompleter->includeGlobals()); 5548 5549 // If we are in an Objective-C method inside a class that has a superclass, 5550 // add "super" as an option. 5551 if (ObjCMethodDecl *Method = getCurMethodDecl()) 5552 if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) 5553 if (Iface->getSuperClass()) { 5554 Results.AddResult(Result("super")); 5555 5556 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results); 5557 } 5558 5559 if (getLangOpts().CPlusPlus11) 5560 addThisCompletion(*this, Results); 5561 5562 Results.ExitScope(); 5563 5564 if (CodeCompleter->includeMacros()) 5565 AddMacroResults(PP, Results, false); 5566 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5567 Results.data(), Results.size()); 5568 5569 } 5570 5571 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 5572 ArrayRef<IdentifierInfo *> SelIdents, 5573 bool AtArgumentExpression) { 5574 ObjCInterfaceDecl *CDecl = nullptr; 5575 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 5576 // Figure out which interface we're in. 5577 CDecl = CurMethod->getClassInterface(); 5578 if (!CDecl) 5579 return; 5580 5581 // Find the superclass of this class. 5582 CDecl = CDecl->getSuperClass(); 5583 if (!CDecl) 5584 return; 5585 5586 if (CurMethod->isInstanceMethod()) { 5587 // We are inside an instance method, which means that the message 5588 // send [super ...] is actually calling an instance method on the 5589 // current object. 5590 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents, 5591 AtArgumentExpression, 5592 CDecl); 5593 } 5594 5595 // Fall through to send to the superclass in CDecl. 5596 } else { 5597 // "super" may be the name of a type or variable. Figure out which 5598 // it is. 5599 IdentifierInfo *Super = getSuperIdentifier(); 5600 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, 5601 LookupOrdinaryName); 5602 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { 5603 // "super" names an interface. Use it. 5604 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) { 5605 if (const ObjCObjectType *Iface 5606 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>()) 5607 CDecl = Iface->getInterface(); 5608 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) { 5609 // "super" names an unresolved type; we can't be more specific. 5610 } else { 5611 // Assume that "super" names some kind of value and parse that way. 5612 CXXScopeSpec SS; 5613 SourceLocation TemplateKWLoc; 5614 UnqualifiedId id; 5615 id.setIdentifier(Super, SuperLoc); 5616 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id, 5617 false, false); 5618 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(), 5619 SelIdents, 5620 AtArgumentExpression); 5621 } 5622 5623 // Fall through 5624 } 5625 5626 ParsedType Receiver; 5627 if (CDecl) 5628 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl)); 5629 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, 5630 AtArgumentExpression, 5631 /*IsSuper=*/true); 5632 } 5633 5634 /// \brief Given a set of code-completion results for the argument of a message 5635 /// send, determine the preferred type (if any) for that argument expression. 5636 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, 5637 unsigned NumSelIdents) { 5638 typedef CodeCompletionResult Result; 5639 ASTContext &Context = Results.getSema().Context; 5640 5641 QualType PreferredType; 5642 unsigned BestPriority = CCP_Unlikely * 2; 5643 Result *ResultsData = Results.data(); 5644 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 5645 Result &R = ResultsData[I]; 5646 if (R.Kind == Result::RK_Declaration && 5647 isa<ObjCMethodDecl>(R.Declaration)) { 5648 if (R.Priority <= BestPriority) { 5649 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration); 5650 if (NumSelIdents <= Method->param_size()) { 5651 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1] 5652 ->getType(); 5653 if (R.Priority < BestPriority || PreferredType.isNull()) { 5654 BestPriority = R.Priority; 5655 PreferredType = MyPreferredType; 5656 } else if (!Context.hasSameUnqualifiedType(PreferredType, 5657 MyPreferredType)) { 5658 PreferredType = QualType(); 5659 } 5660 } 5661 } 5662 } 5663 } 5664 5665 return PreferredType; 5666 } 5667 5668 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 5669 ParsedType Receiver, 5670 ArrayRef<IdentifierInfo *> SelIdents, 5671 bool AtArgumentExpression, 5672 bool IsSuper, 5673 ResultBuilder &Results) { 5674 typedef CodeCompletionResult Result; 5675 ObjCInterfaceDecl *CDecl = nullptr; 5676 5677 // If the given name refers to an interface type, retrieve the 5678 // corresponding declaration. 5679 if (Receiver) { 5680 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr); 5681 if (!T.isNull()) 5682 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) 5683 CDecl = Interface->getInterface(); 5684 } 5685 5686 // Add all of the factory methods in this Objective-C class, its protocols, 5687 // superclasses, categories, implementation, etc. 5688 Results.EnterNewScope(); 5689 5690 // If this is a send-to-super, try to add the special "super" send 5691 // completion. 5692 if (IsSuper) { 5693 if (ObjCMethodDecl *SuperMethod 5694 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results)) 5695 Results.Ignore(SuperMethod); 5696 } 5697 5698 // If we're inside an Objective-C method definition, prefer its selector to 5699 // others. 5700 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) 5701 Results.setPreferredSelector(CurMethod->getSelector()); 5702 5703 VisitedSelectorSet Selectors; 5704 if (CDecl) 5705 AddObjCMethods(CDecl, false, MK_Any, SelIdents, 5706 SemaRef.CurContext, Selectors, AtArgumentExpression, 5707 Results); 5708 else { 5709 // We're messaging "id" as a type; provide all class/factory methods. 5710 5711 // If we have an external source, load the entire class method 5712 // pool from the AST file. 5713 if (SemaRef.getExternalSource()) { 5714 for (uint32_t I = 0, 5715 N = SemaRef.getExternalSource()->GetNumExternalSelectors(); 5716 I != N; ++I) { 5717 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I); 5718 if (Sel.isNull() || SemaRef.MethodPool.count(Sel)) 5719 continue; 5720 5721 SemaRef.ReadMethodPool(Sel); 5722 } 5723 } 5724 5725 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(), 5726 MEnd = SemaRef.MethodPool.end(); 5727 M != MEnd; ++M) { 5728 for (ObjCMethodList *MethList = &M->second.second; 5729 MethList && MethList->getMethod(); 5730 MethList = MethList->getNext()) { 5731 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 5732 continue; 5733 5734 Result R(MethList->getMethod(), 5735 Results.getBasePriority(MethList->getMethod()), nullptr); 5736 R.StartParameter = SelIdents.size(); 5737 R.AllParametersAreInformative = false; 5738 Results.MaybeAddResult(R, SemaRef.CurContext); 5739 } 5740 } 5741 } 5742 5743 Results.ExitScope(); 5744 } 5745 5746 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 5747 ArrayRef<IdentifierInfo *> SelIdents, 5748 bool AtArgumentExpression, 5749 bool IsSuper) { 5750 5751 QualType T = this->GetTypeFromParser(Receiver); 5752 5753 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5754 CodeCompleter->getCodeCompletionTUInfo(), 5755 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, 5756 T, SelIdents)); 5757 5758 AddClassMessageCompletions(*this, S, Receiver, SelIdents, 5759 AtArgumentExpression, IsSuper, Results); 5760 5761 // If we're actually at the argument expression (rather than prior to the 5762 // selector), we're actually performing code completion for an expression. 5763 // Determine whether we have a single, best method. If so, we can 5764 // code-complete the expression using the corresponding parameter type as 5765 // our preferred type, improving completion results. 5766 if (AtArgumentExpression) { 5767 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, 5768 SelIdents.size()); 5769 if (PreferredType.isNull()) 5770 CodeCompleteOrdinaryName(S, PCC_Expression); 5771 else 5772 CodeCompleteExpression(S, PreferredType); 5773 return; 5774 } 5775 5776 HandleCodeCompleteResults(this, CodeCompleter, 5777 Results.getCompletionContext(), 5778 Results.data(), Results.size()); 5779 } 5780 5781 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 5782 ArrayRef<IdentifierInfo *> SelIdents, 5783 bool AtArgumentExpression, 5784 ObjCInterfaceDecl *Super) { 5785 typedef CodeCompletionResult Result; 5786 5787 Expr *RecExpr = static_cast<Expr *>(Receiver); 5788 5789 // If necessary, apply function/array conversion to the receiver. 5790 // C99 6.7.5.3p[7,8]. 5791 if (RecExpr) { 5792 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr); 5793 if (Conv.isInvalid()) // conversion failed. bail. 5794 return; 5795 RecExpr = Conv.get(); 5796 } 5797 QualType ReceiverType = RecExpr? RecExpr->getType() 5798 : Super? Context.getObjCObjectPointerType( 5799 Context.getObjCInterfaceType(Super)) 5800 : Context.getObjCIdType(); 5801 5802 // If we're messaging an expression with type "id" or "Class", check 5803 // whether we know something special about the receiver that allows 5804 // us to assume a more-specific receiver type. 5805 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) { 5806 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) { 5807 if (ReceiverType->isObjCClassType()) 5808 return CodeCompleteObjCClassMessage(S, 5809 ParsedType::make(Context.getObjCInterfaceType(IFace)), 5810 SelIdents, 5811 AtArgumentExpression, Super); 5812 5813 ReceiverType = Context.getObjCObjectPointerType( 5814 Context.getObjCInterfaceType(IFace)); 5815 } 5816 } else if (RecExpr && getLangOpts().CPlusPlus) { 5817 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr); 5818 if (Conv.isUsable()) { 5819 RecExpr = Conv.get(); 5820 ReceiverType = RecExpr->getType(); 5821 } 5822 } 5823 5824 // Build the set of methods we can see. 5825 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5826 CodeCompleter->getCodeCompletionTUInfo(), 5827 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage, 5828 ReceiverType, SelIdents)); 5829 5830 Results.EnterNewScope(); 5831 5832 // If this is a send-to-super, try to add the special "super" send 5833 // completion. 5834 if (Super) { 5835 if (ObjCMethodDecl *SuperMethod 5836 = AddSuperSendCompletion(*this, false, SelIdents, Results)) 5837 Results.Ignore(SuperMethod); 5838 } 5839 5840 // If we're inside an Objective-C method definition, prefer its selector to 5841 // others. 5842 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) 5843 Results.setPreferredSelector(CurMethod->getSelector()); 5844 5845 // Keep track of the selectors we've already added. 5846 VisitedSelectorSet Selectors; 5847 5848 // Handle messages to Class. This really isn't a message to an instance 5849 // method, so we treat it the same way we would treat a message send to a 5850 // class method. 5851 if (ReceiverType->isObjCClassType() || 5852 ReceiverType->isObjCQualifiedClassType()) { 5853 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 5854 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) 5855 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, 5856 CurContext, Selectors, AtArgumentExpression, Results); 5857 } 5858 } 5859 // Handle messages to a qualified ID ("id<foo>"). 5860 else if (const ObjCObjectPointerType *QualID 5861 = ReceiverType->getAsObjCQualifiedIdType()) { 5862 // Search protocols for instance methods. 5863 for (auto *I : QualID->quals()) 5864 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, 5865 Selectors, AtArgumentExpression, Results); 5866 } 5867 // Handle messages to a pointer to interface type. 5868 else if (const ObjCObjectPointerType *IFacePtr 5869 = ReceiverType->getAsObjCInterfacePointerType()) { 5870 // Search the class, its superclasses, etc., for instance methods. 5871 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, 5872 CurContext, Selectors, AtArgumentExpression, 5873 Results); 5874 5875 // Search protocols for instance methods. 5876 for (auto *I : IFacePtr->quals()) 5877 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, 5878 Selectors, AtArgumentExpression, Results); 5879 } 5880 // Handle messages to "id". 5881 else if (ReceiverType->isObjCIdType()) { 5882 // We're messaging "id", so provide all instance methods we know 5883 // about as code-completion results. 5884 5885 // If we have an external source, load the entire class method 5886 // pool from the AST file. 5887 if (ExternalSource) { 5888 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 5889 I != N; ++I) { 5890 Selector Sel = ExternalSource->GetExternalSelector(I); 5891 if (Sel.isNull() || MethodPool.count(Sel)) 5892 continue; 5893 5894 ReadMethodPool(Sel); 5895 } 5896 } 5897 5898 for (GlobalMethodPool::iterator M = MethodPool.begin(), 5899 MEnd = MethodPool.end(); 5900 M != MEnd; ++M) { 5901 for (ObjCMethodList *MethList = &M->second.first; 5902 MethList && MethList->getMethod(); 5903 MethList = MethList->getNext()) { 5904 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 5905 continue; 5906 5907 if (!Selectors.insert(MethList->getMethod()->getSelector()).second) 5908 continue; 5909 5910 Result R(MethList->getMethod(), 5911 Results.getBasePriority(MethList->getMethod()), nullptr); 5912 R.StartParameter = SelIdents.size(); 5913 R.AllParametersAreInformative = false; 5914 Results.MaybeAddResult(R, CurContext); 5915 } 5916 } 5917 } 5918 Results.ExitScope(); 5919 5920 5921 // If we're actually at the argument expression (rather than prior to the 5922 // selector), we're actually performing code completion for an expression. 5923 // Determine whether we have a single, best method. If so, we can 5924 // code-complete the expression using the corresponding parameter type as 5925 // our preferred type, improving completion results. 5926 if (AtArgumentExpression) { 5927 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, 5928 SelIdents.size()); 5929 if (PreferredType.isNull()) 5930 CodeCompleteOrdinaryName(S, PCC_Expression); 5931 else 5932 CodeCompleteExpression(S, PreferredType); 5933 return; 5934 } 5935 5936 HandleCodeCompleteResults(this, CodeCompleter, 5937 Results.getCompletionContext(), 5938 Results.data(),Results.size()); 5939 } 5940 5941 void Sema::CodeCompleteObjCForCollection(Scope *S, 5942 DeclGroupPtrTy IterationVar) { 5943 CodeCompleteExpressionData Data; 5944 Data.ObjCCollection = true; 5945 5946 if (IterationVar.getAsOpaquePtr()) { 5947 DeclGroupRef DG = IterationVar.get(); 5948 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { 5949 if (*I) 5950 Data.IgnoreDecls.push_back(*I); 5951 } 5952 } 5953 5954 CodeCompleteExpression(S, Data); 5955 } 5956 5957 void Sema::CodeCompleteObjCSelector(Scope *S, 5958 ArrayRef<IdentifierInfo *> SelIdents) { 5959 // If we have an external source, load the entire class method 5960 // pool from the AST file. 5961 if (ExternalSource) { 5962 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 5963 I != N; ++I) { 5964 Selector Sel = ExternalSource->GetExternalSelector(I); 5965 if (Sel.isNull() || MethodPool.count(Sel)) 5966 continue; 5967 5968 ReadMethodPool(Sel); 5969 } 5970 } 5971 5972 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5973 CodeCompleter->getCodeCompletionTUInfo(), 5974 CodeCompletionContext::CCC_SelectorName); 5975 Results.EnterNewScope(); 5976 for (GlobalMethodPool::iterator M = MethodPool.begin(), 5977 MEnd = MethodPool.end(); 5978 M != MEnd; ++M) { 5979 5980 Selector Sel = M->first; 5981 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents)) 5982 continue; 5983 5984 CodeCompletionBuilder Builder(Results.getAllocator(), 5985 Results.getCodeCompletionTUInfo()); 5986 if (Sel.isUnarySelector()) { 5987 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 5988 Sel.getNameForSlot(0))); 5989 Results.AddResult(Builder.TakeString()); 5990 continue; 5991 } 5992 5993 std::string Accumulator; 5994 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { 5995 if (I == SelIdents.size()) { 5996 if (!Accumulator.empty()) { 5997 Builder.AddInformativeChunk(Builder.getAllocator().CopyString( 5998 Accumulator)); 5999 Accumulator.clear(); 6000 } 6001 } 6002 6003 Accumulator += Sel.getNameForSlot(I); 6004 Accumulator += ':'; 6005 } 6006 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator)); 6007 Results.AddResult(Builder.TakeString()); 6008 } 6009 Results.ExitScope(); 6010 6011 HandleCodeCompleteResults(this, CodeCompleter, 6012 CodeCompletionContext::CCC_SelectorName, 6013 Results.data(), Results.size()); 6014 } 6015 6016 /// \brief Add all of the protocol declarations that we find in the given 6017 /// (translation unit) context. 6018 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, 6019 bool OnlyForwardDeclarations, 6020 ResultBuilder &Results) { 6021 typedef CodeCompletionResult Result; 6022 6023 for (const auto *D : Ctx->decls()) { 6024 // Record any protocols we find. 6025 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D)) 6026 if (!OnlyForwardDeclarations || !Proto->hasDefinition()) 6027 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr), 6028 CurContext, nullptr, false); 6029 } 6030 } 6031 6032 void Sema::CodeCompleteObjCProtocolReferences( 6033 ArrayRef<IdentifierLocPair> Protocols) { 6034 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6035 CodeCompleter->getCodeCompletionTUInfo(), 6036 CodeCompletionContext::CCC_ObjCProtocolName); 6037 6038 if (CodeCompleter->includeGlobals()) { 6039 Results.EnterNewScope(); 6040 6041 // Tell the result set to ignore all of the protocols we have 6042 // already seen. 6043 // FIXME: This doesn't work when caching code-completion results. 6044 for (const IdentifierLocPair &Pair : Protocols) 6045 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, 6046 Pair.second)) 6047 Results.Ignore(Protocol); 6048 6049 // Add all protocols. 6050 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false, 6051 Results); 6052 6053 Results.ExitScope(); 6054 } 6055 6056 HandleCodeCompleteResults(this, CodeCompleter, 6057 CodeCompletionContext::CCC_ObjCProtocolName, 6058 Results.data(),Results.size()); 6059 } 6060 6061 void Sema::CodeCompleteObjCProtocolDecl(Scope *) { 6062 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6063 CodeCompleter->getCodeCompletionTUInfo(), 6064 CodeCompletionContext::CCC_ObjCProtocolName); 6065 6066 if (CodeCompleter->includeGlobals()) { 6067 Results.EnterNewScope(); 6068 6069 // Add all protocols. 6070 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true, 6071 Results); 6072 6073 Results.ExitScope(); 6074 } 6075 6076 HandleCodeCompleteResults(this, CodeCompleter, 6077 CodeCompletionContext::CCC_ObjCProtocolName, 6078 Results.data(),Results.size()); 6079 } 6080 6081 /// \brief Add all of the Objective-C interface declarations that we find in 6082 /// the given (translation unit) context. 6083 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, 6084 bool OnlyForwardDeclarations, 6085 bool OnlyUnimplemented, 6086 ResultBuilder &Results) { 6087 typedef CodeCompletionResult Result; 6088 6089 for (const auto *D : Ctx->decls()) { 6090 // Record any interfaces we find. 6091 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D)) 6092 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) && 6093 (!OnlyUnimplemented || !Class->getImplementation())) 6094 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr), 6095 CurContext, nullptr, false); 6096 } 6097 } 6098 6099 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { 6100 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6101 CodeCompleter->getCodeCompletionTUInfo(), 6102 CodeCompletionContext::CCC_Other); 6103 Results.EnterNewScope(); 6104 6105 if (CodeCompleter->includeGlobals()) { 6106 // Add all classes. 6107 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 6108 false, Results); 6109 } 6110 6111 Results.ExitScope(); 6112 6113 HandleCodeCompleteResults(this, CodeCompleter, 6114 CodeCompletionContext::CCC_ObjCInterfaceName, 6115 Results.data(),Results.size()); 6116 } 6117 6118 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, 6119 SourceLocation ClassNameLoc) { 6120 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6121 CodeCompleter->getCodeCompletionTUInfo(), 6122 CodeCompletionContext::CCC_ObjCInterfaceName); 6123 Results.EnterNewScope(); 6124 6125 // Make sure that we ignore the class we're currently defining. 6126 NamedDecl *CurClass 6127 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 6128 if (CurClass && isa<ObjCInterfaceDecl>(CurClass)) 6129 Results.Ignore(CurClass); 6130 6131 if (CodeCompleter->includeGlobals()) { 6132 // Add all classes. 6133 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 6134 false, Results); 6135 } 6136 6137 Results.ExitScope(); 6138 6139 HandleCodeCompleteResults(this, CodeCompleter, 6140 CodeCompletionContext::CCC_ObjCInterfaceName, 6141 Results.data(),Results.size()); 6142 } 6143 6144 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { 6145 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6146 CodeCompleter->getCodeCompletionTUInfo(), 6147 CodeCompletionContext::CCC_Other); 6148 Results.EnterNewScope(); 6149 6150 if (CodeCompleter->includeGlobals()) { 6151 // Add all unimplemented classes. 6152 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 6153 true, Results); 6154 } 6155 6156 Results.ExitScope(); 6157 6158 HandleCodeCompleteResults(this, CodeCompleter, 6159 CodeCompletionContext::CCC_ObjCInterfaceName, 6160 Results.data(),Results.size()); 6161 } 6162 6163 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, 6164 IdentifierInfo *ClassName, 6165 SourceLocation ClassNameLoc) { 6166 typedef CodeCompletionResult Result; 6167 6168 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6169 CodeCompleter->getCodeCompletionTUInfo(), 6170 CodeCompletionContext::CCC_ObjCCategoryName); 6171 6172 // Ignore any categories we find that have already been implemented by this 6173 // interface. 6174 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 6175 NamedDecl *CurClass 6176 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 6177 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){ 6178 for (const auto *Cat : Class->visible_categories()) 6179 CategoryNames.insert(Cat->getIdentifier()); 6180 } 6181 6182 // Add all of the categories we know about. 6183 Results.EnterNewScope(); 6184 TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 6185 for (const auto *D : TU->decls()) 6186 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D)) 6187 if (CategoryNames.insert(Category->getIdentifier()).second) 6188 Results.AddResult(Result(Category, Results.getBasePriority(Category), 6189 nullptr), 6190 CurContext, nullptr, false); 6191 Results.ExitScope(); 6192 6193 HandleCodeCompleteResults(this, CodeCompleter, 6194 CodeCompletionContext::CCC_ObjCCategoryName, 6195 Results.data(),Results.size()); 6196 } 6197 6198 void Sema::CodeCompleteObjCImplementationCategory(Scope *S, 6199 IdentifierInfo *ClassName, 6200 SourceLocation ClassNameLoc) { 6201 typedef CodeCompletionResult Result; 6202 6203 // Find the corresponding interface. If we couldn't find the interface, the 6204 // program itself is ill-formed. However, we'll try to be helpful still by 6205 // providing the list of all of the categories we know about. 6206 NamedDecl *CurClass 6207 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 6208 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); 6209 if (!Class) 6210 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); 6211 6212 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6213 CodeCompleter->getCodeCompletionTUInfo(), 6214 CodeCompletionContext::CCC_ObjCCategoryName); 6215 6216 // Add all of the categories that have have corresponding interface 6217 // declarations in this class and any of its superclasses, except for 6218 // already-implemented categories in the class itself. 6219 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 6220 Results.EnterNewScope(); 6221 bool IgnoreImplemented = true; 6222 while (Class) { 6223 for (const auto *Cat : Class->visible_categories()) { 6224 if ((!IgnoreImplemented || !Cat->getImplementation()) && 6225 CategoryNames.insert(Cat->getIdentifier()).second) 6226 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr), 6227 CurContext, nullptr, false); 6228 } 6229 6230 Class = Class->getSuperClass(); 6231 IgnoreImplemented = false; 6232 } 6233 Results.ExitScope(); 6234 6235 HandleCodeCompleteResults(this, CodeCompleter, 6236 CodeCompletionContext::CCC_ObjCCategoryName, 6237 Results.data(),Results.size()); 6238 } 6239 6240 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) { 6241 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other); 6242 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6243 CodeCompleter->getCodeCompletionTUInfo(), 6244 CCContext); 6245 6246 // Figure out where this @synthesize lives. 6247 ObjCContainerDecl *Container 6248 = dyn_cast_or_null<ObjCContainerDecl>(CurContext); 6249 if (!Container || 6250 (!isa<ObjCImplementationDecl>(Container) && 6251 !isa<ObjCCategoryImplDecl>(Container))) 6252 return; 6253 6254 // Ignore any properties that have already been implemented. 6255 Container = getContainerDef(Container); 6256 for (const auto *D : Container->decls()) 6257 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D)) 6258 Results.Ignore(PropertyImpl->getPropertyDecl()); 6259 6260 // Add any properties that we find. 6261 AddedPropertiesSet AddedProperties; 6262 Results.EnterNewScope(); 6263 if (ObjCImplementationDecl *ClassImpl 6264 = dyn_cast<ObjCImplementationDecl>(Container)) 6265 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false, 6266 /*AllowNullaryMethods=*/false, CurContext, 6267 AddedProperties, Results); 6268 else 6269 AddObjCProperties(CCContext, 6270 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), 6271 false, /*AllowNullaryMethods=*/false, CurContext, 6272 AddedProperties, Results); 6273 Results.ExitScope(); 6274 6275 HandleCodeCompleteResults(this, CodeCompleter, 6276 CodeCompletionContext::CCC_Other, 6277 Results.data(),Results.size()); 6278 } 6279 6280 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 6281 IdentifierInfo *PropertyName) { 6282 typedef CodeCompletionResult Result; 6283 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6284 CodeCompleter->getCodeCompletionTUInfo(), 6285 CodeCompletionContext::CCC_Other); 6286 6287 // Figure out where this @synthesize lives. 6288 ObjCContainerDecl *Container 6289 = dyn_cast_or_null<ObjCContainerDecl>(CurContext); 6290 if (!Container || 6291 (!isa<ObjCImplementationDecl>(Container) && 6292 !isa<ObjCCategoryImplDecl>(Container))) 6293 return; 6294 6295 // Figure out which interface we're looking into. 6296 ObjCInterfaceDecl *Class = nullptr; 6297 if (ObjCImplementationDecl *ClassImpl 6298 = dyn_cast<ObjCImplementationDecl>(Container)) 6299 Class = ClassImpl->getClassInterface(); 6300 else 6301 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl() 6302 ->getClassInterface(); 6303 6304 // Determine the type of the property we're synthesizing. 6305 QualType PropertyType = Context.getObjCIdType(); 6306 if (Class) { 6307 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration( 6308 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 6309 PropertyType 6310 = Property->getType().getNonReferenceType().getUnqualifiedType(); 6311 6312 // Give preference to ivars 6313 Results.setPreferredType(PropertyType); 6314 } 6315 } 6316 6317 // Add all of the instance variables in this class and its superclasses. 6318 Results.EnterNewScope(); 6319 bool SawSimilarlyNamedIvar = false; 6320 std::string NameWithPrefix; 6321 NameWithPrefix += '_'; 6322 NameWithPrefix += PropertyName->getName(); 6323 std::string NameWithSuffix = PropertyName->getName().str(); 6324 NameWithSuffix += '_'; 6325 for(; Class; Class = Class->getSuperClass()) { 6326 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar; 6327 Ivar = Ivar->getNextIvar()) { 6328 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr), 6329 CurContext, nullptr, false); 6330 6331 // Determine whether we've seen an ivar with a name similar to the 6332 // property. 6333 if ((PropertyName == Ivar->getIdentifier() || 6334 NameWithPrefix == Ivar->getName() || 6335 NameWithSuffix == Ivar->getName())) { 6336 SawSimilarlyNamedIvar = true; 6337 6338 // Reduce the priority of this result by one, to give it a slight 6339 // advantage over other results whose names don't match so closely. 6340 if (Results.size() && 6341 Results.data()[Results.size() - 1].Kind 6342 == CodeCompletionResult::RK_Declaration && 6343 Results.data()[Results.size() - 1].Declaration == Ivar) 6344 Results.data()[Results.size() - 1].Priority--; 6345 } 6346 } 6347 } 6348 6349 if (!SawSimilarlyNamedIvar) { 6350 // Create ivar result _propName, that the user can use to synthesize 6351 // an ivar of the appropriate type. 6352 unsigned Priority = CCP_MemberDeclaration + 1; 6353 typedef CodeCompletionResult Result; 6354 CodeCompletionAllocator &Allocator = Results.getAllocator(); 6355 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(), 6356 Priority,CXAvailability_Available); 6357 6358 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 6359 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context, 6360 Policy, Allocator)); 6361 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix)); 6362 Results.AddResult(Result(Builder.TakeString(), Priority, 6363 CXCursor_ObjCIvarDecl)); 6364 } 6365 6366 Results.ExitScope(); 6367 6368 HandleCodeCompleteResults(this, CodeCompleter, 6369 CodeCompletionContext::CCC_Other, 6370 Results.data(),Results.size()); 6371 } 6372 6373 // Mapping from selectors to the methods that implement that selector, along 6374 // with the "in original class" flag. 6375 typedef llvm::DenseMap< 6376 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap; 6377 6378 /// \brief Find all of the methods that reside in the given container 6379 /// (and its superclasses, protocols, etc.) that meet the given 6380 /// criteria. Insert those methods into the map of known methods, 6381 /// indexed by selector so they can be easily found. 6382 static void FindImplementableMethods(ASTContext &Context, 6383 ObjCContainerDecl *Container, 6384 bool WantInstanceMethods, 6385 QualType ReturnType, 6386 KnownMethodsMap &KnownMethods, 6387 bool InOriginalClass = true) { 6388 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) { 6389 // Make sure we have a definition; that's what we'll walk. 6390 if (!IFace->hasDefinition()) 6391 return; 6392 6393 IFace = IFace->getDefinition(); 6394 Container = IFace; 6395 6396 const ObjCList<ObjCProtocolDecl> &Protocols 6397 = IFace->getReferencedProtocols(); 6398 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6399 E = Protocols.end(); 6400 I != E; ++I) 6401 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 6402 KnownMethods, InOriginalClass); 6403 6404 // Add methods from any class extensions and categories. 6405 for (auto *Cat : IFace->visible_categories()) { 6406 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType, 6407 KnownMethods, false); 6408 } 6409 6410 // Visit the superclass. 6411 if (IFace->getSuperClass()) 6412 FindImplementableMethods(Context, IFace->getSuperClass(), 6413 WantInstanceMethods, ReturnType, 6414 KnownMethods, false); 6415 } 6416 6417 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 6418 // Recurse into protocols. 6419 const ObjCList<ObjCProtocolDecl> &Protocols 6420 = Category->getReferencedProtocols(); 6421 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6422 E = Protocols.end(); 6423 I != E; ++I) 6424 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 6425 KnownMethods, InOriginalClass); 6426 6427 // If this category is the original class, jump to the interface. 6428 if (InOriginalClass && Category->getClassInterface()) 6429 FindImplementableMethods(Context, Category->getClassInterface(), 6430 WantInstanceMethods, ReturnType, KnownMethods, 6431 false); 6432 } 6433 6434 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 6435 // Make sure we have a definition; that's what we'll walk. 6436 if (!Protocol->hasDefinition()) 6437 return; 6438 Protocol = Protocol->getDefinition(); 6439 Container = Protocol; 6440 6441 // Recurse into protocols. 6442 const ObjCList<ObjCProtocolDecl> &Protocols 6443 = Protocol->getReferencedProtocols(); 6444 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6445 E = Protocols.end(); 6446 I != E; ++I) 6447 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 6448 KnownMethods, false); 6449 } 6450 6451 // Add methods in this container. This operation occurs last because 6452 // we want the methods from this container to override any methods 6453 // we've previously seen with the same selector. 6454 for (auto *M : Container->methods()) { 6455 if (M->isInstanceMethod() == WantInstanceMethods) { 6456 if (!ReturnType.isNull() && 6457 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType())) 6458 continue; 6459 6460 KnownMethods[M->getSelector()] = 6461 KnownMethodsMap::mapped_type(M, InOriginalClass); 6462 } 6463 } 6464 } 6465 6466 /// \brief Add the parenthesized return or parameter type chunk to a code 6467 /// completion string. 6468 static void AddObjCPassingTypeChunk(QualType Type, 6469 unsigned ObjCDeclQuals, 6470 ASTContext &Context, 6471 const PrintingPolicy &Policy, 6472 CodeCompletionBuilder &Builder) { 6473 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6474 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type); 6475 if (!Quals.empty()) 6476 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals)); 6477 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy, 6478 Builder.getAllocator())); 6479 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6480 } 6481 6482 /// \brief Determine whether the given class is or inherits from a class by 6483 /// the given name. 6484 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, 6485 StringRef Name) { 6486 if (!Class) 6487 return false; 6488 6489 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name) 6490 return true; 6491 6492 return InheritsFromClassNamed(Class->getSuperClass(), Name); 6493 } 6494 6495 /// \brief Add code completions for Objective-C Key-Value Coding (KVC) and 6496 /// Key-Value Observing (KVO). 6497 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, 6498 bool IsInstanceMethod, 6499 QualType ReturnType, 6500 ASTContext &Context, 6501 VisitedSelectorSet &KnownSelectors, 6502 ResultBuilder &Results) { 6503 IdentifierInfo *PropName = Property->getIdentifier(); 6504 if (!PropName || PropName->getLength() == 0) 6505 return; 6506 6507 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 6508 6509 // Builder that will create each code completion. 6510 typedef CodeCompletionResult Result; 6511 CodeCompletionAllocator &Allocator = Results.getAllocator(); 6512 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 6513 6514 // The selector table. 6515 SelectorTable &Selectors = Context.Selectors; 6516 6517 // The property name, copied into the code completion allocation region 6518 // on demand. 6519 struct KeyHolder { 6520 CodeCompletionAllocator &Allocator; 6521 StringRef Key; 6522 const char *CopiedKey; 6523 6524 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key) 6525 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {} 6526 6527 operator const char *() { 6528 if (CopiedKey) 6529 return CopiedKey; 6530 6531 return CopiedKey = Allocator.CopyString(Key); 6532 } 6533 } Key(Allocator, PropName->getName()); 6534 6535 // The uppercased name of the property name. 6536 std::string UpperKey = PropName->getName(); 6537 if (!UpperKey.empty()) 6538 UpperKey[0] = toUppercase(UpperKey[0]); 6539 6540 bool ReturnTypeMatchesProperty = ReturnType.isNull() || 6541 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(), 6542 Property->getType()); 6543 bool ReturnTypeMatchesVoid 6544 = ReturnType.isNull() || ReturnType->isVoidType(); 6545 6546 // Add the normal accessor -(type)key. 6547 if (IsInstanceMethod && 6548 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second && 6549 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) { 6550 if (ReturnType.isNull()) 6551 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, 6552 Context, Policy, Builder); 6553 6554 Builder.AddTypedTextChunk(Key); 6555 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 6556 CXCursor_ObjCInstanceMethodDecl)); 6557 } 6558 6559 // If we have an integral or boolean property (or the user has provided 6560 // an integral or boolean return type), add the accessor -(type)isKey. 6561 if (IsInstanceMethod && 6562 ((!ReturnType.isNull() && 6563 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) || 6564 (ReturnType.isNull() && 6565 (Property->getType()->isIntegerType() || 6566 Property->getType()->isBooleanType())))) { 6567 std::string SelectorName = (Twine("is") + UpperKey).str(); 6568 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6569 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 6570 .second) { 6571 if (ReturnType.isNull()) { 6572 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6573 Builder.AddTextChunk("BOOL"); 6574 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6575 } 6576 6577 Builder.AddTypedTextChunk( 6578 Allocator.CopyString(SelectorId->getName())); 6579 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 6580 CXCursor_ObjCInstanceMethodDecl)); 6581 } 6582 } 6583 6584 // Add the normal mutator. 6585 if (IsInstanceMethod && ReturnTypeMatchesVoid && 6586 !Property->getSetterMethodDecl()) { 6587 std::string SelectorName = (Twine("set") + UpperKey).str(); 6588 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6589 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 6590 if (ReturnType.isNull()) { 6591 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6592 Builder.AddTextChunk("void"); 6593 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6594 } 6595 6596 Builder.AddTypedTextChunk( 6597 Allocator.CopyString(SelectorId->getName())); 6598 Builder.AddTypedTextChunk(":"); 6599 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, 6600 Context, Policy, Builder); 6601 Builder.AddTextChunk(Key); 6602 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 6603 CXCursor_ObjCInstanceMethodDecl)); 6604 } 6605 } 6606 6607 // Indexed and unordered accessors 6608 unsigned IndexedGetterPriority = CCP_CodePattern; 6609 unsigned IndexedSetterPriority = CCP_CodePattern; 6610 unsigned UnorderedGetterPriority = CCP_CodePattern; 6611 unsigned UnorderedSetterPriority = CCP_CodePattern; 6612 if (const ObjCObjectPointerType *ObjCPointer 6613 = Property->getType()->getAs<ObjCObjectPointerType>()) { 6614 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) { 6615 // If this interface type is not provably derived from a known 6616 // collection, penalize the corresponding completions. 6617 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) { 6618 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 6619 if (!InheritsFromClassNamed(IFace, "NSArray")) 6620 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 6621 } 6622 6623 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) { 6624 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 6625 if (!InheritsFromClassNamed(IFace, "NSSet")) 6626 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 6627 } 6628 } 6629 } else { 6630 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 6631 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 6632 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 6633 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 6634 } 6635 6636 // Add -(NSUInteger)countOf<key> 6637 if (IsInstanceMethod && 6638 (ReturnType.isNull() || ReturnType->isIntegerType())) { 6639 std::string SelectorName = (Twine("countOf") + UpperKey).str(); 6640 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6641 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 6642 .second) { 6643 if (ReturnType.isNull()) { 6644 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6645 Builder.AddTextChunk("NSUInteger"); 6646 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6647 } 6648 6649 Builder.AddTypedTextChunk( 6650 Allocator.CopyString(SelectorId->getName())); 6651 Results.AddResult(Result(Builder.TakeString(), 6652 std::min(IndexedGetterPriority, 6653 UnorderedGetterPriority), 6654 CXCursor_ObjCInstanceMethodDecl)); 6655 } 6656 } 6657 6658 // Indexed getters 6659 // Add -(id)objectInKeyAtIndex:(NSUInteger)index 6660 if (IsInstanceMethod && 6661 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 6662 std::string SelectorName 6663 = (Twine("objectIn") + UpperKey + "AtIndex").str(); 6664 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6665 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 6666 if (ReturnType.isNull()) { 6667 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6668 Builder.AddTextChunk("id"); 6669 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6670 } 6671 6672 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 6673 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6674 Builder.AddTextChunk("NSUInteger"); 6675 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6676 Builder.AddTextChunk("index"); 6677 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 6678 CXCursor_ObjCInstanceMethodDecl)); 6679 } 6680 } 6681 6682 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes 6683 if (IsInstanceMethod && 6684 (ReturnType.isNull() || 6685 (ReturnType->isObjCObjectPointerType() && 6686 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 6687 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() 6688 ->getName() == "NSArray"))) { 6689 std::string SelectorName 6690 = (Twine(Property->getName()) + "AtIndexes").str(); 6691 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6692 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 6693 if (ReturnType.isNull()) { 6694 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6695 Builder.AddTextChunk("NSArray *"); 6696 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6697 } 6698 6699 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 6700 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6701 Builder.AddTextChunk("NSIndexSet *"); 6702 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6703 Builder.AddTextChunk("indexes"); 6704 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 6705 CXCursor_ObjCInstanceMethodDecl)); 6706 } 6707 } 6708 6709 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange 6710 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 6711 std::string SelectorName = (Twine("get") + UpperKey).str(); 6712 IdentifierInfo *SelectorIds[2] = { 6713 &Context.Idents.get(SelectorName), 6714 &Context.Idents.get("range") 6715 }; 6716 6717 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 6718 if (ReturnType.isNull()) { 6719 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6720 Builder.AddTextChunk("void"); 6721 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6722 } 6723 6724 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 6725 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6726 Builder.AddPlaceholderChunk("object-type"); 6727 Builder.AddTextChunk(" **"); 6728 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6729 Builder.AddTextChunk("buffer"); 6730 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6731 Builder.AddTypedTextChunk("range:"); 6732 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6733 Builder.AddTextChunk("NSRange"); 6734 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6735 Builder.AddTextChunk("inRange"); 6736 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 6737 CXCursor_ObjCInstanceMethodDecl)); 6738 } 6739 } 6740 6741 // Mutable indexed accessors 6742 6743 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index 6744 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 6745 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str(); 6746 IdentifierInfo *SelectorIds[2] = { 6747 &Context.Idents.get("insertObject"), 6748 &Context.Idents.get(SelectorName) 6749 }; 6750 6751 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 6752 if (ReturnType.isNull()) { 6753 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6754 Builder.AddTextChunk("void"); 6755 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6756 } 6757 6758 Builder.AddTypedTextChunk("insertObject:"); 6759 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6760 Builder.AddPlaceholderChunk("object-type"); 6761 Builder.AddTextChunk(" *"); 6762 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6763 Builder.AddTextChunk("object"); 6764 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6765 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 6766 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6767 Builder.AddPlaceholderChunk("NSUInteger"); 6768 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6769 Builder.AddTextChunk("index"); 6770 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 6771 CXCursor_ObjCInstanceMethodDecl)); 6772 } 6773 } 6774 6775 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes 6776 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 6777 std::string SelectorName = (Twine("insert") + UpperKey).str(); 6778 IdentifierInfo *SelectorIds[2] = { 6779 &Context.Idents.get(SelectorName), 6780 &Context.Idents.get("atIndexes") 6781 }; 6782 6783 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 6784 if (ReturnType.isNull()) { 6785 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6786 Builder.AddTextChunk("void"); 6787 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6788 } 6789 6790 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 6791 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6792 Builder.AddTextChunk("NSArray *"); 6793 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6794 Builder.AddTextChunk("array"); 6795 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6796 Builder.AddTypedTextChunk("atIndexes:"); 6797 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6798 Builder.AddPlaceholderChunk("NSIndexSet *"); 6799 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6800 Builder.AddTextChunk("indexes"); 6801 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 6802 CXCursor_ObjCInstanceMethodDecl)); 6803 } 6804 } 6805 6806 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index 6807 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 6808 std::string SelectorName 6809 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str(); 6810 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6811 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 6812 if (ReturnType.isNull()) { 6813 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6814 Builder.AddTextChunk("void"); 6815 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6816 } 6817 6818 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 6819 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6820 Builder.AddTextChunk("NSUInteger"); 6821 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6822 Builder.AddTextChunk("index"); 6823 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 6824 CXCursor_ObjCInstanceMethodDecl)); 6825 } 6826 } 6827 6828 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes 6829 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 6830 std::string SelectorName 6831 = (Twine("remove") + UpperKey + "AtIndexes").str(); 6832 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6833 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 6834 if (ReturnType.isNull()) { 6835 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6836 Builder.AddTextChunk("void"); 6837 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6838 } 6839 6840 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 6841 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6842 Builder.AddTextChunk("NSIndexSet *"); 6843 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6844 Builder.AddTextChunk("indexes"); 6845 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 6846 CXCursor_ObjCInstanceMethodDecl)); 6847 } 6848 } 6849 6850 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object 6851 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 6852 std::string SelectorName 6853 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str(); 6854 IdentifierInfo *SelectorIds[2] = { 6855 &Context.Idents.get(SelectorName), 6856 &Context.Idents.get("withObject") 6857 }; 6858 6859 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 6860 if (ReturnType.isNull()) { 6861 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6862 Builder.AddTextChunk("void"); 6863 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6864 } 6865 6866 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 6867 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6868 Builder.AddPlaceholderChunk("NSUInteger"); 6869 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6870 Builder.AddTextChunk("index"); 6871 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6872 Builder.AddTypedTextChunk("withObject:"); 6873 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6874 Builder.AddTextChunk("id"); 6875 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6876 Builder.AddTextChunk("object"); 6877 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 6878 CXCursor_ObjCInstanceMethodDecl)); 6879 } 6880 } 6881 6882 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array 6883 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 6884 std::string SelectorName1 6885 = (Twine("replace") + UpperKey + "AtIndexes").str(); 6886 std::string SelectorName2 = (Twine("with") + UpperKey).str(); 6887 IdentifierInfo *SelectorIds[2] = { 6888 &Context.Idents.get(SelectorName1), 6889 &Context.Idents.get(SelectorName2) 6890 }; 6891 6892 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 6893 if (ReturnType.isNull()) { 6894 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6895 Builder.AddTextChunk("void"); 6896 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6897 } 6898 6899 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":")); 6900 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6901 Builder.AddPlaceholderChunk("NSIndexSet *"); 6902 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6903 Builder.AddTextChunk("indexes"); 6904 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6905 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":")); 6906 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6907 Builder.AddTextChunk("NSArray *"); 6908 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6909 Builder.AddTextChunk("array"); 6910 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 6911 CXCursor_ObjCInstanceMethodDecl)); 6912 } 6913 } 6914 6915 // Unordered getters 6916 // - (NSEnumerator *)enumeratorOfKey 6917 if (IsInstanceMethod && 6918 (ReturnType.isNull() || 6919 (ReturnType->isObjCObjectPointerType() && 6920 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 6921 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() 6922 ->getName() == "NSEnumerator"))) { 6923 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str(); 6924 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6925 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 6926 .second) { 6927 if (ReturnType.isNull()) { 6928 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6929 Builder.AddTextChunk("NSEnumerator *"); 6930 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6931 } 6932 6933 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 6934 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 6935 CXCursor_ObjCInstanceMethodDecl)); 6936 } 6937 } 6938 6939 // - (type *)memberOfKey:(type *)object 6940 if (IsInstanceMethod && 6941 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 6942 std::string SelectorName = (Twine("memberOf") + UpperKey).str(); 6943 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6944 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 6945 if (ReturnType.isNull()) { 6946 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6947 Builder.AddPlaceholderChunk("object-type"); 6948 Builder.AddTextChunk(" *"); 6949 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6950 } 6951 6952 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 6953 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6954 if (ReturnType.isNull()) { 6955 Builder.AddPlaceholderChunk("object-type"); 6956 Builder.AddTextChunk(" *"); 6957 } else { 6958 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context, 6959 Policy, 6960 Builder.getAllocator())); 6961 } 6962 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6963 Builder.AddTextChunk("object"); 6964 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 6965 CXCursor_ObjCInstanceMethodDecl)); 6966 } 6967 } 6968 6969 // Mutable unordered accessors 6970 // - (void)addKeyObject:(type *)object 6971 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 6972 std::string SelectorName 6973 = (Twine("add") + UpperKey + Twine("Object")).str(); 6974 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6975 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 6976 if (ReturnType.isNull()) { 6977 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6978 Builder.AddTextChunk("void"); 6979 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6980 } 6981 6982 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 6983 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6984 Builder.AddPlaceholderChunk("object-type"); 6985 Builder.AddTextChunk(" *"); 6986 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6987 Builder.AddTextChunk("object"); 6988 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 6989 CXCursor_ObjCInstanceMethodDecl)); 6990 } 6991 } 6992 6993 // - (void)addKey:(NSSet *)objects 6994 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 6995 std::string SelectorName = (Twine("add") + UpperKey).str(); 6996 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6997 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 6998 if (ReturnType.isNull()) { 6999 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7000 Builder.AddTextChunk("void"); 7001 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7002 } 7003 7004 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7005 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7006 Builder.AddTextChunk("NSSet *"); 7007 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7008 Builder.AddTextChunk("objects"); 7009 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7010 CXCursor_ObjCInstanceMethodDecl)); 7011 } 7012 } 7013 7014 // - (void)removeKeyObject:(type *)object 7015 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7016 std::string SelectorName 7017 = (Twine("remove") + UpperKey + Twine("Object")).str(); 7018 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7019 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7020 if (ReturnType.isNull()) { 7021 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7022 Builder.AddTextChunk("void"); 7023 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7024 } 7025 7026 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7027 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7028 Builder.AddPlaceholderChunk("object-type"); 7029 Builder.AddTextChunk(" *"); 7030 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7031 Builder.AddTextChunk("object"); 7032 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7033 CXCursor_ObjCInstanceMethodDecl)); 7034 } 7035 } 7036 7037 // - (void)removeKey:(NSSet *)objects 7038 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7039 std::string SelectorName = (Twine("remove") + UpperKey).str(); 7040 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7041 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7042 if (ReturnType.isNull()) { 7043 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7044 Builder.AddTextChunk("void"); 7045 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7046 } 7047 7048 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7049 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7050 Builder.AddTextChunk("NSSet *"); 7051 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7052 Builder.AddTextChunk("objects"); 7053 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7054 CXCursor_ObjCInstanceMethodDecl)); 7055 } 7056 } 7057 7058 // - (void)intersectKey:(NSSet *)objects 7059 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7060 std::string SelectorName = (Twine("intersect") + UpperKey).str(); 7061 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7062 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7063 if (ReturnType.isNull()) { 7064 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7065 Builder.AddTextChunk("void"); 7066 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7067 } 7068 7069 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7070 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7071 Builder.AddTextChunk("NSSet *"); 7072 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7073 Builder.AddTextChunk("objects"); 7074 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7075 CXCursor_ObjCInstanceMethodDecl)); 7076 } 7077 } 7078 7079 // Key-Value Observing 7080 // + (NSSet *)keyPathsForValuesAffectingKey 7081 if (!IsInstanceMethod && 7082 (ReturnType.isNull() || 7083 (ReturnType->isObjCObjectPointerType() && 7084 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 7085 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() 7086 ->getName() == "NSSet"))) { 7087 std::string SelectorName 7088 = (Twine("keyPathsForValuesAffecting") + UpperKey).str(); 7089 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7090 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7091 .second) { 7092 if (ReturnType.isNull()) { 7093 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7094 Builder.AddTextChunk("NSSet *"); 7095 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7096 } 7097 7098 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 7099 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7100 CXCursor_ObjCClassMethodDecl)); 7101 } 7102 } 7103 7104 // + (BOOL)automaticallyNotifiesObserversForKey 7105 if (!IsInstanceMethod && 7106 (ReturnType.isNull() || 7107 ReturnType->isIntegerType() || 7108 ReturnType->isBooleanType())) { 7109 std::string SelectorName 7110 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str(); 7111 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7112 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7113 .second) { 7114 if (ReturnType.isNull()) { 7115 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7116 Builder.AddTextChunk("BOOL"); 7117 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7118 } 7119 7120 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 7121 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7122 CXCursor_ObjCClassMethodDecl)); 7123 } 7124 } 7125 } 7126 7127 void Sema::CodeCompleteObjCMethodDecl(Scope *S, 7128 bool IsInstanceMethod, 7129 ParsedType ReturnTy) { 7130 // Determine the return type of the method we're declaring, if 7131 // provided. 7132 QualType ReturnType = GetTypeFromParser(ReturnTy); 7133 Decl *IDecl = nullptr; 7134 if (CurContext->isObjCContainer()) { 7135 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 7136 IDecl = cast<Decl>(OCD); 7137 } 7138 // Determine where we should start searching for methods. 7139 ObjCContainerDecl *SearchDecl = nullptr; 7140 bool IsInImplementation = false; 7141 if (Decl *D = IDecl) { 7142 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { 7143 SearchDecl = Impl->getClassInterface(); 7144 IsInImplementation = true; 7145 } else if (ObjCCategoryImplDecl *CatImpl 7146 = dyn_cast<ObjCCategoryImplDecl>(D)) { 7147 SearchDecl = CatImpl->getCategoryDecl(); 7148 IsInImplementation = true; 7149 } else 7150 SearchDecl = dyn_cast<ObjCContainerDecl>(D); 7151 } 7152 7153 if (!SearchDecl && S) { 7154 if (DeclContext *DC = S->getEntity()) 7155 SearchDecl = dyn_cast<ObjCContainerDecl>(DC); 7156 } 7157 7158 if (!SearchDecl) { 7159 HandleCodeCompleteResults(this, CodeCompleter, 7160 CodeCompletionContext::CCC_Other, 7161 nullptr, 0); 7162 return; 7163 } 7164 7165 // Find all of the methods that we could declare/implement here. 7166 KnownMethodsMap KnownMethods; 7167 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, 7168 ReturnType, KnownMethods); 7169 7170 // Add declarations or definitions for each of the known methods. 7171 typedef CodeCompletionResult Result; 7172 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7173 CodeCompleter->getCodeCompletionTUInfo(), 7174 CodeCompletionContext::CCC_Other); 7175 Results.EnterNewScope(); 7176 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 7177 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 7178 MEnd = KnownMethods.end(); 7179 M != MEnd; ++M) { 7180 ObjCMethodDecl *Method = M->second.getPointer(); 7181 CodeCompletionBuilder Builder(Results.getAllocator(), 7182 Results.getCodeCompletionTUInfo()); 7183 7184 // If the result type was not already provided, add it to the 7185 // pattern as (type). 7186 if (ReturnType.isNull()) { 7187 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context); 7188 AttributedType::stripOuterNullability(ResTy); 7189 AddObjCPassingTypeChunk(ResTy, 7190 Method->getObjCDeclQualifier(), Context, Policy, 7191 Builder); 7192 } 7193 7194 Selector Sel = Method->getSelector(); 7195 7196 // Add the first part of the selector to the pattern. 7197 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 7198 Sel.getNameForSlot(0))); 7199 7200 // Add parameters to the pattern. 7201 unsigned I = 0; 7202 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 7203 PEnd = Method->param_end(); 7204 P != PEnd; (void)++P, ++I) { 7205 // Add the part of the selector name. 7206 if (I == 0) 7207 Builder.AddTypedTextChunk(":"); 7208 else if (I < Sel.getNumArgs()) { 7209 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7210 Builder.AddTypedTextChunk( 7211 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 7212 } else 7213 break; 7214 7215 // Add the parameter type. 7216 QualType ParamType; 7217 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 7218 ParamType = (*P)->getType(); 7219 else 7220 ParamType = (*P)->getOriginalType(); 7221 ParamType = ParamType.substObjCTypeArgs(Context, {}, 7222 ObjCSubstitutionContext::Parameter); 7223 AttributedType::stripOuterNullability(ParamType); 7224 AddObjCPassingTypeChunk(ParamType, 7225 (*P)->getObjCDeclQualifier(), 7226 Context, Policy, 7227 Builder); 7228 7229 if (IdentifierInfo *Id = (*P)->getIdentifier()) 7230 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName())); 7231 } 7232 7233 if (Method->isVariadic()) { 7234 if (Method->param_size() > 0) 7235 Builder.AddChunk(CodeCompletionString::CK_Comma); 7236 Builder.AddTextChunk("..."); 7237 } 7238 7239 if (IsInImplementation && Results.includeCodePatterns()) { 7240 // We will be defining the method here, so add a compound statement. 7241 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7242 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 7243 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 7244 if (!Method->getReturnType()->isVoidType()) { 7245 // If the result type is not void, add a return clause. 7246 Builder.AddTextChunk("return"); 7247 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7248 Builder.AddPlaceholderChunk("expression"); 7249 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 7250 } else 7251 Builder.AddPlaceholderChunk("statements"); 7252 7253 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 7254 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 7255 } 7256 7257 unsigned Priority = CCP_CodePattern; 7258 if (!M->second.getInt()) 7259 Priority += CCD_InBaseClass; 7260 7261 Results.AddResult(Result(Builder.TakeString(), Method, Priority)); 7262 } 7263 7264 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of 7265 // the properties in this class and its categories. 7266 if (Context.getLangOpts().ObjC2) { 7267 SmallVector<ObjCContainerDecl *, 4> Containers; 7268 Containers.push_back(SearchDecl); 7269 7270 VisitedSelectorSet KnownSelectors; 7271 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 7272 MEnd = KnownMethods.end(); 7273 M != MEnd; ++M) 7274 KnownSelectors.insert(M->first); 7275 7276 7277 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl); 7278 if (!IFace) 7279 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl)) 7280 IFace = Category->getClassInterface(); 7281 7282 if (IFace) 7283 for (auto *Cat : IFace->visible_categories()) 7284 Containers.push_back(Cat); 7285 7286 for (unsigned I = 0, N = Containers.size(); I != N; ++I) 7287 for (auto *P : Containers[I]->instance_properties()) 7288 AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context, 7289 KnownSelectors, Results); 7290 } 7291 7292 Results.ExitScope(); 7293 7294 HandleCodeCompleteResults(this, CodeCompleter, 7295 CodeCompletionContext::CCC_Other, 7296 Results.data(),Results.size()); 7297 } 7298 7299 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S, 7300 bool IsInstanceMethod, 7301 bool AtParameterName, 7302 ParsedType ReturnTy, 7303 ArrayRef<IdentifierInfo *> SelIdents) { 7304 // If we have an external source, load the entire class method 7305 // pool from the AST file. 7306 if (ExternalSource) { 7307 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 7308 I != N; ++I) { 7309 Selector Sel = ExternalSource->GetExternalSelector(I); 7310 if (Sel.isNull() || MethodPool.count(Sel)) 7311 continue; 7312 7313 ReadMethodPool(Sel); 7314 } 7315 } 7316 7317 // Build the set of methods we can see. 7318 typedef CodeCompletionResult Result; 7319 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7320 CodeCompleter->getCodeCompletionTUInfo(), 7321 CodeCompletionContext::CCC_Other); 7322 7323 if (ReturnTy) 7324 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType()); 7325 7326 Results.EnterNewScope(); 7327 for (GlobalMethodPool::iterator M = MethodPool.begin(), 7328 MEnd = MethodPool.end(); 7329 M != MEnd; ++M) { 7330 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first : 7331 &M->second.second; 7332 MethList && MethList->getMethod(); 7333 MethList = MethList->getNext()) { 7334 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 7335 continue; 7336 7337 if (AtParameterName) { 7338 // Suggest parameter names we've seen before. 7339 unsigned NumSelIdents = SelIdents.size(); 7340 if (NumSelIdents && 7341 NumSelIdents <= MethList->getMethod()->param_size()) { 7342 ParmVarDecl *Param = 7343 MethList->getMethod()->parameters()[NumSelIdents - 1]; 7344 if (Param->getIdentifier()) { 7345 CodeCompletionBuilder Builder(Results.getAllocator(), 7346 Results.getCodeCompletionTUInfo()); 7347 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 7348 Param->getIdentifier()->getName())); 7349 Results.AddResult(Builder.TakeString()); 7350 } 7351 } 7352 7353 continue; 7354 } 7355 7356 Result R(MethList->getMethod(), 7357 Results.getBasePriority(MethList->getMethod()), nullptr); 7358 R.StartParameter = SelIdents.size(); 7359 R.AllParametersAreInformative = false; 7360 R.DeclaringEntity = true; 7361 Results.MaybeAddResult(R, CurContext); 7362 } 7363 } 7364 7365 Results.ExitScope(); 7366 HandleCodeCompleteResults(this, CodeCompleter, 7367 CodeCompletionContext::CCC_Other, 7368 Results.data(),Results.size()); 7369 } 7370 7371 void Sema::CodeCompletePreprocessorDirective(bool InConditional) { 7372 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7373 CodeCompleter->getCodeCompletionTUInfo(), 7374 CodeCompletionContext::CCC_PreprocessorDirective); 7375 Results.EnterNewScope(); 7376 7377 // #if <condition> 7378 CodeCompletionBuilder Builder(Results.getAllocator(), 7379 Results.getCodeCompletionTUInfo()); 7380 Builder.AddTypedTextChunk("if"); 7381 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7382 Builder.AddPlaceholderChunk("condition"); 7383 Results.AddResult(Builder.TakeString()); 7384 7385 // #ifdef <macro> 7386 Builder.AddTypedTextChunk("ifdef"); 7387 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7388 Builder.AddPlaceholderChunk("macro"); 7389 Results.AddResult(Builder.TakeString()); 7390 7391 // #ifndef <macro> 7392 Builder.AddTypedTextChunk("ifndef"); 7393 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7394 Builder.AddPlaceholderChunk("macro"); 7395 Results.AddResult(Builder.TakeString()); 7396 7397 if (InConditional) { 7398 // #elif <condition> 7399 Builder.AddTypedTextChunk("elif"); 7400 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7401 Builder.AddPlaceholderChunk("condition"); 7402 Results.AddResult(Builder.TakeString()); 7403 7404 // #else 7405 Builder.AddTypedTextChunk("else"); 7406 Results.AddResult(Builder.TakeString()); 7407 7408 // #endif 7409 Builder.AddTypedTextChunk("endif"); 7410 Results.AddResult(Builder.TakeString()); 7411 } 7412 7413 // #include "header" 7414 Builder.AddTypedTextChunk("include"); 7415 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7416 Builder.AddTextChunk("\""); 7417 Builder.AddPlaceholderChunk("header"); 7418 Builder.AddTextChunk("\""); 7419 Results.AddResult(Builder.TakeString()); 7420 7421 // #include <header> 7422 Builder.AddTypedTextChunk("include"); 7423 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7424 Builder.AddTextChunk("<"); 7425 Builder.AddPlaceholderChunk("header"); 7426 Builder.AddTextChunk(">"); 7427 Results.AddResult(Builder.TakeString()); 7428 7429 // #define <macro> 7430 Builder.AddTypedTextChunk("define"); 7431 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7432 Builder.AddPlaceholderChunk("macro"); 7433 Results.AddResult(Builder.TakeString()); 7434 7435 // #define <macro>(<args>) 7436 Builder.AddTypedTextChunk("define"); 7437 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7438 Builder.AddPlaceholderChunk("macro"); 7439 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7440 Builder.AddPlaceholderChunk("args"); 7441 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7442 Results.AddResult(Builder.TakeString()); 7443 7444 // #undef <macro> 7445 Builder.AddTypedTextChunk("undef"); 7446 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7447 Builder.AddPlaceholderChunk("macro"); 7448 Results.AddResult(Builder.TakeString()); 7449 7450 // #line <number> 7451 Builder.AddTypedTextChunk("line"); 7452 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7453 Builder.AddPlaceholderChunk("number"); 7454 Results.AddResult(Builder.TakeString()); 7455 7456 // #line <number> "filename" 7457 Builder.AddTypedTextChunk("line"); 7458 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7459 Builder.AddPlaceholderChunk("number"); 7460 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7461 Builder.AddTextChunk("\""); 7462 Builder.AddPlaceholderChunk("filename"); 7463 Builder.AddTextChunk("\""); 7464 Results.AddResult(Builder.TakeString()); 7465 7466 // #error <message> 7467 Builder.AddTypedTextChunk("error"); 7468 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7469 Builder.AddPlaceholderChunk("message"); 7470 Results.AddResult(Builder.TakeString()); 7471 7472 // #pragma <arguments> 7473 Builder.AddTypedTextChunk("pragma"); 7474 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7475 Builder.AddPlaceholderChunk("arguments"); 7476 Results.AddResult(Builder.TakeString()); 7477 7478 if (getLangOpts().ObjC1) { 7479 // #import "header" 7480 Builder.AddTypedTextChunk("import"); 7481 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7482 Builder.AddTextChunk("\""); 7483 Builder.AddPlaceholderChunk("header"); 7484 Builder.AddTextChunk("\""); 7485 Results.AddResult(Builder.TakeString()); 7486 7487 // #import <header> 7488 Builder.AddTypedTextChunk("import"); 7489 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7490 Builder.AddTextChunk("<"); 7491 Builder.AddPlaceholderChunk("header"); 7492 Builder.AddTextChunk(">"); 7493 Results.AddResult(Builder.TakeString()); 7494 } 7495 7496 // #include_next "header" 7497 Builder.AddTypedTextChunk("include_next"); 7498 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7499 Builder.AddTextChunk("\""); 7500 Builder.AddPlaceholderChunk("header"); 7501 Builder.AddTextChunk("\""); 7502 Results.AddResult(Builder.TakeString()); 7503 7504 // #include_next <header> 7505 Builder.AddTypedTextChunk("include_next"); 7506 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7507 Builder.AddTextChunk("<"); 7508 Builder.AddPlaceholderChunk("header"); 7509 Builder.AddTextChunk(">"); 7510 Results.AddResult(Builder.TakeString()); 7511 7512 // #warning <message> 7513 Builder.AddTypedTextChunk("warning"); 7514 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7515 Builder.AddPlaceholderChunk("message"); 7516 Results.AddResult(Builder.TakeString()); 7517 7518 // Note: #ident and #sccs are such crazy anachronisms that we don't provide 7519 // completions for them. And __include_macros is a Clang-internal extension 7520 // that we don't want to encourage anyone to use. 7521 7522 // FIXME: we don't support #assert or #unassert, so don't suggest them. 7523 Results.ExitScope(); 7524 7525 HandleCodeCompleteResults(this, CodeCompleter, 7526 CodeCompletionContext::CCC_PreprocessorDirective, 7527 Results.data(), Results.size()); 7528 } 7529 7530 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) { 7531 CodeCompleteOrdinaryName(S, 7532 S->getFnParent()? Sema::PCC_RecoveryInFunction 7533 : Sema::PCC_Namespace); 7534 } 7535 7536 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) { 7537 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7538 CodeCompleter->getCodeCompletionTUInfo(), 7539 IsDefinition? CodeCompletionContext::CCC_MacroName 7540 : CodeCompletionContext::CCC_MacroNameUse); 7541 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) { 7542 // Add just the names of macros, not their arguments. 7543 CodeCompletionBuilder Builder(Results.getAllocator(), 7544 Results.getCodeCompletionTUInfo()); 7545 Results.EnterNewScope(); 7546 for (Preprocessor::macro_iterator M = PP.macro_begin(), 7547 MEnd = PP.macro_end(); 7548 M != MEnd; ++M) { 7549 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 7550 M->first->getName())); 7551 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 7552 CCP_CodePattern, 7553 CXCursor_MacroDefinition)); 7554 } 7555 Results.ExitScope(); 7556 } else if (IsDefinition) { 7557 // FIXME: Can we detect when the user just wrote an include guard above? 7558 } 7559 7560 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7561 Results.data(), Results.size()); 7562 } 7563 7564 void Sema::CodeCompletePreprocessorExpression() { 7565 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7566 CodeCompleter->getCodeCompletionTUInfo(), 7567 CodeCompletionContext::CCC_PreprocessorExpression); 7568 7569 if (!CodeCompleter || CodeCompleter->includeMacros()) 7570 AddMacroResults(PP, Results, true); 7571 7572 // defined (<macro>) 7573 Results.EnterNewScope(); 7574 CodeCompletionBuilder Builder(Results.getAllocator(), 7575 Results.getCodeCompletionTUInfo()); 7576 Builder.AddTypedTextChunk("defined"); 7577 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7578 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7579 Builder.AddPlaceholderChunk("macro"); 7580 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7581 Results.AddResult(Builder.TakeString()); 7582 Results.ExitScope(); 7583 7584 HandleCodeCompleteResults(this, CodeCompleter, 7585 CodeCompletionContext::CCC_PreprocessorExpression, 7586 Results.data(), Results.size()); 7587 } 7588 7589 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S, 7590 IdentifierInfo *Macro, 7591 MacroInfo *MacroInfo, 7592 unsigned Argument) { 7593 // FIXME: In the future, we could provide "overload" results, much like we 7594 // do for function calls. 7595 7596 // Now just ignore this. There will be another code-completion callback 7597 // for the expanded tokens. 7598 } 7599 7600 void Sema::CodeCompleteNaturalLanguage() { 7601 HandleCodeCompleteResults(this, CodeCompleter, 7602 CodeCompletionContext::CCC_NaturalLanguage, 7603 nullptr, 0); 7604 } 7605 7606 void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 7607 CodeCompletionTUInfo &CCTUInfo, 7608 SmallVectorImpl<CodeCompletionResult> &Results) { 7609 ResultBuilder Builder(*this, Allocator, CCTUInfo, 7610 CodeCompletionContext::CCC_Recovery); 7611 if (!CodeCompleter || CodeCompleter->includeGlobals()) { 7612 CodeCompletionDeclConsumer Consumer(Builder, 7613 Context.getTranslationUnitDecl()); 7614 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName, 7615 Consumer); 7616 } 7617 7618 if (!CodeCompleter || CodeCompleter->includeMacros()) 7619 AddMacroResults(PP, Builder, true); 7620 7621 Results.clear(); 7622 Results.insert(Results.end(), 7623 Builder.data(), Builder.data() + Builder.size()); 7624 } 7625