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