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