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->getTypedefForAnonDecl()) { 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->getTypedefDecl()->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::Var: return CXCursor_VarDecl; 2644 case Decl::Namespace: return CXCursor_Namespace; 2645 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias; 2646 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter; 2647 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter; 2648 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter; 2649 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate; 2650 case Decl::ClassTemplate: return CXCursor_ClassTemplate; 2651 case Decl::ClassTemplatePartialSpecialization: 2652 return CXCursor_ClassTemplatePartialSpecialization; 2653 case Decl::UsingDirective: return CXCursor_UsingDirective; 2654 2655 case Decl::Using: 2656 case Decl::UnresolvedUsingValue: 2657 case Decl::UnresolvedUsingTypename: 2658 return CXCursor_UsingDeclaration; 2659 2660 default: 2661 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 2662 switch (TD->getTagKind()) { 2663 case TTK_Struct: return CXCursor_StructDecl; 2664 case TTK_Class: return CXCursor_ClassDecl; 2665 case TTK_Union: return CXCursor_UnionDecl; 2666 case TTK_Enum: return CXCursor_EnumDecl; 2667 } 2668 } 2669 } 2670 2671 return CXCursor_UnexposedDecl; 2672 } 2673 2674 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results, 2675 bool TargetTypeIsPointer = false) { 2676 typedef CodeCompletionResult Result; 2677 2678 Results.EnterNewScope(); 2679 2680 for (Preprocessor::macro_iterator M = PP.macro_begin(), 2681 MEnd = PP.macro_end(); 2682 M != MEnd; ++M) { 2683 Results.AddResult(Result(M->first, 2684 getMacroUsagePriority(M->first->getName(), 2685 PP.getLangOptions(), 2686 TargetTypeIsPointer))); 2687 } 2688 2689 Results.ExitScope(); 2690 2691 } 2692 2693 static void AddPrettyFunctionResults(const LangOptions &LangOpts, 2694 ResultBuilder &Results) { 2695 typedef CodeCompletionResult Result; 2696 2697 Results.EnterNewScope(); 2698 2699 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant)); 2700 Results.AddResult(Result("__FUNCTION__", CCP_Constant)); 2701 if (LangOpts.C99 || LangOpts.CPlusPlus0x) 2702 Results.AddResult(Result("__func__", CCP_Constant)); 2703 Results.ExitScope(); 2704 } 2705 2706 static void HandleCodeCompleteResults(Sema *S, 2707 CodeCompleteConsumer *CodeCompleter, 2708 CodeCompletionContext Context, 2709 CodeCompletionResult *Results, 2710 unsigned NumResults) { 2711 if (CodeCompleter) 2712 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults); 2713 } 2714 2715 static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S, 2716 Sema::ParserCompletionContext PCC) { 2717 switch (PCC) { 2718 case Sema::PCC_Namespace: 2719 return CodeCompletionContext::CCC_TopLevel; 2720 2721 case Sema::PCC_Class: 2722 return CodeCompletionContext::CCC_ClassStructUnion; 2723 2724 case Sema::PCC_ObjCInterface: 2725 return CodeCompletionContext::CCC_ObjCInterface; 2726 2727 case Sema::PCC_ObjCImplementation: 2728 return CodeCompletionContext::CCC_ObjCImplementation; 2729 2730 case Sema::PCC_ObjCInstanceVariableList: 2731 return CodeCompletionContext::CCC_ObjCIvarList; 2732 2733 case Sema::PCC_Template: 2734 case Sema::PCC_MemberTemplate: 2735 if (S.CurContext->isFileContext()) 2736 return CodeCompletionContext::CCC_TopLevel; 2737 else if (S.CurContext->isRecord()) 2738 return CodeCompletionContext::CCC_ClassStructUnion; 2739 else 2740 return CodeCompletionContext::CCC_Other; 2741 2742 case Sema::PCC_RecoveryInFunction: 2743 return CodeCompletionContext::CCC_Recovery; 2744 2745 case Sema::PCC_ForInit: 2746 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 || 2747 S.getLangOptions().ObjC1) 2748 return CodeCompletionContext::CCC_ParenthesizedExpression; 2749 else 2750 return CodeCompletionContext::CCC_Expression; 2751 2752 case Sema::PCC_Expression: 2753 case Sema::PCC_Condition: 2754 return CodeCompletionContext::CCC_Expression; 2755 2756 case Sema::PCC_Statement: 2757 return CodeCompletionContext::CCC_Statement; 2758 2759 case Sema::PCC_Type: 2760 return CodeCompletionContext::CCC_Type; 2761 2762 case Sema::PCC_ParenthesizedExpression: 2763 return CodeCompletionContext::CCC_ParenthesizedExpression; 2764 2765 case Sema::PCC_LocalDeclarationSpecifiers: 2766 return CodeCompletionContext::CCC_Type; 2767 } 2768 2769 return CodeCompletionContext::CCC_Other; 2770 } 2771 2772 /// \brief If we're in a C++ virtual member function, add completion results 2773 /// that invoke the functions we override, since it's common to invoke the 2774 /// overridden function as well as adding new functionality. 2775 /// 2776 /// \param S The semantic analysis object for which we are generating results. 2777 /// 2778 /// \param InContext This context in which the nested-name-specifier preceding 2779 /// the code-completion point 2780 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext, 2781 ResultBuilder &Results) { 2782 // Look through blocks. 2783 DeclContext *CurContext = S.CurContext; 2784 while (isa<BlockDecl>(CurContext)) 2785 CurContext = CurContext->getParent(); 2786 2787 2788 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext); 2789 if (!Method || !Method->isVirtual()) 2790 return; 2791 2792 // We need to have names for all of the parameters, if we're going to 2793 // generate a forwarding call. 2794 for (CXXMethodDecl::param_iterator P = Method->param_begin(), 2795 PEnd = Method->param_end(); 2796 P != PEnd; 2797 ++P) { 2798 if (!(*P)->getDeclName()) 2799 return; 2800 } 2801 2802 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(), 2803 MEnd = Method->end_overridden_methods(); 2804 M != MEnd; ++M) { 2805 CodeCompletionBuilder Builder(Results.getAllocator()); 2806 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M); 2807 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl()) 2808 continue; 2809 2810 // If we need a nested-name-specifier, add one now. 2811 if (!InContext) { 2812 NestedNameSpecifier *NNS 2813 = getRequiredQualification(S.Context, CurContext, 2814 Overridden->getDeclContext()); 2815 if (NNS) { 2816 std::string Str; 2817 llvm::raw_string_ostream OS(Str); 2818 NNS->print(OS, S.Context.PrintingPolicy); 2819 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str())); 2820 } 2821 } else if (!InContext->Equals(Overridden->getDeclContext())) 2822 continue; 2823 2824 Builder.AddTypedTextChunk(Results.getAllocator().CopyString( 2825 Overridden->getNameAsString())); 2826 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2827 bool FirstParam = true; 2828 for (CXXMethodDecl::param_iterator P = Method->param_begin(), 2829 PEnd = Method->param_end(); 2830 P != PEnd; ++P) { 2831 if (FirstParam) 2832 FirstParam = false; 2833 else 2834 Builder.AddChunk(CodeCompletionString::CK_Comma); 2835 2836 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString( 2837 (*P)->getIdentifier()->getName())); 2838 } 2839 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2840 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 2841 CCP_SuperCompletion, 2842 CXCursor_CXXMethod)); 2843 Results.Ignore(Overridden); 2844 } 2845 } 2846 2847 void Sema::CodeCompleteOrdinaryName(Scope *S, 2848 ParserCompletionContext CompletionContext) { 2849 typedef CodeCompletionResult Result; 2850 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 2851 mapCodeCompletionContext(*this, CompletionContext)); 2852 Results.EnterNewScope(); 2853 2854 // Determine how to filter results, e.g., so that the names of 2855 // values (functions, enumerators, function templates, etc.) are 2856 // only allowed where we can have an expression. 2857 switch (CompletionContext) { 2858 case PCC_Namespace: 2859 case PCC_Class: 2860 case PCC_ObjCInterface: 2861 case PCC_ObjCImplementation: 2862 case PCC_ObjCInstanceVariableList: 2863 case PCC_Template: 2864 case PCC_MemberTemplate: 2865 case PCC_Type: 2866 case PCC_LocalDeclarationSpecifiers: 2867 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 2868 break; 2869 2870 case PCC_Statement: 2871 case PCC_ParenthesizedExpression: 2872 case PCC_Expression: 2873 case PCC_ForInit: 2874 case PCC_Condition: 2875 if (WantTypesInContext(CompletionContext, getLangOptions())) 2876 Results.setFilter(&ResultBuilder::IsOrdinaryName); 2877 else 2878 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); 2879 2880 if (getLangOptions().CPlusPlus) 2881 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results); 2882 break; 2883 2884 case PCC_RecoveryInFunction: 2885 // Unfiltered 2886 break; 2887 } 2888 2889 // If we are in a C++ non-static member function, check the qualifiers on 2890 // the member function to filter/prioritize the results list. 2891 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext)) 2892 if (CurMethod->isInstance()) 2893 Results.setObjectTypeQualifiers( 2894 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers())); 2895 2896 CodeCompletionDeclConsumer Consumer(Results, CurContext); 2897 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 2898 CodeCompleter->includeGlobals()); 2899 2900 AddOrdinaryNameResults(CompletionContext, S, *this, Results); 2901 Results.ExitScope(); 2902 2903 switch (CompletionContext) { 2904 case PCC_ParenthesizedExpression: 2905 case PCC_Expression: 2906 case PCC_Statement: 2907 case PCC_RecoveryInFunction: 2908 if (S->getFnParent()) 2909 AddPrettyFunctionResults(PP.getLangOptions(), Results); 2910 break; 2911 2912 case PCC_Namespace: 2913 case PCC_Class: 2914 case PCC_ObjCInterface: 2915 case PCC_ObjCImplementation: 2916 case PCC_ObjCInstanceVariableList: 2917 case PCC_Template: 2918 case PCC_MemberTemplate: 2919 case PCC_ForInit: 2920 case PCC_Condition: 2921 case PCC_Type: 2922 case PCC_LocalDeclarationSpecifiers: 2923 break; 2924 } 2925 2926 if (CodeCompleter->includeMacros()) 2927 AddMacroResults(PP, Results); 2928 2929 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 2930 Results.data(),Results.size()); 2931 } 2932 2933 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 2934 ParsedType Receiver, 2935 IdentifierInfo **SelIdents, 2936 unsigned NumSelIdents, 2937 bool AtArgumentExpression, 2938 bool IsSuper, 2939 ResultBuilder &Results); 2940 2941 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 2942 bool AllowNonIdentifiers, 2943 bool AllowNestedNameSpecifiers) { 2944 typedef CodeCompletionResult Result; 2945 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 2946 AllowNestedNameSpecifiers 2947 ? CodeCompletionContext::CCC_PotentiallyQualifiedName 2948 : CodeCompletionContext::CCC_Name); 2949 Results.EnterNewScope(); 2950 2951 // Type qualifiers can come after names. 2952 Results.AddResult(Result("const")); 2953 Results.AddResult(Result("volatile")); 2954 if (getLangOptions().C99) 2955 Results.AddResult(Result("restrict")); 2956 2957 if (getLangOptions().CPlusPlus) { 2958 if (AllowNonIdentifiers) { 2959 Results.AddResult(Result("operator")); 2960 } 2961 2962 // Add nested-name-specifiers. 2963 if (AllowNestedNameSpecifiers) { 2964 Results.allowNestedNameSpecifiers(); 2965 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy); 2966 CodeCompletionDeclConsumer Consumer(Results, CurContext); 2967 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, 2968 CodeCompleter->includeGlobals()); 2969 Results.setFilter(0); 2970 } 2971 } 2972 Results.ExitScope(); 2973 2974 // If we're in a context where we might have an expression (rather than a 2975 // declaration), and what we've seen so far is an Objective-C type that could 2976 // be a receiver of a class message, this may be a class message send with 2977 // the initial opening bracket '[' missing. Add appropriate completions. 2978 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers && 2979 DS.getTypeSpecType() == DeclSpec::TST_typename && 2980 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified && 2981 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() && 2982 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified && 2983 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 2984 DS.getTypeQualifiers() == 0 && 2985 S && 2986 (S->getFlags() & Scope::DeclScope) != 0 && 2987 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope | 2988 Scope::FunctionPrototypeScope | 2989 Scope::AtCatchScope)) == 0) { 2990 ParsedType T = DS.getRepAsType(); 2991 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType()) 2992 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results); 2993 } 2994 2995 // Note that we intentionally suppress macro results here, since we do not 2996 // encourage using macros to produce the names of entities. 2997 2998 HandleCodeCompleteResults(this, CodeCompleter, 2999 Results.getCompletionContext(), 3000 Results.data(), Results.size()); 3001 } 3002 3003 struct Sema::CodeCompleteExpressionData { 3004 CodeCompleteExpressionData(QualType PreferredType = QualType()) 3005 : PreferredType(PreferredType), IntegralConstantExpression(false), 3006 ObjCCollection(false) { } 3007 3008 QualType PreferredType; 3009 bool IntegralConstantExpression; 3010 bool ObjCCollection; 3011 llvm::SmallVector<Decl *, 4> IgnoreDecls; 3012 }; 3013 3014 /// \brief Perform code-completion in an expression context when we know what 3015 /// type we're looking for. 3016 /// 3017 /// \param IntegralConstantExpression Only permit integral constant 3018 /// expressions. 3019 void Sema::CodeCompleteExpression(Scope *S, 3020 const CodeCompleteExpressionData &Data) { 3021 typedef CodeCompletionResult Result; 3022 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3023 CodeCompletionContext::CCC_Expression); 3024 if (Data.ObjCCollection) 3025 Results.setFilter(&ResultBuilder::IsObjCCollection); 3026 else if (Data.IntegralConstantExpression) 3027 Results.setFilter(&ResultBuilder::IsIntegralConstantValue); 3028 else if (WantTypesInContext(PCC_Expression, getLangOptions())) 3029 Results.setFilter(&ResultBuilder::IsOrdinaryName); 3030 else 3031 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); 3032 3033 if (!Data.PreferredType.isNull()) 3034 Results.setPreferredType(Data.PreferredType.getNonReferenceType()); 3035 3036 // Ignore any declarations that we were told that we don't care about. 3037 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I) 3038 Results.Ignore(Data.IgnoreDecls[I]); 3039 3040 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3041 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3042 CodeCompleter->includeGlobals()); 3043 3044 Results.EnterNewScope(); 3045 AddOrdinaryNameResults(PCC_Expression, S, *this, Results); 3046 Results.ExitScope(); 3047 3048 bool PreferredTypeIsPointer = false; 3049 if (!Data.PreferredType.isNull()) 3050 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() 3051 || Data.PreferredType->isMemberPointerType() 3052 || Data.PreferredType->isBlockPointerType(); 3053 3054 if (S->getFnParent() && 3055 !Data.ObjCCollection && 3056 !Data.IntegralConstantExpression) 3057 AddPrettyFunctionResults(PP.getLangOptions(), Results); 3058 3059 if (CodeCompleter->includeMacros()) 3060 AddMacroResults(PP, Results, PreferredTypeIsPointer); 3061 HandleCodeCompleteResults(this, CodeCompleter, 3062 CodeCompletionContext(CodeCompletionContext::CCC_Expression, 3063 Data.PreferredType), 3064 Results.data(),Results.size()); 3065 } 3066 3067 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) { 3068 if (E.isInvalid()) 3069 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction); 3070 else if (getLangOptions().ObjC1) 3071 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false); 3072 } 3073 3074 /// \brief The set of properties that have already been added, referenced by 3075 /// property name. 3076 typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet; 3077 3078 static void AddObjCProperties(ObjCContainerDecl *Container, 3079 bool AllowCategories, 3080 DeclContext *CurContext, 3081 AddedPropertiesSet &AddedProperties, 3082 ResultBuilder &Results) { 3083 typedef CodeCompletionResult Result; 3084 3085 // Add properties in this container. 3086 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(), 3087 PEnd = Container->prop_end(); 3088 P != PEnd; 3089 ++P) { 3090 if (AddedProperties.insert(P->getIdentifier())) 3091 Results.MaybeAddResult(Result(*P, 0), CurContext); 3092 } 3093 3094 // Add properties in referenced protocols. 3095 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 3096 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(), 3097 PEnd = Protocol->protocol_end(); 3098 P != PEnd; ++P) 3099 AddObjCProperties(*P, AllowCategories, CurContext, AddedProperties, 3100 Results); 3101 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){ 3102 if (AllowCategories) { 3103 // Look through categories. 3104 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); 3105 Category; Category = Category->getNextClassCategory()) 3106 AddObjCProperties(Category, AllowCategories, CurContext, 3107 AddedProperties, Results); 3108 } 3109 3110 // Look through protocols. 3111 for (ObjCInterfaceDecl::all_protocol_iterator 3112 I = IFace->all_referenced_protocol_begin(), 3113 E = IFace->all_referenced_protocol_end(); I != E; ++I) 3114 AddObjCProperties(*I, AllowCategories, CurContext, AddedProperties, 3115 Results); 3116 3117 // Look in the superclass. 3118 if (IFace->getSuperClass()) 3119 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext, 3120 AddedProperties, Results); 3121 } else if (const ObjCCategoryDecl *Category 3122 = dyn_cast<ObjCCategoryDecl>(Container)) { 3123 // Look through protocols. 3124 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(), 3125 PEnd = Category->protocol_end(); 3126 P != PEnd; ++P) 3127 AddObjCProperties(*P, AllowCategories, CurContext, AddedProperties, 3128 Results); 3129 } 3130 } 3131 3132 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE, 3133 SourceLocation OpLoc, 3134 bool IsArrow) { 3135 if (!BaseE || !CodeCompleter) 3136 return; 3137 3138 typedef CodeCompletionResult Result; 3139 3140 Expr *Base = static_cast<Expr *>(BaseE); 3141 QualType BaseType = Base->getType(); 3142 3143 if (IsArrow) { 3144 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 3145 BaseType = Ptr->getPointeeType(); 3146 else if (BaseType->isObjCObjectPointerType()) 3147 /*Do nothing*/ ; 3148 else 3149 return; 3150 } 3151 3152 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3153 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess, 3154 BaseType), 3155 &ResultBuilder::IsMember); 3156 Results.EnterNewScope(); 3157 if (const RecordType *Record = BaseType->getAs<RecordType>()) { 3158 // Indicate that we are performing a member access, and the cv-qualifiers 3159 // for the base object type. 3160 Results.setObjectTypeQualifiers(BaseType.getQualifiers()); 3161 3162 // Access to a C/C++ class, struct, or union. 3163 Results.allowNestedNameSpecifiers(); 3164 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3165 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer, 3166 CodeCompleter->includeGlobals()); 3167 3168 if (getLangOptions().CPlusPlus) { 3169 if (!Results.empty()) { 3170 // The "template" keyword can follow "->" or "." in the grammar. 3171 // However, we only want to suggest the template keyword if something 3172 // is dependent. 3173 bool IsDependent = BaseType->isDependentType(); 3174 if (!IsDependent) { 3175 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) 3176 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) { 3177 IsDependent = Ctx->isDependentContext(); 3178 break; 3179 } 3180 } 3181 3182 if (IsDependent) 3183 Results.AddResult(Result("template")); 3184 } 3185 } 3186 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) { 3187 // Objective-C property reference. 3188 AddedPropertiesSet AddedProperties; 3189 3190 // Add property results based on our interface. 3191 const ObjCObjectPointerType *ObjCPtr 3192 = BaseType->getAsObjCInterfacePointerType(); 3193 assert(ObjCPtr && "Non-NULL pointer guaranteed above!"); 3194 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, 3195 AddedProperties, Results); 3196 3197 // Add properties from the protocols in a qualified interface. 3198 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(), 3199 E = ObjCPtr->qual_end(); 3200 I != E; ++I) 3201 AddObjCProperties(*I, true, CurContext, AddedProperties, Results); 3202 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || 3203 (!IsArrow && BaseType->isObjCObjectType())) { 3204 // Objective-C instance variable access. 3205 ObjCInterfaceDecl *Class = 0; 3206 if (const ObjCObjectPointerType *ObjCPtr 3207 = BaseType->getAs<ObjCObjectPointerType>()) 3208 Class = ObjCPtr->getInterfaceDecl(); 3209 else 3210 Class = BaseType->getAs<ObjCObjectType>()->getInterface(); 3211 3212 // Add all ivars from this class and its superclasses. 3213 if (Class) { 3214 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3215 Results.setFilter(&ResultBuilder::IsObjCIvar); 3216 LookupVisibleDecls(Class, LookupMemberName, Consumer, 3217 CodeCompleter->includeGlobals()); 3218 } 3219 } 3220 3221 // FIXME: How do we cope with isa? 3222 3223 Results.ExitScope(); 3224 3225 // Hand off the results found for code completion. 3226 HandleCodeCompleteResults(this, CodeCompleter, 3227 Results.getCompletionContext(), 3228 Results.data(),Results.size()); 3229 } 3230 3231 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) { 3232 if (!CodeCompleter) 3233 return; 3234 3235 typedef CodeCompletionResult Result; 3236 ResultBuilder::LookupFilter Filter = 0; 3237 enum CodeCompletionContext::Kind ContextKind 3238 = CodeCompletionContext::CCC_Other; 3239 switch ((DeclSpec::TST)TagSpec) { 3240 case DeclSpec::TST_enum: 3241 Filter = &ResultBuilder::IsEnum; 3242 ContextKind = CodeCompletionContext::CCC_EnumTag; 3243 break; 3244 3245 case DeclSpec::TST_union: 3246 Filter = &ResultBuilder::IsUnion; 3247 ContextKind = CodeCompletionContext::CCC_UnionTag; 3248 break; 3249 3250 case DeclSpec::TST_struct: 3251 case DeclSpec::TST_class: 3252 Filter = &ResultBuilder::IsClassOrStruct; 3253 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag; 3254 break; 3255 3256 default: 3257 assert(false && "Unknown type specifier kind in CodeCompleteTag"); 3258 return; 3259 } 3260 3261 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind); 3262 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3263 3264 // First pass: look for tags. 3265 Results.setFilter(Filter); 3266 LookupVisibleDecls(S, LookupTagName, Consumer, 3267 CodeCompleter->includeGlobals()); 3268 3269 if (CodeCompleter->includeGlobals()) { 3270 // Second pass: look for nested name specifiers. 3271 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); 3272 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer); 3273 } 3274 3275 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 3276 Results.data(),Results.size()); 3277 } 3278 3279 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) { 3280 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3281 CodeCompletionContext::CCC_TypeQualifiers); 3282 Results.EnterNewScope(); 3283 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const)) 3284 Results.AddResult("const"); 3285 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile)) 3286 Results.AddResult("volatile"); 3287 if (getLangOptions().C99 && 3288 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict)) 3289 Results.AddResult("restrict"); 3290 Results.ExitScope(); 3291 HandleCodeCompleteResults(this, CodeCompleter, 3292 Results.getCompletionContext(), 3293 Results.data(), Results.size()); 3294 } 3295 3296 void Sema::CodeCompleteCase(Scope *S) { 3297 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter) 3298 return; 3299 3300 SwitchStmt *Switch = getCurFunction()->SwitchStack.back(); 3301 if (!Switch->getCond()->getType()->isEnumeralType()) { 3302 CodeCompleteExpressionData Data(Switch->getCond()->getType()); 3303 Data.IntegralConstantExpression = true; 3304 CodeCompleteExpression(S, Data); 3305 return; 3306 } 3307 3308 // Code-complete the cases of a switch statement over an enumeration type 3309 // by providing the list of 3310 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl(); 3311 3312 // Determine which enumerators we have already seen in the switch statement. 3313 // FIXME: Ideally, we would also be able to look *past* the code-completion 3314 // token, in case we are code-completing in the middle of the switch and not 3315 // at the end. However, we aren't able to do so at the moment. 3316 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen; 3317 NestedNameSpecifier *Qualifier = 0; 3318 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; 3319 SC = SC->getNextSwitchCase()) { 3320 CaseStmt *Case = dyn_cast<CaseStmt>(SC); 3321 if (!Case) 3322 continue; 3323 3324 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); 3325 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal)) 3326 if (EnumConstantDecl *Enumerator 3327 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 3328 // We look into the AST of the case statement to determine which 3329 // enumerator was named. Alternatively, we could compute the value of 3330 // the integral constant expression, then compare it against the 3331 // values of each enumerator. However, value-based approach would not 3332 // work as well with C++ templates where enumerators declared within a 3333 // template are type- and value-dependent. 3334 EnumeratorsSeen.insert(Enumerator); 3335 3336 // If this is a qualified-id, keep track of the nested-name-specifier 3337 // so that we can reproduce it as part of code completion, e.g., 3338 // 3339 // switch (TagD.getKind()) { 3340 // case TagDecl::TK_enum: 3341 // break; 3342 // case XXX 3343 // 3344 // At the XXX, our completions are TagDecl::TK_union, 3345 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union, 3346 // TK_struct, and TK_class. 3347 Qualifier = DRE->getQualifier(); 3348 } 3349 } 3350 3351 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) { 3352 // If there are no prior enumerators in C++, check whether we have to 3353 // qualify the names of the enumerators that we suggest, because they 3354 // may not be visible in this scope. 3355 Qualifier = getRequiredQualification(Context, CurContext, 3356 Enum->getDeclContext()); 3357 3358 // FIXME: Scoped enums need to start with "EnumDecl" as the context! 3359 } 3360 3361 // Add any enumerators that have not yet been mentioned. 3362 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3363 CodeCompletionContext::CCC_Expression); 3364 Results.EnterNewScope(); 3365 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(), 3366 EEnd = Enum->enumerator_end(); 3367 E != EEnd; ++E) { 3368 if (EnumeratorsSeen.count(*E)) 3369 continue; 3370 3371 CodeCompletionResult R(*E, Qualifier); 3372 R.Priority = CCP_EnumInCase; 3373 Results.AddResult(R, CurContext, 0, false); 3374 } 3375 Results.ExitScope(); 3376 3377 if (CodeCompleter->includeMacros()) 3378 AddMacroResults(PP, Results); 3379 HandleCodeCompleteResults(this, CodeCompleter, 3380 CodeCompletionContext::CCC_OtherWithMacros, 3381 Results.data(),Results.size()); 3382 } 3383 3384 namespace { 3385 struct IsBetterOverloadCandidate { 3386 Sema &S; 3387 SourceLocation Loc; 3388 3389 public: 3390 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc) 3391 : S(S), Loc(Loc) { } 3392 3393 bool 3394 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const { 3395 return isBetterOverloadCandidate(S, X, Y, Loc); 3396 } 3397 }; 3398 } 3399 3400 static bool anyNullArguments(Expr **Args, unsigned NumArgs) { 3401 if (NumArgs && !Args) 3402 return true; 3403 3404 for (unsigned I = 0; I != NumArgs; ++I) 3405 if (!Args[I]) 3406 return true; 3407 3408 return false; 3409 } 3410 3411 void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn, 3412 ExprTy **ArgsIn, unsigned NumArgs) { 3413 if (!CodeCompleter) 3414 return; 3415 3416 // When we're code-completing for a call, we fall back to ordinary 3417 // name code-completion whenever we can't produce specific 3418 // results. We may want to revisit this strategy in the future, 3419 // e.g., by merging the two kinds of results. 3420 3421 Expr *Fn = (Expr *)FnIn; 3422 Expr **Args = (Expr **)ArgsIn; 3423 3424 // Ignore type-dependent call expressions entirely. 3425 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) || 3426 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) { 3427 CodeCompleteOrdinaryName(S, PCC_Expression); 3428 return; 3429 } 3430 3431 // Build an overload candidate set based on the functions we find. 3432 SourceLocation Loc = Fn->getExprLoc(); 3433 OverloadCandidateSet CandidateSet(Loc); 3434 3435 // FIXME: What if we're calling something that isn't a function declaration? 3436 // FIXME: What if we're calling a pseudo-destructor? 3437 // FIXME: What if we're calling a member function? 3438 3439 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate; 3440 llvm::SmallVector<ResultCandidate, 8> Results; 3441 3442 Expr *NakedFn = Fn->IgnoreParenCasts(); 3443 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) 3444 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet, 3445 /*PartialOverloading=*/ true); 3446 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 3447 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl()); 3448 if (FDecl) { 3449 if (!getLangOptions().CPlusPlus || 3450 !FDecl->getType()->getAs<FunctionProtoType>()) 3451 Results.push_back(ResultCandidate(FDecl)); 3452 else 3453 // FIXME: access? 3454 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none), 3455 Args, NumArgs, CandidateSet, 3456 false, /*PartialOverloading*/true); 3457 } 3458 } 3459 3460 QualType ParamType; 3461 3462 if (!CandidateSet.empty()) { 3463 // Sort the overload candidate set by placing the best overloads first. 3464 std::stable_sort(CandidateSet.begin(), CandidateSet.end(), 3465 IsBetterOverloadCandidate(*this, Loc)); 3466 3467 // Add the remaining viable overload candidates as code-completion reslults. 3468 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 3469 CandEnd = CandidateSet.end(); 3470 Cand != CandEnd; ++Cand) { 3471 if (Cand->Viable) 3472 Results.push_back(ResultCandidate(Cand->Function)); 3473 } 3474 3475 // From the viable candidates, try to determine the type of this parameter. 3476 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 3477 if (const FunctionType *FType = Results[I].getFunctionType()) 3478 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType)) 3479 if (NumArgs < Proto->getNumArgs()) { 3480 if (ParamType.isNull()) 3481 ParamType = Proto->getArgType(NumArgs); 3482 else if (!Context.hasSameUnqualifiedType( 3483 ParamType.getNonReferenceType(), 3484 Proto->getArgType(NumArgs).getNonReferenceType())) { 3485 ParamType = QualType(); 3486 break; 3487 } 3488 } 3489 } 3490 } else { 3491 // Try to determine the parameter type from the type of the expression 3492 // being called. 3493 QualType FunctionType = Fn->getType(); 3494 if (const PointerType *Ptr = FunctionType->getAs<PointerType>()) 3495 FunctionType = Ptr->getPointeeType(); 3496 else if (const BlockPointerType *BlockPtr 3497 = FunctionType->getAs<BlockPointerType>()) 3498 FunctionType = BlockPtr->getPointeeType(); 3499 else if (const MemberPointerType *MemPtr 3500 = FunctionType->getAs<MemberPointerType>()) 3501 FunctionType = MemPtr->getPointeeType(); 3502 3503 if (const FunctionProtoType *Proto 3504 = FunctionType->getAs<FunctionProtoType>()) { 3505 if (NumArgs < Proto->getNumArgs()) 3506 ParamType = Proto->getArgType(NumArgs); 3507 } 3508 } 3509 3510 if (ParamType.isNull()) 3511 CodeCompleteOrdinaryName(S, PCC_Expression); 3512 else 3513 CodeCompleteExpression(S, ParamType); 3514 3515 if (!Results.empty()) 3516 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(), 3517 Results.size()); 3518 } 3519 3520 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) { 3521 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 3522 if (!VD) { 3523 CodeCompleteOrdinaryName(S, PCC_Expression); 3524 return; 3525 } 3526 3527 CodeCompleteExpression(S, VD->getType()); 3528 } 3529 3530 void Sema::CodeCompleteReturn(Scope *S) { 3531 QualType ResultType; 3532 if (isa<BlockDecl>(CurContext)) { 3533 if (BlockScopeInfo *BSI = getCurBlock()) 3534 ResultType = BSI->ReturnType; 3535 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext)) 3536 ResultType = Function->getResultType(); 3537 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext)) 3538 ResultType = Method->getResultType(); 3539 3540 if (ResultType.isNull()) 3541 CodeCompleteOrdinaryName(S, PCC_Expression); 3542 else 3543 CodeCompleteExpression(S, ResultType); 3544 } 3545 3546 void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) { 3547 if (LHS) 3548 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType()); 3549 else 3550 CodeCompleteOrdinaryName(S, PCC_Expression); 3551 } 3552 3553 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 3554 bool EnteringContext) { 3555 if (!SS.getScopeRep() || !CodeCompleter) 3556 return; 3557 3558 DeclContext *Ctx = computeDeclContext(SS, EnteringContext); 3559 if (!Ctx) 3560 return; 3561 3562 // Try to instantiate any non-dependent declaration contexts before 3563 // we look in them. 3564 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx)) 3565 return; 3566 3567 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3568 CodeCompletionContext::CCC_Name); 3569 Results.EnterNewScope(); 3570 3571 // The "template" keyword can follow "::" in the grammar, but only 3572 // put it into the grammar if the nested-name-specifier is dependent. 3573 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 3574 if (!Results.empty() && NNS->isDependent()) 3575 Results.AddResult("template"); 3576 3577 // Add calls to overridden virtual functions, if there are any. 3578 // 3579 // FIXME: This isn't wonderful, because we don't know whether we're actually 3580 // in a context that permits expressions. This is a general issue with 3581 // qualified-id completions. 3582 if (!EnteringContext) 3583 MaybeAddOverrideCalls(*this, Ctx, Results); 3584 Results.ExitScope(); 3585 3586 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3587 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer); 3588 3589 HandleCodeCompleteResults(this, CodeCompleter, 3590 CodeCompletionContext::CCC_Name, 3591 Results.data(),Results.size()); 3592 } 3593 3594 void Sema::CodeCompleteUsing(Scope *S) { 3595 if (!CodeCompleter) 3596 return; 3597 3598 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3599 CodeCompletionContext::CCC_PotentiallyQualifiedName, 3600 &ResultBuilder::IsNestedNameSpecifier); 3601 Results.EnterNewScope(); 3602 3603 // If we aren't in class scope, we could see the "namespace" keyword. 3604 if (!S->isClassScope()) 3605 Results.AddResult(CodeCompletionResult("namespace")); 3606 3607 // After "using", we can see anything that would start a 3608 // nested-name-specifier. 3609 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3610 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3611 CodeCompleter->includeGlobals()); 3612 Results.ExitScope(); 3613 3614 HandleCodeCompleteResults(this, CodeCompleter, 3615 CodeCompletionContext::CCC_PotentiallyQualifiedName, 3616 Results.data(),Results.size()); 3617 } 3618 3619 void Sema::CodeCompleteUsingDirective(Scope *S) { 3620 if (!CodeCompleter) 3621 return; 3622 3623 // After "using namespace", we expect to see a namespace name or namespace 3624 // alias. 3625 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3626 CodeCompletionContext::CCC_Namespace, 3627 &ResultBuilder::IsNamespaceOrAlias); 3628 Results.EnterNewScope(); 3629 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3630 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3631 CodeCompleter->includeGlobals()); 3632 Results.ExitScope(); 3633 HandleCodeCompleteResults(this, CodeCompleter, 3634 CodeCompletionContext::CCC_Namespace, 3635 Results.data(),Results.size()); 3636 } 3637 3638 void Sema::CodeCompleteNamespaceDecl(Scope *S) { 3639 if (!CodeCompleter) 3640 return; 3641 3642 DeclContext *Ctx = (DeclContext *)S->getEntity(); 3643 if (!S->getParent()) 3644 Ctx = Context.getTranslationUnitDecl(); 3645 3646 bool SuppressedGlobalResults 3647 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx); 3648 3649 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3650 SuppressedGlobalResults 3651 ? CodeCompletionContext::CCC_Namespace 3652 : CodeCompletionContext::CCC_Other, 3653 &ResultBuilder::IsNamespace); 3654 3655 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { 3656 // We only want to see those namespaces that have already been defined 3657 // within this scope, because its likely that the user is creating an 3658 // extended namespace declaration. Keep track of the most recent 3659 // definition of each namespace. 3660 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; 3661 for (DeclContext::specific_decl_iterator<NamespaceDecl> 3662 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end()); 3663 NS != NSEnd; ++NS) 3664 OrigToLatest[NS->getOriginalNamespace()] = *NS; 3665 3666 // Add the most recent definition (or extended definition) of each 3667 // namespace to the list of results. 3668 Results.EnterNewScope(); 3669 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator 3670 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end(); 3671 NS != NSEnd; ++NS) 3672 Results.AddResult(CodeCompletionResult(NS->second, 0), 3673 CurContext, 0, false); 3674 Results.ExitScope(); 3675 } 3676 3677 HandleCodeCompleteResults(this, CodeCompleter, 3678 Results.getCompletionContext(), 3679 Results.data(),Results.size()); 3680 } 3681 3682 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { 3683 if (!CodeCompleter) 3684 return; 3685 3686 // After "namespace", we expect to see a namespace or alias. 3687 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3688 CodeCompletionContext::CCC_Namespace, 3689 &ResultBuilder::IsNamespaceOrAlias); 3690 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3691 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3692 CodeCompleter->includeGlobals()); 3693 HandleCodeCompleteResults(this, CodeCompleter, 3694 Results.getCompletionContext(), 3695 Results.data(),Results.size()); 3696 } 3697 3698 void Sema::CodeCompleteOperatorName(Scope *S) { 3699 if (!CodeCompleter) 3700 return; 3701 3702 typedef CodeCompletionResult Result; 3703 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3704 CodeCompletionContext::CCC_Type, 3705 &ResultBuilder::IsType); 3706 Results.EnterNewScope(); 3707 3708 // Add the names of overloadable operators. 3709 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 3710 if (std::strcmp(Spelling, "?")) \ 3711 Results.AddResult(Result(Spelling)); 3712 #include "clang/Basic/OperatorKinds.def" 3713 3714 // Add any type names visible from the current scope 3715 Results.allowNestedNameSpecifiers(); 3716 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3717 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3718 CodeCompleter->includeGlobals()); 3719 3720 // Add any type specifiers 3721 AddTypeSpecifierResults(getLangOptions(), Results); 3722 Results.ExitScope(); 3723 3724 HandleCodeCompleteResults(this, CodeCompleter, 3725 CodeCompletionContext::CCC_Type, 3726 Results.data(),Results.size()); 3727 } 3728 3729 void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD, 3730 CXXCtorInitializer** Initializers, 3731 unsigned NumInitializers) { 3732 CXXConstructorDecl *Constructor 3733 = static_cast<CXXConstructorDecl *>(ConstructorD); 3734 if (!Constructor) 3735 return; 3736 3737 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3738 CodeCompletionContext::CCC_PotentiallyQualifiedName); 3739 Results.EnterNewScope(); 3740 3741 // Fill in any already-initialized fields or base classes. 3742 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; 3743 llvm::SmallPtrSet<CanQualType, 4> InitializedBases; 3744 for (unsigned I = 0; I != NumInitializers; ++I) { 3745 if (Initializers[I]->isBaseInitializer()) 3746 InitializedBases.insert( 3747 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0))); 3748 else 3749 InitializedFields.insert(cast<FieldDecl>( 3750 Initializers[I]->getAnyMember())); 3751 } 3752 3753 // Add completions for base classes. 3754 CodeCompletionBuilder Builder(Results.getAllocator()); 3755 bool SawLastInitializer = (NumInitializers == 0); 3756 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3757 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3758 BaseEnd = ClassDecl->bases_end(); 3759 Base != BaseEnd; ++Base) { 3760 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) { 3761 SawLastInitializer 3762 = NumInitializers > 0 && 3763 Initializers[NumInitializers - 1]->isBaseInitializer() && 3764 Context.hasSameUnqualifiedType(Base->getType(), 3765 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0)); 3766 continue; 3767 } 3768 3769 Builder.AddTypedTextChunk( 3770 Results.getAllocator().CopyString( 3771 Base->getType().getAsString(Context.PrintingPolicy))); 3772 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3773 Builder.AddPlaceholderChunk("args"); 3774 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3775 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 3776 SawLastInitializer? CCP_NextInitializer 3777 : CCP_MemberDeclaration)); 3778 SawLastInitializer = false; 3779 } 3780 3781 // Add completions for virtual base classes. 3782 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 3783 BaseEnd = ClassDecl->vbases_end(); 3784 Base != BaseEnd; ++Base) { 3785 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) { 3786 SawLastInitializer 3787 = NumInitializers > 0 && 3788 Initializers[NumInitializers - 1]->isBaseInitializer() && 3789 Context.hasSameUnqualifiedType(Base->getType(), 3790 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0)); 3791 continue; 3792 } 3793 3794 Builder.AddTypedTextChunk( 3795 Builder.getAllocator().CopyString( 3796 Base->getType().getAsString(Context.PrintingPolicy))); 3797 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3798 Builder.AddPlaceholderChunk("args"); 3799 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3800 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 3801 SawLastInitializer? CCP_NextInitializer 3802 : CCP_MemberDeclaration)); 3803 SawLastInitializer = false; 3804 } 3805 3806 // Add completions for members. 3807 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3808 FieldEnd = ClassDecl->field_end(); 3809 Field != FieldEnd; ++Field) { 3810 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) { 3811 SawLastInitializer 3812 = NumInitializers > 0 && 3813 Initializers[NumInitializers - 1]->isAnyMemberInitializer() && 3814 Initializers[NumInitializers - 1]->getAnyMember() == *Field; 3815 continue; 3816 } 3817 3818 if (!Field->getDeclName()) 3819 continue; 3820 3821 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 3822 Field->getIdentifier()->getName())); 3823 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3824 Builder.AddPlaceholderChunk("args"); 3825 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3826 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 3827 SawLastInitializer? CCP_NextInitializer 3828 : CCP_MemberDeclaration, 3829 CXCursor_MemberRef)); 3830 SawLastInitializer = false; 3831 } 3832 Results.ExitScope(); 3833 3834 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 3835 Results.data(), Results.size()); 3836 } 3837 3838 // Macro that expands to @Keyword or Keyword, depending on whether NeedAt is 3839 // true or false. 3840 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword 3841 static void AddObjCImplementationResults(const LangOptions &LangOpts, 3842 ResultBuilder &Results, 3843 bool NeedAt) { 3844 typedef CodeCompletionResult Result; 3845 // Since we have an implementation, we can end it. 3846 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end))); 3847 3848 CodeCompletionBuilder Builder(Results.getAllocator()); 3849 if (LangOpts.ObjC2) { 3850 // @dynamic 3851 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic)); 3852 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3853 Builder.AddPlaceholderChunk("property"); 3854 Results.AddResult(Result(Builder.TakeString())); 3855 3856 // @synthesize 3857 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize)); 3858 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3859 Builder.AddPlaceholderChunk("property"); 3860 Results.AddResult(Result(Builder.TakeString())); 3861 } 3862 } 3863 3864 static void AddObjCInterfaceResults(const LangOptions &LangOpts, 3865 ResultBuilder &Results, 3866 bool NeedAt) { 3867 typedef CodeCompletionResult Result; 3868 3869 // Since we have an interface or protocol, we can end it. 3870 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end))); 3871 3872 if (LangOpts.ObjC2) { 3873 // @property 3874 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property))); 3875 3876 // @required 3877 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required))); 3878 3879 // @optional 3880 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional))); 3881 } 3882 } 3883 3884 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { 3885 typedef CodeCompletionResult Result; 3886 CodeCompletionBuilder Builder(Results.getAllocator()); 3887 3888 // @class name ; 3889 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class)); 3890 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3891 Builder.AddPlaceholderChunk("name"); 3892 Results.AddResult(Result(Builder.TakeString())); 3893 3894 if (Results.includeCodePatterns()) { 3895 // @interface name 3896 // FIXME: Could introduce the whole pattern, including superclasses and 3897 // such. 3898 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface)); 3899 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3900 Builder.AddPlaceholderChunk("class"); 3901 Results.AddResult(Result(Builder.TakeString())); 3902 3903 // @protocol name 3904 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol)); 3905 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3906 Builder.AddPlaceholderChunk("protocol"); 3907 Results.AddResult(Result(Builder.TakeString())); 3908 3909 // @implementation name 3910 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation)); 3911 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3912 Builder.AddPlaceholderChunk("class"); 3913 Results.AddResult(Result(Builder.TakeString())); 3914 } 3915 3916 // @compatibility_alias name 3917 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias)); 3918 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3919 Builder.AddPlaceholderChunk("alias"); 3920 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3921 Builder.AddPlaceholderChunk("class"); 3922 Results.AddResult(Result(Builder.TakeString())); 3923 } 3924 3925 void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl, 3926 bool InInterface) { 3927 typedef CodeCompletionResult Result; 3928 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3929 CodeCompletionContext::CCC_Other); 3930 Results.EnterNewScope(); 3931 if (ObjCImpDecl) 3932 AddObjCImplementationResults(getLangOptions(), Results, false); 3933 else if (InInterface) 3934 AddObjCInterfaceResults(getLangOptions(), Results, false); 3935 else 3936 AddObjCTopLevelResults(Results, false); 3937 Results.ExitScope(); 3938 HandleCodeCompleteResults(this, CodeCompleter, 3939 CodeCompletionContext::CCC_Other, 3940 Results.data(),Results.size()); 3941 } 3942 3943 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { 3944 typedef CodeCompletionResult Result; 3945 CodeCompletionBuilder Builder(Results.getAllocator()); 3946 3947 // @encode ( type-name ) 3948 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode)); 3949 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3950 Builder.AddPlaceholderChunk("type-name"); 3951 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3952 Results.AddResult(Result(Builder.TakeString())); 3953 3954 // @protocol ( protocol-name ) 3955 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol)); 3956 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3957 Builder.AddPlaceholderChunk("protocol-name"); 3958 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3959 Results.AddResult(Result(Builder.TakeString())); 3960 3961 // @selector ( selector ) 3962 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector)); 3963 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3964 Builder.AddPlaceholderChunk("selector"); 3965 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3966 Results.AddResult(Result(Builder.TakeString())); 3967 } 3968 3969 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { 3970 typedef CodeCompletionResult Result; 3971 CodeCompletionBuilder Builder(Results.getAllocator()); 3972 3973 if (Results.includeCodePatterns()) { 3974 // @try { statements } @catch ( declaration ) { statements } @finally 3975 // { statements } 3976 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try)); 3977 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 3978 Builder.AddPlaceholderChunk("statements"); 3979 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 3980 Builder.AddTextChunk("@catch"); 3981 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3982 Builder.AddPlaceholderChunk("parameter"); 3983 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3984 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 3985 Builder.AddPlaceholderChunk("statements"); 3986 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 3987 Builder.AddTextChunk("@finally"); 3988 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 3989 Builder.AddPlaceholderChunk("statements"); 3990 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 3991 Results.AddResult(Result(Builder.TakeString())); 3992 } 3993 3994 // @throw 3995 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw)); 3996 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3997 Builder.AddPlaceholderChunk("expression"); 3998 Results.AddResult(Result(Builder.TakeString())); 3999 4000 if (Results.includeCodePatterns()) { 4001 // @synchronized ( expression ) { statements } 4002 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized)); 4003 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4004 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4005 Builder.AddPlaceholderChunk("expression"); 4006 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4007 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 4008 Builder.AddPlaceholderChunk("statements"); 4009 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 4010 Results.AddResult(Result(Builder.TakeString())); 4011 } 4012 } 4013 4014 static void AddObjCVisibilityResults(const LangOptions &LangOpts, 4015 ResultBuilder &Results, 4016 bool NeedAt) { 4017 typedef CodeCompletionResult Result; 4018 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private))); 4019 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected))); 4020 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public))); 4021 if (LangOpts.ObjC2) 4022 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package))); 4023 } 4024 4025 void Sema::CodeCompleteObjCAtVisibility(Scope *S) { 4026 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4027 CodeCompletionContext::CCC_Other); 4028 Results.EnterNewScope(); 4029 AddObjCVisibilityResults(getLangOptions(), Results, false); 4030 Results.ExitScope(); 4031 HandleCodeCompleteResults(this, CodeCompleter, 4032 CodeCompletionContext::CCC_Other, 4033 Results.data(),Results.size()); 4034 } 4035 4036 void Sema::CodeCompleteObjCAtStatement(Scope *S) { 4037 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4038 CodeCompletionContext::CCC_Other); 4039 Results.EnterNewScope(); 4040 AddObjCStatementResults(Results, false); 4041 AddObjCExpressionResults(Results, false); 4042 Results.ExitScope(); 4043 HandleCodeCompleteResults(this, CodeCompleter, 4044 CodeCompletionContext::CCC_Other, 4045 Results.data(),Results.size()); 4046 } 4047 4048 void Sema::CodeCompleteObjCAtExpression(Scope *S) { 4049 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4050 CodeCompletionContext::CCC_Other); 4051 Results.EnterNewScope(); 4052 AddObjCExpressionResults(Results, false); 4053 Results.ExitScope(); 4054 HandleCodeCompleteResults(this, CodeCompleter, 4055 CodeCompletionContext::CCC_Other, 4056 Results.data(),Results.size()); 4057 } 4058 4059 /// \brief Determine whether the addition of the given flag to an Objective-C 4060 /// property's attributes will cause a conflict. 4061 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { 4062 // Check if we've already added this flag. 4063 if (Attributes & NewFlag) 4064 return true; 4065 4066 Attributes |= NewFlag; 4067 4068 // Check for collisions with "readonly". 4069 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && 4070 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite | 4071 ObjCDeclSpec::DQ_PR_assign | 4072 ObjCDeclSpec::DQ_PR_copy | 4073 ObjCDeclSpec::DQ_PR_retain))) 4074 return true; 4075 4076 // Check for more than one of { assign, copy, retain }. 4077 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign | 4078 ObjCDeclSpec::DQ_PR_copy | 4079 ObjCDeclSpec::DQ_PR_retain); 4080 if (AssignCopyRetMask && 4081 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign && 4082 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy && 4083 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain) 4084 return true; 4085 4086 return false; 4087 } 4088 4089 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { 4090 if (!CodeCompleter) 4091 return; 4092 4093 unsigned Attributes = ODS.getPropertyAttributes(); 4094 4095 typedef CodeCompletionResult Result; 4096 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4097 CodeCompletionContext::CCC_Other); 4098 Results.EnterNewScope(); 4099 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly)) 4100 Results.AddResult(CodeCompletionResult("readonly")); 4101 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign)) 4102 Results.AddResult(CodeCompletionResult("assign")); 4103 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite)) 4104 Results.AddResult(CodeCompletionResult("readwrite")); 4105 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain)) 4106 Results.AddResult(CodeCompletionResult("retain")); 4107 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy)) 4108 Results.AddResult(CodeCompletionResult("copy")); 4109 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic)) 4110 Results.AddResult(CodeCompletionResult("nonatomic")); 4111 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) { 4112 CodeCompletionBuilder Setter(Results.getAllocator()); 4113 Setter.AddTypedTextChunk("setter"); 4114 Setter.AddTextChunk(" = "); 4115 Setter.AddPlaceholderChunk("method"); 4116 Results.AddResult(CodeCompletionResult(Setter.TakeString())); 4117 } 4118 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) { 4119 CodeCompletionBuilder Getter(Results.getAllocator()); 4120 Getter.AddTypedTextChunk("getter"); 4121 Getter.AddTextChunk(" = "); 4122 Getter.AddPlaceholderChunk("method"); 4123 Results.AddResult(CodeCompletionResult(Getter.TakeString())); 4124 } 4125 Results.ExitScope(); 4126 HandleCodeCompleteResults(this, CodeCompleter, 4127 CodeCompletionContext::CCC_Other, 4128 Results.data(),Results.size()); 4129 } 4130 4131 /// \brief Descripts the kind of Objective-C method that we want to find 4132 /// via code completion. 4133 enum ObjCMethodKind { 4134 MK_Any, //< Any kind of method, provided it means other specified criteria. 4135 MK_ZeroArgSelector, //< Zero-argument (unary) selector. 4136 MK_OneArgSelector //< One-argument selector. 4137 }; 4138 4139 static bool isAcceptableObjCSelector(Selector Sel, 4140 ObjCMethodKind WantKind, 4141 IdentifierInfo **SelIdents, 4142 unsigned NumSelIdents, 4143 bool AllowSameLength = true) { 4144 if (NumSelIdents > Sel.getNumArgs()) 4145 return false; 4146 4147 switch (WantKind) { 4148 case MK_Any: break; 4149 case MK_ZeroArgSelector: return Sel.isUnarySelector(); 4150 case MK_OneArgSelector: return Sel.getNumArgs() == 1; 4151 } 4152 4153 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) 4154 return false; 4155 4156 for (unsigned I = 0; I != NumSelIdents; ++I) 4157 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) 4158 return false; 4159 4160 return true; 4161 } 4162 4163 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, 4164 ObjCMethodKind WantKind, 4165 IdentifierInfo **SelIdents, 4166 unsigned NumSelIdents, 4167 bool AllowSameLength = true) { 4168 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents, 4169 NumSelIdents, AllowSameLength); 4170 } 4171 4172 namespace { 4173 /// \brief A set of selectors, which is used to avoid introducing multiple 4174 /// completions with the same selector into the result set. 4175 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; 4176 } 4177 4178 /// \brief Add all of the Objective-C methods in the given Objective-C 4179 /// container to the set of results. 4180 /// 4181 /// The container will be a class, protocol, category, or implementation of 4182 /// any of the above. This mether will recurse to include methods from 4183 /// the superclasses of classes along with their categories, protocols, and 4184 /// implementations. 4185 /// 4186 /// \param Container the container in which we'll look to find methods. 4187 /// 4188 /// \param WantInstance whether to add instance methods (only); if false, this 4189 /// routine will add factory methods (only). 4190 /// 4191 /// \param CurContext the context in which we're performing the lookup that 4192 /// finds methods. 4193 /// 4194 /// \param AllowSameLength Whether we allow a method to be added to the list 4195 /// when it has the same number of parameters as we have selector identifiers. 4196 /// 4197 /// \param Results the structure into which we'll add results. 4198 static void AddObjCMethods(ObjCContainerDecl *Container, 4199 bool WantInstanceMethods, 4200 ObjCMethodKind WantKind, 4201 IdentifierInfo **SelIdents, 4202 unsigned NumSelIdents, 4203 DeclContext *CurContext, 4204 VisitedSelectorSet &Selectors, 4205 bool AllowSameLength, 4206 ResultBuilder &Results, 4207 bool InOriginalClass = true) { 4208 typedef CodeCompletionResult Result; 4209 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(), 4210 MEnd = Container->meth_end(); 4211 M != MEnd; ++M) { 4212 if ((*M)->isInstanceMethod() == WantInstanceMethods) { 4213 // Check whether the selector identifiers we've been given are a 4214 // subset of the identifiers for this particular method. 4215 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents, 4216 AllowSameLength)) 4217 continue; 4218 4219 if (!Selectors.insert((*M)->getSelector())) 4220 continue; 4221 4222 Result R = Result(*M, 0); 4223 R.StartParameter = NumSelIdents; 4224 R.AllParametersAreInformative = (WantKind != MK_Any); 4225 if (!InOriginalClass) 4226 R.Priority += CCD_InBaseClass; 4227 Results.MaybeAddResult(R, CurContext); 4228 } 4229 } 4230 4231 // Visit the protocols of protocols. 4232 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4233 const ObjCList<ObjCProtocolDecl> &Protocols 4234 = Protocol->getReferencedProtocols(); 4235 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 4236 E = Protocols.end(); 4237 I != E; ++I) 4238 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents, 4239 CurContext, Selectors, AllowSameLength, Results, false); 4240 } 4241 4242 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container); 4243 if (!IFace) 4244 return; 4245 4246 // Add methods in protocols. 4247 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols(); 4248 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 4249 E = Protocols.end(); 4250 I != E; ++I) 4251 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents, 4252 CurContext, Selectors, AllowSameLength, Results, false); 4253 4254 // Add methods in categories. 4255 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl; 4256 CatDecl = CatDecl->getNextClassCategory()) { 4257 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, 4258 NumSelIdents, CurContext, Selectors, AllowSameLength, 4259 Results, InOriginalClass); 4260 4261 // Add a categories protocol methods. 4262 const ObjCList<ObjCProtocolDecl> &Protocols 4263 = CatDecl->getReferencedProtocols(); 4264 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 4265 E = Protocols.end(); 4266 I != E; ++I) 4267 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, 4268 NumSelIdents, CurContext, Selectors, AllowSameLength, 4269 Results, false); 4270 4271 // Add methods in category implementations. 4272 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) 4273 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, 4274 NumSelIdents, CurContext, Selectors, AllowSameLength, 4275 Results, InOriginalClass); 4276 } 4277 4278 // Add methods in superclass. 4279 if (IFace->getSuperClass()) 4280 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, 4281 SelIdents, NumSelIdents, CurContext, Selectors, 4282 AllowSameLength, Results, false); 4283 4284 // Add methods in our implementation, if any. 4285 if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 4286 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, 4287 NumSelIdents, CurContext, Selectors, AllowSameLength, 4288 Results, InOriginalClass); 4289 } 4290 4291 4292 void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl) { 4293 typedef CodeCompletionResult Result; 4294 4295 // Try to find the interface where getters might live. 4296 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl); 4297 if (!Class) { 4298 if (ObjCCategoryDecl *Category 4299 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl)) 4300 Class = Category->getClassInterface(); 4301 4302 if (!Class) 4303 return; 4304 } 4305 4306 // Find all of the potential getters. 4307 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4308 CodeCompletionContext::CCC_Other); 4309 Results.EnterNewScope(); 4310 4311 VisitedSelectorSet Selectors; 4312 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors, 4313 /*AllowSameLength=*/true, Results); 4314 Results.ExitScope(); 4315 HandleCodeCompleteResults(this, CodeCompleter, 4316 CodeCompletionContext::CCC_Other, 4317 Results.data(),Results.size()); 4318 } 4319 4320 void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl) { 4321 typedef CodeCompletionResult Result; 4322 4323 // Try to find the interface where setters might live. 4324 ObjCInterfaceDecl *Class 4325 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl); 4326 if (!Class) { 4327 if (ObjCCategoryDecl *Category 4328 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl)) 4329 Class = Category->getClassInterface(); 4330 4331 if (!Class) 4332 return; 4333 } 4334 4335 // Find all of the potential getters. 4336 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4337 CodeCompletionContext::CCC_Other); 4338 Results.EnterNewScope(); 4339 4340 VisitedSelectorSet Selectors; 4341 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, 4342 Selectors, /*AllowSameLength=*/true, Results); 4343 4344 Results.ExitScope(); 4345 HandleCodeCompleteResults(this, CodeCompleter, 4346 CodeCompletionContext::CCC_Other, 4347 Results.data(),Results.size()); 4348 } 4349 4350 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 4351 bool IsParameter) { 4352 typedef CodeCompletionResult Result; 4353 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4354 CodeCompletionContext::CCC_Type); 4355 Results.EnterNewScope(); 4356 4357 // Add context-sensitive, Objective-C parameter-passing keywords. 4358 bool AddedInOut = false; 4359 if ((DS.getObjCDeclQualifier() & 4360 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { 4361 Results.AddResult("in"); 4362 Results.AddResult("inout"); 4363 AddedInOut = true; 4364 } 4365 if ((DS.getObjCDeclQualifier() & 4366 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { 4367 Results.AddResult("out"); 4368 if (!AddedInOut) 4369 Results.AddResult("inout"); 4370 } 4371 if ((DS.getObjCDeclQualifier() & 4372 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | 4373 ObjCDeclSpec::DQ_Oneway)) == 0) { 4374 Results.AddResult("bycopy"); 4375 Results.AddResult("byref"); 4376 Results.AddResult("oneway"); 4377 } 4378 4379 // If we're completing the return type of an Objective-C method and the 4380 // identifier IBAction refers to a macro, provide a completion item for 4381 // an action, e.g., 4382 // IBAction)<#selector#>:(id)sender 4383 if (DS.getObjCDeclQualifier() == 0 && !IsParameter && 4384 Context.Idents.get("IBAction").hasMacroDefinition()) { 4385 typedef CodeCompletionString::Chunk Chunk; 4386 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern, 4387 CXAvailability_Available); 4388 Builder.AddTypedTextChunk("IBAction"); 4389 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 4390 Builder.AddPlaceholderChunk("selector"); 4391 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon)); 4392 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen)); 4393 Builder.AddTextChunk("id"); 4394 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 4395 Builder.AddTextChunk("sender"); 4396 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 4397 } 4398 4399 // Add various builtin type names and specifiers. 4400 AddOrdinaryNameResults(PCC_Type, S, *this, Results); 4401 Results.ExitScope(); 4402 4403 // Add the various type names 4404 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 4405 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4406 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4407 CodeCompleter->includeGlobals()); 4408 4409 if (CodeCompleter->includeMacros()) 4410 AddMacroResults(PP, Results); 4411 4412 HandleCodeCompleteResults(this, CodeCompleter, 4413 CodeCompletionContext::CCC_Type, 4414 Results.data(), Results.size()); 4415 } 4416 4417 /// \brief When we have an expression with type "id", we may assume 4418 /// that it has some more-specific class type based on knowledge of 4419 /// common uses of Objective-C. This routine returns that class type, 4420 /// or NULL if no better result could be determined. 4421 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { 4422 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E); 4423 if (!Msg) 4424 return 0; 4425 4426 Selector Sel = Msg->getSelector(); 4427 if (Sel.isNull()) 4428 return 0; 4429 4430 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0); 4431 if (!Id) 4432 return 0; 4433 4434 ObjCMethodDecl *Method = Msg->getMethodDecl(); 4435 if (!Method) 4436 return 0; 4437 4438 // Determine the class that we're sending the message to. 4439 ObjCInterfaceDecl *IFace = 0; 4440 switch (Msg->getReceiverKind()) { 4441 case ObjCMessageExpr::Class: 4442 if (const ObjCObjectType *ObjType 4443 = Msg->getClassReceiver()->getAs<ObjCObjectType>()) 4444 IFace = ObjType->getInterface(); 4445 break; 4446 4447 case ObjCMessageExpr::Instance: { 4448 QualType T = Msg->getInstanceReceiver()->getType(); 4449 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) 4450 IFace = Ptr->getInterfaceDecl(); 4451 break; 4452 } 4453 4454 case ObjCMessageExpr::SuperInstance: 4455 case ObjCMessageExpr::SuperClass: 4456 break; 4457 } 4458 4459 if (!IFace) 4460 return 0; 4461 4462 ObjCInterfaceDecl *Super = IFace->getSuperClass(); 4463 if (Method->isInstanceMethod()) 4464 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 4465 .Case("retain", IFace) 4466 .Case("autorelease", IFace) 4467 .Case("copy", IFace) 4468 .Case("copyWithZone", IFace) 4469 .Case("mutableCopy", IFace) 4470 .Case("mutableCopyWithZone", IFace) 4471 .Case("awakeFromCoder", IFace) 4472 .Case("replacementObjectFromCoder", IFace) 4473 .Case("class", IFace) 4474 .Case("classForCoder", IFace) 4475 .Case("superclass", Super) 4476 .Default(0); 4477 4478 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 4479 .Case("new", IFace) 4480 .Case("alloc", IFace) 4481 .Case("allocWithZone", IFace) 4482 .Case("class", IFace) 4483 .Case("superclass", Super) 4484 .Default(0); 4485 } 4486 4487 // Add a special completion for a message send to "super", which fills in the 4488 // most likely case of forwarding all of our arguments to the superclass 4489 // function. 4490 /// 4491 /// \param S The semantic analysis object. 4492 /// 4493 /// \param S NeedSuperKeyword Whether we need to prefix this completion with 4494 /// the "super" keyword. Otherwise, we just need to provide the arguments. 4495 /// 4496 /// \param SelIdents The identifiers in the selector that have already been 4497 /// provided as arguments for a send to "super". 4498 /// 4499 /// \param NumSelIdents The number of identifiers in \p SelIdents. 4500 /// 4501 /// \param Results The set of results to augment. 4502 /// 4503 /// \returns the Objective-C method declaration that would be invoked by 4504 /// this "super" completion. If NULL, no completion was added. 4505 static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword, 4506 IdentifierInfo **SelIdents, 4507 unsigned NumSelIdents, 4508 ResultBuilder &Results) { 4509 ObjCMethodDecl *CurMethod = S.getCurMethodDecl(); 4510 if (!CurMethod) 4511 return 0; 4512 4513 ObjCInterfaceDecl *Class = CurMethod->getClassInterface(); 4514 if (!Class) 4515 return 0; 4516 4517 // Try to find a superclass method with the same selector. 4518 ObjCMethodDecl *SuperMethod = 0; 4519 while ((Class = Class->getSuperClass()) && !SuperMethod) { 4520 // Check in the class 4521 SuperMethod = Class->getMethod(CurMethod->getSelector(), 4522 CurMethod->isInstanceMethod()); 4523 4524 // Check in categories or class extensions. 4525 if (!SuperMethod) { 4526 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category; 4527 Category = Category->getNextClassCategory()) 4528 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(), 4529 CurMethod->isInstanceMethod()))) 4530 break; 4531 } 4532 } 4533 4534 if (!SuperMethod) 4535 return 0; 4536 4537 // Check whether the superclass method has the same signature. 4538 if (CurMethod->param_size() != SuperMethod->param_size() || 4539 CurMethod->isVariadic() != SuperMethod->isVariadic()) 4540 return 0; 4541 4542 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(), 4543 CurPEnd = CurMethod->param_end(), 4544 SuperP = SuperMethod->param_begin(); 4545 CurP != CurPEnd; ++CurP, ++SuperP) { 4546 // Make sure the parameter types are compatible. 4547 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), 4548 (*SuperP)->getType())) 4549 return 0; 4550 4551 // Make sure we have a parameter name to forward! 4552 if (!(*CurP)->getIdentifier()) 4553 return 0; 4554 } 4555 4556 // We have a superclass method. Now, form the send-to-super completion. 4557 CodeCompletionBuilder Builder(Results.getAllocator()); 4558 4559 // Give this completion a return type. 4560 AddResultTypeChunk(S.Context, SuperMethod, Builder); 4561 4562 // If we need the "super" keyword, add it (plus some spacing). 4563 if (NeedSuperKeyword) { 4564 Builder.AddTypedTextChunk("super"); 4565 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4566 } 4567 4568 Selector Sel = CurMethod->getSelector(); 4569 if (Sel.isUnarySelector()) { 4570 if (NeedSuperKeyword) 4571 Builder.AddTextChunk(Builder.getAllocator().CopyString( 4572 Sel.getNameForSlot(0))); 4573 else 4574 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 4575 Sel.getNameForSlot(0))); 4576 } else { 4577 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(); 4578 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { 4579 if (I > NumSelIdents) 4580 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4581 4582 if (I < NumSelIdents) 4583 Builder.AddInformativeChunk( 4584 Builder.getAllocator().CopyString( 4585 Sel.getNameForSlot(I) + ":")); 4586 else if (NeedSuperKeyword || I > NumSelIdents) { 4587 Builder.AddTextChunk( 4588 Builder.getAllocator().CopyString( 4589 Sel.getNameForSlot(I) + ":")); 4590 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 4591 (*CurP)->getIdentifier()->getName())); 4592 } else { 4593 Builder.AddTypedTextChunk( 4594 Builder.getAllocator().CopyString( 4595 Sel.getNameForSlot(I) + ":")); 4596 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 4597 (*CurP)->getIdentifier()->getName())); 4598 } 4599 } 4600 } 4601 4602 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion, 4603 SuperMethod->isInstanceMethod() 4604 ? CXCursor_ObjCInstanceMethodDecl 4605 : CXCursor_ObjCClassMethodDecl)); 4606 return SuperMethod; 4607 } 4608 4609 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) { 4610 typedef CodeCompletionResult Result; 4611 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4612 CodeCompletionContext::CCC_ObjCMessageReceiver, 4613 &ResultBuilder::IsObjCMessageReceiver); 4614 4615 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4616 Results.EnterNewScope(); 4617 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4618 CodeCompleter->includeGlobals()); 4619 4620 // If we are in an Objective-C method inside a class that has a superclass, 4621 // add "super" as an option. 4622 if (ObjCMethodDecl *Method = getCurMethodDecl()) 4623 if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) 4624 if (Iface->getSuperClass()) { 4625 Results.AddResult(Result("super")); 4626 4627 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results); 4628 } 4629 4630 Results.ExitScope(); 4631 4632 if (CodeCompleter->includeMacros()) 4633 AddMacroResults(PP, Results); 4634 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4635 Results.data(), Results.size()); 4636 4637 } 4638 4639 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 4640 IdentifierInfo **SelIdents, 4641 unsigned NumSelIdents, 4642 bool AtArgumentExpression) { 4643 ObjCInterfaceDecl *CDecl = 0; 4644 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 4645 // Figure out which interface we're in. 4646 CDecl = CurMethod->getClassInterface(); 4647 if (!CDecl) 4648 return; 4649 4650 // Find the superclass of this class. 4651 CDecl = CDecl->getSuperClass(); 4652 if (!CDecl) 4653 return; 4654 4655 if (CurMethod->isInstanceMethod()) { 4656 // We are inside an instance method, which means that the message 4657 // send [super ...] is actually calling an instance method on the 4658 // current object. 4659 return CodeCompleteObjCInstanceMessage(S, 0, 4660 SelIdents, NumSelIdents, 4661 AtArgumentExpression, 4662 CDecl); 4663 } 4664 4665 // Fall through to send to the superclass in CDecl. 4666 } else { 4667 // "super" may be the name of a type or variable. Figure out which 4668 // it is. 4669 IdentifierInfo *Super = &Context.Idents.get("super"); 4670 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, 4671 LookupOrdinaryName); 4672 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { 4673 // "super" names an interface. Use it. 4674 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) { 4675 if (const ObjCObjectType *Iface 4676 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>()) 4677 CDecl = Iface->getInterface(); 4678 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) { 4679 // "super" names an unresolved type; we can't be more specific. 4680 } else { 4681 // Assume that "super" names some kind of value and parse that way. 4682 CXXScopeSpec SS; 4683 UnqualifiedId id; 4684 id.setIdentifier(Super, SuperLoc); 4685 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false); 4686 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(), 4687 SelIdents, NumSelIdents, 4688 AtArgumentExpression); 4689 } 4690 4691 // Fall through 4692 } 4693 4694 ParsedType Receiver; 4695 if (CDecl) 4696 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl)); 4697 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, 4698 NumSelIdents, AtArgumentExpression, 4699 /*IsSuper=*/true); 4700 } 4701 4702 /// \brief Given a set of code-completion results for the argument of a message 4703 /// send, determine the preferred type (if any) for that argument expression. 4704 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, 4705 unsigned NumSelIdents) { 4706 typedef CodeCompletionResult Result; 4707 ASTContext &Context = Results.getSema().Context; 4708 4709 QualType PreferredType; 4710 unsigned BestPriority = CCP_Unlikely * 2; 4711 Result *ResultsData = Results.data(); 4712 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 4713 Result &R = ResultsData[I]; 4714 if (R.Kind == Result::RK_Declaration && 4715 isa<ObjCMethodDecl>(R.Declaration)) { 4716 if (R.Priority <= BestPriority) { 4717 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration); 4718 if (NumSelIdents <= Method->param_size()) { 4719 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1] 4720 ->getType(); 4721 if (R.Priority < BestPriority || PreferredType.isNull()) { 4722 BestPriority = R.Priority; 4723 PreferredType = MyPreferredType; 4724 } else if (!Context.hasSameUnqualifiedType(PreferredType, 4725 MyPreferredType)) { 4726 PreferredType = QualType(); 4727 } 4728 } 4729 } 4730 } 4731 } 4732 4733 return PreferredType; 4734 } 4735 4736 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 4737 ParsedType Receiver, 4738 IdentifierInfo **SelIdents, 4739 unsigned NumSelIdents, 4740 bool AtArgumentExpression, 4741 bool IsSuper, 4742 ResultBuilder &Results) { 4743 typedef CodeCompletionResult Result; 4744 ObjCInterfaceDecl *CDecl = 0; 4745 4746 // If the given name refers to an interface type, retrieve the 4747 // corresponding declaration. 4748 if (Receiver) { 4749 QualType T = SemaRef.GetTypeFromParser(Receiver, 0); 4750 if (!T.isNull()) 4751 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) 4752 CDecl = Interface->getInterface(); 4753 } 4754 4755 // Add all of the factory methods in this Objective-C class, its protocols, 4756 // superclasses, categories, implementation, etc. 4757 Results.EnterNewScope(); 4758 4759 // If this is a send-to-super, try to add the special "super" send 4760 // completion. 4761 if (IsSuper) { 4762 if (ObjCMethodDecl *SuperMethod 4763 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents, 4764 Results)) 4765 Results.Ignore(SuperMethod); 4766 } 4767 4768 // If we're inside an Objective-C method definition, prefer its selector to 4769 // others. 4770 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) 4771 Results.setPreferredSelector(CurMethod->getSelector()); 4772 4773 VisitedSelectorSet Selectors; 4774 if (CDecl) 4775 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, 4776 SemaRef.CurContext, Selectors, AtArgumentExpression, 4777 Results); 4778 else { 4779 // We're messaging "id" as a type; provide all class/factory methods. 4780 4781 // If we have an external source, load the entire class method 4782 // pool from the AST file. 4783 if (SemaRef.ExternalSource) { 4784 for (uint32_t I = 0, 4785 N = SemaRef.ExternalSource->GetNumExternalSelectors(); 4786 I != N; ++I) { 4787 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I); 4788 if (Sel.isNull() || SemaRef.MethodPool.count(Sel)) 4789 continue; 4790 4791 SemaRef.ReadMethodPool(Sel); 4792 } 4793 } 4794 4795 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(), 4796 MEnd = SemaRef.MethodPool.end(); 4797 M != MEnd; ++M) { 4798 for (ObjCMethodList *MethList = &M->second.second; 4799 MethList && MethList->Method; 4800 MethList = MethList->Next) { 4801 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents, 4802 NumSelIdents)) 4803 continue; 4804 4805 Result R(MethList->Method, 0); 4806 R.StartParameter = NumSelIdents; 4807 R.AllParametersAreInformative = false; 4808 Results.MaybeAddResult(R, SemaRef.CurContext); 4809 } 4810 } 4811 } 4812 4813 Results.ExitScope(); 4814 } 4815 4816 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 4817 IdentifierInfo **SelIdents, 4818 unsigned NumSelIdents, 4819 bool AtArgumentExpression, 4820 bool IsSuper) { 4821 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4822 CodeCompletionContext::CCC_Other); 4823 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents, 4824 AtArgumentExpression, IsSuper, Results); 4825 4826 // If we're actually at the argument expression (rather than prior to the 4827 // selector), we're actually performing code completion for an expression. 4828 // Determine whether we have a single, best method. If so, we can 4829 // code-complete the expression using the corresponding parameter type as 4830 // our preferred type, improving completion results. 4831 if (AtArgumentExpression) { 4832 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, 4833 NumSelIdents); 4834 if (PreferredType.isNull()) 4835 CodeCompleteOrdinaryName(S, PCC_Expression); 4836 else 4837 CodeCompleteExpression(S, PreferredType); 4838 return; 4839 } 4840 4841 HandleCodeCompleteResults(this, CodeCompleter, 4842 CodeCompletionContext::CCC_Other, 4843 Results.data(), Results.size()); 4844 } 4845 4846 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver, 4847 IdentifierInfo **SelIdents, 4848 unsigned NumSelIdents, 4849 bool AtArgumentExpression, 4850 ObjCInterfaceDecl *Super) { 4851 typedef CodeCompletionResult Result; 4852 4853 Expr *RecExpr = static_cast<Expr *>(Receiver); 4854 4855 // If necessary, apply function/array conversion to the receiver. 4856 // C99 6.7.5.3p[7,8]. 4857 if (RecExpr) { 4858 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr); 4859 if (Conv.isInvalid()) // conversion failed. bail. 4860 return; 4861 RecExpr = Conv.take(); 4862 } 4863 QualType ReceiverType = RecExpr? RecExpr->getType() 4864 : Super? Context.getObjCObjectPointerType( 4865 Context.getObjCInterfaceType(Super)) 4866 : Context.getObjCIdType(); 4867 4868 // If we're messaging an expression with type "id" or "Class", check 4869 // whether we know something special about the receiver that allows 4870 // us to assume a more-specific receiver type. 4871 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) 4872 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) { 4873 if (ReceiverType->isObjCClassType()) 4874 return CodeCompleteObjCClassMessage(S, 4875 ParsedType::make(Context.getObjCInterfaceType(IFace)), 4876 SelIdents, NumSelIdents, 4877 AtArgumentExpression, Super); 4878 4879 ReceiverType = Context.getObjCObjectPointerType( 4880 Context.getObjCInterfaceType(IFace)); 4881 } 4882 4883 // Build the set of methods we can see. 4884 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4885 CodeCompletionContext::CCC_Other); 4886 Results.EnterNewScope(); 4887 4888 // If this is a send-to-super, try to add the special "super" send 4889 // completion. 4890 if (Super) { 4891 if (ObjCMethodDecl *SuperMethod 4892 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents, 4893 Results)) 4894 Results.Ignore(SuperMethod); 4895 } 4896 4897 // If we're inside an Objective-C method definition, prefer its selector to 4898 // others. 4899 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) 4900 Results.setPreferredSelector(CurMethod->getSelector()); 4901 4902 // Keep track of the selectors we've already added. 4903 VisitedSelectorSet Selectors; 4904 4905 // Handle messages to Class. This really isn't a message to an instance 4906 // method, so we treat it the same way we would treat a message send to a 4907 // class method. 4908 if (ReceiverType->isObjCClassType() || 4909 ReceiverType->isObjCQualifiedClassType()) { 4910 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 4911 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) 4912 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents, 4913 CurContext, Selectors, AtArgumentExpression, Results); 4914 } 4915 } 4916 // Handle messages to a qualified ID ("id<foo>"). 4917 else if (const ObjCObjectPointerType *QualID 4918 = ReceiverType->getAsObjCQualifiedIdType()) { 4919 // Search protocols for instance methods. 4920 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(), 4921 E = QualID->qual_end(); 4922 I != E; ++I) 4923 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext, 4924 Selectors, AtArgumentExpression, Results); 4925 } 4926 // Handle messages to a pointer to interface type. 4927 else if (const ObjCObjectPointerType *IFacePtr 4928 = ReceiverType->getAsObjCInterfacePointerType()) { 4929 // Search the class, its superclasses, etc., for instance methods. 4930 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, 4931 NumSelIdents, CurContext, Selectors, AtArgumentExpression, 4932 Results); 4933 4934 // Search protocols for instance methods. 4935 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(), 4936 E = IFacePtr->qual_end(); 4937 I != E; ++I) 4938 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext, 4939 Selectors, AtArgumentExpression, Results); 4940 } 4941 // Handle messages to "id". 4942 else if (ReceiverType->isObjCIdType()) { 4943 // We're messaging "id", so provide all instance methods we know 4944 // about as code-completion results. 4945 4946 // If we have an external source, load the entire class method 4947 // pool from the AST file. 4948 if (ExternalSource) { 4949 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 4950 I != N; ++I) { 4951 Selector Sel = ExternalSource->GetExternalSelector(I); 4952 if (Sel.isNull() || MethodPool.count(Sel)) 4953 continue; 4954 4955 ReadMethodPool(Sel); 4956 } 4957 } 4958 4959 for (GlobalMethodPool::iterator M = MethodPool.begin(), 4960 MEnd = MethodPool.end(); 4961 M != MEnd; ++M) { 4962 for (ObjCMethodList *MethList = &M->second.first; 4963 MethList && MethList->Method; 4964 MethList = MethList->Next) { 4965 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents, 4966 NumSelIdents)) 4967 continue; 4968 4969 if (!Selectors.insert(MethList->Method->getSelector())) 4970 continue; 4971 4972 Result R(MethList->Method, 0); 4973 R.StartParameter = NumSelIdents; 4974 R.AllParametersAreInformative = false; 4975 Results.MaybeAddResult(R, CurContext); 4976 } 4977 } 4978 } 4979 Results.ExitScope(); 4980 4981 4982 // If we're actually at the argument expression (rather than prior to the 4983 // selector), we're actually performing code completion for an expression. 4984 // Determine whether we have a single, best method. If so, we can 4985 // code-complete the expression using the corresponding parameter type as 4986 // our preferred type, improving completion results. 4987 if (AtArgumentExpression) { 4988 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, 4989 NumSelIdents); 4990 if (PreferredType.isNull()) 4991 CodeCompleteOrdinaryName(S, PCC_Expression); 4992 else 4993 CodeCompleteExpression(S, PreferredType); 4994 return; 4995 } 4996 4997 HandleCodeCompleteResults(this, CodeCompleter, 4998 CodeCompletionContext::CCC_Other, 4999 Results.data(),Results.size()); 5000 } 5001 5002 void Sema::CodeCompleteObjCForCollection(Scope *S, 5003 DeclGroupPtrTy IterationVar) { 5004 CodeCompleteExpressionData Data; 5005 Data.ObjCCollection = true; 5006 5007 if (IterationVar.getAsOpaquePtr()) { 5008 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>(); 5009 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { 5010 if (*I) 5011 Data.IgnoreDecls.push_back(*I); 5012 } 5013 } 5014 5015 CodeCompleteExpression(S, Data); 5016 } 5017 5018 void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents, 5019 unsigned NumSelIdents) { 5020 // If we have an external source, load the entire class method 5021 // pool from the AST file. 5022 if (ExternalSource) { 5023 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 5024 I != N; ++I) { 5025 Selector Sel = ExternalSource->GetExternalSelector(I); 5026 if (Sel.isNull() || MethodPool.count(Sel)) 5027 continue; 5028 5029 ReadMethodPool(Sel); 5030 } 5031 } 5032 5033 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5034 CodeCompletionContext::CCC_SelectorName); 5035 Results.EnterNewScope(); 5036 for (GlobalMethodPool::iterator M = MethodPool.begin(), 5037 MEnd = MethodPool.end(); 5038 M != MEnd; ++M) { 5039 5040 Selector Sel = M->first; 5041 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents)) 5042 continue; 5043 5044 CodeCompletionBuilder Builder(Results.getAllocator()); 5045 if (Sel.isUnarySelector()) { 5046 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 5047 Sel.getNameForSlot(0))); 5048 Results.AddResult(Builder.TakeString()); 5049 continue; 5050 } 5051 5052 std::string Accumulator; 5053 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { 5054 if (I == NumSelIdents) { 5055 if (!Accumulator.empty()) { 5056 Builder.AddInformativeChunk(Builder.getAllocator().CopyString( 5057 Accumulator)); 5058 Accumulator.clear(); 5059 } 5060 } 5061 5062 Accumulator += Sel.getNameForSlot(I).str(); 5063 Accumulator += ':'; 5064 } 5065 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator)); 5066 Results.AddResult(Builder.TakeString()); 5067 } 5068 Results.ExitScope(); 5069 5070 HandleCodeCompleteResults(this, CodeCompleter, 5071 CodeCompletionContext::CCC_SelectorName, 5072 Results.data(), Results.size()); 5073 } 5074 5075 /// \brief Add all of the protocol declarations that we find in the given 5076 /// (translation unit) context. 5077 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, 5078 bool OnlyForwardDeclarations, 5079 ResultBuilder &Results) { 5080 typedef CodeCompletionResult Result; 5081 5082 for (DeclContext::decl_iterator D = Ctx->decls_begin(), 5083 DEnd = Ctx->decls_end(); 5084 D != DEnd; ++D) { 5085 // Record any protocols we find. 5086 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D)) 5087 if (!OnlyForwardDeclarations || Proto->isForwardDecl()) 5088 Results.AddResult(Result(Proto, 0), CurContext, 0, false); 5089 5090 // Record any forward-declared protocols we find. 5091 if (ObjCForwardProtocolDecl *Forward 5092 = dyn_cast<ObjCForwardProtocolDecl>(*D)) { 5093 for (ObjCForwardProtocolDecl::protocol_iterator 5094 P = Forward->protocol_begin(), 5095 PEnd = Forward->protocol_end(); 5096 P != PEnd; ++P) 5097 if (!OnlyForwardDeclarations || (*P)->isForwardDecl()) 5098 Results.AddResult(Result(*P, 0), CurContext, 0, false); 5099 } 5100 } 5101 } 5102 5103 void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols, 5104 unsigned NumProtocols) { 5105 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5106 CodeCompletionContext::CCC_ObjCProtocolName); 5107 5108 if (CodeCompleter && CodeCompleter->includeGlobals()) { 5109 Results.EnterNewScope(); 5110 5111 // Tell the result set to ignore all of the protocols we have 5112 // already seen. 5113 // FIXME: This doesn't work when caching code-completion results. 5114 for (unsigned I = 0; I != NumProtocols; ++I) 5115 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first, 5116 Protocols[I].second)) 5117 Results.Ignore(Protocol); 5118 5119 // Add all protocols. 5120 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false, 5121 Results); 5122 5123 Results.ExitScope(); 5124 } 5125 5126 HandleCodeCompleteResults(this, CodeCompleter, 5127 CodeCompletionContext::CCC_ObjCProtocolName, 5128 Results.data(),Results.size()); 5129 } 5130 5131 void Sema::CodeCompleteObjCProtocolDecl(Scope *) { 5132 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5133 CodeCompletionContext::CCC_ObjCProtocolName); 5134 5135 if (CodeCompleter && CodeCompleter->includeGlobals()) { 5136 Results.EnterNewScope(); 5137 5138 // Add all protocols. 5139 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true, 5140 Results); 5141 5142 Results.ExitScope(); 5143 } 5144 5145 HandleCodeCompleteResults(this, CodeCompleter, 5146 CodeCompletionContext::CCC_ObjCProtocolName, 5147 Results.data(),Results.size()); 5148 } 5149 5150 /// \brief Add all of the Objective-C interface declarations that we find in 5151 /// the given (translation unit) context. 5152 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, 5153 bool OnlyForwardDeclarations, 5154 bool OnlyUnimplemented, 5155 ResultBuilder &Results) { 5156 typedef CodeCompletionResult Result; 5157 5158 for (DeclContext::decl_iterator D = Ctx->decls_begin(), 5159 DEnd = Ctx->decls_end(); 5160 D != DEnd; ++D) { 5161 // Record any interfaces we find. 5162 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D)) 5163 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) && 5164 (!OnlyUnimplemented || !Class->getImplementation())) 5165 Results.AddResult(Result(Class, 0), CurContext, 0, false); 5166 5167 // Record any forward-declared interfaces we find. 5168 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) { 5169 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end(); 5170 C != CEnd; ++C) 5171 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) && 5172 (!OnlyUnimplemented || !C->getInterface()->getImplementation())) 5173 Results.AddResult(Result(C->getInterface(), 0), CurContext, 5174 0, false); 5175 } 5176 } 5177 } 5178 5179 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { 5180 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5181 CodeCompletionContext::CCC_Other); 5182 Results.EnterNewScope(); 5183 5184 // Add all classes. 5185 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true, 5186 false, Results); 5187 5188 Results.ExitScope(); 5189 // FIXME: Add a special context for this, use cached global completion 5190 // results. 5191 HandleCodeCompleteResults(this, CodeCompleter, 5192 CodeCompletionContext::CCC_Other, 5193 Results.data(),Results.size()); 5194 } 5195 5196 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, 5197 SourceLocation ClassNameLoc) { 5198 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5199 CodeCompletionContext::CCC_Other); 5200 Results.EnterNewScope(); 5201 5202 // Make sure that we ignore the class we're currently defining. 5203 NamedDecl *CurClass 5204 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 5205 if (CurClass && isa<ObjCInterfaceDecl>(CurClass)) 5206 Results.Ignore(CurClass); 5207 5208 // Add all classes. 5209 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 5210 false, Results); 5211 5212 Results.ExitScope(); 5213 // FIXME: Add a special context for this, use cached global completion 5214 // results. 5215 HandleCodeCompleteResults(this, CodeCompleter, 5216 CodeCompletionContext::CCC_Other, 5217 Results.data(),Results.size()); 5218 } 5219 5220 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { 5221 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5222 CodeCompletionContext::CCC_Other); 5223 Results.EnterNewScope(); 5224 5225 // Add all unimplemented classes. 5226 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 5227 true, Results); 5228 5229 Results.ExitScope(); 5230 // FIXME: Add a special context for this, use cached global completion 5231 // results. 5232 HandleCodeCompleteResults(this, CodeCompleter, 5233 CodeCompletionContext::CCC_Other, 5234 Results.data(),Results.size()); 5235 } 5236 5237 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, 5238 IdentifierInfo *ClassName, 5239 SourceLocation ClassNameLoc) { 5240 typedef CodeCompletionResult Result; 5241 5242 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5243 CodeCompletionContext::CCC_Other); 5244 5245 // Ignore any categories we find that have already been implemented by this 5246 // interface. 5247 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 5248 NamedDecl *CurClass 5249 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 5250 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) 5251 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category; 5252 Category = Category->getNextClassCategory()) 5253 CategoryNames.insert(Category->getIdentifier()); 5254 5255 // Add all of the categories we know about. 5256 Results.EnterNewScope(); 5257 TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 5258 for (DeclContext::decl_iterator D = TU->decls_begin(), 5259 DEnd = TU->decls_end(); 5260 D != DEnd; ++D) 5261 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D)) 5262 if (CategoryNames.insert(Category->getIdentifier())) 5263 Results.AddResult(Result(Category, 0), CurContext, 0, false); 5264 Results.ExitScope(); 5265 5266 HandleCodeCompleteResults(this, CodeCompleter, 5267 CodeCompletionContext::CCC_Other, 5268 Results.data(),Results.size()); 5269 } 5270 5271 void Sema::CodeCompleteObjCImplementationCategory(Scope *S, 5272 IdentifierInfo *ClassName, 5273 SourceLocation ClassNameLoc) { 5274 typedef CodeCompletionResult Result; 5275 5276 // Find the corresponding interface. If we couldn't find the interface, the 5277 // program itself is ill-formed. However, we'll try to be helpful still by 5278 // providing the list of all of the categories we know about. 5279 NamedDecl *CurClass 5280 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 5281 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); 5282 if (!Class) 5283 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); 5284 5285 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5286 CodeCompletionContext::CCC_Other); 5287 5288 // Add all of the categories that have have corresponding interface 5289 // declarations in this class and any of its superclasses, except for 5290 // already-implemented categories in the class itself. 5291 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 5292 Results.EnterNewScope(); 5293 bool IgnoreImplemented = true; 5294 while (Class) { 5295 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category; 5296 Category = Category->getNextClassCategory()) 5297 if ((!IgnoreImplemented || !Category->getImplementation()) && 5298 CategoryNames.insert(Category->getIdentifier())) 5299 Results.AddResult(Result(Category, 0), CurContext, 0, false); 5300 5301 Class = Class->getSuperClass(); 5302 IgnoreImplemented = false; 5303 } 5304 Results.ExitScope(); 5305 5306 HandleCodeCompleteResults(this, CodeCompleter, 5307 CodeCompletionContext::CCC_Other, 5308 Results.data(),Results.size()); 5309 } 5310 5311 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) { 5312 typedef CodeCompletionResult Result; 5313 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5314 CodeCompletionContext::CCC_Other); 5315 5316 // Figure out where this @synthesize lives. 5317 ObjCContainerDecl *Container 5318 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl); 5319 if (!Container || 5320 (!isa<ObjCImplementationDecl>(Container) && 5321 !isa<ObjCCategoryImplDecl>(Container))) 5322 return; 5323 5324 // Ignore any properties that have already been implemented. 5325 for (DeclContext::decl_iterator D = Container->decls_begin(), 5326 DEnd = Container->decls_end(); 5327 D != DEnd; ++D) 5328 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D)) 5329 Results.Ignore(PropertyImpl->getPropertyDecl()); 5330 5331 // Add any properties that we find. 5332 AddedPropertiesSet AddedProperties; 5333 Results.EnterNewScope(); 5334 if (ObjCImplementationDecl *ClassImpl 5335 = dyn_cast<ObjCImplementationDecl>(Container)) 5336 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext, 5337 AddedProperties, Results); 5338 else 5339 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), 5340 false, CurContext, AddedProperties, Results); 5341 Results.ExitScope(); 5342 5343 HandleCodeCompleteResults(this, CodeCompleter, 5344 CodeCompletionContext::CCC_Other, 5345 Results.data(),Results.size()); 5346 } 5347 5348 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 5349 IdentifierInfo *PropertyName, 5350 Decl *ObjCImpDecl) { 5351 typedef CodeCompletionResult Result; 5352 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5353 CodeCompletionContext::CCC_Other); 5354 5355 // Figure out where this @synthesize lives. 5356 ObjCContainerDecl *Container 5357 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl); 5358 if (!Container || 5359 (!isa<ObjCImplementationDecl>(Container) && 5360 !isa<ObjCCategoryImplDecl>(Container))) 5361 return; 5362 5363 // Figure out which interface we're looking into. 5364 ObjCInterfaceDecl *Class = 0; 5365 if (ObjCImplementationDecl *ClassImpl 5366 = dyn_cast<ObjCImplementationDecl>(Container)) 5367 Class = ClassImpl->getClassInterface(); 5368 else 5369 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl() 5370 ->getClassInterface(); 5371 5372 // Add all of the instance variables in this class and its superclasses. 5373 Results.EnterNewScope(); 5374 for(; Class; Class = Class->getSuperClass()) { 5375 // FIXME: We could screen the type of each ivar for compatibility with 5376 // the property, but is that being too paternal? 5377 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(), 5378 IVarEnd = Class->ivar_end(); 5379 IVar != IVarEnd; ++IVar) 5380 Results.AddResult(Result(*IVar, 0), CurContext, 0, false); 5381 } 5382 Results.ExitScope(); 5383 5384 HandleCodeCompleteResults(this, CodeCompleter, 5385 CodeCompletionContext::CCC_Other, 5386 Results.data(),Results.size()); 5387 } 5388 5389 // Mapping from selectors to the methods that implement that selector, along 5390 // with the "in original class" flag. 5391 typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> > 5392 KnownMethodsMap; 5393 5394 /// \brief Find all of the methods that reside in the given container 5395 /// (and its superclasses, protocols, etc.) that meet the given 5396 /// criteria. Insert those methods into the map of known methods, 5397 /// indexed by selector so they can be easily found. 5398 static void FindImplementableMethods(ASTContext &Context, 5399 ObjCContainerDecl *Container, 5400 bool WantInstanceMethods, 5401 QualType ReturnType, 5402 KnownMethodsMap &KnownMethods, 5403 bool InOriginalClass = true) { 5404 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) { 5405 // Recurse into protocols. 5406 const ObjCList<ObjCProtocolDecl> &Protocols 5407 = IFace->getReferencedProtocols(); 5408 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 5409 E = Protocols.end(); 5410 I != E; ++I) 5411 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 5412 KnownMethods, InOriginalClass); 5413 5414 // Add methods from any class extensions and categories. 5415 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat; 5416 Cat = Cat->getNextClassCategory()) 5417 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat), 5418 WantInstanceMethods, ReturnType, 5419 KnownMethods, false); 5420 5421 // Visit the superclass. 5422 if (IFace->getSuperClass()) 5423 FindImplementableMethods(Context, IFace->getSuperClass(), 5424 WantInstanceMethods, ReturnType, 5425 KnownMethods, false); 5426 } 5427 5428 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 5429 // Recurse into protocols. 5430 const ObjCList<ObjCProtocolDecl> &Protocols 5431 = Category->getReferencedProtocols(); 5432 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 5433 E = Protocols.end(); 5434 I != E; ++I) 5435 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 5436 KnownMethods, InOriginalClass); 5437 5438 // If this category is the original class, jump to the interface. 5439 if (InOriginalClass && Category->getClassInterface()) 5440 FindImplementableMethods(Context, Category->getClassInterface(), 5441 WantInstanceMethods, ReturnType, KnownMethods, 5442 false); 5443 } 5444 5445 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 5446 // Recurse into protocols. 5447 const ObjCList<ObjCProtocolDecl> &Protocols 5448 = Protocol->getReferencedProtocols(); 5449 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 5450 E = Protocols.end(); 5451 I != E; ++I) 5452 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 5453 KnownMethods, false); 5454 } 5455 5456 // Add methods in this container. This operation occurs last because 5457 // we want the methods from this container to override any methods 5458 // we've previously seen with the same selector. 5459 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(), 5460 MEnd = Container->meth_end(); 5461 M != MEnd; ++M) { 5462 if ((*M)->isInstanceMethod() == WantInstanceMethods) { 5463 if (!ReturnType.isNull() && 5464 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType())) 5465 continue; 5466 5467 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass); 5468 } 5469 } 5470 } 5471 5472 /// \brief Add the parenthesized return or parameter type chunk to a code 5473 /// completion string. 5474 static void AddObjCPassingTypeChunk(QualType Type, 5475 ASTContext &Context, 5476 CodeCompletionBuilder &Builder) { 5477 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5478 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, 5479 Builder.getAllocator())); 5480 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5481 } 5482 5483 /// \brief Determine whether the given class is or inherits from a class by 5484 /// the given name. 5485 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, 5486 llvm::StringRef Name) { 5487 if (!Class) 5488 return false; 5489 5490 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name) 5491 return true; 5492 5493 return InheritsFromClassNamed(Class->getSuperClass(), Name); 5494 } 5495 5496 /// \brief Add code completions for Objective-C Key-Value Coding (KVC) and 5497 /// Key-Value Observing (KVO). 5498 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, 5499 bool IsInstanceMethod, 5500 QualType ReturnType, 5501 ASTContext &Context, 5502 const KnownMethodsMap &KnownMethods, 5503 ResultBuilder &Results) { 5504 IdentifierInfo *PropName = Property->getIdentifier(); 5505 if (!PropName || PropName->getLength() == 0) 5506 return; 5507 5508 5509 // Builder that will create each code completion. 5510 typedef CodeCompletionResult Result; 5511 CodeCompletionAllocator &Allocator = Results.getAllocator(); 5512 CodeCompletionBuilder Builder(Allocator); 5513 5514 // The selector table. 5515 SelectorTable &Selectors = Context.Selectors; 5516 5517 // The property name, copied into the code completion allocation region 5518 // on demand. 5519 struct KeyHolder { 5520 CodeCompletionAllocator &Allocator; 5521 llvm::StringRef Key; 5522 const char *CopiedKey; 5523 5524 KeyHolder(CodeCompletionAllocator &Allocator, llvm::StringRef Key) 5525 : Allocator(Allocator), Key(Key), CopiedKey(0) { } 5526 5527 operator const char *() { 5528 if (CopiedKey) 5529 return CopiedKey; 5530 5531 return CopiedKey = Allocator.CopyString(Key); 5532 } 5533 } Key(Allocator, PropName->getName()); 5534 5535 // The uppercased name of the property name. 5536 std::string UpperKey = PropName->getName(); 5537 if (!UpperKey.empty()) 5538 UpperKey[0] = toupper(UpperKey[0]); 5539 5540 bool ReturnTypeMatchesProperty = ReturnType.isNull() || 5541 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(), 5542 Property->getType()); 5543 bool ReturnTypeMatchesVoid 5544 = ReturnType.isNull() || ReturnType->isVoidType(); 5545 5546 // Add the normal accessor -(type)key. 5547 if (IsInstanceMethod && 5548 !KnownMethods.count(Selectors.getNullarySelector(PropName)) && 5549 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) { 5550 if (ReturnType.isNull()) 5551 AddObjCPassingTypeChunk(Property->getType(), Context, Builder); 5552 5553 Builder.AddTypedTextChunk(Key); 5554 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 5555 CXCursor_ObjCInstanceMethodDecl)); 5556 } 5557 5558 // If we have an integral or boolean property (or the user has provided 5559 // an integral or boolean return type), add the accessor -(type)isKey. 5560 if (IsInstanceMethod && 5561 ((!ReturnType.isNull() && 5562 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) || 5563 (ReturnType.isNull() && 5564 (Property->getType()->isIntegerType() || 5565 Property->getType()->isBooleanType())))) { 5566 std::string SelectorName = (llvm::Twine("is") + UpperKey).str(); 5567 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 5568 if (!KnownMethods.count(Selectors.getNullarySelector(SelectorId))) { 5569 if (ReturnType.isNull()) { 5570 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5571 Builder.AddTextChunk("BOOL"); 5572 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5573 } 5574 5575 Builder.AddTypedTextChunk( 5576 Allocator.CopyString(SelectorId->getName())); 5577 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 5578 CXCursor_ObjCInstanceMethodDecl)); 5579 } 5580 } 5581 5582 // Add the normal mutator. 5583 if (IsInstanceMethod && ReturnTypeMatchesVoid && 5584 !Property->getSetterMethodDecl()) { 5585 std::string SelectorName = (llvm::Twine("set") + UpperKey).str(); 5586 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 5587 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) { 5588 if (ReturnType.isNull()) { 5589 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5590 Builder.AddTextChunk("void"); 5591 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5592 } 5593 5594 Builder.AddTypedTextChunk( 5595 Allocator.CopyString(SelectorId->getName())); 5596 Builder.AddTypedTextChunk(":"); 5597 AddObjCPassingTypeChunk(Property->getType(), Context, Builder); 5598 Builder.AddTextChunk(Key); 5599 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 5600 CXCursor_ObjCInstanceMethodDecl)); 5601 } 5602 } 5603 5604 // Indexed and unordered accessors 5605 unsigned IndexedGetterPriority = CCP_CodePattern; 5606 unsigned IndexedSetterPriority = CCP_CodePattern; 5607 unsigned UnorderedGetterPriority = CCP_CodePattern; 5608 unsigned UnorderedSetterPriority = CCP_CodePattern; 5609 if (const ObjCObjectPointerType *ObjCPointer 5610 = Property->getType()->getAs<ObjCObjectPointerType>()) { 5611 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) { 5612 // If this interface type is not provably derived from a known 5613 // collection, penalize the corresponding completions. 5614 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) { 5615 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 5616 if (!InheritsFromClassNamed(IFace, "NSArray")) 5617 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 5618 } 5619 5620 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) { 5621 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 5622 if (!InheritsFromClassNamed(IFace, "NSSet")) 5623 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 5624 } 5625 } 5626 } else { 5627 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 5628 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 5629 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 5630 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 5631 } 5632 5633 // Add -(NSUInteger)countOf<key> 5634 if (IsInstanceMethod && 5635 (ReturnType.isNull() || ReturnType->isIntegerType())) { 5636 std::string SelectorName = (llvm::Twine("countOf") + UpperKey).str(); 5637 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 5638 if (!KnownMethods.count(Selectors.getNullarySelector(SelectorId))) { 5639 if (ReturnType.isNull()) { 5640 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5641 Builder.AddTextChunk("NSUInteger"); 5642 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5643 } 5644 5645 Builder.AddTypedTextChunk( 5646 Allocator.CopyString(SelectorId->getName())); 5647 Results.AddResult(Result(Builder.TakeString(), 5648 std::min(IndexedGetterPriority, 5649 UnorderedGetterPriority), 5650 CXCursor_ObjCInstanceMethodDecl)); 5651 } 5652 } 5653 5654 // Indexed getters 5655 // Add -(id)objectInKeyAtIndex:(NSUInteger)index 5656 if (IsInstanceMethod && 5657 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 5658 std::string SelectorName 5659 = (llvm::Twine("objectIn") + UpperKey + "AtIndex").str(); 5660 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 5661 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) { 5662 if (ReturnType.isNull()) { 5663 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5664 Builder.AddTextChunk("id"); 5665 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5666 } 5667 5668 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 5669 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5670 Builder.AddTextChunk("NSUInteger"); 5671 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5672 Builder.AddTextChunk("index"); 5673 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 5674 CXCursor_ObjCInstanceMethodDecl)); 5675 } 5676 } 5677 5678 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes 5679 if (IsInstanceMethod && 5680 (ReturnType.isNull() || 5681 (ReturnType->isObjCObjectPointerType() && 5682 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 5683 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() 5684 ->getName() == "NSArray"))) { 5685 std::string SelectorName 5686 = (llvm::Twine(Property->getName()) + "AtIndexes").str(); 5687 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 5688 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) { 5689 if (ReturnType.isNull()) { 5690 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5691 Builder.AddTextChunk("NSArray *"); 5692 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5693 } 5694 5695 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 5696 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5697 Builder.AddTextChunk("NSIndexSet *"); 5698 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5699 Builder.AddTextChunk("indexes"); 5700 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 5701 CXCursor_ObjCInstanceMethodDecl)); 5702 } 5703 } 5704 5705 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange 5706 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 5707 std::string SelectorName = (llvm::Twine("get") + UpperKey).str(); 5708 IdentifierInfo *SelectorIds[2] = { 5709 &Context.Idents.get(SelectorName), 5710 &Context.Idents.get("range") 5711 }; 5712 5713 if (!KnownMethods.count(Selectors.getSelector(2, SelectorIds))) { 5714 if (ReturnType.isNull()) { 5715 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5716 Builder.AddTextChunk("void"); 5717 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5718 } 5719 5720 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 5721 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5722 Builder.AddPlaceholderChunk("object-type"); 5723 Builder.AddTextChunk(" **"); 5724 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5725 Builder.AddTextChunk("buffer"); 5726 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5727 Builder.AddTypedTextChunk("range:"); 5728 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5729 Builder.AddTextChunk("NSRange"); 5730 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5731 Builder.AddTextChunk("inRange"); 5732 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 5733 CXCursor_ObjCInstanceMethodDecl)); 5734 } 5735 } 5736 5737 // Mutable indexed accessors 5738 5739 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index 5740 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 5741 std::string SelectorName = (llvm::Twine("in") + UpperKey + "AtIndex").str(); 5742 IdentifierInfo *SelectorIds[2] = { 5743 &Context.Idents.get("insertObject"), 5744 &Context.Idents.get(SelectorName) 5745 }; 5746 5747 if (!KnownMethods.count(Selectors.getSelector(2, SelectorIds))) { 5748 if (ReturnType.isNull()) { 5749 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5750 Builder.AddTextChunk("void"); 5751 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5752 } 5753 5754 Builder.AddTypedTextChunk("insertObject:"); 5755 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5756 Builder.AddPlaceholderChunk("object-type"); 5757 Builder.AddTextChunk(" *"); 5758 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5759 Builder.AddTextChunk("object"); 5760 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5761 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 5762 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5763 Builder.AddPlaceholderChunk("NSUInteger"); 5764 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5765 Builder.AddTextChunk("index"); 5766 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 5767 CXCursor_ObjCInstanceMethodDecl)); 5768 } 5769 } 5770 5771 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes 5772 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 5773 std::string SelectorName = (llvm::Twine("insert") + UpperKey).str(); 5774 IdentifierInfo *SelectorIds[2] = { 5775 &Context.Idents.get(SelectorName), 5776 &Context.Idents.get("atIndexes") 5777 }; 5778 5779 if (!KnownMethods.count(Selectors.getSelector(2, SelectorIds))) { 5780 if (ReturnType.isNull()) { 5781 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5782 Builder.AddTextChunk("void"); 5783 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5784 } 5785 5786 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 5787 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5788 Builder.AddTextChunk("NSArray *"); 5789 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5790 Builder.AddTextChunk("array"); 5791 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5792 Builder.AddTypedTextChunk("atIndexes:"); 5793 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5794 Builder.AddPlaceholderChunk("NSIndexSet *"); 5795 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5796 Builder.AddTextChunk("indexes"); 5797 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 5798 CXCursor_ObjCInstanceMethodDecl)); 5799 } 5800 } 5801 5802 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index 5803 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 5804 std::string SelectorName 5805 = (llvm::Twine("removeObjectFrom") + UpperKey + "AtIndex").str(); 5806 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 5807 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) { 5808 if (ReturnType.isNull()) { 5809 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5810 Builder.AddTextChunk("void"); 5811 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5812 } 5813 5814 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 5815 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5816 Builder.AddTextChunk("NSUInteger"); 5817 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5818 Builder.AddTextChunk("index"); 5819 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 5820 CXCursor_ObjCInstanceMethodDecl)); 5821 } 5822 } 5823 5824 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes 5825 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 5826 std::string SelectorName 5827 = (llvm::Twine("remove") + UpperKey + "AtIndexes").str(); 5828 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 5829 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) { 5830 if (ReturnType.isNull()) { 5831 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5832 Builder.AddTextChunk("void"); 5833 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5834 } 5835 5836 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 5837 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5838 Builder.AddTextChunk("NSIndexSet *"); 5839 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5840 Builder.AddTextChunk("indexes"); 5841 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 5842 CXCursor_ObjCInstanceMethodDecl)); 5843 } 5844 } 5845 5846 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object 5847 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 5848 std::string SelectorName 5849 = (llvm::Twine("replaceObjectIn") + UpperKey + "AtIndex").str(); 5850 IdentifierInfo *SelectorIds[2] = { 5851 &Context.Idents.get(SelectorName), 5852 &Context.Idents.get("withObject") 5853 }; 5854 5855 if (!KnownMethods.count(Selectors.getSelector(2, SelectorIds))) { 5856 if (ReturnType.isNull()) { 5857 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5858 Builder.AddTextChunk("void"); 5859 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5860 } 5861 5862 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 5863 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5864 Builder.AddPlaceholderChunk("NSUInteger"); 5865 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5866 Builder.AddTextChunk("index"); 5867 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5868 Builder.AddTypedTextChunk("withObject:"); 5869 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5870 Builder.AddTextChunk("id"); 5871 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5872 Builder.AddTextChunk("object"); 5873 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 5874 CXCursor_ObjCInstanceMethodDecl)); 5875 } 5876 } 5877 5878 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array 5879 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 5880 std::string SelectorName1 5881 = (llvm::Twine("replace") + UpperKey + "AtIndexes").str(); 5882 std::string SelectorName2 = (llvm::Twine("with") + UpperKey).str(); 5883 IdentifierInfo *SelectorIds[2] = { 5884 &Context.Idents.get(SelectorName1), 5885 &Context.Idents.get(SelectorName2) 5886 }; 5887 5888 if (!KnownMethods.count(Selectors.getSelector(2, SelectorIds))) { 5889 if (ReturnType.isNull()) { 5890 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5891 Builder.AddTextChunk("void"); 5892 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5893 } 5894 5895 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":")); 5896 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5897 Builder.AddPlaceholderChunk("NSIndexSet *"); 5898 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5899 Builder.AddTextChunk("indexes"); 5900 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5901 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":")); 5902 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5903 Builder.AddTextChunk("NSArray *"); 5904 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5905 Builder.AddTextChunk("array"); 5906 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 5907 CXCursor_ObjCInstanceMethodDecl)); 5908 } 5909 } 5910 5911 // Unordered getters 5912 // - (NSEnumerator *)enumeratorOfKey 5913 if (IsInstanceMethod && 5914 (ReturnType.isNull() || 5915 (ReturnType->isObjCObjectPointerType() && 5916 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 5917 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() 5918 ->getName() == "NSEnumerator"))) { 5919 std::string SelectorName = (llvm::Twine("enumeratorOf") + UpperKey).str(); 5920 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 5921 if (!KnownMethods.count(Selectors.getNullarySelector(SelectorId))) { 5922 if (ReturnType.isNull()) { 5923 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5924 Builder.AddTextChunk("NSEnumerator *"); 5925 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5926 } 5927 5928 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 5929 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 5930 CXCursor_ObjCInstanceMethodDecl)); 5931 } 5932 } 5933 5934 // - (type *)memberOfKey:(type *)object 5935 if (IsInstanceMethod && 5936 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 5937 std::string SelectorName = (llvm::Twine("memberOf") + UpperKey).str(); 5938 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 5939 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) { 5940 if (ReturnType.isNull()) { 5941 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5942 Builder.AddPlaceholderChunk("object-type"); 5943 Builder.AddTextChunk(" *"); 5944 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5945 } 5946 5947 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 5948 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5949 if (ReturnType.isNull()) { 5950 Builder.AddPlaceholderChunk("object-type"); 5951 Builder.AddTextChunk(" *"); 5952 } else { 5953 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context, 5954 Builder.getAllocator())); 5955 } 5956 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5957 Builder.AddTextChunk("object"); 5958 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 5959 CXCursor_ObjCInstanceMethodDecl)); 5960 } 5961 } 5962 5963 // Mutable unordered accessors 5964 // - (void)addKeyObject:(type *)object 5965 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 5966 std::string SelectorName 5967 = (llvm::Twine("add") + UpperKey + llvm::Twine("Object")).str(); 5968 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 5969 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) { 5970 if (ReturnType.isNull()) { 5971 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5972 Builder.AddTextChunk("void"); 5973 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5974 } 5975 5976 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 5977 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5978 Builder.AddPlaceholderChunk("object-type"); 5979 Builder.AddTextChunk(" *"); 5980 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5981 Builder.AddTextChunk("object"); 5982 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 5983 CXCursor_ObjCInstanceMethodDecl)); 5984 } 5985 } 5986 5987 // - (void)addKey:(NSSet *)objects 5988 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 5989 std::string SelectorName = (llvm::Twine("add") + UpperKey).str(); 5990 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 5991 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) { 5992 if (ReturnType.isNull()) { 5993 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5994 Builder.AddTextChunk("void"); 5995 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5996 } 5997 5998 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 5999 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6000 Builder.AddTextChunk("NSSet *"); 6001 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6002 Builder.AddTextChunk("objects"); 6003 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 6004 CXCursor_ObjCInstanceMethodDecl)); 6005 } 6006 } 6007 6008 // - (void)removeKeyObject:(type *)object 6009 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 6010 std::string SelectorName 6011 = (llvm::Twine("remove") + UpperKey + llvm::Twine("Object")).str(); 6012 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6013 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) { 6014 if (ReturnType.isNull()) { 6015 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6016 Builder.AddTextChunk("void"); 6017 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6018 } 6019 6020 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 6021 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6022 Builder.AddPlaceholderChunk("object-type"); 6023 Builder.AddTextChunk(" *"); 6024 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6025 Builder.AddTextChunk("object"); 6026 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 6027 CXCursor_ObjCInstanceMethodDecl)); 6028 } 6029 } 6030 6031 // - (void)removeKey:(NSSet *)objects 6032 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 6033 std::string SelectorName = (llvm::Twine("remove") + UpperKey).str(); 6034 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6035 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) { 6036 if (ReturnType.isNull()) { 6037 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6038 Builder.AddTextChunk("void"); 6039 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6040 } 6041 6042 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 6043 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6044 Builder.AddTextChunk("NSSet *"); 6045 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6046 Builder.AddTextChunk("objects"); 6047 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 6048 CXCursor_ObjCInstanceMethodDecl)); 6049 } 6050 } 6051 6052 // - (void)intersectKey:(NSSet *)objects 6053 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 6054 std::string SelectorName = (llvm::Twine("intersect") + UpperKey).str(); 6055 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6056 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) { 6057 if (ReturnType.isNull()) { 6058 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6059 Builder.AddTextChunk("void"); 6060 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6061 } 6062 6063 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 6064 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6065 Builder.AddTextChunk("NSSet *"); 6066 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6067 Builder.AddTextChunk("objects"); 6068 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 6069 CXCursor_ObjCInstanceMethodDecl)); 6070 } 6071 } 6072 6073 // Key-Value Observing 6074 // + (NSSet *)keyPathsForValuesAffectingKey 6075 if (!IsInstanceMethod && 6076 (ReturnType.isNull() || 6077 (ReturnType->isObjCObjectPointerType() && 6078 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 6079 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() 6080 ->getName() == "NSSet"))) { 6081 std::string SelectorName 6082 = (llvm::Twine("keyPathsForValuesAffecting") + UpperKey).str(); 6083 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 6084 if (!KnownMethods.count(Selectors.getNullarySelector(SelectorId))) { 6085 if (ReturnType.isNull()) { 6086 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6087 Builder.AddTextChunk("NSSet *"); 6088 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6089 } 6090 6091 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 6092 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 6093 CXCursor_ObjCInstanceMethodDecl)); 6094 } 6095 } 6096 } 6097 6098 void Sema::CodeCompleteObjCMethodDecl(Scope *S, 6099 bool IsInstanceMethod, 6100 ParsedType ReturnTy, 6101 Decl *IDecl) { 6102 // Determine the return type of the method we're declaring, if 6103 // provided. 6104 QualType ReturnType = GetTypeFromParser(ReturnTy); 6105 6106 // Determine where we should start searching for methods. 6107 ObjCContainerDecl *SearchDecl = 0; 6108 bool IsInImplementation = false; 6109 if (Decl *D = IDecl) { 6110 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { 6111 SearchDecl = Impl->getClassInterface(); 6112 IsInImplementation = true; 6113 } else if (ObjCCategoryImplDecl *CatImpl 6114 = dyn_cast<ObjCCategoryImplDecl>(D)) { 6115 SearchDecl = CatImpl->getCategoryDecl(); 6116 IsInImplementation = true; 6117 } else 6118 SearchDecl = dyn_cast<ObjCContainerDecl>(D); 6119 } 6120 6121 if (!SearchDecl && S) { 6122 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) 6123 SearchDecl = dyn_cast<ObjCContainerDecl>(DC); 6124 } 6125 6126 if (!SearchDecl) { 6127 HandleCodeCompleteResults(this, CodeCompleter, 6128 CodeCompletionContext::CCC_Other, 6129 0, 0); 6130 return; 6131 } 6132 6133 // Find all of the methods that we could declare/implement here. 6134 KnownMethodsMap KnownMethods; 6135 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, 6136 ReturnType, KnownMethods); 6137 6138 // Add declarations or definitions for each of the known methods. 6139 typedef CodeCompletionResult Result; 6140 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6141 CodeCompletionContext::CCC_Other); 6142 Results.EnterNewScope(); 6143 PrintingPolicy Policy(Context.PrintingPolicy); 6144 Policy.AnonymousTagLocations = false; 6145 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 6146 MEnd = KnownMethods.end(); 6147 M != MEnd; ++M) { 6148 ObjCMethodDecl *Method = M->second.first; 6149 CodeCompletionBuilder Builder(Results.getAllocator()); 6150 6151 // If the result type was not already provided, add it to the 6152 // pattern as (type). 6153 if (ReturnType.isNull()) 6154 AddObjCPassingTypeChunk(Method->getResultType(), Context, Builder); 6155 6156 Selector Sel = Method->getSelector(); 6157 6158 // Add the first part of the selector to the pattern. 6159 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 6160 Sel.getNameForSlot(0))); 6161 6162 // Add parameters to the pattern. 6163 unsigned I = 0; 6164 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 6165 PEnd = Method->param_end(); 6166 P != PEnd; (void)++P, ++I) { 6167 // Add the part of the selector name. 6168 if (I == 0) 6169 Builder.AddTypedTextChunk(":"); 6170 else if (I < Sel.getNumArgs()) { 6171 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6172 Builder.AddTypedTextChunk( 6173 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 6174 } else 6175 break; 6176 6177 // Add the parameter type. 6178 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Builder); 6179 6180 if (IdentifierInfo *Id = (*P)->getIdentifier()) 6181 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName())); 6182 } 6183 6184 if (Method->isVariadic()) { 6185 if (Method->param_size() > 0) 6186 Builder.AddChunk(CodeCompletionString::CK_Comma); 6187 Builder.AddTextChunk("..."); 6188 } 6189 6190 if (IsInImplementation && Results.includeCodePatterns()) { 6191 // We will be defining the method here, so add a compound statement. 6192 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6193 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 6194 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 6195 if (!Method->getResultType()->isVoidType()) { 6196 // If the result type is not void, add a return clause. 6197 Builder.AddTextChunk("return"); 6198 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6199 Builder.AddPlaceholderChunk("expression"); 6200 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 6201 } else 6202 Builder.AddPlaceholderChunk("statements"); 6203 6204 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 6205 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 6206 } 6207 6208 unsigned Priority = CCP_CodePattern; 6209 if (!M->second.second) 6210 Priority += CCD_InBaseClass; 6211 6212 Results.AddResult(Result(Builder.TakeString(), Priority, 6213 Method->isInstanceMethod() 6214 ? CXCursor_ObjCInstanceMethodDecl 6215 : CXCursor_ObjCClassMethodDecl)); 6216 } 6217 6218 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of 6219 // the properties in this class and its categories. 6220 if (Context.getLangOptions().ObjC2) { 6221 llvm::SmallVector<ObjCContainerDecl *, 4> Containers; 6222 Containers.push_back(SearchDecl); 6223 6224 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl); 6225 if (!IFace) 6226 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl)) 6227 IFace = Category->getClassInterface(); 6228 6229 if (IFace) { 6230 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category; 6231 Category = Category->getNextClassCategory()) 6232 Containers.push_back(Category); 6233 } 6234 6235 for (unsigned I = 0, N = Containers.size(); I != N; ++I) { 6236 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(), 6237 PEnd = Containers[I]->prop_end(); 6238 P != PEnd; ++P) { 6239 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context, 6240 KnownMethods, Results); 6241 } 6242 } 6243 } 6244 6245 Results.ExitScope(); 6246 6247 HandleCodeCompleteResults(this, CodeCompleter, 6248 CodeCompletionContext::CCC_Other, 6249 Results.data(),Results.size()); 6250 } 6251 6252 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S, 6253 bool IsInstanceMethod, 6254 bool AtParameterName, 6255 ParsedType ReturnTy, 6256 IdentifierInfo **SelIdents, 6257 unsigned NumSelIdents) { 6258 // If we have an external source, load the entire class method 6259 // pool from the AST file. 6260 if (ExternalSource) { 6261 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 6262 I != N; ++I) { 6263 Selector Sel = ExternalSource->GetExternalSelector(I); 6264 if (Sel.isNull() || MethodPool.count(Sel)) 6265 continue; 6266 6267 ReadMethodPool(Sel); 6268 } 6269 } 6270 6271 // Build the set of methods we can see. 6272 typedef CodeCompletionResult Result; 6273 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6274 CodeCompletionContext::CCC_Other); 6275 6276 if (ReturnTy) 6277 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType()); 6278 6279 Results.EnterNewScope(); 6280 for (GlobalMethodPool::iterator M = MethodPool.begin(), 6281 MEnd = MethodPool.end(); 6282 M != MEnd; ++M) { 6283 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first : 6284 &M->second.second; 6285 MethList && MethList->Method; 6286 MethList = MethList->Next) { 6287 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents, 6288 NumSelIdents)) 6289 continue; 6290 6291 if (AtParameterName) { 6292 // Suggest parameter names we've seen before. 6293 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) { 6294 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1]; 6295 if (Param->getIdentifier()) { 6296 CodeCompletionBuilder Builder(Results.getAllocator()); 6297 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 6298 Param->getIdentifier()->getName())); 6299 Results.AddResult(Builder.TakeString()); 6300 } 6301 } 6302 6303 continue; 6304 } 6305 6306 Result R(MethList->Method, 0); 6307 R.StartParameter = NumSelIdents; 6308 R.AllParametersAreInformative = false; 6309 R.DeclaringEntity = true; 6310 Results.MaybeAddResult(R, CurContext); 6311 } 6312 } 6313 6314 Results.ExitScope(); 6315 HandleCodeCompleteResults(this, CodeCompleter, 6316 CodeCompletionContext::CCC_Other, 6317 Results.data(),Results.size()); 6318 } 6319 6320 void Sema::CodeCompletePreprocessorDirective(bool InConditional) { 6321 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6322 CodeCompletionContext::CCC_PreprocessorDirective); 6323 Results.EnterNewScope(); 6324 6325 // #if <condition> 6326 CodeCompletionBuilder Builder(Results.getAllocator()); 6327 Builder.AddTypedTextChunk("if"); 6328 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6329 Builder.AddPlaceholderChunk("condition"); 6330 Results.AddResult(Builder.TakeString()); 6331 6332 // #ifdef <macro> 6333 Builder.AddTypedTextChunk("ifdef"); 6334 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6335 Builder.AddPlaceholderChunk("macro"); 6336 Results.AddResult(Builder.TakeString()); 6337 6338 // #ifndef <macro> 6339 Builder.AddTypedTextChunk("ifndef"); 6340 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6341 Builder.AddPlaceholderChunk("macro"); 6342 Results.AddResult(Builder.TakeString()); 6343 6344 if (InConditional) { 6345 // #elif <condition> 6346 Builder.AddTypedTextChunk("elif"); 6347 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6348 Builder.AddPlaceholderChunk("condition"); 6349 Results.AddResult(Builder.TakeString()); 6350 6351 // #else 6352 Builder.AddTypedTextChunk("else"); 6353 Results.AddResult(Builder.TakeString()); 6354 6355 // #endif 6356 Builder.AddTypedTextChunk("endif"); 6357 Results.AddResult(Builder.TakeString()); 6358 } 6359 6360 // #include "header" 6361 Builder.AddTypedTextChunk("include"); 6362 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6363 Builder.AddTextChunk("\""); 6364 Builder.AddPlaceholderChunk("header"); 6365 Builder.AddTextChunk("\""); 6366 Results.AddResult(Builder.TakeString()); 6367 6368 // #include <header> 6369 Builder.AddTypedTextChunk("include"); 6370 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6371 Builder.AddTextChunk("<"); 6372 Builder.AddPlaceholderChunk("header"); 6373 Builder.AddTextChunk(">"); 6374 Results.AddResult(Builder.TakeString()); 6375 6376 // #define <macro> 6377 Builder.AddTypedTextChunk("define"); 6378 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6379 Builder.AddPlaceholderChunk("macro"); 6380 Results.AddResult(Builder.TakeString()); 6381 6382 // #define <macro>(<args>) 6383 Builder.AddTypedTextChunk("define"); 6384 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6385 Builder.AddPlaceholderChunk("macro"); 6386 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6387 Builder.AddPlaceholderChunk("args"); 6388 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6389 Results.AddResult(Builder.TakeString()); 6390 6391 // #undef <macro> 6392 Builder.AddTypedTextChunk("undef"); 6393 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6394 Builder.AddPlaceholderChunk("macro"); 6395 Results.AddResult(Builder.TakeString()); 6396 6397 // #line <number> 6398 Builder.AddTypedTextChunk("line"); 6399 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6400 Builder.AddPlaceholderChunk("number"); 6401 Results.AddResult(Builder.TakeString()); 6402 6403 // #line <number> "filename" 6404 Builder.AddTypedTextChunk("line"); 6405 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6406 Builder.AddPlaceholderChunk("number"); 6407 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6408 Builder.AddTextChunk("\""); 6409 Builder.AddPlaceholderChunk("filename"); 6410 Builder.AddTextChunk("\""); 6411 Results.AddResult(Builder.TakeString()); 6412 6413 // #error <message> 6414 Builder.AddTypedTextChunk("error"); 6415 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6416 Builder.AddPlaceholderChunk("message"); 6417 Results.AddResult(Builder.TakeString()); 6418 6419 // #pragma <arguments> 6420 Builder.AddTypedTextChunk("pragma"); 6421 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6422 Builder.AddPlaceholderChunk("arguments"); 6423 Results.AddResult(Builder.TakeString()); 6424 6425 if (getLangOptions().ObjC1) { 6426 // #import "header" 6427 Builder.AddTypedTextChunk("import"); 6428 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6429 Builder.AddTextChunk("\""); 6430 Builder.AddPlaceholderChunk("header"); 6431 Builder.AddTextChunk("\""); 6432 Results.AddResult(Builder.TakeString()); 6433 6434 // #import <header> 6435 Builder.AddTypedTextChunk("import"); 6436 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6437 Builder.AddTextChunk("<"); 6438 Builder.AddPlaceholderChunk("header"); 6439 Builder.AddTextChunk(">"); 6440 Results.AddResult(Builder.TakeString()); 6441 } 6442 6443 // #include_next "header" 6444 Builder.AddTypedTextChunk("include_next"); 6445 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6446 Builder.AddTextChunk("\""); 6447 Builder.AddPlaceholderChunk("header"); 6448 Builder.AddTextChunk("\""); 6449 Results.AddResult(Builder.TakeString()); 6450 6451 // #include_next <header> 6452 Builder.AddTypedTextChunk("include_next"); 6453 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6454 Builder.AddTextChunk("<"); 6455 Builder.AddPlaceholderChunk("header"); 6456 Builder.AddTextChunk(">"); 6457 Results.AddResult(Builder.TakeString()); 6458 6459 // #warning <message> 6460 Builder.AddTypedTextChunk("warning"); 6461 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6462 Builder.AddPlaceholderChunk("message"); 6463 Results.AddResult(Builder.TakeString()); 6464 6465 // Note: #ident and #sccs are such crazy anachronisms that we don't provide 6466 // completions for them. And __include_macros is a Clang-internal extension 6467 // that we don't want to encourage anyone to use. 6468 6469 // FIXME: we don't support #assert or #unassert, so don't suggest them. 6470 Results.ExitScope(); 6471 6472 HandleCodeCompleteResults(this, CodeCompleter, 6473 CodeCompletionContext::CCC_PreprocessorDirective, 6474 Results.data(), Results.size()); 6475 } 6476 6477 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) { 6478 CodeCompleteOrdinaryName(S, 6479 S->getFnParent()? Sema::PCC_RecoveryInFunction 6480 : Sema::PCC_Namespace); 6481 } 6482 6483 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) { 6484 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6485 IsDefinition? CodeCompletionContext::CCC_MacroName 6486 : CodeCompletionContext::CCC_MacroNameUse); 6487 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) { 6488 // Add just the names of macros, not their arguments. 6489 CodeCompletionBuilder Builder(Results.getAllocator()); 6490 Results.EnterNewScope(); 6491 for (Preprocessor::macro_iterator M = PP.macro_begin(), 6492 MEnd = PP.macro_end(); 6493 M != MEnd; ++M) { 6494 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 6495 M->first->getName())); 6496 Results.AddResult(Builder.TakeString()); 6497 } 6498 Results.ExitScope(); 6499 } else if (IsDefinition) { 6500 // FIXME: Can we detect when the user just wrote an include guard above? 6501 } 6502 6503 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6504 Results.data(), Results.size()); 6505 } 6506 6507 void Sema::CodeCompletePreprocessorExpression() { 6508 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6509 CodeCompletionContext::CCC_PreprocessorExpression); 6510 6511 if (!CodeCompleter || CodeCompleter->includeMacros()) 6512 AddMacroResults(PP, Results); 6513 6514 // defined (<macro>) 6515 Results.EnterNewScope(); 6516 CodeCompletionBuilder Builder(Results.getAllocator()); 6517 Builder.AddTypedTextChunk("defined"); 6518 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6519 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6520 Builder.AddPlaceholderChunk("macro"); 6521 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6522 Results.AddResult(Builder.TakeString()); 6523 Results.ExitScope(); 6524 6525 HandleCodeCompleteResults(this, CodeCompleter, 6526 CodeCompletionContext::CCC_PreprocessorExpression, 6527 Results.data(), Results.size()); 6528 } 6529 6530 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S, 6531 IdentifierInfo *Macro, 6532 MacroInfo *MacroInfo, 6533 unsigned Argument) { 6534 // FIXME: In the future, we could provide "overload" results, much like we 6535 // do for function calls. 6536 6537 CodeCompleteOrdinaryName(S, 6538 S->getFnParent()? Sema::PCC_RecoveryInFunction 6539 : Sema::PCC_Namespace); 6540 } 6541 6542 void Sema::CodeCompleteNaturalLanguage() { 6543 HandleCodeCompleteResults(this, CodeCompleter, 6544 CodeCompletionContext::CCC_NaturalLanguage, 6545 0, 0); 6546 } 6547 6548 void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 6549 llvm::SmallVectorImpl<CodeCompletionResult> &Results) { 6550 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery); 6551 if (!CodeCompleter || CodeCompleter->includeGlobals()) { 6552 CodeCompletionDeclConsumer Consumer(Builder, 6553 Context.getTranslationUnitDecl()); 6554 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName, 6555 Consumer); 6556 } 6557 6558 if (!CodeCompleter || CodeCompleter->includeMacros()) 6559 AddMacroResults(PP, Builder); 6560 6561 Results.clear(); 6562 Results.insert(Results.end(), 6563 Builder.data(), Builder.data() + Builder.size()); 6564 } 6565