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