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