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