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