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