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