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