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