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