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