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.AddPlaceholderChunk("declarations"); 1903 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1904 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1905 Results.AddResult(Result(Builder.TakeString())); 1906 } 1907 1908 // namespace identifier = identifier ; 1909 Builder.AddTypedTextChunk("namespace"); 1910 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1911 Builder.AddPlaceholderChunk("name"); 1912 Builder.AddChunk(CodeCompletionString::CK_Equal); 1913 Builder.AddPlaceholderChunk("namespace"); 1914 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 1915 Results.AddResult(Result(Builder.TakeString())); 1916 1917 // Using directives 1918 Builder.AddTypedTextChunk("using"); 1919 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1920 Builder.AddTextChunk("namespace"); 1921 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1922 Builder.AddPlaceholderChunk("identifier"); 1923 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 1924 Results.AddResult(Result(Builder.TakeString())); 1925 1926 // asm(string-literal) 1927 Builder.AddTypedTextChunk("asm"); 1928 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1929 Builder.AddPlaceholderChunk("string-literal"); 1930 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1931 Results.AddResult(Result(Builder.TakeString())); 1932 1933 if (Results.includeCodePatterns()) { 1934 // Explicit template instantiation 1935 Builder.AddTypedTextChunk("template"); 1936 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1937 Builder.AddPlaceholderChunk("declaration"); 1938 Results.AddResult(Result(Builder.TakeString())); 1939 } else { 1940 Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword)); 1941 } 1942 } 1943 1944 if (SemaRef.getLangOpts().ObjC) 1945 AddObjCTopLevelResults(Results, true); 1946 1947 AddTypedefResult(Results); 1948 LLVM_FALLTHROUGH; 1949 1950 case Sema::PCC_Class: 1951 if (SemaRef.getLangOpts().CPlusPlus) { 1952 // Using declaration 1953 Builder.AddTypedTextChunk("using"); 1954 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1955 Builder.AddPlaceholderChunk("qualifier"); 1956 Builder.AddTextChunk("::"); 1957 Builder.AddPlaceholderChunk("name"); 1958 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 1959 Results.AddResult(Result(Builder.TakeString())); 1960 1961 // using typename qualifier::name (only in a dependent context) 1962 if (SemaRef.CurContext->isDependentContext()) { 1963 Builder.AddTypedTextChunk("using"); 1964 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1965 Builder.AddTextChunk("typename"); 1966 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1967 Builder.AddPlaceholderChunk("qualifier"); 1968 Builder.AddTextChunk("::"); 1969 Builder.AddPlaceholderChunk("name"); 1970 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 1971 Results.AddResult(Result(Builder.TakeString())); 1972 } 1973 1974 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts()); 1975 1976 if (CCC == Sema::PCC_Class) { 1977 AddTypedefResult(Results); 1978 1979 bool IsNotInheritanceScope = 1980 !(S->getFlags() & Scope::ClassInheritanceScope); 1981 // public: 1982 Builder.AddTypedTextChunk("public"); 1983 if (IsNotInheritanceScope && Results.includeCodePatterns()) 1984 Builder.AddChunk(CodeCompletionString::CK_Colon); 1985 Results.AddResult(Result(Builder.TakeString())); 1986 1987 // protected: 1988 Builder.AddTypedTextChunk("protected"); 1989 if (IsNotInheritanceScope && Results.includeCodePatterns()) 1990 Builder.AddChunk(CodeCompletionString::CK_Colon); 1991 Results.AddResult(Result(Builder.TakeString())); 1992 1993 // private: 1994 Builder.AddTypedTextChunk("private"); 1995 if (IsNotInheritanceScope && Results.includeCodePatterns()) 1996 Builder.AddChunk(CodeCompletionString::CK_Colon); 1997 Results.AddResult(Result(Builder.TakeString())); 1998 1999 // FIXME: This adds override results only if we are at the first word of 2000 // the declaration/definition. Also call this from other sides to have 2001 // more use-cases. 2002 AddOverrideResults(Results, CodeCompletionContext::CCC_ClassStructUnion, 2003 Builder); 2004 } 2005 } 2006 LLVM_FALLTHROUGH; 2007 2008 case Sema::PCC_Template: 2009 case Sema::PCC_MemberTemplate: 2010 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) { 2011 // template < parameters > 2012 Builder.AddTypedTextChunk("template"); 2013 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 2014 Builder.AddPlaceholderChunk("parameters"); 2015 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 2016 Results.AddResult(Result(Builder.TakeString())); 2017 } else { 2018 Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword)); 2019 } 2020 2021 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); 2022 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results); 2023 break; 2024 2025 case Sema::PCC_ObjCInterface: 2026 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true); 2027 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); 2028 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results); 2029 break; 2030 2031 case Sema::PCC_ObjCImplementation: 2032 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true); 2033 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); 2034 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results); 2035 break; 2036 2037 case Sema::PCC_ObjCInstanceVariableList: 2038 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true); 2039 break; 2040 2041 case Sema::PCC_RecoveryInFunction: 2042 case Sema::PCC_Statement: { 2043 AddTypedefResult(Results); 2044 2045 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() && 2046 SemaRef.getLangOpts().CXXExceptions) { 2047 Builder.AddTypedTextChunk("try"); 2048 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 2049 Builder.AddPlaceholderChunk("statements"); 2050 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 2051 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 2052 Builder.AddTextChunk("catch"); 2053 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2054 Builder.AddPlaceholderChunk("declaration"); 2055 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2056 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 2057 Builder.AddPlaceholderChunk("statements"); 2058 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 2059 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 2060 Results.AddResult(Result(Builder.TakeString())); 2061 } 2062 if (SemaRef.getLangOpts().ObjC) 2063 AddObjCStatementResults(Results, true); 2064 2065 if (Results.includeCodePatterns()) { 2066 // if (condition) { statements } 2067 Builder.AddTypedTextChunk("if"); 2068 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2069 if (SemaRef.getLangOpts().CPlusPlus) 2070 Builder.AddPlaceholderChunk("condition"); 2071 else 2072 Builder.AddPlaceholderChunk("expression"); 2073 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2074 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 2075 Builder.AddPlaceholderChunk("statements"); 2076 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 2077 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 2078 Results.AddResult(Result(Builder.TakeString())); 2079 2080 // switch (condition) { } 2081 Builder.AddTypedTextChunk("switch"); 2082 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2083 if (SemaRef.getLangOpts().CPlusPlus) 2084 Builder.AddPlaceholderChunk("condition"); 2085 else 2086 Builder.AddPlaceholderChunk("expression"); 2087 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2088 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 2089 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 2090 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 2091 Results.AddResult(Result(Builder.TakeString())); 2092 } 2093 2094 // Switch-specific statements. 2095 if (SemaRef.getCurFunction() && 2096 !SemaRef.getCurFunction()->SwitchStack.empty()) { 2097 // case expression: 2098 Builder.AddTypedTextChunk("case"); 2099 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2100 Builder.AddPlaceholderChunk("expression"); 2101 Builder.AddChunk(CodeCompletionString::CK_Colon); 2102 Results.AddResult(Result(Builder.TakeString())); 2103 2104 // default: 2105 Builder.AddTypedTextChunk("default"); 2106 Builder.AddChunk(CodeCompletionString::CK_Colon); 2107 Results.AddResult(Result(Builder.TakeString())); 2108 } 2109 2110 if (Results.includeCodePatterns()) { 2111 /// while (condition) { statements } 2112 Builder.AddTypedTextChunk("while"); 2113 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2114 if (SemaRef.getLangOpts().CPlusPlus) 2115 Builder.AddPlaceholderChunk("condition"); 2116 else 2117 Builder.AddPlaceholderChunk("expression"); 2118 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2119 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 2120 Builder.AddPlaceholderChunk("statements"); 2121 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 2122 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 2123 Results.AddResult(Result(Builder.TakeString())); 2124 2125 // do { statements } while ( expression ); 2126 Builder.AddTypedTextChunk("do"); 2127 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 2128 Builder.AddPlaceholderChunk("statements"); 2129 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 2130 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 2131 Builder.AddTextChunk("while"); 2132 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2133 Builder.AddPlaceholderChunk("expression"); 2134 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2135 Results.AddResult(Result(Builder.TakeString())); 2136 2137 // for ( for-init-statement ; condition ; expression ) { statements } 2138 Builder.AddTypedTextChunk("for"); 2139 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2140 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99) 2141 Builder.AddPlaceholderChunk("init-statement"); 2142 else 2143 Builder.AddPlaceholderChunk("init-expression"); 2144 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2145 Builder.AddPlaceholderChunk("condition"); 2146 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2147 Builder.AddPlaceholderChunk("inc-expression"); 2148 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2149 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 2150 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 2151 Builder.AddPlaceholderChunk("statements"); 2152 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 2153 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 2154 Results.AddResult(Result(Builder.TakeString())); 2155 } 2156 2157 if (S->getContinueParent()) { 2158 // continue ; 2159 Builder.AddTypedTextChunk("continue"); 2160 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2161 Results.AddResult(Result(Builder.TakeString())); 2162 } 2163 2164 if (S->getBreakParent()) { 2165 // break ; 2166 Builder.AddTypedTextChunk("break"); 2167 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2168 Results.AddResult(Result(Builder.TakeString())); 2169 } 2170 2171 // "return expression ;" or "return ;", depending on the return type. 2172 QualType ReturnType; 2173 if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext)) 2174 ReturnType = Function->getReturnType(); 2175 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext)) 2176 ReturnType = Method->getReturnType(); 2177 else if (SemaRef.getCurBlock() && 2178 !SemaRef.getCurBlock()->ReturnType.isNull()) 2179 ReturnType = SemaRef.getCurBlock()->ReturnType;; 2180 if (ReturnType.isNull() || ReturnType->isVoidType()) { 2181 Builder.AddTypedTextChunk("return"); 2182 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2183 Results.AddResult(Result(Builder.TakeString())); 2184 } else { 2185 assert(!ReturnType.isNull()); 2186 // "return expression ;" 2187 Builder.AddTypedTextChunk("return"); 2188 Builder.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace); 2189 Builder.AddPlaceholderChunk("expression"); 2190 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2191 Results.AddResult(Result(Builder.TakeString())); 2192 // When boolean, also add 'return true;' and 'return false;'. 2193 if (ReturnType->isBooleanType()) { 2194 Builder.AddTypedTextChunk("return true"); 2195 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2196 Results.AddResult(Result(Builder.TakeString())); 2197 2198 Builder.AddTypedTextChunk("return false"); 2199 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2200 Results.AddResult(Result(Builder.TakeString())); 2201 } 2202 } 2203 2204 // goto identifier ; 2205 Builder.AddTypedTextChunk("goto"); 2206 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2207 Builder.AddPlaceholderChunk("label"); 2208 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2209 Results.AddResult(Result(Builder.TakeString())); 2210 2211 // Using directives 2212 Builder.AddTypedTextChunk("using"); 2213 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2214 Builder.AddTextChunk("namespace"); 2215 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2216 Builder.AddPlaceholderChunk("identifier"); 2217 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2218 Results.AddResult(Result(Builder.TakeString())); 2219 2220 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts()); 2221 } 2222 LLVM_FALLTHROUGH; 2223 2224 // Fall through (for statement expressions). 2225 case Sema::PCC_ForInit: 2226 case Sema::PCC_Condition: 2227 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); 2228 // Fall through: conditions and statements can have expressions. 2229 LLVM_FALLTHROUGH; 2230 2231 case Sema::PCC_ParenthesizedExpression: 2232 if (SemaRef.getLangOpts().ObjCAutoRefCount && 2233 CCC == Sema::PCC_ParenthesizedExpression) { 2234 // (__bridge <type>)<expression> 2235 Builder.AddTypedTextChunk("__bridge"); 2236 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2237 Builder.AddPlaceholderChunk("type"); 2238 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2239 Builder.AddPlaceholderChunk("expression"); 2240 Results.AddResult(Result(Builder.TakeString())); 2241 2242 // (__bridge_transfer <Objective-C type>)<expression> 2243 Builder.AddTypedTextChunk("__bridge_transfer"); 2244 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2245 Builder.AddPlaceholderChunk("Objective-C type"); 2246 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2247 Builder.AddPlaceholderChunk("expression"); 2248 Results.AddResult(Result(Builder.TakeString())); 2249 2250 // (__bridge_retained <CF type>)<expression> 2251 Builder.AddTypedTextChunk("__bridge_retained"); 2252 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2253 Builder.AddPlaceholderChunk("CF type"); 2254 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2255 Builder.AddPlaceholderChunk("expression"); 2256 Results.AddResult(Result(Builder.TakeString())); 2257 } 2258 // Fall through 2259 LLVM_FALLTHROUGH; 2260 2261 case Sema::PCC_Expression: { 2262 if (SemaRef.getLangOpts().CPlusPlus) { 2263 // 'this', if we're in a non-static member function. 2264 addThisCompletion(SemaRef, Results); 2265 2266 // true 2267 Builder.AddResultTypeChunk("bool"); 2268 Builder.AddTypedTextChunk("true"); 2269 Results.AddResult(Result(Builder.TakeString())); 2270 2271 // false 2272 Builder.AddResultTypeChunk("bool"); 2273 Builder.AddTypedTextChunk("false"); 2274 Results.AddResult(Result(Builder.TakeString())); 2275 2276 if (SemaRef.getLangOpts().RTTI) { 2277 // dynamic_cast < type-id > ( expression ) 2278 Builder.AddTypedTextChunk("dynamic_cast"); 2279 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 2280 Builder.AddPlaceholderChunk("type"); 2281 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 2282 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2283 Builder.AddPlaceholderChunk("expression"); 2284 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2285 Results.AddResult(Result(Builder.TakeString())); 2286 } 2287 2288 // static_cast < type-id > ( expression ) 2289 Builder.AddTypedTextChunk("static_cast"); 2290 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 2291 Builder.AddPlaceholderChunk("type"); 2292 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 2293 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2294 Builder.AddPlaceholderChunk("expression"); 2295 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2296 Results.AddResult(Result(Builder.TakeString())); 2297 2298 // reinterpret_cast < type-id > ( expression ) 2299 Builder.AddTypedTextChunk("reinterpret_cast"); 2300 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 2301 Builder.AddPlaceholderChunk("type"); 2302 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 2303 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2304 Builder.AddPlaceholderChunk("expression"); 2305 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2306 Results.AddResult(Result(Builder.TakeString())); 2307 2308 // const_cast < type-id > ( expression ) 2309 Builder.AddTypedTextChunk("const_cast"); 2310 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 2311 Builder.AddPlaceholderChunk("type"); 2312 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 2313 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2314 Builder.AddPlaceholderChunk("expression"); 2315 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2316 Results.AddResult(Result(Builder.TakeString())); 2317 2318 if (SemaRef.getLangOpts().RTTI) { 2319 // typeid ( expression-or-type ) 2320 Builder.AddResultTypeChunk("std::type_info"); 2321 Builder.AddTypedTextChunk("typeid"); 2322 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2323 Builder.AddPlaceholderChunk("expression-or-type"); 2324 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2325 Results.AddResult(Result(Builder.TakeString())); 2326 } 2327 2328 // new T ( ... ) 2329 Builder.AddTypedTextChunk("new"); 2330 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2331 Builder.AddPlaceholderChunk("type"); 2332 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2333 Builder.AddPlaceholderChunk("expressions"); 2334 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2335 Results.AddResult(Result(Builder.TakeString())); 2336 2337 // new T [ ] ( ... ) 2338 Builder.AddTypedTextChunk("new"); 2339 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2340 Builder.AddPlaceholderChunk("type"); 2341 Builder.AddChunk(CodeCompletionString::CK_LeftBracket); 2342 Builder.AddPlaceholderChunk("size"); 2343 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 2344 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2345 Builder.AddPlaceholderChunk("expressions"); 2346 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2347 Results.AddResult(Result(Builder.TakeString())); 2348 2349 // delete expression 2350 Builder.AddResultTypeChunk("void"); 2351 Builder.AddTypedTextChunk("delete"); 2352 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2353 Builder.AddPlaceholderChunk("expression"); 2354 Results.AddResult(Result(Builder.TakeString())); 2355 2356 // delete [] expression 2357 Builder.AddResultTypeChunk("void"); 2358 Builder.AddTypedTextChunk("delete"); 2359 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2360 Builder.AddChunk(CodeCompletionString::CK_LeftBracket); 2361 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 2362 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2363 Builder.AddPlaceholderChunk("expression"); 2364 Results.AddResult(Result(Builder.TakeString())); 2365 2366 if (SemaRef.getLangOpts().CXXExceptions) { 2367 // throw expression 2368 Builder.AddResultTypeChunk("void"); 2369 Builder.AddTypedTextChunk("throw"); 2370 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2371 Builder.AddPlaceholderChunk("expression"); 2372 Results.AddResult(Result(Builder.TakeString())); 2373 } 2374 2375 // FIXME: Rethrow? 2376 2377 if (SemaRef.getLangOpts().CPlusPlus11) { 2378 // nullptr 2379 Builder.AddResultTypeChunk("std::nullptr_t"); 2380 Builder.AddTypedTextChunk("nullptr"); 2381 Results.AddResult(Result(Builder.TakeString())); 2382 2383 // alignof 2384 Builder.AddResultTypeChunk("size_t"); 2385 Builder.AddTypedTextChunk("alignof"); 2386 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2387 Builder.AddPlaceholderChunk("type"); 2388 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2389 Results.AddResult(Result(Builder.TakeString())); 2390 2391 // noexcept 2392 Builder.AddResultTypeChunk("bool"); 2393 Builder.AddTypedTextChunk("noexcept"); 2394 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2395 Builder.AddPlaceholderChunk("expression"); 2396 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2397 Results.AddResult(Result(Builder.TakeString())); 2398 2399 // sizeof... expression 2400 Builder.AddResultTypeChunk("size_t"); 2401 Builder.AddTypedTextChunk("sizeof..."); 2402 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2403 Builder.AddPlaceholderChunk("parameter-pack"); 2404 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2405 Results.AddResult(Result(Builder.TakeString())); 2406 } 2407 } 2408 2409 if (SemaRef.getLangOpts().ObjC) { 2410 // Add "super", if we're in an Objective-C class with a superclass. 2411 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { 2412 // The interface can be NULL. 2413 if (ObjCInterfaceDecl *ID = Method->getClassInterface()) 2414 if (ID->getSuperClass()) { 2415 std::string SuperType; 2416 SuperType = ID->getSuperClass()->getNameAsString(); 2417 if (Method->isInstanceMethod()) 2418 SuperType += " *"; 2419 2420 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType)); 2421 Builder.AddTypedTextChunk("super"); 2422 Results.AddResult(Result(Builder.TakeString())); 2423 } 2424 } 2425 2426 AddObjCExpressionResults(Results, true); 2427 } 2428 2429 if (SemaRef.getLangOpts().C11) { 2430 // _Alignof 2431 Builder.AddResultTypeChunk("size_t"); 2432 if (SemaRef.PP.isMacroDefined("alignof")) 2433 Builder.AddTypedTextChunk("alignof"); 2434 else 2435 Builder.AddTypedTextChunk("_Alignof"); 2436 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2437 Builder.AddPlaceholderChunk("type"); 2438 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2439 Results.AddResult(Result(Builder.TakeString())); 2440 } 2441 2442 // sizeof expression 2443 Builder.AddResultTypeChunk("size_t"); 2444 Builder.AddTypedTextChunk("sizeof"); 2445 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2446 Builder.AddPlaceholderChunk("expression-or-type"); 2447 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2448 Results.AddResult(Result(Builder.TakeString())); 2449 break; 2450 } 2451 2452 case Sema::PCC_Type: 2453 case Sema::PCC_LocalDeclarationSpecifiers: 2454 break; 2455 } 2456 2457 if (WantTypesInContext(CCC, SemaRef.getLangOpts())) 2458 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results); 2459 2460 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type) 2461 Results.AddResult(Result("operator")); 2462 } 2463 2464 /// If the given declaration has an associated type, add it as a result 2465 /// type chunk. 2466 static void AddResultTypeChunk(ASTContext &Context, 2467 const PrintingPolicy &Policy, 2468 const NamedDecl *ND, QualType BaseType, 2469 CodeCompletionBuilder &Result) { 2470 if (!ND) 2471 return; 2472 2473 // Skip constructors and conversion functions, which have their return types 2474 // built into their names. 2475 if (isConstructor(ND) || isa<CXXConversionDecl>(ND)) 2476 return; 2477 2478 // Determine the type of the declaration (if it has a type). 2479 QualType T; 2480 if (const FunctionDecl *Function = ND->getAsFunction()) 2481 T = Function->getReturnType(); 2482 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) { 2483 if (!BaseType.isNull()) 2484 T = Method->getSendResultType(BaseType); 2485 else 2486 T = Method->getReturnType(); 2487 } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) { 2488 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext())); 2489 T = clang::TypeName::getFullyQualifiedType(T, Context); 2490 } else if (isa<UnresolvedUsingValueDecl>(ND)) { 2491 /* Do nothing: ignore unresolved using declarations*/ 2492 } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { 2493 if (!BaseType.isNull()) 2494 T = Ivar->getUsageType(BaseType); 2495 else 2496 T = Ivar->getType(); 2497 } else if (const auto *Value = dyn_cast<ValueDecl>(ND)) { 2498 T = Value->getType(); 2499 } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) { 2500 if (!BaseType.isNull()) 2501 T = Property->getUsageType(BaseType); 2502 else 2503 T = Property->getType(); 2504 } 2505 2506 if (T.isNull() || Context.hasSameType(T, Context.DependentTy)) 2507 return; 2508 2509 Result.AddResultTypeChunk( 2510 GetCompletionTypeString(T, Context, Policy, Result.getAllocator())); 2511 } 2512 2513 static void MaybeAddSentinel(Preprocessor &PP, 2514 const NamedDecl *FunctionOrMethod, 2515 CodeCompletionBuilder &Result) { 2516 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>()) 2517 if (Sentinel->getSentinel() == 0) { 2518 if (PP.getLangOpts().ObjC && PP.isMacroDefined("nil")) 2519 Result.AddTextChunk(", nil"); 2520 else if (PP.isMacroDefined("NULL")) 2521 Result.AddTextChunk(", NULL"); 2522 else 2523 Result.AddTextChunk(", (void*)0"); 2524 } 2525 } 2526 2527 static std::string formatObjCParamQualifiers(unsigned ObjCQuals, 2528 QualType &Type) { 2529 std::string Result; 2530 if (ObjCQuals & Decl::OBJC_TQ_In) 2531 Result += "in "; 2532 else if (ObjCQuals & Decl::OBJC_TQ_Inout) 2533 Result += "inout "; 2534 else if (ObjCQuals & Decl::OBJC_TQ_Out) 2535 Result += "out "; 2536 if (ObjCQuals & Decl::OBJC_TQ_Bycopy) 2537 Result += "bycopy "; 2538 else if (ObjCQuals & Decl::OBJC_TQ_Byref) 2539 Result += "byref "; 2540 if (ObjCQuals & Decl::OBJC_TQ_Oneway) 2541 Result += "oneway "; 2542 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) { 2543 if (auto nullability = AttributedType::stripOuterNullability(Type)) { 2544 switch (*nullability) { 2545 case NullabilityKind::NonNull: 2546 Result += "nonnull "; 2547 break; 2548 2549 case NullabilityKind::Nullable: 2550 Result += "nullable "; 2551 break; 2552 2553 case NullabilityKind::Unspecified: 2554 Result += "null_unspecified "; 2555 break; 2556 } 2557 } 2558 } 2559 return Result; 2560 } 2561 2562 /// Tries to find the most appropriate type location for an Objective-C 2563 /// block placeholder. 2564 /// 2565 /// This function ignores things like typedefs and qualifiers in order to 2566 /// present the most relevant and accurate block placeholders in code completion 2567 /// results. 2568 static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo, 2569 FunctionTypeLoc &Block, 2570 FunctionProtoTypeLoc &BlockProto, 2571 bool SuppressBlock = false) { 2572 if (!TSInfo) 2573 return; 2574 TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc(); 2575 while (true) { 2576 // Look through typedefs. 2577 if (!SuppressBlock) { 2578 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) { 2579 if (TypeSourceInfo *InnerTSInfo = 2580 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) { 2581 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc(); 2582 continue; 2583 } 2584 } 2585 2586 // Look through qualified types 2587 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) { 2588 TL = QualifiedTL.getUnqualifiedLoc(); 2589 continue; 2590 } 2591 2592 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) { 2593 TL = AttrTL.getModifiedLoc(); 2594 continue; 2595 } 2596 } 2597 2598 // Try to get the function prototype behind the block pointer type, 2599 // then we're done. 2600 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) { 2601 TL = BlockPtr.getPointeeLoc().IgnoreParens(); 2602 Block = TL.getAs<FunctionTypeLoc>(); 2603 BlockProto = TL.getAs<FunctionProtoTypeLoc>(); 2604 } 2605 break; 2606 } 2607 } 2608 2609 static std::string 2610 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl, 2611 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, 2612 bool SuppressBlockName = false, 2613 bool SuppressBlock = false, 2614 Optional<ArrayRef<QualType>> ObjCSubsts = None); 2615 2616 static std::string 2617 FormatFunctionParameter(const PrintingPolicy &Policy, const ParmVarDecl *Param, 2618 bool SuppressName = false, bool SuppressBlock = false, 2619 Optional<ArrayRef<QualType>> ObjCSubsts = None) { 2620 // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid. 2621 // It would be better to pass in the param Type, which is usually avaliable. 2622 // But this case is rare, so just pretend we fell back to int as elsewhere. 2623 if (!Param) 2624 return "int"; 2625 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext()); 2626 if (Param->getType()->isDependentType() || 2627 !Param->getType()->isBlockPointerType()) { 2628 // The argument for a dependent or non-block parameter is a placeholder 2629 // containing that parameter's type. 2630 std::string Result; 2631 2632 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName) 2633 Result = Param->getIdentifier()->getName(); 2634 2635 QualType Type = Param->getType(); 2636 if (ObjCSubsts) 2637 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts, 2638 ObjCSubstitutionContext::Parameter); 2639 if (ObjCMethodParam) { 2640 Result = 2641 "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type); 2642 Result += Type.getAsString(Policy) + ")"; 2643 if (Param->getIdentifier() && !SuppressName) 2644 Result += Param->getIdentifier()->getName(); 2645 } else { 2646 Type.getAsStringInternal(Result, Policy); 2647 } 2648 return Result; 2649 } 2650 2651 // The argument for a block pointer parameter is a block literal with 2652 // the appropriate type. 2653 FunctionTypeLoc Block; 2654 FunctionProtoTypeLoc BlockProto; 2655 findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto, 2656 SuppressBlock); 2657 // Try to retrieve the block type information from the property if this is a 2658 // parameter in a setter. 2659 if (!Block && ObjCMethodParam && 2660 cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) { 2661 if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext()) 2662 ->findPropertyDecl(/*CheckOverrides=*/false)) 2663 findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto, 2664 SuppressBlock); 2665 } 2666 2667 if (!Block) { 2668 // We were unable to find a FunctionProtoTypeLoc with parameter names 2669 // for the block; just use the parameter type as a placeholder. 2670 std::string Result; 2671 if (!ObjCMethodParam && Param->getIdentifier()) 2672 Result = Param->getIdentifier()->getName(); 2673 2674 QualType Type = Param->getType().getUnqualifiedType(); 2675 2676 if (ObjCMethodParam) { 2677 Result = Type.getAsString(Policy); 2678 std::string Quals = 2679 formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type); 2680 if (!Quals.empty()) 2681 Result = "(" + Quals + " " + Result + ")"; 2682 if (Result.back() != ')') 2683 Result += " "; 2684 if (Param->getIdentifier()) 2685 Result += Param->getIdentifier()->getName(); 2686 } else { 2687 Type.getAsStringInternal(Result, Policy); 2688 } 2689 2690 return Result; 2691 } 2692 2693 // We have the function prototype behind the block pointer type, as it was 2694 // written in the source. 2695 return formatBlockPlaceholder(Policy, Param, Block, BlockProto, 2696 /*SuppressBlockName=*/false, SuppressBlock, 2697 ObjCSubsts); 2698 } 2699 2700 /// Returns a placeholder string that corresponds to an Objective-C block 2701 /// declaration. 2702 /// 2703 /// \param BlockDecl A declaration with an Objective-C block type. 2704 /// 2705 /// \param Block The most relevant type location for that block type. 2706 /// 2707 /// \param SuppressBlockName Determines whether or not the name of the block 2708 /// declaration is included in the resulting string. 2709 static std::string 2710 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl, 2711 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, 2712 bool SuppressBlockName, bool SuppressBlock, 2713 Optional<ArrayRef<QualType>> ObjCSubsts) { 2714 std::string Result; 2715 QualType ResultType = Block.getTypePtr()->getReturnType(); 2716 if (ObjCSubsts) 2717 ResultType = 2718 ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts, 2719 ObjCSubstitutionContext::Result); 2720 if (!ResultType->isVoidType() || SuppressBlock) 2721 ResultType.getAsStringInternal(Result, Policy); 2722 2723 // Format the parameter list. 2724 std::string Params; 2725 if (!BlockProto || Block.getNumParams() == 0) { 2726 if (BlockProto && BlockProto.getTypePtr()->isVariadic()) 2727 Params = "(...)"; 2728 else 2729 Params = "(void)"; 2730 } else { 2731 Params += "("; 2732 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) { 2733 if (I) 2734 Params += ", "; 2735 Params += FormatFunctionParameter(Policy, Block.getParam(I), 2736 /*SuppressName=*/false, 2737 /*SuppressBlock=*/true, ObjCSubsts); 2738 2739 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic()) 2740 Params += ", ..."; 2741 } 2742 Params += ")"; 2743 } 2744 2745 if (SuppressBlock) { 2746 // Format as a parameter. 2747 Result = Result + " (^"; 2748 if (!SuppressBlockName && BlockDecl->getIdentifier()) 2749 Result += BlockDecl->getIdentifier()->getName(); 2750 Result += ")"; 2751 Result += Params; 2752 } else { 2753 // Format as a block literal argument. 2754 Result = '^' + Result; 2755 Result += Params; 2756 2757 if (!SuppressBlockName && BlockDecl->getIdentifier()) 2758 Result += BlockDecl->getIdentifier()->getName(); 2759 } 2760 2761 return Result; 2762 } 2763 2764 static std::string GetDefaultValueString(const ParmVarDecl *Param, 2765 const SourceManager &SM, 2766 const LangOptions &LangOpts) { 2767 const SourceRange SrcRange = Param->getDefaultArgRange(); 2768 CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange); 2769 bool Invalid = CharSrcRange.isInvalid(); 2770 if (Invalid) 2771 return ""; 2772 StringRef srcText = 2773 Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid); 2774 if (Invalid) 2775 return ""; 2776 2777 if (srcText.empty() || srcText == "=") { 2778 // Lexer can't determine the value. 2779 // This happens if the code is incorrect (for example class is forward 2780 // declared). 2781 return ""; 2782 } 2783 std::string DefValue(srcText.str()); 2784 // FIXME: remove this check if the Lexer::getSourceText value is fixed and 2785 // this value always has (or always does not have) '=' in front of it 2786 if (DefValue.at(0) != '=') { 2787 // If we don't have '=' in front of value. 2788 // Lexer returns built-in types values without '=' and user-defined types 2789 // values with it. 2790 return " = " + DefValue; 2791 } 2792 return " " + DefValue; 2793 } 2794 2795 /// Add function parameter chunks to the given code completion string. 2796 static void AddFunctionParameterChunks(Preprocessor &PP, 2797 const PrintingPolicy &Policy, 2798 const FunctionDecl *Function, 2799 CodeCompletionBuilder &Result, 2800 unsigned Start = 0, 2801 bool InOptional = false) { 2802 bool FirstParameter = true; 2803 2804 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) { 2805 const ParmVarDecl *Param = Function->getParamDecl(P); 2806 2807 if (Param->hasDefaultArg() && !InOptional) { 2808 // When we see an optional default argument, put that argument and 2809 // the remaining default arguments into a new, optional string. 2810 CodeCompletionBuilder Opt(Result.getAllocator(), 2811 Result.getCodeCompletionTUInfo()); 2812 if (!FirstParameter) 2813 Opt.AddChunk(CodeCompletionString::CK_Comma); 2814 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true); 2815 Result.AddOptionalChunk(Opt.TakeString()); 2816 break; 2817 } 2818 2819 if (FirstParameter) 2820 FirstParameter = false; 2821 else 2822 Result.AddChunk(CodeCompletionString::CK_Comma); 2823 2824 InOptional = false; 2825 2826 // Format the placeholder string. 2827 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param); 2828 if (Param->hasDefaultArg()) 2829 PlaceholderStr += 2830 GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts()); 2831 2832 if (Function->isVariadic() && P == N - 1) 2833 PlaceholderStr += ", ..."; 2834 2835 // Add the placeholder string. 2836 Result.AddPlaceholderChunk( 2837 Result.getAllocator().CopyString(PlaceholderStr)); 2838 } 2839 2840 if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>()) 2841 if (Proto->isVariadic()) { 2842 if (Proto->getNumParams() == 0) 2843 Result.AddPlaceholderChunk("..."); 2844 2845 MaybeAddSentinel(PP, Function, Result); 2846 } 2847 } 2848 2849 /// Add template parameter chunks to the given code completion string. 2850 static void AddTemplateParameterChunks( 2851 ASTContext &Context, const PrintingPolicy &Policy, 2852 const TemplateDecl *Template, CodeCompletionBuilder &Result, 2853 unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) { 2854 bool FirstParameter = true; 2855 2856 // Prefer to take the template parameter names from the first declaration of 2857 // the template. 2858 Template = cast<TemplateDecl>(Template->getCanonicalDecl()); 2859 2860 TemplateParameterList *Params = Template->getTemplateParameters(); 2861 TemplateParameterList::iterator PEnd = Params->end(); 2862 if (MaxParameters) 2863 PEnd = Params->begin() + MaxParameters; 2864 for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd; 2865 ++P) { 2866 bool HasDefaultArg = false; 2867 std::string PlaceholderStr; 2868 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 2869 if (TTP->wasDeclaredWithTypename()) 2870 PlaceholderStr = "typename"; 2871 else 2872 PlaceholderStr = "class"; 2873 2874 if (TTP->getIdentifier()) { 2875 PlaceholderStr += ' '; 2876 PlaceholderStr += TTP->getIdentifier()->getName(); 2877 } 2878 2879 HasDefaultArg = TTP->hasDefaultArgument(); 2880 } else if (NonTypeTemplateParmDecl *NTTP = 2881 dyn_cast<NonTypeTemplateParmDecl>(*P)) { 2882 if (NTTP->getIdentifier()) 2883 PlaceholderStr = NTTP->getIdentifier()->getName(); 2884 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy); 2885 HasDefaultArg = NTTP->hasDefaultArgument(); 2886 } else { 2887 assert(isa<TemplateTemplateParmDecl>(*P)); 2888 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 2889 2890 // Since putting the template argument list into the placeholder would 2891 // be very, very long, we just use an abbreviation. 2892 PlaceholderStr = "template<...> class"; 2893 if (TTP->getIdentifier()) { 2894 PlaceholderStr += ' '; 2895 PlaceholderStr += TTP->getIdentifier()->getName(); 2896 } 2897 2898 HasDefaultArg = TTP->hasDefaultArgument(); 2899 } 2900 2901 if (HasDefaultArg && !InDefaultArg) { 2902 // When we see an optional default argument, put that argument and 2903 // the remaining default arguments into a new, optional string. 2904 CodeCompletionBuilder Opt(Result.getAllocator(), 2905 Result.getCodeCompletionTUInfo()); 2906 if (!FirstParameter) 2907 Opt.AddChunk(CodeCompletionString::CK_Comma); 2908 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters, 2909 P - Params->begin(), true); 2910 Result.AddOptionalChunk(Opt.TakeString()); 2911 break; 2912 } 2913 2914 InDefaultArg = false; 2915 2916 if (FirstParameter) 2917 FirstParameter = false; 2918 else 2919 Result.AddChunk(CodeCompletionString::CK_Comma); 2920 2921 // Add the placeholder string. 2922 Result.AddPlaceholderChunk( 2923 Result.getAllocator().CopyString(PlaceholderStr)); 2924 } 2925 } 2926 2927 /// Add a qualifier to the given code-completion string, if the 2928 /// provided nested-name-specifier is non-NULL. 2929 static void AddQualifierToCompletionString(CodeCompletionBuilder &Result, 2930 NestedNameSpecifier *Qualifier, 2931 bool QualifierIsInformative, 2932 ASTContext &Context, 2933 const PrintingPolicy &Policy) { 2934 if (!Qualifier) 2935 return; 2936 2937 std::string PrintedNNS; 2938 { 2939 llvm::raw_string_ostream OS(PrintedNNS); 2940 Qualifier->print(OS, Policy); 2941 } 2942 if (QualifierIsInformative) 2943 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS)); 2944 else 2945 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS)); 2946 } 2947 2948 static void 2949 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result, 2950 const FunctionDecl *Function) { 2951 const auto *Proto = Function->getType()->getAs<FunctionProtoType>(); 2952 if (!Proto || !Proto->getMethodQuals()) 2953 return; 2954 2955 // FIXME: Add ref-qualifier! 2956 2957 // Handle single qualifiers without copying 2958 if (Proto->getMethodQuals().hasOnlyConst()) { 2959 Result.AddInformativeChunk(" const"); 2960 return; 2961 } 2962 2963 if (Proto->getMethodQuals().hasOnlyVolatile()) { 2964 Result.AddInformativeChunk(" volatile"); 2965 return; 2966 } 2967 2968 if (Proto->getMethodQuals().hasOnlyRestrict()) { 2969 Result.AddInformativeChunk(" restrict"); 2970 return; 2971 } 2972 2973 // Handle multiple qualifiers. 2974 std::string QualsStr; 2975 if (Proto->isConst()) 2976 QualsStr += " const"; 2977 if (Proto->isVolatile()) 2978 QualsStr += " volatile"; 2979 if (Proto->isRestrict()) 2980 QualsStr += " restrict"; 2981 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr)); 2982 } 2983 2984 /// Add the name of the given declaration 2985 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy, 2986 const NamedDecl *ND, 2987 CodeCompletionBuilder &Result) { 2988 DeclarationName Name = ND->getDeclName(); 2989 if (!Name) 2990 return; 2991 2992 switch (Name.getNameKind()) { 2993 case DeclarationName::CXXOperatorName: { 2994 const char *OperatorName = nullptr; 2995 switch (Name.getCXXOverloadedOperator()) { 2996 case OO_None: 2997 case OO_Conditional: 2998 case NUM_OVERLOADED_OPERATORS: 2999 OperatorName = "operator"; 3000 break; 3001 3002 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ 3003 case OO_##Name: \ 3004 OperatorName = "operator" Spelling; \ 3005 break; 3006 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly) 3007 #include "clang/Basic/OperatorKinds.def" 3008 3009 case OO_New: 3010 OperatorName = "operator new"; 3011 break; 3012 case OO_Delete: 3013 OperatorName = "operator delete"; 3014 break; 3015 case OO_Array_New: 3016 OperatorName = "operator new[]"; 3017 break; 3018 case OO_Array_Delete: 3019 OperatorName = "operator delete[]"; 3020 break; 3021 case OO_Call: 3022 OperatorName = "operator()"; 3023 break; 3024 case OO_Subscript: 3025 OperatorName = "operator[]"; 3026 break; 3027 } 3028 Result.AddTypedTextChunk(OperatorName); 3029 break; 3030 } 3031 3032 case DeclarationName::Identifier: 3033 case DeclarationName::CXXConversionFunctionName: 3034 case DeclarationName::CXXDestructorName: 3035 case DeclarationName::CXXLiteralOperatorName: 3036 Result.AddTypedTextChunk( 3037 Result.getAllocator().CopyString(ND->getNameAsString())); 3038 break; 3039 3040 case DeclarationName::CXXDeductionGuideName: 3041 case DeclarationName::CXXUsingDirective: 3042 case DeclarationName::ObjCZeroArgSelector: 3043 case DeclarationName::ObjCOneArgSelector: 3044 case DeclarationName::ObjCMultiArgSelector: 3045 break; 3046 3047 case DeclarationName::CXXConstructorName: { 3048 CXXRecordDecl *Record = nullptr; 3049 QualType Ty = Name.getCXXNameType(); 3050 if (const auto *RecordTy = Ty->getAs<RecordType>()) 3051 Record = cast<CXXRecordDecl>(RecordTy->getDecl()); 3052 else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>()) 3053 Record = InjectedTy->getDecl(); 3054 else { 3055 Result.AddTypedTextChunk( 3056 Result.getAllocator().CopyString(ND->getNameAsString())); 3057 break; 3058 } 3059 3060 Result.AddTypedTextChunk( 3061 Result.getAllocator().CopyString(Record->getNameAsString())); 3062 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) { 3063 Result.AddChunk(CodeCompletionString::CK_LeftAngle); 3064 AddTemplateParameterChunks(Context, Policy, Template, Result); 3065 Result.AddChunk(CodeCompletionString::CK_RightAngle); 3066 } 3067 break; 3068 } 3069 } 3070 } 3071 3072 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString( 3073 Sema &S, const CodeCompletionContext &CCContext, 3074 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, 3075 bool IncludeBriefComments) { 3076 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator, 3077 CCTUInfo, IncludeBriefComments); 3078 } 3079 3080 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro( 3081 Preprocessor &PP, CodeCompletionAllocator &Allocator, 3082 CodeCompletionTUInfo &CCTUInfo) { 3083 assert(Kind == RK_Macro); 3084 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability); 3085 const MacroInfo *MI = PP.getMacroInfo(Macro); 3086 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName())); 3087 3088 if (!MI || !MI->isFunctionLike()) 3089 return Result.TakeString(); 3090 3091 // Format a function-like macro with placeholders for the arguments. 3092 Result.AddChunk(CodeCompletionString::CK_LeftParen); 3093 MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end(); 3094 3095 // C99 variadic macros add __VA_ARGS__ at the end. Skip it. 3096 if (MI->isC99Varargs()) { 3097 --AEnd; 3098 3099 if (A == AEnd) { 3100 Result.AddPlaceholderChunk("..."); 3101 } 3102 } 3103 3104 for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) { 3105 if (A != MI->param_begin()) 3106 Result.AddChunk(CodeCompletionString::CK_Comma); 3107 3108 if (MI->isVariadic() && (A + 1) == AEnd) { 3109 SmallString<32> Arg = (*A)->getName(); 3110 if (MI->isC99Varargs()) 3111 Arg += ", ..."; 3112 else 3113 Arg += "..."; 3114 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg)); 3115 break; 3116 } 3117 3118 // Non-variadic macros are simple. 3119 Result.AddPlaceholderChunk( 3120 Result.getAllocator().CopyString((*A)->getName())); 3121 } 3122 Result.AddChunk(CodeCompletionString::CK_RightParen); 3123 return Result.TakeString(); 3124 } 3125 3126 /// If possible, create a new code completion string for the given 3127 /// result. 3128 /// 3129 /// \returns Either a new, heap-allocated code completion string describing 3130 /// how to use this result, or NULL to indicate that the string or name of the 3131 /// result is all that is needed. 3132 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString( 3133 ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext, 3134 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, 3135 bool IncludeBriefComments) { 3136 if (Kind == RK_Macro) 3137 return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo); 3138 3139 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability); 3140 3141 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP); 3142 if (Kind == RK_Pattern) { 3143 Pattern->Priority = Priority; 3144 Pattern->Availability = Availability; 3145 3146 if (Declaration) { 3147 Result.addParentContext(Declaration->getDeclContext()); 3148 Pattern->ParentName = Result.getParentName(); 3149 if (const RawComment *RC = 3150 getPatternCompletionComment(Ctx, Declaration)) { 3151 Result.addBriefComment(RC->getBriefText(Ctx)); 3152 Pattern->BriefComment = Result.getBriefComment(); 3153 } 3154 } 3155 3156 return Pattern; 3157 } 3158 3159 if (Kind == RK_Keyword) { 3160 Result.AddTypedTextChunk(Keyword); 3161 return Result.TakeString(); 3162 } 3163 assert(Kind == RK_Declaration && "Missed a result kind?"); 3164 return createCodeCompletionStringForDecl( 3165 PP, Ctx, Result, IncludeBriefComments, CCContext, Policy); 3166 } 3167 3168 static void printOverrideString(const CodeCompletionString &CCS, 3169 std::string &BeforeName, 3170 std::string &NameAndSignature) { 3171 bool SeenTypedChunk = false; 3172 for (auto &Chunk : CCS) { 3173 if (Chunk.Kind == CodeCompletionString::CK_Optional) { 3174 assert(SeenTypedChunk && "optional parameter before name"); 3175 // Note that we put all chunks inside into NameAndSignature. 3176 printOverrideString(*Chunk.Optional, NameAndSignature, NameAndSignature); 3177 continue; 3178 } 3179 SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText; 3180 if (SeenTypedChunk) 3181 NameAndSignature += Chunk.Text; 3182 else 3183 BeforeName += Chunk.Text; 3184 } 3185 } 3186 3187 CodeCompletionString * 3188 CodeCompletionResult::createCodeCompletionStringForOverride( 3189 Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result, 3190 bool IncludeBriefComments, const CodeCompletionContext &CCContext, 3191 PrintingPolicy &Policy) { 3192 auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result, 3193 /*IncludeBriefComments=*/false, 3194 CCContext, Policy); 3195 std::string BeforeName; 3196 std::string NameAndSignature; 3197 // For overrides all chunks go into the result, none are informative. 3198 printOverrideString(*CCS, BeforeName, NameAndSignature); 3199 NameAndSignature += " override"; 3200 3201 Result.AddTextChunk(Result.getAllocator().CopyString(BeforeName)); 3202 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3203 Result.AddTypedTextChunk(Result.getAllocator().CopyString(NameAndSignature)); 3204 return Result.TakeString(); 3205 } 3206 3207 CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl( 3208 Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result, 3209 bool IncludeBriefComments, const CodeCompletionContext &CCContext, 3210 PrintingPolicy &Policy) { 3211 const NamedDecl *ND = Declaration; 3212 Result.addParentContext(ND->getDeclContext()); 3213 3214 if (IncludeBriefComments) { 3215 // Add documentation comment, if it exists. 3216 if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) { 3217 Result.addBriefComment(RC->getBriefText(Ctx)); 3218 } 3219 } 3220 3221 if (StartsNestedNameSpecifier) { 3222 Result.AddTypedTextChunk( 3223 Result.getAllocator().CopyString(ND->getNameAsString())); 3224 Result.AddTextChunk("::"); 3225 return Result.TakeString(); 3226 } 3227 3228 for (const auto *I : ND->specific_attrs<AnnotateAttr>()) 3229 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation())); 3230 3231 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result); 3232 3233 if (const auto *Function = dyn_cast<FunctionDecl>(ND)) { 3234 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 3235 Ctx, Policy); 3236 AddTypedNameChunk(Ctx, Policy, ND, Result); 3237 Result.AddChunk(CodeCompletionString::CK_LeftParen); 3238 AddFunctionParameterChunks(PP, Policy, Function, Result); 3239 Result.AddChunk(CodeCompletionString::CK_RightParen); 3240 AddFunctionTypeQualsToCompletionString(Result, Function); 3241 return Result.TakeString(); 3242 } 3243 3244 if (const FunctionTemplateDecl *FunTmpl = 3245 dyn_cast<FunctionTemplateDecl>(ND)) { 3246 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 3247 Ctx, Policy); 3248 FunctionDecl *Function = FunTmpl->getTemplatedDecl(); 3249 AddTypedNameChunk(Ctx, Policy, Function, Result); 3250 3251 // Figure out which template parameters are deduced (or have default 3252 // arguments). 3253 llvm::SmallBitVector Deduced; 3254 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced); 3255 unsigned LastDeducibleArgument; 3256 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0; 3257 --LastDeducibleArgument) { 3258 if (!Deduced[LastDeducibleArgument - 1]) { 3259 // C++0x: Figure out if the template argument has a default. If so, 3260 // the user doesn't need to type this argument. 3261 // FIXME: We need to abstract template parameters better! 3262 bool HasDefaultArg = false; 3263 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam( 3264 LastDeducibleArgument - 1); 3265 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 3266 HasDefaultArg = TTP->hasDefaultArgument(); 3267 else if (NonTypeTemplateParmDecl *NTTP = 3268 dyn_cast<NonTypeTemplateParmDecl>(Param)) 3269 HasDefaultArg = NTTP->hasDefaultArgument(); 3270 else { 3271 assert(isa<TemplateTemplateParmDecl>(Param)); 3272 HasDefaultArg = 3273 cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument(); 3274 } 3275 3276 if (!HasDefaultArg) 3277 break; 3278 } 3279 } 3280 3281 if (LastDeducibleArgument) { 3282 // Some of the function template arguments cannot be deduced from a 3283 // function call, so we introduce an explicit template argument list 3284 // containing all of the arguments up to the first deducible argument. 3285 Result.AddChunk(CodeCompletionString::CK_LeftAngle); 3286 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result, 3287 LastDeducibleArgument); 3288 Result.AddChunk(CodeCompletionString::CK_RightAngle); 3289 } 3290 3291 // Add the function parameters 3292 Result.AddChunk(CodeCompletionString::CK_LeftParen); 3293 AddFunctionParameterChunks(PP, Policy, Function, Result); 3294 Result.AddChunk(CodeCompletionString::CK_RightParen); 3295 AddFunctionTypeQualsToCompletionString(Result, Function); 3296 return Result.TakeString(); 3297 } 3298 3299 if (const auto *Template = dyn_cast<TemplateDecl>(ND)) { 3300 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 3301 Ctx, Policy); 3302 Result.AddTypedTextChunk( 3303 Result.getAllocator().CopyString(Template->getNameAsString())); 3304 Result.AddChunk(CodeCompletionString::CK_LeftAngle); 3305 AddTemplateParameterChunks(Ctx, Policy, Template, Result); 3306 Result.AddChunk(CodeCompletionString::CK_RightAngle); 3307 return Result.TakeString(); 3308 } 3309 if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) { 3310 Selector Sel = Method->getSelector(); 3311 if (Sel.isUnarySelector()) { 3312 Result.AddTypedTextChunk( 3313 Result.getAllocator().CopyString(Sel.getNameForSlot(0))); 3314 return Result.TakeString(); 3315 } 3316 3317 std::string SelName = Sel.getNameForSlot(0).str(); 3318 SelName += ':'; 3319 if (StartParameter == 0) 3320 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName)); 3321 else { 3322 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName)); 3323 3324 // If there is only one parameter, and we're past it, add an empty 3325 // typed-text chunk since there is nothing to type. 3326 if (Method->param_size() == 1) 3327 Result.AddTypedTextChunk(""); 3328 } 3329 unsigned Idx = 0; 3330 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(), 3331 PEnd = Method->param_end(); 3332 P != PEnd; (void)++P, ++Idx) { 3333 if (Idx > 0) { 3334 std::string Keyword; 3335 if (Idx > StartParameter) 3336 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3337 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx)) 3338 Keyword += II->getName(); 3339 Keyword += ":"; 3340 if (Idx < StartParameter || AllParametersAreInformative) 3341 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword)); 3342 else 3343 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword)); 3344 } 3345 3346 // If we're before the starting parameter, skip the placeholder. 3347 if (Idx < StartParameter) 3348 continue; 3349 3350 std::string Arg; 3351 QualType ParamType = (*P)->getType(); 3352 Optional<ArrayRef<QualType>> ObjCSubsts; 3353 if (!CCContext.getBaseType().isNull()) 3354 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method); 3355 3356 if (ParamType->isBlockPointerType() && !DeclaringEntity) 3357 Arg = FormatFunctionParameter(Policy, *P, true, 3358 /*SuppressBlock=*/false, ObjCSubsts); 3359 else { 3360 if (ObjCSubsts) 3361 ParamType = ParamType.substObjCTypeArgs( 3362 Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter); 3363 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(), 3364 ParamType); 3365 Arg += ParamType.getAsString(Policy) + ")"; 3366 if (IdentifierInfo *II = (*P)->getIdentifier()) 3367 if (DeclaringEntity || AllParametersAreInformative) 3368 Arg += II->getName(); 3369 } 3370 3371 if (Method->isVariadic() && (P + 1) == PEnd) 3372 Arg += ", ..."; 3373 3374 if (DeclaringEntity) 3375 Result.AddTextChunk(Result.getAllocator().CopyString(Arg)); 3376 else if (AllParametersAreInformative) 3377 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg)); 3378 else 3379 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg)); 3380 } 3381 3382 if (Method->isVariadic()) { 3383 if (Method->param_size() == 0) { 3384 if (DeclaringEntity) 3385 Result.AddTextChunk(", ..."); 3386 else if (AllParametersAreInformative) 3387 Result.AddInformativeChunk(", ..."); 3388 else 3389 Result.AddPlaceholderChunk(", ..."); 3390 } 3391 3392 MaybeAddSentinel(PP, Method, Result); 3393 } 3394 3395 return Result.TakeString(); 3396 } 3397 3398 if (Qualifier) 3399 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 3400 Ctx, Policy); 3401 3402 Result.AddTypedTextChunk( 3403 Result.getAllocator().CopyString(ND->getNameAsString())); 3404 return Result.TakeString(); 3405 } 3406 3407 const RawComment *clang::getCompletionComment(const ASTContext &Ctx, 3408 const NamedDecl *ND) { 3409 if (!ND) 3410 return nullptr; 3411 if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND)) 3412 return RC; 3413 3414 // Try to find comment from a property for ObjC methods. 3415 const auto *M = dyn_cast<ObjCMethodDecl>(ND); 3416 if (!M) 3417 return nullptr; 3418 const ObjCPropertyDecl *PDecl = M->findPropertyDecl(); 3419 if (!PDecl) 3420 return nullptr; 3421 3422 return Ctx.getRawCommentForAnyRedecl(PDecl); 3423 } 3424 3425 const RawComment *clang::getPatternCompletionComment(const ASTContext &Ctx, 3426 const NamedDecl *ND) { 3427 const auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND); 3428 if (!M || !M->isPropertyAccessor()) 3429 return nullptr; 3430 3431 // Provide code completion comment for self.GetterName where 3432 // GetterName is the getter method for a property with name 3433 // different from the property name (declared via a property 3434 // getter attribute. 3435 const ObjCPropertyDecl *PDecl = M->findPropertyDecl(); 3436 if (!PDecl) 3437 return nullptr; 3438 if (PDecl->getGetterName() == M->getSelector() && 3439 PDecl->getIdentifier() != M->getIdentifier()) { 3440 if (auto *RC = Ctx.getRawCommentForAnyRedecl(M)) 3441 return RC; 3442 if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl)) 3443 return RC; 3444 } 3445 return nullptr; 3446 } 3447 3448 const RawComment *clang::getParameterComment( 3449 const ASTContext &Ctx, 3450 const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) { 3451 auto FDecl = Result.getFunction(); 3452 if (!FDecl) 3453 return nullptr; 3454 if (ArgIndex < FDecl->getNumParams()) 3455 return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex)); 3456 return nullptr; 3457 } 3458 3459 /// Add function overload parameter chunks to the given code completion 3460 /// string. 3461 static void AddOverloadParameterChunks(ASTContext &Context, 3462 const PrintingPolicy &Policy, 3463 const FunctionDecl *Function, 3464 const FunctionProtoType *Prototype, 3465 CodeCompletionBuilder &Result, 3466 unsigned CurrentArg, unsigned Start = 0, 3467 bool InOptional = false) { 3468 bool FirstParameter = true; 3469 unsigned NumParams = 3470 Function ? Function->getNumParams() : Prototype->getNumParams(); 3471 3472 for (unsigned P = Start; P != NumParams; ++P) { 3473 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) { 3474 // When we see an optional default argument, put that argument and 3475 // the remaining default arguments into a new, optional string. 3476 CodeCompletionBuilder Opt(Result.getAllocator(), 3477 Result.getCodeCompletionTUInfo()); 3478 if (!FirstParameter) 3479 Opt.AddChunk(CodeCompletionString::CK_Comma); 3480 // Optional sections are nested. 3481 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt, 3482 CurrentArg, P, /*InOptional=*/true); 3483 Result.AddOptionalChunk(Opt.TakeString()); 3484 return; 3485 } 3486 3487 if (FirstParameter) 3488 FirstParameter = false; 3489 else 3490 Result.AddChunk(CodeCompletionString::CK_Comma); 3491 3492 InOptional = false; 3493 3494 // Format the placeholder string. 3495 std::string Placeholder; 3496 if (Function) { 3497 const ParmVarDecl *Param = Function->getParamDecl(P); 3498 Placeholder = FormatFunctionParameter(Policy, Param); 3499 if (Param->hasDefaultArg()) 3500 Placeholder += GetDefaultValueString(Param, Context.getSourceManager(), 3501 Context.getLangOpts()); 3502 } else { 3503 Placeholder = Prototype->getParamType(P).getAsString(Policy); 3504 } 3505 3506 if (P == CurrentArg) 3507 Result.AddCurrentParameterChunk( 3508 Result.getAllocator().CopyString(Placeholder)); 3509 else 3510 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder)); 3511 } 3512 3513 if (Prototype && Prototype->isVariadic()) { 3514 CodeCompletionBuilder Opt(Result.getAllocator(), 3515 Result.getCodeCompletionTUInfo()); 3516 if (!FirstParameter) 3517 Opt.AddChunk(CodeCompletionString::CK_Comma); 3518 3519 if (CurrentArg < NumParams) 3520 Opt.AddPlaceholderChunk("..."); 3521 else 3522 Opt.AddCurrentParameterChunk("..."); 3523 3524 Result.AddOptionalChunk(Opt.TakeString()); 3525 } 3526 } 3527 3528 CodeCompletionString * 3529 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString( 3530 unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator, 3531 CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments) const { 3532 PrintingPolicy Policy = getCompletionPrintingPolicy(S); 3533 3534 // FIXME: Set priority, availability appropriately. 3535 CodeCompletionBuilder Result(Allocator, CCTUInfo, 1, 3536 CXAvailability_Available); 3537 FunctionDecl *FDecl = getFunction(); 3538 const FunctionProtoType *Proto = 3539 dyn_cast<FunctionProtoType>(getFunctionType()); 3540 if (!FDecl && !Proto) { 3541 // Function without a prototype. Just give the return type and a 3542 // highlighted ellipsis. 3543 const FunctionType *FT = getFunctionType(); 3544 Result.AddResultTypeChunk(Result.getAllocator().CopyString( 3545 FT->getReturnType().getAsString(Policy))); 3546 Result.AddChunk(CodeCompletionString::CK_LeftParen); 3547 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "..."); 3548 Result.AddChunk(CodeCompletionString::CK_RightParen); 3549 return Result.TakeString(); 3550 } 3551 3552 if (FDecl) { 3553 if (IncludeBriefComments) { 3554 if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg)) 3555 Result.addBriefComment(RC->getBriefText(S.getASTContext())); 3556 } 3557 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result); 3558 Result.AddTextChunk( 3559 Result.getAllocator().CopyString(FDecl->getNameAsString())); 3560 } else { 3561 Result.AddResultTypeChunk(Result.getAllocator().CopyString( 3562 Proto->getReturnType().getAsString(Policy))); 3563 } 3564 3565 Result.AddChunk(CodeCompletionString::CK_LeftParen); 3566 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result, 3567 CurrentArg); 3568 Result.AddChunk(CodeCompletionString::CK_RightParen); 3569 3570 return Result.TakeString(); 3571 } 3572 3573 unsigned clang::getMacroUsagePriority(StringRef MacroName, 3574 const LangOptions &LangOpts, 3575 bool PreferredTypeIsPointer) { 3576 unsigned Priority = CCP_Macro; 3577 3578 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants. 3579 if (MacroName.equals("nil") || MacroName.equals("NULL") || 3580 MacroName.equals("Nil")) { 3581 Priority = CCP_Constant; 3582 if (PreferredTypeIsPointer) 3583 Priority = Priority / CCF_SimilarTypeMatch; 3584 } 3585 // Treat "YES", "NO", "true", and "false" as constants. 3586 else if (MacroName.equals("YES") || MacroName.equals("NO") || 3587 MacroName.equals("true") || MacroName.equals("false")) 3588 Priority = CCP_Constant; 3589 // Treat "bool" as a type. 3590 else if (MacroName.equals("bool")) 3591 Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0); 3592 3593 return Priority; 3594 } 3595 3596 CXCursorKind clang::getCursorKindForDecl(const Decl *D) { 3597 if (!D) 3598 return CXCursor_UnexposedDecl; 3599 3600 switch (D->getKind()) { 3601 case Decl::Enum: 3602 return CXCursor_EnumDecl; 3603 case Decl::EnumConstant: 3604 return CXCursor_EnumConstantDecl; 3605 case Decl::Field: 3606 return CXCursor_FieldDecl; 3607 case Decl::Function: 3608 return CXCursor_FunctionDecl; 3609 case Decl::ObjCCategory: 3610 return CXCursor_ObjCCategoryDecl; 3611 case Decl::ObjCCategoryImpl: 3612 return CXCursor_ObjCCategoryImplDecl; 3613 case Decl::ObjCImplementation: 3614 return CXCursor_ObjCImplementationDecl; 3615 3616 case Decl::ObjCInterface: 3617 return CXCursor_ObjCInterfaceDecl; 3618 case Decl::ObjCIvar: 3619 return CXCursor_ObjCIvarDecl; 3620 case Decl::ObjCMethod: 3621 return cast<ObjCMethodDecl>(D)->isInstanceMethod() 3622 ? CXCursor_ObjCInstanceMethodDecl 3623 : CXCursor_ObjCClassMethodDecl; 3624 case Decl::CXXMethod: 3625 return CXCursor_CXXMethod; 3626 case Decl::CXXConstructor: 3627 return CXCursor_Constructor; 3628 case Decl::CXXDestructor: 3629 return CXCursor_Destructor; 3630 case Decl::CXXConversion: 3631 return CXCursor_ConversionFunction; 3632 case Decl::ObjCProperty: 3633 return CXCursor_ObjCPropertyDecl; 3634 case Decl::ObjCProtocol: 3635 return CXCursor_ObjCProtocolDecl; 3636 case Decl::ParmVar: 3637 return CXCursor_ParmDecl; 3638 case Decl::Typedef: 3639 return CXCursor_TypedefDecl; 3640 case Decl::TypeAlias: 3641 return CXCursor_TypeAliasDecl; 3642 case Decl::TypeAliasTemplate: 3643 return CXCursor_TypeAliasTemplateDecl; 3644 case Decl::Var: 3645 return CXCursor_VarDecl; 3646 case Decl::Namespace: 3647 return CXCursor_Namespace; 3648 case Decl::NamespaceAlias: 3649 return CXCursor_NamespaceAlias; 3650 case Decl::TemplateTypeParm: 3651 return CXCursor_TemplateTypeParameter; 3652 case Decl::NonTypeTemplateParm: 3653 return CXCursor_NonTypeTemplateParameter; 3654 case Decl::TemplateTemplateParm: 3655 return CXCursor_TemplateTemplateParameter; 3656 case Decl::FunctionTemplate: 3657 return CXCursor_FunctionTemplate; 3658 case Decl::ClassTemplate: 3659 return CXCursor_ClassTemplate; 3660 case Decl::AccessSpec: 3661 return CXCursor_CXXAccessSpecifier; 3662 case Decl::ClassTemplatePartialSpecialization: 3663 return CXCursor_ClassTemplatePartialSpecialization; 3664 case Decl::UsingDirective: 3665 return CXCursor_UsingDirective; 3666 case Decl::StaticAssert: 3667 return CXCursor_StaticAssert; 3668 case Decl::Friend: 3669 return CXCursor_FriendDecl; 3670 case Decl::TranslationUnit: 3671 return CXCursor_TranslationUnit; 3672 3673 case Decl::Using: 3674 case Decl::UnresolvedUsingValue: 3675 case Decl::UnresolvedUsingTypename: 3676 return CXCursor_UsingDeclaration; 3677 3678 case Decl::ObjCPropertyImpl: 3679 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) { 3680 case ObjCPropertyImplDecl::Dynamic: 3681 return CXCursor_ObjCDynamicDecl; 3682 3683 case ObjCPropertyImplDecl::Synthesize: 3684 return CXCursor_ObjCSynthesizeDecl; 3685 } 3686 llvm_unreachable("Unexpected Kind!"); 3687 3688 case Decl::Import: 3689 return CXCursor_ModuleImportDecl; 3690 3691 case Decl::ObjCTypeParam: 3692 return CXCursor_TemplateTypeParameter; 3693 3694 default: 3695 if (const auto *TD = dyn_cast<TagDecl>(D)) { 3696 switch (TD->getTagKind()) { 3697 case TTK_Interface: // fall through 3698 case TTK_Struct: 3699 return CXCursor_StructDecl; 3700 case TTK_Class: 3701 return CXCursor_ClassDecl; 3702 case TTK_Union: 3703 return CXCursor_UnionDecl; 3704 case TTK_Enum: 3705 return CXCursor_EnumDecl; 3706 } 3707 } 3708 } 3709 3710 return CXCursor_UnexposedDecl; 3711 } 3712 3713 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results, 3714 bool LoadExternal, bool IncludeUndefined, 3715 bool TargetTypeIsPointer = false) { 3716 typedef CodeCompletionResult Result; 3717 3718 Results.EnterNewScope(); 3719 3720 for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal), 3721 MEnd = PP.macro_end(LoadExternal); 3722 M != MEnd; ++M) { 3723 auto MD = PP.getMacroDefinition(M->first); 3724 if (IncludeUndefined || MD) { 3725 MacroInfo *MI = MD.getMacroInfo(); 3726 if (MI && MI->isUsedForHeaderGuard()) 3727 continue; 3728 3729 Results.AddResult( 3730 Result(M->first, MI, 3731 getMacroUsagePriority(M->first->getName(), PP.getLangOpts(), 3732 TargetTypeIsPointer))); 3733 } 3734 } 3735 3736 Results.ExitScope(); 3737 } 3738 3739 static void AddPrettyFunctionResults(const LangOptions &LangOpts, 3740 ResultBuilder &Results) { 3741 typedef CodeCompletionResult Result; 3742 3743 Results.EnterNewScope(); 3744 3745 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant)); 3746 Results.AddResult(Result("__FUNCTION__", CCP_Constant)); 3747 if (LangOpts.C99 || LangOpts.CPlusPlus11) 3748 Results.AddResult(Result("__func__", CCP_Constant)); 3749 Results.ExitScope(); 3750 } 3751 3752 static void HandleCodeCompleteResults(Sema *S, 3753 CodeCompleteConsumer *CodeCompleter, 3754 CodeCompletionContext Context, 3755 CodeCompletionResult *Results, 3756 unsigned NumResults) { 3757 if (CodeCompleter) 3758 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults); 3759 } 3760 3761 static CodeCompletionContext 3762 mapCodeCompletionContext(Sema &S, Sema::ParserCompletionContext PCC) { 3763 switch (PCC) { 3764 case Sema::PCC_Namespace: 3765 return CodeCompletionContext::CCC_TopLevel; 3766 3767 case Sema::PCC_Class: 3768 return CodeCompletionContext::CCC_ClassStructUnion; 3769 3770 case Sema::PCC_ObjCInterface: 3771 return CodeCompletionContext::CCC_ObjCInterface; 3772 3773 case Sema::PCC_ObjCImplementation: 3774 return CodeCompletionContext::CCC_ObjCImplementation; 3775 3776 case Sema::PCC_ObjCInstanceVariableList: 3777 return CodeCompletionContext::CCC_ObjCIvarList; 3778 3779 case Sema::PCC_Template: 3780 case Sema::PCC_MemberTemplate: 3781 if (S.CurContext->isFileContext()) 3782 return CodeCompletionContext::CCC_TopLevel; 3783 if (S.CurContext->isRecord()) 3784 return CodeCompletionContext::CCC_ClassStructUnion; 3785 return CodeCompletionContext::CCC_Other; 3786 3787 case Sema::PCC_RecoveryInFunction: 3788 return CodeCompletionContext::CCC_Recovery; 3789 3790 case Sema::PCC_ForInit: 3791 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 || 3792 S.getLangOpts().ObjC) 3793 return CodeCompletionContext::CCC_ParenthesizedExpression; 3794 else 3795 return CodeCompletionContext::CCC_Expression; 3796 3797 case Sema::PCC_Expression: 3798 return CodeCompletionContext::CCC_Expression; 3799 case Sema::PCC_Condition: 3800 return CodeCompletionContext(CodeCompletionContext::CCC_Expression, 3801 S.getASTContext().BoolTy); 3802 3803 case Sema::PCC_Statement: 3804 return CodeCompletionContext::CCC_Statement; 3805 3806 case Sema::PCC_Type: 3807 return CodeCompletionContext::CCC_Type; 3808 3809 case Sema::PCC_ParenthesizedExpression: 3810 return CodeCompletionContext::CCC_ParenthesizedExpression; 3811 3812 case Sema::PCC_LocalDeclarationSpecifiers: 3813 return CodeCompletionContext::CCC_Type; 3814 } 3815 3816 llvm_unreachable("Invalid ParserCompletionContext!"); 3817 } 3818 3819 /// If we're in a C++ virtual member function, add completion results 3820 /// that invoke the functions we override, since it's common to invoke the 3821 /// overridden function as well as adding new functionality. 3822 /// 3823 /// \param S The semantic analysis object for which we are generating results. 3824 /// 3825 /// \param InContext This context in which the nested-name-specifier preceding 3826 /// the code-completion point 3827 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext, 3828 ResultBuilder &Results) { 3829 // Look through blocks. 3830 DeclContext *CurContext = S.CurContext; 3831 while (isa<BlockDecl>(CurContext)) 3832 CurContext = CurContext->getParent(); 3833 3834 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext); 3835 if (!Method || !Method->isVirtual()) 3836 return; 3837 3838 // We need to have names for all of the parameters, if we're going to 3839 // generate a forwarding call. 3840 for (auto P : Method->parameters()) 3841 if (!P->getDeclName()) 3842 return; 3843 3844 PrintingPolicy Policy = getCompletionPrintingPolicy(S); 3845 for (const CXXMethodDecl *Overridden : Method->overridden_methods()) { 3846 CodeCompletionBuilder Builder(Results.getAllocator(), 3847 Results.getCodeCompletionTUInfo()); 3848 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl()) 3849 continue; 3850 3851 // If we need a nested-name-specifier, add one now. 3852 if (!InContext) { 3853 NestedNameSpecifier *NNS = getRequiredQualification( 3854 S.Context, CurContext, Overridden->getDeclContext()); 3855 if (NNS) { 3856 std::string Str; 3857 llvm::raw_string_ostream OS(Str); 3858 NNS->print(OS, Policy); 3859 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str())); 3860 } 3861 } else if (!InContext->Equals(Overridden->getDeclContext())) 3862 continue; 3863 3864 Builder.AddTypedTextChunk( 3865 Results.getAllocator().CopyString(Overridden->getNameAsString())); 3866 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3867 bool FirstParam = true; 3868 for (auto P : Method->parameters()) { 3869 if (FirstParam) 3870 FirstParam = false; 3871 else 3872 Builder.AddChunk(CodeCompletionString::CK_Comma); 3873 3874 Builder.AddPlaceholderChunk( 3875 Results.getAllocator().CopyString(P->getIdentifier()->getName())); 3876 } 3877 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3878 Results.AddResult(CodeCompletionResult( 3879 Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod, 3880 CXAvailability_Available, Overridden)); 3881 Results.Ignore(Overridden); 3882 } 3883 } 3884 3885 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc, 3886 ModuleIdPath Path) { 3887 typedef CodeCompletionResult Result; 3888 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3889 CodeCompleter->getCodeCompletionTUInfo(), 3890 CodeCompletionContext::CCC_Other); 3891 Results.EnterNewScope(); 3892 3893 CodeCompletionAllocator &Allocator = Results.getAllocator(); 3894 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 3895 typedef CodeCompletionResult Result; 3896 if (Path.empty()) { 3897 // Enumerate all top-level modules. 3898 SmallVector<Module *, 8> Modules; 3899 PP.getHeaderSearchInfo().collectAllModules(Modules); 3900 for (unsigned I = 0, N = Modules.size(); I != N; ++I) { 3901 Builder.AddTypedTextChunk( 3902 Builder.getAllocator().CopyString(Modules[I]->Name)); 3903 Results.AddResult(Result( 3904 Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl, 3905 Modules[I]->isAvailable() ? CXAvailability_Available 3906 : CXAvailability_NotAvailable)); 3907 } 3908 } else if (getLangOpts().Modules) { 3909 // Load the named module. 3910 Module *Mod = 3911 PP.getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 3912 /*IsInclusionDirective=*/false); 3913 // Enumerate submodules. 3914 if (Mod) { 3915 for (Module::submodule_iterator Sub = Mod->submodule_begin(), 3916 SubEnd = Mod->submodule_end(); 3917 Sub != SubEnd; ++Sub) { 3918 3919 Builder.AddTypedTextChunk( 3920 Builder.getAllocator().CopyString((*Sub)->Name)); 3921 Results.AddResult(Result( 3922 Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl, 3923 (*Sub)->isAvailable() ? CXAvailability_Available 3924 : CXAvailability_NotAvailable)); 3925 } 3926 } 3927 } 3928 Results.ExitScope(); 3929 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 3930 Results.data(), Results.size()); 3931 } 3932 3933 void Sema::CodeCompleteOrdinaryName(Scope *S, 3934 ParserCompletionContext CompletionContext) { 3935 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3936 CodeCompleter->getCodeCompletionTUInfo(), 3937 mapCodeCompletionContext(*this, CompletionContext)); 3938 Results.EnterNewScope(); 3939 3940 // Determine how to filter results, e.g., so that the names of 3941 // values (functions, enumerators, function templates, etc.) are 3942 // only allowed where we can have an expression. 3943 switch (CompletionContext) { 3944 case PCC_Namespace: 3945 case PCC_Class: 3946 case PCC_ObjCInterface: 3947 case PCC_ObjCImplementation: 3948 case PCC_ObjCInstanceVariableList: 3949 case PCC_Template: 3950 case PCC_MemberTemplate: 3951 case PCC_Type: 3952 case PCC_LocalDeclarationSpecifiers: 3953 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 3954 break; 3955 3956 case PCC_Statement: 3957 case PCC_ParenthesizedExpression: 3958 case PCC_Expression: 3959 case PCC_ForInit: 3960 case PCC_Condition: 3961 if (WantTypesInContext(CompletionContext, getLangOpts())) 3962 Results.setFilter(&ResultBuilder::IsOrdinaryName); 3963 else 3964 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); 3965 3966 if (getLangOpts().CPlusPlus) 3967 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results); 3968 break; 3969 3970 case PCC_RecoveryInFunction: 3971 // Unfiltered 3972 break; 3973 } 3974 3975 // If we are in a C++ non-static member function, check the qualifiers on 3976 // the member function to filter/prioritize the results list. 3977 auto ThisType = getCurrentThisType(); 3978 if (!ThisType.isNull()) 3979 Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers()); 3980 3981 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3982 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3983 CodeCompleter->includeGlobals(), 3984 CodeCompleter->loadExternal()); 3985 3986 AddOrdinaryNameResults(CompletionContext, S, *this, Results); 3987 Results.ExitScope(); 3988 3989 switch (CompletionContext) { 3990 case PCC_ParenthesizedExpression: 3991 case PCC_Expression: 3992 case PCC_Statement: 3993 case PCC_RecoveryInFunction: 3994 if (S->getFnParent()) 3995 AddPrettyFunctionResults(getLangOpts(), Results); 3996 break; 3997 3998 case PCC_Namespace: 3999 case PCC_Class: 4000 case PCC_ObjCInterface: 4001 case PCC_ObjCImplementation: 4002 case PCC_ObjCInstanceVariableList: 4003 case PCC_Template: 4004 case PCC_MemberTemplate: 4005 case PCC_ForInit: 4006 case PCC_Condition: 4007 case PCC_Type: 4008 case PCC_LocalDeclarationSpecifiers: 4009 break; 4010 } 4011 4012 if (CodeCompleter->includeMacros()) 4013 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 4014 4015 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4016 Results.data(), Results.size()); 4017 } 4018 4019 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 4020 ParsedType Receiver, 4021 ArrayRef<IdentifierInfo *> SelIdents, 4022 bool AtArgumentExpression, bool IsSuper, 4023 ResultBuilder &Results); 4024 4025 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 4026 bool AllowNonIdentifiers, 4027 bool AllowNestedNameSpecifiers) { 4028 typedef CodeCompletionResult Result; 4029 ResultBuilder Results( 4030 *this, CodeCompleter->getAllocator(), 4031 CodeCompleter->getCodeCompletionTUInfo(), 4032 AllowNestedNameSpecifiers 4033 // FIXME: Try to separate codepath leading here to deduce whether we 4034 // need an existing symbol or a new one. 4035 ? CodeCompletionContext::CCC_SymbolOrNewName 4036 : CodeCompletionContext::CCC_NewName); 4037 Results.EnterNewScope(); 4038 4039 // Type qualifiers can come after names. 4040 Results.AddResult(Result("const")); 4041 Results.AddResult(Result("volatile")); 4042 if (getLangOpts().C99) 4043 Results.AddResult(Result("restrict")); 4044 4045 if (getLangOpts().CPlusPlus) { 4046 if (getLangOpts().CPlusPlus11 && 4047 (DS.getTypeSpecType() == DeclSpec::TST_class || 4048 DS.getTypeSpecType() == DeclSpec::TST_struct)) 4049 Results.AddResult("final"); 4050 4051 if (AllowNonIdentifiers) { 4052 Results.AddResult(Result("operator")); 4053 } 4054 4055 // Add nested-name-specifiers. 4056 if (AllowNestedNameSpecifiers) { 4057 Results.allowNestedNameSpecifiers(); 4058 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy); 4059 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4060 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, 4061 CodeCompleter->includeGlobals(), 4062 CodeCompleter->loadExternal()); 4063 Results.setFilter(nullptr); 4064 } 4065 } 4066 Results.ExitScope(); 4067 4068 // If we're in a context where we might have an expression (rather than a 4069 // declaration), and what we've seen so far is an Objective-C type that could 4070 // be a receiver of a class message, this may be a class message send with 4071 // the initial opening bracket '[' missing. Add appropriate completions. 4072 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers && 4073 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && 4074 DS.getTypeSpecType() == DeclSpec::TST_typename && 4075 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified && 4076 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 4077 !DS.isTypeAltiVecVector() && S && 4078 (S->getFlags() & Scope::DeclScope) != 0 && 4079 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope | 4080 Scope::FunctionPrototypeScope | Scope::AtCatchScope)) == 4081 0) { 4082 ParsedType T = DS.getRepAsType(); 4083 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType()) 4084 AddClassMessageCompletions(*this, S, T, None, false, false, Results); 4085 } 4086 4087 // Note that we intentionally suppress macro results here, since we do not 4088 // encourage using macros to produce the names of entities. 4089 4090 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4091 Results.data(), Results.size()); 4092 } 4093 4094 struct Sema::CodeCompleteExpressionData { 4095 CodeCompleteExpressionData(QualType PreferredType = QualType(), 4096 bool IsParenthesized = false) 4097 : PreferredType(PreferredType), IntegralConstantExpression(false), 4098 ObjCCollection(false), IsParenthesized(IsParenthesized) {} 4099 4100 QualType PreferredType; 4101 bool IntegralConstantExpression; 4102 bool ObjCCollection; 4103 bool IsParenthesized; 4104 SmallVector<Decl *, 4> IgnoreDecls; 4105 }; 4106 4107 namespace { 4108 /// Information that allows to avoid completing redundant enumerators. 4109 struct CoveredEnumerators { 4110 llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen; 4111 NestedNameSpecifier *SuggestedQualifier = nullptr; 4112 }; 4113 } // namespace 4114 4115 static void AddEnumerators(ResultBuilder &Results, ASTContext &Context, 4116 EnumDecl *Enum, DeclContext *CurContext, 4117 const CoveredEnumerators &Enumerators) { 4118 NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier; 4119 if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) { 4120 // If there are no prior enumerators in C++, check whether we have to 4121 // qualify the names of the enumerators that we suggest, because they 4122 // may not be visible in this scope. 4123 Qualifier = getRequiredQualification(Context, CurContext, Enum); 4124 } 4125 4126 Results.EnterNewScope(); 4127 for (auto *E : Enum->enumerators()) { 4128 if (Enumerators.Seen.count(E)) 4129 continue; 4130 4131 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier); 4132 Results.AddResult(R, CurContext, nullptr, false); 4133 } 4134 Results.ExitScope(); 4135 } 4136 4137 /// Try to find a corresponding FunctionProtoType for function-like types (e.g. 4138 /// function pointers, std::function, etc). 4139 static const FunctionProtoType *TryDeconstructFunctionLike(QualType T) { 4140 assert(!T.isNull()); 4141 // Try to extract first template argument from std::function<> and similar. 4142 // Note we only handle the sugared types, they closely match what users wrote. 4143 // We explicitly choose to not handle ClassTemplateSpecializationDecl. 4144 if (auto *Specialization = T->getAs<TemplateSpecializationType>()) { 4145 if (Specialization->getNumArgs() != 1) 4146 return nullptr; 4147 const TemplateArgument &Argument = Specialization->getArg(0); 4148 if (Argument.getKind() != TemplateArgument::Type) 4149 return nullptr; 4150 return Argument.getAsType()->getAs<FunctionProtoType>(); 4151 } 4152 // Handle other cases. 4153 if (T->isPointerType()) 4154 T = T->getPointeeType(); 4155 return T->getAs<FunctionProtoType>(); 4156 } 4157 4158 /// Adds a pattern completion for a lambda expression with the specified 4159 /// parameter types and placeholders for parameter names. 4160 static void AddLambdaCompletion(ResultBuilder &Results, 4161 llvm::ArrayRef<QualType> Parameters, 4162 const LangOptions &LangOpts) { 4163 if (!Results.includeCodePatterns()) 4164 return; 4165 CodeCompletionBuilder Completion(Results.getAllocator(), 4166 Results.getCodeCompletionTUInfo()); 4167 // [](<parameters>) {} 4168 Completion.AddChunk(CodeCompletionString::CK_LeftBracket); 4169 Completion.AddPlaceholderChunk("="); 4170 Completion.AddChunk(CodeCompletionString::CK_RightBracket); 4171 if (!Parameters.empty()) { 4172 Completion.AddChunk(CodeCompletionString::CK_LeftParen); 4173 bool First = true; 4174 for (auto Parameter : Parameters) { 4175 if (!First) 4176 Completion.AddChunk(CodeCompletionString::ChunkKind::CK_Comma); 4177 else 4178 First = false; 4179 4180 constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!"; 4181 std::string Type = NamePlaceholder; 4182 Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts)); 4183 llvm::StringRef Prefix, Suffix; 4184 std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder); 4185 Prefix = Prefix.rtrim(); 4186 Suffix = Suffix.ltrim(); 4187 4188 Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix)); 4189 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4190 Completion.AddPlaceholderChunk("parameter"); 4191 Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix)); 4192 }; 4193 Completion.AddChunk(CodeCompletionString::CK_RightParen); 4194 } 4195 Completion.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace); 4196 Completion.AddChunk(CodeCompletionString::CK_LeftBrace); 4197 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4198 Completion.AddPlaceholderChunk("body"); 4199 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4200 Completion.AddChunk(CodeCompletionString::CK_RightBrace); 4201 4202 Results.AddResult(Completion.TakeString()); 4203 } 4204 4205 /// Perform code-completion in an expression context when we know what 4206 /// type we're looking for. 4207 void Sema::CodeCompleteExpression(Scope *S, 4208 const CodeCompleteExpressionData &Data) { 4209 ResultBuilder Results( 4210 *this, CodeCompleter->getAllocator(), 4211 CodeCompleter->getCodeCompletionTUInfo(), 4212 CodeCompletionContext( 4213 Data.IsParenthesized 4214 ? CodeCompletionContext::CCC_ParenthesizedExpression 4215 : CodeCompletionContext::CCC_Expression, 4216 Data.PreferredType)); 4217 auto PCC = 4218 Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression; 4219 if (Data.ObjCCollection) 4220 Results.setFilter(&ResultBuilder::IsObjCCollection); 4221 else if (Data.IntegralConstantExpression) 4222 Results.setFilter(&ResultBuilder::IsIntegralConstantValue); 4223 else if (WantTypesInContext(PCC, getLangOpts())) 4224 Results.setFilter(&ResultBuilder::IsOrdinaryName); 4225 else 4226 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); 4227 4228 if (!Data.PreferredType.isNull()) 4229 Results.setPreferredType(Data.PreferredType.getNonReferenceType()); 4230 4231 // Ignore any declarations that we were told that we don't care about. 4232 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I) 4233 Results.Ignore(Data.IgnoreDecls[I]); 4234 4235 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4236 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4237 CodeCompleter->includeGlobals(), 4238 CodeCompleter->loadExternal()); 4239 4240 Results.EnterNewScope(); 4241 AddOrdinaryNameResults(PCC, S, *this, Results); 4242 Results.ExitScope(); 4243 4244 bool PreferredTypeIsPointer = false; 4245 if (!Data.PreferredType.isNull()) { 4246 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() || 4247 Data.PreferredType->isMemberPointerType() || 4248 Data.PreferredType->isBlockPointerType(); 4249 if (Data.PreferredType->isEnumeralType()) { 4250 EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl(); 4251 if (auto *Def = Enum->getDefinition()) 4252 Enum = Def; 4253 // FIXME: collect covered enumerators in cases like: 4254 // if (x == my_enum::one) { ... } else if (x == ^) {} 4255 AddEnumerators(Results, Context, Enum, CurContext, CoveredEnumerators()); 4256 } 4257 } 4258 4259 if (S->getFnParent() && !Data.ObjCCollection && 4260 !Data.IntegralConstantExpression) 4261 AddPrettyFunctionResults(getLangOpts(), Results); 4262 4263 if (CodeCompleter->includeMacros()) 4264 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false, 4265 PreferredTypeIsPointer); 4266 4267 // Complete a lambda expression when preferred type is a function. 4268 if (!Data.PreferredType.isNull() && getLangOpts().CPlusPlus11) { 4269 if (const FunctionProtoType *F = 4270 TryDeconstructFunctionLike(Data.PreferredType)) 4271 AddLambdaCompletion(Results, F->getParamTypes(), getLangOpts()); 4272 } 4273 4274 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4275 Results.data(), Results.size()); 4276 } 4277 4278 void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType, 4279 bool IsParenthesized) { 4280 return CodeCompleteExpression( 4281 S, CodeCompleteExpressionData(PreferredType, IsParenthesized)); 4282 } 4283 4284 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E, 4285 QualType PreferredType) { 4286 if (E.isInvalid()) 4287 CodeCompleteExpression(S, PreferredType); 4288 else if (getLangOpts().ObjC) 4289 CodeCompleteObjCInstanceMessage(S, E.get(), None, false); 4290 } 4291 4292 /// The set of properties that have already been added, referenced by 4293 /// property name. 4294 typedef llvm::SmallPtrSet<IdentifierInfo *, 16> AddedPropertiesSet; 4295 4296 /// Retrieve the container definition, if any? 4297 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) { 4298 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 4299 if (Interface->hasDefinition()) 4300 return Interface->getDefinition(); 4301 4302 return Interface; 4303 } 4304 4305 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4306 if (Protocol->hasDefinition()) 4307 return Protocol->getDefinition(); 4308 4309 return Protocol; 4310 } 4311 return Container; 4312 } 4313 4314 /// Adds a block invocation code completion result for the given block 4315 /// declaration \p BD. 4316 static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy, 4317 CodeCompletionBuilder &Builder, 4318 const NamedDecl *BD, 4319 const FunctionTypeLoc &BlockLoc, 4320 const FunctionProtoTypeLoc &BlockProtoLoc) { 4321 Builder.AddResultTypeChunk( 4322 GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context, 4323 Policy, Builder.getAllocator())); 4324 4325 AddTypedNameChunk(Context, Policy, BD, Builder); 4326 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4327 4328 if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) { 4329 Builder.AddPlaceholderChunk("..."); 4330 } else { 4331 for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) { 4332 if (I) 4333 Builder.AddChunk(CodeCompletionString::CK_Comma); 4334 4335 // Format the placeholder string. 4336 std::string PlaceholderStr = 4337 FormatFunctionParameter(Policy, BlockLoc.getParam(I)); 4338 4339 if (I == N - 1 && BlockProtoLoc && 4340 BlockProtoLoc.getTypePtr()->isVariadic()) 4341 PlaceholderStr += ", ..."; 4342 4343 // Add the placeholder string. 4344 Builder.AddPlaceholderChunk( 4345 Builder.getAllocator().CopyString(PlaceholderStr)); 4346 } 4347 } 4348 4349 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4350 } 4351 4352 static void 4353 AddObjCProperties(const CodeCompletionContext &CCContext, 4354 ObjCContainerDecl *Container, bool AllowCategories, 4355 bool AllowNullaryMethods, DeclContext *CurContext, 4356 AddedPropertiesSet &AddedProperties, ResultBuilder &Results, 4357 bool IsBaseExprStatement = false, 4358 bool IsClassProperty = false, bool InOriginalClass = true) { 4359 typedef CodeCompletionResult Result; 4360 4361 // Retrieve the definition. 4362 Container = getContainerDef(Container); 4363 4364 // Add properties in this container. 4365 const auto AddProperty = [&](const ObjCPropertyDecl *P) { 4366 if (!AddedProperties.insert(P->getIdentifier()).second) 4367 return; 4368 4369 // FIXME: Provide block invocation completion for non-statement 4370 // expressions. 4371 if (!P->getType().getTypePtr()->isBlockPointerType() || 4372 !IsBaseExprStatement) { 4373 Result R = Result(P, Results.getBasePriority(P), nullptr); 4374 if (!InOriginalClass) 4375 setInBaseClass(R); 4376 Results.MaybeAddResult(R, CurContext); 4377 return; 4378 } 4379 4380 // Block setter and invocation completion is provided only when we are able 4381 // to find the FunctionProtoTypeLoc with parameter names for the block. 4382 FunctionTypeLoc BlockLoc; 4383 FunctionProtoTypeLoc BlockProtoLoc; 4384 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc, 4385 BlockProtoLoc); 4386 if (!BlockLoc) { 4387 Result R = Result(P, Results.getBasePriority(P), nullptr); 4388 if (!InOriginalClass) 4389 setInBaseClass(R); 4390 Results.MaybeAddResult(R, CurContext); 4391 return; 4392 } 4393 4394 // The default completion result for block properties should be the block 4395 // invocation completion when the base expression is a statement. 4396 CodeCompletionBuilder Builder(Results.getAllocator(), 4397 Results.getCodeCompletionTUInfo()); 4398 AddObjCBlockCall(Container->getASTContext(), 4399 getCompletionPrintingPolicy(Results.getSema()), Builder, P, 4400 BlockLoc, BlockProtoLoc); 4401 Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P)); 4402 if (!InOriginalClass) 4403 setInBaseClass(R); 4404 Results.MaybeAddResult(R, CurContext); 4405 4406 // Provide additional block setter completion iff the base expression is a 4407 // statement and the block property is mutable. 4408 if (!P->isReadOnly()) { 4409 CodeCompletionBuilder Builder(Results.getAllocator(), 4410 Results.getCodeCompletionTUInfo()); 4411 AddResultTypeChunk(Container->getASTContext(), 4412 getCompletionPrintingPolicy(Results.getSema()), P, 4413 CCContext.getBaseType(), Builder); 4414 Builder.AddTypedTextChunk( 4415 Results.getAllocator().CopyString(P->getName())); 4416 Builder.AddChunk(CodeCompletionString::CK_Equal); 4417 4418 std::string PlaceholderStr = formatBlockPlaceholder( 4419 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc, 4420 BlockProtoLoc, /*SuppressBlockName=*/true); 4421 // Add the placeholder string. 4422 Builder.AddPlaceholderChunk( 4423 Builder.getAllocator().CopyString(PlaceholderStr)); 4424 4425 // When completing blocks properties that return void the default 4426 // property completion result should show up before the setter, 4427 // otherwise the setter completion should show up before the default 4428 // property completion, as we normally want to use the result of the 4429 // call. 4430 Result R = 4431 Result(Builder.TakeString(), P, 4432 Results.getBasePriority(P) + 4433 (BlockLoc.getTypePtr()->getReturnType()->isVoidType() 4434 ? CCD_BlockPropertySetter 4435 : -CCD_BlockPropertySetter)); 4436 if (!InOriginalClass) 4437 setInBaseClass(R); 4438 Results.MaybeAddResult(R, CurContext); 4439 } 4440 }; 4441 4442 if (IsClassProperty) { 4443 for (const auto *P : Container->class_properties()) 4444 AddProperty(P); 4445 } else { 4446 for (const auto *P : Container->instance_properties()) 4447 AddProperty(P); 4448 } 4449 4450 // Add nullary methods or implicit class properties 4451 if (AllowNullaryMethods) { 4452 ASTContext &Context = Container->getASTContext(); 4453 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 4454 // Adds a method result 4455 const auto AddMethod = [&](const ObjCMethodDecl *M) { 4456 IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0); 4457 if (!Name) 4458 return; 4459 if (!AddedProperties.insert(Name).second) 4460 return; 4461 CodeCompletionBuilder Builder(Results.getAllocator(), 4462 Results.getCodeCompletionTUInfo()); 4463 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder); 4464 Builder.AddTypedTextChunk( 4465 Results.getAllocator().CopyString(Name->getName())); 4466 Result R = Result(Builder.TakeString(), M, 4467 CCP_MemberDeclaration + CCD_MethodAsProperty); 4468 if (!InOriginalClass) 4469 setInBaseClass(R); 4470 Results.MaybeAddResult(R, CurContext); 4471 }; 4472 4473 if (IsClassProperty) { 4474 for (const auto *M : Container->methods()) { 4475 // Gather the class method that can be used as implicit property 4476 // getters. Methods with arguments or methods that return void aren't 4477 // added to the results as they can't be used as a getter. 4478 if (!M->getSelector().isUnarySelector() || 4479 M->getReturnType()->isVoidType() || M->isInstanceMethod()) 4480 continue; 4481 AddMethod(M); 4482 } 4483 } else { 4484 for (auto *M : Container->methods()) { 4485 if (M->getSelector().isUnarySelector()) 4486 AddMethod(M); 4487 } 4488 } 4489 } 4490 4491 // Add properties in referenced protocols. 4492 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4493 for (auto *P : Protocol->protocols()) 4494 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, 4495 CurContext, AddedProperties, Results, 4496 IsBaseExprStatement, IsClassProperty, 4497 /*InOriginalClass*/ false); 4498 } else if (ObjCInterfaceDecl *IFace = 4499 dyn_cast<ObjCInterfaceDecl>(Container)) { 4500 if (AllowCategories) { 4501 // Look through categories. 4502 for (auto *Cat : IFace->known_categories()) 4503 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods, 4504 CurContext, AddedProperties, Results, 4505 IsBaseExprStatement, IsClassProperty, 4506 InOriginalClass); 4507 } 4508 4509 // Look through protocols. 4510 for (auto *I : IFace->all_referenced_protocols()) 4511 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods, 4512 CurContext, AddedProperties, Results, 4513 IsBaseExprStatement, IsClassProperty, 4514 /*InOriginalClass*/ false); 4515 4516 // Look in the superclass. 4517 if (IFace->getSuperClass()) 4518 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories, 4519 AllowNullaryMethods, CurContext, AddedProperties, 4520 Results, IsBaseExprStatement, IsClassProperty, 4521 /*InOriginalClass*/ false); 4522 } else if (const auto *Category = 4523 dyn_cast<ObjCCategoryDecl>(Container)) { 4524 // Look through protocols. 4525 for (auto *P : Category->protocols()) 4526 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, 4527 CurContext, AddedProperties, Results, 4528 IsBaseExprStatement, IsClassProperty, 4529 /*InOriginalClass*/ false); 4530 } 4531 } 4532 4533 static void 4534 AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results, 4535 Scope *S, QualType BaseType, RecordDecl *RD, 4536 Optional<FixItHint> AccessOpFixIt) { 4537 // Indicate that we are performing a member access, and the cv-qualifiers 4538 // for the base object type. 4539 Results.setObjectTypeQualifiers(BaseType.getQualifiers()); 4540 4541 // Access to a C/C++ class, struct, or union. 4542 Results.allowNestedNameSpecifiers(); 4543 std::vector<FixItHint> FixIts; 4544 if (AccessOpFixIt) 4545 FixIts.emplace_back(AccessOpFixIt.getValue()); 4546 CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts)); 4547 SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer, 4548 SemaRef.CodeCompleter->includeGlobals(), 4549 /*IncludeDependentBases=*/true, 4550 SemaRef.CodeCompleter->loadExternal()); 4551 4552 if (SemaRef.getLangOpts().CPlusPlus) { 4553 if (!Results.empty()) { 4554 // The "template" keyword can follow "->" or "." in the grammar. 4555 // However, we only want to suggest the template keyword if something 4556 // is dependent. 4557 bool IsDependent = BaseType->isDependentType(); 4558 if (!IsDependent) { 4559 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) 4560 if (DeclContext *Ctx = DepScope->getEntity()) { 4561 IsDependent = Ctx->isDependentContext(); 4562 break; 4563 } 4564 } 4565 4566 if (IsDependent) 4567 Results.AddResult(CodeCompletionResult("template")); 4568 } 4569 } 4570 } 4571 4572 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 4573 Expr *OtherOpBase, 4574 SourceLocation OpLoc, bool IsArrow, 4575 bool IsBaseExprStatement, 4576 QualType PreferredType) { 4577 if (!Base || !CodeCompleter) 4578 return; 4579 4580 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); 4581 if (ConvertedBase.isInvalid()) 4582 return; 4583 QualType ConvertedBaseType = ConvertedBase.get()->getType(); 4584 4585 enum CodeCompletionContext::Kind contextKind; 4586 4587 if (IsArrow) { 4588 if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>()) 4589 ConvertedBaseType = Ptr->getPointeeType(); 4590 } 4591 4592 if (IsArrow) { 4593 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess; 4594 } else { 4595 if (ConvertedBaseType->isObjCObjectPointerType() || 4596 ConvertedBaseType->isObjCObjectOrInterfaceType()) { 4597 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess; 4598 } else { 4599 contextKind = CodeCompletionContext::CCC_DotMemberAccess; 4600 } 4601 } 4602 4603 CodeCompletionContext CCContext(contextKind, ConvertedBaseType); 4604 CCContext.setPreferredType(PreferredType); 4605 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4606 CodeCompleter->getCodeCompletionTUInfo(), CCContext, 4607 &ResultBuilder::IsMember); 4608 4609 auto DoCompletion = [&](Expr *Base, bool IsArrow, 4610 Optional<FixItHint> AccessOpFixIt) -> bool { 4611 if (!Base) 4612 return false; 4613 4614 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); 4615 if (ConvertedBase.isInvalid()) 4616 return false; 4617 Base = ConvertedBase.get(); 4618 4619 QualType BaseType = Base->getType(); 4620 4621 if (IsArrow) { 4622 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 4623 BaseType = Ptr->getPointeeType(); 4624 else if (BaseType->isObjCObjectPointerType()) 4625 /*Do nothing*/; 4626 else 4627 return false; 4628 } 4629 4630 if (const RecordType *Record = BaseType->getAs<RecordType>()) { 4631 AddRecordMembersCompletionResults(*this, Results, S, BaseType, 4632 Record->getDecl(), 4633 std::move(AccessOpFixIt)); 4634 } else if (const auto *TST = 4635 BaseType->getAs<TemplateSpecializationType>()) { 4636 TemplateName TN = TST->getTemplateName(); 4637 if (const auto *TD = 4638 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) { 4639 CXXRecordDecl *RD = TD->getTemplatedDecl(); 4640 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD, 4641 std::move(AccessOpFixIt)); 4642 } 4643 } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) { 4644 if (auto *RD = ICNT->getDecl()) 4645 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD, 4646 std::move(AccessOpFixIt)); 4647 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) { 4648 // Objective-C property reference. 4649 AddedPropertiesSet AddedProperties; 4650 4651 if (const ObjCObjectPointerType *ObjCPtr = 4652 BaseType->getAsObjCInterfacePointerType()) { 4653 // Add property results based on our interface. 4654 assert(ObjCPtr && "Non-NULL pointer guaranteed above!"); 4655 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true, 4656 /*AllowNullaryMethods=*/true, CurContext, 4657 AddedProperties, Results, IsBaseExprStatement); 4658 } 4659 4660 // Add properties from the protocols in a qualified interface. 4661 for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals()) 4662 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true, 4663 CurContext, AddedProperties, Results, 4664 IsBaseExprStatement, /*IsClassProperty*/ false, 4665 /*InOriginalClass*/ false); 4666 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || 4667 (!IsArrow && BaseType->isObjCObjectType())) { 4668 // Objective-C instance variable access. 4669 ObjCInterfaceDecl *Class = nullptr; 4670 if (const ObjCObjectPointerType *ObjCPtr = 4671 BaseType->getAs<ObjCObjectPointerType>()) 4672 Class = ObjCPtr->getInterfaceDecl(); 4673 else 4674 Class = BaseType->getAs<ObjCObjectType>()->getInterface(); 4675 4676 // Add all ivars from this class and its superclasses. 4677 if (Class) { 4678 CodeCompletionDeclConsumer Consumer(Results, Class, BaseType); 4679 Results.setFilter(&ResultBuilder::IsObjCIvar); 4680 LookupVisibleDecls( 4681 Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(), 4682 /*IncludeDependentBases=*/false, CodeCompleter->loadExternal()); 4683 } 4684 } 4685 4686 // FIXME: How do we cope with isa? 4687 return true; 4688 }; 4689 4690 Results.EnterNewScope(); 4691 4692 bool CompletionSucceded = DoCompletion(Base, IsArrow, None); 4693 if (CodeCompleter->includeFixIts()) { 4694 const CharSourceRange OpRange = 4695 CharSourceRange::getTokenRange(OpLoc, OpLoc); 4696 CompletionSucceded |= DoCompletion( 4697 OtherOpBase, !IsArrow, 4698 FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->")); 4699 } 4700 4701 Results.ExitScope(); 4702 4703 if (!CompletionSucceded) 4704 return; 4705 4706 // Hand off the results found for code completion. 4707 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4708 Results.data(), Results.size()); 4709 } 4710 4711 void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S, 4712 IdentifierInfo &ClassName, 4713 SourceLocation ClassNameLoc, 4714 bool IsBaseExprStatement) { 4715 IdentifierInfo *ClassNamePtr = &ClassName; 4716 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc); 4717 if (!IFace) 4718 return; 4719 CodeCompletionContext CCContext( 4720 CodeCompletionContext::CCC_ObjCPropertyAccess); 4721 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4722 CodeCompleter->getCodeCompletionTUInfo(), CCContext, 4723 &ResultBuilder::IsMember); 4724 Results.EnterNewScope(); 4725 AddedPropertiesSet AddedProperties; 4726 AddObjCProperties(CCContext, IFace, true, 4727 /*AllowNullaryMethods=*/true, CurContext, AddedProperties, 4728 Results, IsBaseExprStatement, 4729 /*IsClassProperty=*/true); 4730 Results.ExitScope(); 4731 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4732 Results.data(), Results.size()); 4733 } 4734 4735 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) { 4736 if (!CodeCompleter) 4737 return; 4738 4739 ResultBuilder::LookupFilter Filter = nullptr; 4740 enum CodeCompletionContext::Kind ContextKind = 4741 CodeCompletionContext::CCC_Other; 4742 switch ((DeclSpec::TST)TagSpec) { 4743 case DeclSpec::TST_enum: 4744 Filter = &ResultBuilder::IsEnum; 4745 ContextKind = CodeCompletionContext::CCC_EnumTag; 4746 break; 4747 4748 case DeclSpec::TST_union: 4749 Filter = &ResultBuilder::IsUnion; 4750 ContextKind = CodeCompletionContext::CCC_UnionTag; 4751 break; 4752 4753 case DeclSpec::TST_struct: 4754 case DeclSpec::TST_class: 4755 case DeclSpec::TST_interface: 4756 Filter = &ResultBuilder::IsClassOrStruct; 4757 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag; 4758 break; 4759 4760 default: 4761 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag"); 4762 } 4763 4764 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4765 CodeCompleter->getCodeCompletionTUInfo(), ContextKind); 4766 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4767 4768 // First pass: look for tags. 4769 Results.setFilter(Filter); 4770 LookupVisibleDecls(S, LookupTagName, Consumer, 4771 CodeCompleter->includeGlobals(), 4772 CodeCompleter->loadExternal()); 4773 4774 if (CodeCompleter->includeGlobals()) { 4775 // Second pass: look for nested name specifiers. 4776 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); 4777 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, 4778 CodeCompleter->includeGlobals(), 4779 CodeCompleter->loadExternal()); 4780 } 4781 4782 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4783 Results.data(), Results.size()); 4784 } 4785 4786 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results, 4787 const LangOptions &LangOpts) { 4788 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const)) 4789 Results.AddResult("const"); 4790 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile)) 4791 Results.AddResult("volatile"); 4792 if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict)) 4793 Results.AddResult("restrict"); 4794 if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic)) 4795 Results.AddResult("_Atomic"); 4796 if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)) 4797 Results.AddResult("__unaligned"); 4798 } 4799 4800 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) { 4801 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4802 CodeCompleter->getCodeCompletionTUInfo(), 4803 CodeCompletionContext::CCC_TypeQualifiers); 4804 Results.EnterNewScope(); 4805 AddTypeQualifierResults(DS, Results, LangOpts); 4806 Results.ExitScope(); 4807 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4808 Results.data(), Results.size()); 4809 } 4810 4811 void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, 4812 const VirtSpecifiers *VS) { 4813 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4814 CodeCompleter->getCodeCompletionTUInfo(), 4815 CodeCompletionContext::CCC_TypeQualifiers); 4816 Results.EnterNewScope(); 4817 AddTypeQualifierResults(DS, Results, LangOpts); 4818 if (LangOpts.CPlusPlus11) { 4819 Results.AddResult("noexcept"); 4820 if (D.getContext() == DeclaratorContext::MemberContext && 4821 !D.isCtorOrDtor() && !D.isStaticMember()) { 4822 if (!VS || !VS->isFinalSpecified()) 4823 Results.AddResult("final"); 4824 if (!VS || !VS->isOverrideSpecified()) 4825 Results.AddResult("override"); 4826 } 4827 } 4828 Results.ExitScope(); 4829 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4830 Results.data(), Results.size()); 4831 } 4832 4833 void Sema::CodeCompleteBracketDeclarator(Scope *S) { 4834 CodeCompleteExpression(S, QualType(getASTContext().getSizeType())); 4835 } 4836 4837 void Sema::CodeCompleteCase(Scope *S) { 4838 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter) 4839 return; 4840 4841 SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer(); 4842 // Condition expression might be invalid, do not continue in this case. 4843 if (!Switch->getCond()) 4844 return; 4845 QualType type = Switch->getCond()->IgnoreImplicit()->getType(); 4846 if (!type->isEnumeralType()) { 4847 CodeCompleteExpressionData Data(type); 4848 Data.IntegralConstantExpression = true; 4849 CodeCompleteExpression(S, Data); 4850 return; 4851 } 4852 4853 // Code-complete the cases of a switch statement over an enumeration type 4854 // by providing the list of 4855 EnumDecl *Enum = type->castAs<EnumType>()->getDecl(); 4856 if (EnumDecl *Def = Enum->getDefinition()) 4857 Enum = Def; 4858 4859 // Determine which enumerators we have already seen in the switch statement. 4860 // FIXME: Ideally, we would also be able to look *past* the code-completion 4861 // token, in case we are code-completing in the middle of the switch and not 4862 // at the end. However, we aren't able to do so at the moment. 4863 CoveredEnumerators Enumerators; 4864 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; 4865 SC = SC->getNextSwitchCase()) { 4866 CaseStmt *Case = dyn_cast<CaseStmt>(SC); 4867 if (!Case) 4868 continue; 4869 4870 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); 4871 if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal)) 4872 if (auto *Enumerator = 4873 dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 4874 // We look into the AST of the case statement to determine which 4875 // enumerator was named. Alternatively, we could compute the value of 4876 // the integral constant expression, then compare it against the 4877 // values of each enumerator. However, value-based approach would not 4878 // work as well with C++ templates where enumerators declared within a 4879 // template are type- and value-dependent. 4880 Enumerators.Seen.insert(Enumerator); 4881 4882 // If this is a qualified-id, keep track of the nested-name-specifier 4883 // so that we can reproduce it as part of code completion, e.g., 4884 // 4885 // switch (TagD.getKind()) { 4886 // case TagDecl::TK_enum: 4887 // break; 4888 // case XXX 4889 // 4890 // At the XXX, our completions are TagDecl::TK_union, 4891 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union, 4892 // TK_struct, and TK_class. 4893 Enumerators.SuggestedQualifier = DRE->getQualifier(); 4894 } 4895 } 4896 4897 // Add any enumerators that have not yet been mentioned. 4898 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4899 CodeCompleter->getCodeCompletionTUInfo(), 4900 CodeCompletionContext::CCC_Expression); 4901 AddEnumerators(Results, Context, Enum, CurContext, Enumerators); 4902 4903 if (CodeCompleter->includeMacros()) { 4904 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 4905 } 4906 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4907 Results.data(), Results.size()); 4908 } 4909 4910 static bool anyNullArguments(ArrayRef<Expr *> Args) { 4911 if (Args.size() && !Args.data()) 4912 return true; 4913 4914 for (unsigned I = 0; I != Args.size(); ++I) 4915 if (!Args[I]) 4916 return true; 4917 4918 return false; 4919 } 4920 4921 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate; 4922 4923 static void mergeCandidatesWithResults( 4924 Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results, 4925 OverloadCandidateSet &CandidateSet, SourceLocation Loc) { 4926 // Sort the overload candidate set by placing the best overloads first. 4927 llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X, 4928 const OverloadCandidate &Y) { 4929 return isBetterOverloadCandidate(SemaRef, X, Y, Loc, 4930 CandidateSet.getKind()); 4931 }); 4932 4933 // Add the remaining viable overload candidates as code-completion results. 4934 for (OverloadCandidate &Candidate : CandidateSet) { 4935 if (Candidate.Function && Candidate.Function->isDeleted()) 4936 continue; 4937 if (Candidate.Viable) 4938 Results.push_back(ResultCandidate(Candidate.Function)); 4939 } 4940 } 4941 4942 /// Get the type of the Nth parameter from a given set of overload 4943 /// candidates. 4944 static QualType getParamType(Sema &SemaRef, 4945 ArrayRef<ResultCandidate> Candidates, unsigned N) { 4946 4947 // Given the overloads 'Candidates' for a function call matching all arguments 4948 // up to N, return the type of the Nth parameter if it is the same for all 4949 // overload candidates. 4950 QualType ParamType; 4951 for (auto &Candidate : Candidates) { 4952 if (const auto *FType = Candidate.getFunctionType()) 4953 if (const auto *Proto = dyn_cast<FunctionProtoType>(FType)) 4954 if (N < Proto->getNumParams()) { 4955 if (ParamType.isNull()) 4956 ParamType = Proto->getParamType(N); 4957 else if (!SemaRef.Context.hasSameUnqualifiedType( 4958 ParamType.getNonReferenceType(), 4959 Proto->getParamType(N).getNonReferenceType())) 4960 // Otherwise return a default-constructed QualType. 4961 return QualType(); 4962 } 4963 } 4964 4965 return ParamType; 4966 } 4967 4968 static QualType 4969 ProduceSignatureHelp(Sema &SemaRef, Scope *S, 4970 MutableArrayRef<ResultCandidate> Candidates, 4971 unsigned CurrentArg, SourceLocation OpenParLoc) { 4972 if (Candidates.empty()) 4973 return QualType(); 4974 SemaRef.CodeCompleter->ProcessOverloadCandidates( 4975 SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc); 4976 return getParamType(SemaRef, Candidates, CurrentArg); 4977 } 4978 4979 QualType Sema::ProduceCallSignatureHelp(Scope *S, Expr *Fn, 4980 ArrayRef<Expr *> Args, 4981 SourceLocation OpenParLoc) { 4982 if (!CodeCompleter) 4983 return QualType(); 4984 4985 // FIXME: Provide support for variadic template functions. 4986 // Ignore type-dependent call expressions entirely. 4987 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) || 4988 Expr::hasAnyTypeDependentArguments(Args)) { 4989 return QualType(); 4990 } 4991 4992 // Build an overload candidate set based on the functions we find. 4993 SourceLocation Loc = Fn->getExprLoc(); 4994 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 4995 4996 SmallVector<ResultCandidate, 8> Results; 4997 4998 Expr *NakedFn = Fn->IgnoreParenCasts(); 4999 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) 5000 AddOverloadedCallCandidates(ULE, Args, CandidateSet, 5001 /*PartialOverloading=*/true); 5002 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) { 5003 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 5004 if (UME->hasExplicitTemplateArgs()) { 5005 UME->copyTemplateArgumentsInto(TemplateArgsBuffer); 5006 TemplateArgs = &TemplateArgsBuffer; 5007 } 5008 5009 // Add the base as first argument (use a nullptr if the base is implicit). 5010 SmallVector<Expr *, 12> ArgExprs( 5011 1, UME->isImplicitAccess() ? nullptr : UME->getBase()); 5012 ArgExprs.append(Args.begin(), Args.end()); 5013 UnresolvedSet<8> Decls; 5014 Decls.append(UME->decls_begin(), UME->decls_end()); 5015 const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase(); 5016 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs, 5017 /*SuppressUsedConversions=*/false, 5018 /*PartialOverloading=*/true, FirstArgumentIsBase); 5019 } else { 5020 FunctionDecl *FD = nullptr; 5021 if (auto *MCE = dyn_cast<MemberExpr>(NakedFn)) 5022 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl()); 5023 else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) 5024 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 5025 if (FD) { // We check whether it's a resolved function declaration. 5026 if (!getLangOpts().CPlusPlus || 5027 !FD->getType()->getAs<FunctionProtoType>()) 5028 Results.push_back(ResultCandidate(FD)); 5029 else 5030 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()), 5031 Args, CandidateSet, 5032 /*SuppressUsedConversions=*/false, 5033 /*PartialOverloading=*/true); 5034 5035 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) { 5036 // If expression's type is CXXRecordDecl, it may overload the function 5037 // call operator, so we check if it does and add them as candidates. 5038 // A complete type is needed to lookup for member function call operators. 5039 if (isCompleteType(Loc, NakedFn->getType())) { 5040 DeclarationName OpName = 5041 Context.DeclarationNames.getCXXOperatorName(OO_Call); 5042 LookupResult R(*this, OpName, Loc, LookupOrdinaryName); 5043 LookupQualifiedName(R, DC); 5044 R.suppressDiagnostics(); 5045 SmallVector<Expr *, 12> ArgExprs(1, NakedFn); 5046 ArgExprs.append(Args.begin(), Args.end()); 5047 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet, 5048 /*ExplicitArgs=*/nullptr, 5049 /*SuppressUsedConversions=*/false, 5050 /*PartialOverloading=*/true); 5051 } 5052 } else { 5053 // Lastly we check whether expression's type is function pointer or 5054 // function. 5055 QualType T = NakedFn->getType(); 5056 if (!T->getPointeeType().isNull()) 5057 T = T->getPointeeType(); 5058 5059 if (auto FP = T->getAs<FunctionProtoType>()) { 5060 if (!TooManyArguments(FP->getNumParams(), Args.size(), 5061 /*PartialOverloading=*/true) || 5062 FP->isVariadic()) 5063 Results.push_back(ResultCandidate(FP)); 5064 } else if (auto FT = T->getAs<FunctionType>()) 5065 // No prototype and declaration, it may be a K & R style function. 5066 Results.push_back(ResultCandidate(FT)); 5067 } 5068 } 5069 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc); 5070 QualType ParamType = 5071 ProduceSignatureHelp(*this, S, Results, Args.size(), OpenParLoc); 5072 return !CandidateSet.empty() ? ParamType : QualType(); 5073 } 5074 5075 QualType Sema::ProduceConstructorSignatureHelp(Scope *S, QualType Type, 5076 SourceLocation Loc, 5077 ArrayRef<Expr *> Args, 5078 SourceLocation OpenParLoc) { 5079 if (!CodeCompleter) 5080 return QualType(); 5081 5082 // A complete type is needed to lookup for constructors. 5083 CXXRecordDecl *RD = 5084 isCompleteType(Loc, Type) ? Type->getAsCXXRecordDecl() : nullptr; 5085 if (!RD) 5086 return Type; 5087 5088 // FIXME: Provide support for member initializers. 5089 // FIXME: Provide support for variadic template constructors. 5090 5091 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5092 5093 for (NamedDecl *C : LookupConstructors(RD)) { 5094 if (auto *FD = dyn_cast<FunctionDecl>(C)) { 5095 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), Args, 5096 CandidateSet, 5097 /*SuppressUsedConversions=*/false, 5098 /*PartialOverloading=*/true, 5099 /*AllowExplicit*/ true); 5100 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) { 5101 AddTemplateOverloadCandidate( 5102 FTD, DeclAccessPair::make(FTD, C->getAccess()), 5103 /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet, 5104 /*SuppressUsedConversions=*/false, 5105 /*PartialOverloading=*/true); 5106 } 5107 } 5108 5109 SmallVector<ResultCandidate, 8> Results; 5110 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc); 5111 return ProduceSignatureHelp(*this, S, Results, Args.size(), OpenParLoc); 5112 } 5113 5114 QualType Sema::ProduceCtorInitMemberSignatureHelp( 5115 Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, 5116 ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc) { 5117 if (!CodeCompleter) 5118 return QualType(); 5119 5120 CXXConstructorDecl *Constructor = 5121 dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5122 if (!Constructor) 5123 return QualType(); 5124 // FIXME: Add support for Base class constructors as well. 5125 if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl( 5126 Constructor->getParent(), SS, TemplateTypeTy, II)) 5127 return ProduceConstructorSignatureHelp(getCurScope(), MemberDecl->getType(), 5128 MemberDecl->getLocation(), ArgExprs, 5129 OpenParLoc); 5130 return QualType(); 5131 } 5132 5133 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) { 5134 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 5135 if (!VD) { 5136 CodeCompleteOrdinaryName(S, PCC_Expression); 5137 return; 5138 } 5139 5140 CodeCompleteExpressionData Data; 5141 Data.PreferredType = VD->getType(); 5142 // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'. 5143 Data.IgnoreDecls.push_back(VD); 5144 5145 CodeCompleteExpression(S, Data); 5146 } 5147 5148 void Sema::CodeCompleteAfterIf(Scope *S) { 5149 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5150 CodeCompleter->getCodeCompletionTUInfo(), 5151 mapCodeCompletionContext(*this, PCC_Statement)); 5152 Results.setFilter(&ResultBuilder::IsOrdinaryName); 5153 Results.EnterNewScope(); 5154 5155 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5156 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5157 CodeCompleter->includeGlobals(), 5158 CodeCompleter->loadExternal()); 5159 5160 AddOrdinaryNameResults(PCC_Statement, S, *this, Results); 5161 5162 // "else" block 5163 CodeCompletionBuilder Builder(Results.getAllocator(), 5164 Results.getCodeCompletionTUInfo()); 5165 Builder.AddTypedTextChunk("else"); 5166 if (Results.includeCodePatterns()) { 5167 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5168 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5169 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5170 Builder.AddPlaceholderChunk("statements"); 5171 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5172 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5173 } 5174 Results.AddResult(Builder.TakeString()); 5175 5176 // "else if" block 5177 Builder.AddTypedTextChunk("else"); 5178 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5179 Builder.AddTextChunk("if"); 5180 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5181 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5182 if (getLangOpts().CPlusPlus) 5183 Builder.AddPlaceholderChunk("condition"); 5184 else 5185 Builder.AddPlaceholderChunk("expression"); 5186 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5187 if (Results.includeCodePatterns()) { 5188 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5189 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5190 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5191 Builder.AddPlaceholderChunk("statements"); 5192 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5193 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5194 } 5195 Results.AddResult(Builder.TakeString()); 5196 5197 Results.ExitScope(); 5198 5199 if (S->getFnParent()) 5200 AddPrettyFunctionResults(getLangOpts(), Results); 5201 5202 if (CodeCompleter->includeMacros()) 5203 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 5204 5205 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5206 Results.data(), Results.size()); 5207 } 5208 5209 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 5210 bool EnteringContext, QualType BaseType) { 5211 if (SS.isEmpty() || !CodeCompleter) 5212 return; 5213 5214 // We want to keep the scope specifier even if it's invalid (e.g. the scope 5215 // "a::b::" is not corresponding to any context/namespace in the AST), since 5216 // it can be useful for global code completion which have information about 5217 // contexts/symbols that are not in the AST. 5218 if (SS.isInvalid()) { 5219 CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol); 5220 CC.setCXXScopeSpecifier(SS); 5221 // As SS is invalid, we try to collect accessible contexts from the current 5222 // scope with a dummy lookup so that the completion consumer can try to 5223 // guess what the specified scope is. 5224 ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(), 5225 CodeCompleter->getCodeCompletionTUInfo(), CC); 5226 if (S->getEntity()) { 5227 CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(), 5228 BaseType); 5229 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5230 /*IncludeGlobalScope=*/false, 5231 /*LoadExternal=*/false); 5232 } 5233 HandleCodeCompleteResults(this, CodeCompleter, 5234 DummyResults.getCompletionContext(), nullptr, 0); 5235 return; 5236 } 5237 // Always pretend to enter a context to ensure that a dependent type 5238 // resolves to a dependent record. 5239 DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true); 5240 if (!Ctx) 5241 return; 5242 5243 // Try to instantiate any non-dependent declaration contexts before 5244 // we look in them. 5245 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx)) 5246 return; 5247 5248 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5249 CodeCompleter->getCodeCompletionTUInfo(), 5250 CodeCompletionContext::CCC_Symbol); 5251 Results.EnterNewScope(); 5252 5253 // The "template" keyword can follow "::" in the grammar, but only 5254 // put it into the grammar if the nested-name-specifier is dependent. 5255 NestedNameSpecifier *NNS = SS.getScopeRep(); 5256 if (!Results.empty() && NNS->isDependent()) 5257 Results.AddResult("template"); 5258 5259 // Add calls to overridden virtual functions, if there are any. 5260 // 5261 // FIXME: This isn't wonderful, because we don't know whether we're actually 5262 // in a context that permits expressions. This is a general issue with 5263 // qualified-id completions. 5264 if (!EnteringContext) 5265 MaybeAddOverrideCalls(*this, Ctx, Results); 5266 Results.ExitScope(); 5267 5268 if (CodeCompleter->includeNamespaceLevelDecls() || 5269 (!Ctx->isNamespace() && !Ctx->isTranslationUnit())) { 5270 CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType); 5271 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer, 5272 /*IncludeGlobalScope=*/true, 5273 /*IncludeDependentBases=*/true, 5274 CodeCompleter->loadExternal()); 5275 } 5276 5277 auto CC = Results.getCompletionContext(); 5278 CC.setCXXScopeSpecifier(SS); 5279 5280 HandleCodeCompleteResults(this, CodeCompleter, CC, Results.data(), 5281 Results.size()); 5282 } 5283 5284 void Sema::CodeCompleteUsing(Scope *S) { 5285 if (!CodeCompleter) 5286 return; 5287 5288 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5289 CodeCompleter->getCodeCompletionTUInfo(), 5290 // This can be both a using alias or using 5291 // declaration, in the former we expect a new name and a 5292 // symbol in the latter case. 5293 CodeCompletionContext::CCC_SymbolOrNewName, 5294 &ResultBuilder::IsNestedNameSpecifier); 5295 Results.EnterNewScope(); 5296 5297 // If we aren't in class scope, we could see the "namespace" keyword. 5298 if (!S->isClassScope()) 5299 Results.AddResult(CodeCompletionResult("namespace")); 5300 5301 // After "using", we can see anything that would start a 5302 // nested-name-specifier. 5303 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5304 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5305 CodeCompleter->includeGlobals(), 5306 CodeCompleter->loadExternal()); 5307 Results.ExitScope(); 5308 5309 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5310 Results.data(), Results.size()); 5311 } 5312 5313 void Sema::CodeCompleteUsingDirective(Scope *S) { 5314 if (!CodeCompleter) 5315 return; 5316 5317 // After "using namespace", we expect to see a namespace name or namespace 5318 // alias. 5319 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5320 CodeCompleter->getCodeCompletionTUInfo(), 5321 CodeCompletionContext::CCC_Namespace, 5322 &ResultBuilder::IsNamespaceOrAlias); 5323 Results.EnterNewScope(); 5324 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5325 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5326 CodeCompleter->includeGlobals(), 5327 CodeCompleter->loadExternal()); 5328 Results.ExitScope(); 5329 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5330 Results.data(), Results.size()); 5331 } 5332 5333 void Sema::CodeCompleteNamespaceDecl(Scope *S) { 5334 if (!CodeCompleter) 5335 return; 5336 5337 DeclContext *Ctx = S->getEntity(); 5338 if (!S->getParent()) 5339 Ctx = Context.getTranslationUnitDecl(); 5340 5341 bool SuppressedGlobalResults = 5342 Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx); 5343 5344 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5345 CodeCompleter->getCodeCompletionTUInfo(), 5346 SuppressedGlobalResults 5347 ? CodeCompletionContext::CCC_Namespace 5348 : CodeCompletionContext::CCC_Other, 5349 &ResultBuilder::IsNamespace); 5350 5351 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { 5352 // We only want to see those namespaces that have already been defined 5353 // within this scope, because its likely that the user is creating an 5354 // extended namespace declaration. Keep track of the most recent 5355 // definition of each namespace. 5356 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; 5357 for (DeclContext::specific_decl_iterator<NamespaceDecl> 5358 NS(Ctx->decls_begin()), 5359 NSEnd(Ctx->decls_end()); 5360 NS != NSEnd; ++NS) 5361 OrigToLatest[NS->getOriginalNamespace()] = *NS; 5362 5363 // Add the most recent definition (or extended definition) of each 5364 // namespace to the list of results. 5365 Results.EnterNewScope(); 5366 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator 5367 NS = OrigToLatest.begin(), 5368 NSEnd = OrigToLatest.end(); 5369 NS != NSEnd; ++NS) 5370 Results.AddResult( 5371 CodeCompletionResult(NS->second, Results.getBasePriority(NS->second), 5372 nullptr), 5373 CurContext, nullptr, false); 5374 Results.ExitScope(); 5375 } 5376 5377 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5378 Results.data(), Results.size()); 5379 } 5380 5381 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { 5382 if (!CodeCompleter) 5383 return; 5384 5385 // After "namespace", we expect to see a namespace or alias. 5386 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5387 CodeCompleter->getCodeCompletionTUInfo(), 5388 CodeCompletionContext::CCC_Namespace, 5389 &ResultBuilder::IsNamespaceOrAlias); 5390 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5391 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5392 CodeCompleter->includeGlobals(), 5393 CodeCompleter->loadExternal()); 5394 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5395 Results.data(), Results.size()); 5396 } 5397 5398 void Sema::CodeCompleteOperatorName(Scope *S) { 5399 if (!CodeCompleter) 5400 return; 5401 5402 typedef CodeCompletionResult Result; 5403 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5404 CodeCompleter->getCodeCompletionTUInfo(), 5405 CodeCompletionContext::CCC_Type, 5406 &ResultBuilder::IsType); 5407 Results.EnterNewScope(); 5408 5409 // Add the names of overloadable operators. 5410 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ 5411 if (std::strcmp(Spelling, "?")) \ 5412 Results.AddResult(Result(Spelling)); 5413 #include "clang/Basic/OperatorKinds.def" 5414 5415 // Add any type names visible from the current scope 5416 Results.allowNestedNameSpecifiers(); 5417 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5418 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5419 CodeCompleter->includeGlobals(), 5420 CodeCompleter->loadExternal()); 5421 5422 // Add any type specifiers 5423 AddTypeSpecifierResults(getLangOpts(), Results); 5424 Results.ExitScope(); 5425 5426 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5427 Results.data(), Results.size()); 5428 } 5429 5430 void Sema::CodeCompleteConstructorInitializer( 5431 Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) { 5432 if (!ConstructorD) 5433 return; 5434 5435 AdjustDeclIfTemplate(ConstructorD); 5436 5437 auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD); 5438 if (!Constructor) 5439 return; 5440 5441 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5442 CodeCompleter->getCodeCompletionTUInfo(), 5443 CodeCompletionContext::CCC_Symbol); 5444 Results.EnterNewScope(); 5445 5446 // Fill in any already-initialized fields or base classes. 5447 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; 5448 llvm::SmallPtrSet<CanQualType, 4> InitializedBases; 5449 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) { 5450 if (Initializers[I]->isBaseInitializer()) 5451 InitializedBases.insert(Context.getCanonicalType( 5452 QualType(Initializers[I]->getBaseClass(), 0))); 5453 else 5454 InitializedFields.insert( 5455 cast<FieldDecl>(Initializers[I]->getAnyMember())); 5456 } 5457 5458 // Add completions for base classes. 5459 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 5460 bool SawLastInitializer = Initializers.empty(); 5461 CXXRecordDecl *ClassDecl = Constructor->getParent(); 5462 5463 auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) { 5464 CodeCompletionBuilder Builder(Results.getAllocator(), 5465 Results.getCodeCompletionTUInfo()); 5466 Builder.AddTypedTextChunk(Name); 5467 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5468 if (const auto *Function = dyn_cast<FunctionDecl>(ND)) 5469 AddFunctionParameterChunks(PP, Policy, Function, Builder); 5470 else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND)) 5471 AddFunctionParameterChunks(PP, Policy, FunTemplDecl->getTemplatedDecl(), 5472 Builder); 5473 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5474 return Builder.TakeString(); 5475 }; 5476 auto AddDefaultCtorInit = [&](const char *Name, const char *Type, 5477 const NamedDecl *ND) { 5478 CodeCompletionBuilder Builder(Results.getAllocator(), 5479 Results.getCodeCompletionTUInfo()); 5480 Builder.AddTypedTextChunk(Name); 5481 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5482 Builder.AddPlaceholderChunk(Type); 5483 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5484 if (ND) { 5485 auto CCR = CodeCompletionResult( 5486 Builder.TakeString(), ND, 5487 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration); 5488 if (isa<FieldDecl>(ND)) 5489 CCR.CursorKind = CXCursor_MemberRef; 5490 return Results.AddResult(CCR); 5491 } 5492 return Results.AddResult(CodeCompletionResult( 5493 Builder.TakeString(), 5494 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration)); 5495 }; 5496 auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority, 5497 const char *Name, const FieldDecl *FD) { 5498 if (!RD) 5499 return AddDefaultCtorInit(Name, 5500 FD ? Results.getAllocator().CopyString( 5501 FD->getType().getAsString(Policy)) 5502 : Name, 5503 FD); 5504 auto Ctors = getConstructors(Context, RD); 5505 if (Ctors.begin() == Ctors.end()) 5506 return AddDefaultCtorInit(Name, Name, RD); 5507 for (const NamedDecl *Ctor : Ctors) { 5508 auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority); 5509 CCR.CursorKind = getCursorKindForDecl(Ctor); 5510 Results.AddResult(CCR); 5511 } 5512 }; 5513 auto AddBase = [&](const CXXBaseSpecifier &Base) { 5514 const char *BaseName = 5515 Results.getAllocator().CopyString(Base.getType().getAsString(Policy)); 5516 const auto *RD = Base.getType()->getAsCXXRecordDecl(); 5517 AddCtorsWithName( 5518 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, 5519 BaseName, nullptr); 5520 }; 5521 auto AddField = [&](const FieldDecl *FD) { 5522 const char *FieldName = 5523 Results.getAllocator().CopyString(FD->getIdentifier()->getName()); 5524 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl(); 5525 AddCtorsWithName( 5526 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, 5527 FieldName, FD); 5528 }; 5529 5530 for (const auto &Base : ClassDecl->bases()) { 5531 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 5532 .second) { 5533 SawLastInitializer = 5534 !Initializers.empty() && Initializers.back()->isBaseInitializer() && 5535 Context.hasSameUnqualifiedType( 5536 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); 5537 continue; 5538 } 5539 5540 AddBase(Base); 5541 SawLastInitializer = false; 5542 } 5543 5544 // Add completions for virtual base classes. 5545 for (const auto &Base : ClassDecl->vbases()) { 5546 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 5547 .second) { 5548 SawLastInitializer = 5549 !Initializers.empty() && Initializers.back()->isBaseInitializer() && 5550 Context.hasSameUnqualifiedType( 5551 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); 5552 continue; 5553 } 5554 5555 AddBase(Base); 5556 SawLastInitializer = false; 5557 } 5558 5559 // Add completions for members. 5560 for (auto *Field : ClassDecl->fields()) { 5561 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl())) 5562 .second) { 5563 SawLastInitializer = !Initializers.empty() && 5564 Initializers.back()->isAnyMemberInitializer() && 5565 Initializers.back()->getAnyMember() == Field; 5566 continue; 5567 } 5568 5569 if (!Field->getDeclName()) 5570 continue; 5571 5572 AddField(Field); 5573 SawLastInitializer = false; 5574 } 5575 Results.ExitScope(); 5576 5577 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5578 Results.data(), Results.size()); 5579 } 5580 5581 /// Determine whether this scope denotes a namespace. 5582 static bool isNamespaceScope(Scope *S) { 5583 DeclContext *DC = S->getEntity(); 5584 if (!DC) 5585 return false; 5586 5587 return DC->isFileContext(); 5588 } 5589 5590 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 5591 bool AfterAmpersand) { 5592 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5593 CodeCompleter->getCodeCompletionTUInfo(), 5594 CodeCompletionContext::CCC_Other); 5595 Results.EnterNewScope(); 5596 5597 // Note what has already been captured. 5598 llvm::SmallPtrSet<IdentifierInfo *, 4> Known; 5599 bool IncludedThis = false; 5600 for (const auto &C : Intro.Captures) { 5601 if (C.Kind == LCK_This) { 5602 IncludedThis = true; 5603 continue; 5604 } 5605 5606 Known.insert(C.Id); 5607 } 5608 5609 // Look for other capturable variables. 5610 for (; S && !isNamespaceScope(S); S = S->getParent()) { 5611 for (const auto *D : S->decls()) { 5612 const auto *Var = dyn_cast<VarDecl>(D); 5613 if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>()) 5614 continue; 5615 5616 if (Known.insert(Var->getIdentifier()).second) 5617 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration), 5618 CurContext, nullptr, false); 5619 } 5620 } 5621 5622 // Add 'this', if it would be valid. 5623 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy) 5624 addThisCompletion(*this, Results); 5625 5626 Results.ExitScope(); 5627 5628 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5629 Results.data(), Results.size()); 5630 } 5631 5632 /// Macro that optionally prepends an "@" to the string literal passed in via 5633 /// Keyword, depending on whether NeedAt is true or false. 5634 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword) 5635 5636 static void AddObjCImplementationResults(const LangOptions &LangOpts, 5637 ResultBuilder &Results, bool NeedAt) { 5638 typedef CodeCompletionResult Result; 5639 // Since we have an implementation, we can end it. 5640 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end"))); 5641 5642 CodeCompletionBuilder Builder(Results.getAllocator(), 5643 Results.getCodeCompletionTUInfo()); 5644 if (LangOpts.ObjC) { 5645 // @dynamic 5646 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic")); 5647 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5648 Builder.AddPlaceholderChunk("property"); 5649 Results.AddResult(Result(Builder.TakeString())); 5650 5651 // @synthesize 5652 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize")); 5653 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5654 Builder.AddPlaceholderChunk("property"); 5655 Results.AddResult(Result(Builder.TakeString())); 5656 } 5657 } 5658 5659 static void AddObjCInterfaceResults(const LangOptions &LangOpts, 5660 ResultBuilder &Results, bool NeedAt) { 5661 typedef CodeCompletionResult Result; 5662 5663 // Since we have an interface or protocol, we can end it. 5664 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end"))); 5665 5666 if (LangOpts.ObjC) { 5667 // @property 5668 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property"))); 5669 5670 // @required 5671 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required"))); 5672 5673 // @optional 5674 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional"))); 5675 } 5676 } 5677 5678 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { 5679 typedef CodeCompletionResult Result; 5680 CodeCompletionBuilder Builder(Results.getAllocator(), 5681 Results.getCodeCompletionTUInfo()); 5682 5683 // @class name ; 5684 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class")); 5685 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5686 Builder.AddPlaceholderChunk("name"); 5687 Results.AddResult(Result(Builder.TakeString())); 5688 5689 if (Results.includeCodePatterns()) { 5690 // @interface name 5691 // FIXME: Could introduce the whole pattern, including superclasses and 5692 // such. 5693 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface")); 5694 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5695 Builder.AddPlaceholderChunk("class"); 5696 Results.AddResult(Result(Builder.TakeString())); 5697 5698 // @protocol name 5699 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")); 5700 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5701 Builder.AddPlaceholderChunk("protocol"); 5702 Results.AddResult(Result(Builder.TakeString())); 5703 5704 // @implementation name 5705 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation")); 5706 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5707 Builder.AddPlaceholderChunk("class"); 5708 Results.AddResult(Result(Builder.TakeString())); 5709 } 5710 5711 // @compatibility_alias name 5712 Builder.AddTypedTextChunk( 5713 OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias")); 5714 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5715 Builder.AddPlaceholderChunk("alias"); 5716 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5717 Builder.AddPlaceholderChunk("class"); 5718 Results.AddResult(Result(Builder.TakeString())); 5719 5720 if (Results.getSema().getLangOpts().Modules) { 5721 // @import name 5722 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import")); 5723 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5724 Builder.AddPlaceholderChunk("module"); 5725 Results.AddResult(Result(Builder.TakeString())); 5726 } 5727 } 5728 5729 void Sema::CodeCompleteObjCAtDirective(Scope *S) { 5730 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5731 CodeCompleter->getCodeCompletionTUInfo(), 5732 CodeCompletionContext::CCC_Other); 5733 Results.EnterNewScope(); 5734 if (isa<ObjCImplDecl>(CurContext)) 5735 AddObjCImplementationResults(getLangOpts(), Results, false); 5736 else if (CurContext->isObjCContainer()) 5737 AddObjCInterfaceResults(getLangOpts(), Results, false); 5738 else 5739 AddObjCTopLevelResults(Results, false); 5740 Results.ExitScope(); 5741 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5742 Results.data(), Results.size()); 5743 } 5744 5745 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { 5746 typedef CodeCompletionResult Result; 5747 CodeCompletionBuilder Builder(Results.getAllocator(), 5748 Results.getCodeCompletionTUInfo()); 5749 5750 // @encode ( type-name ) 5751 const char *EncodeType = "char[]"; 5752 if (Results.getSema().getLangOpts().CPlusPlus || 5753 Results.getSema().getLangOpts().ConstStrings) 5754 EncodeType = "const char[]"; 5755 Builder.AddResultTypeChunk(EncodeType); 5756 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode")); 5757 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5758 Builder.AddPlaceholderChunk("type-name"); 5759 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5760 Results.AddResult(Result(Builder.TakeString())); 5761 5762 // @protocol ( protocol-name ) 5763 Builder.AddResultTypeChunk("Protocol *"); 5764 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")); 5765 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5766 Builder.AddPlaceholderChunk("protocol-name"); 5767 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5768 Results.AddResult(Result(Builder.TakeString())); 5769 5770 // @selector ( selector ) 5771 Builder.AddResultTypeChunk("SEL"); 5772 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector")); 5773 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5774 Builder.AddPlaceholderChunk("selector"); 5775 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5776 Results.AddResult(Result(Builder.TakeString())); 5777 5778 // @"string" 5779 Builder.AddResultTypeChunk("NSString *"); 5780 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\"")); 5781 Builder.AddPlaceholderChunk("string"); 5782 Builder.AddTextChunk("\""); 5783 Results.AddResult(Result(Builder.TakeString())); 5784 5785 // @[objects, ...] 5786 Builder.AddResultTypeChunk("NSArray *"); 5787 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "[")); 5788 Builder.AddPlaceholderChunk("objects, ..."); 5789 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 5790 Results.AddResult(Result(Builder.TakeString())); 5791 5792 // @{key : object, ...} 5793 Builder.AddResultTypeChunk("NSDictionary *"); 5794 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{")); 5795 Builder.AddPlaceholderChunk("key"); 5796 Builder.AddChunk(CodeCompletionString::CK_Colon); 5797 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5798 Builder.AddPlaceholderChunk("object, ..."); 5799 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5800 Results.AddResult(Result(Builder.TakeString())); 5801 5802 // @(expression) 5803 Builder.AddResultTypeChunk("id"); 5804 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "(")); 5805 Builder.AddPlaceholderChunk("expression"); 5806 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5807 Results.AddResult(Result(Builder.TakeString())); 5808 } 5809 5810 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { 5811 typedef CodeCompletionResult Result; 5812 CodeCompletionBuilder Builder(Results.getAllocator(), 5813 Results.getCodeCompletionTUInfo()); 5814 5815 if (Results.includeCodePatterns()) { 5816 // @try { statements } @catch ( declaration ) { statements } @finally 5817 // { statements } 5818 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try")); 5819 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5820 Builder.AddPlaceholderChunk("statements"); 5821 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5822 Builder.AddTextChunk("@catch"); 5823 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5824 Builder.AddPlaceholderChunk("parameter"); 5825 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5826 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5827 Builder.AddPlaceholderChunk("statements"); 5828 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5829 Builder.AddTextChunk("@finally"); 5830 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5831 Builder.AddPlaceholderChunk("statements"); 5832 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5833 Results.AddResult(Result(Builder.TakeString())); 5834 } 5835 5836 // @throw 5837 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw")); 5838 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5839 Builder.AddPlaceholderChunk("expression"); 5840 Results.AddResult(Result(Builder.TakeString())); 5841 5842 if (Results.includeCodePatterns()) { 5843 // @synchronized ( expression ) { statements } 5844 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized")); 5845 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5846 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5847 Builder.AddPlaceholderChunk("expression"); 5848 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5849 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5850 Builder.AddPlaceholderChunk("statements"); 5851 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5852 Results.AddResult(Result(Builder.TakeString())); 5853 } 5854 } 5855 5856 static void AddObjCVisibilityResults(const LangOptions &LangOpts, 5857 ResultBuilder &Results, bool NeedAt) { 5858 typedef CodeCompletionResult Result; 5859 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private"))); 5860 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected"))); 5861 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public"))); 5862 if (LangOpts.ObjC) 5863 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package"))); 5864 } 5865 5866 void Sema::CodeCompleteObjCAtVisibility(Scope *S) { 5867 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5868 CodeCompleter->getCodeCompletionTUInfo(), 5869 CodeCompletionContext::CCC_Other); 5870 Results.EnterNewScope(); 5871 AddObjCVisibilityResults(getLangOpts(), Results, false); 5872 Results.ExitScope(); 5873 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5874 Results.data(), Results.size()); 5875 } 5876 5877 void Sema::CodeCompleteObjCAtStatement(Scope *S) { 5878 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5879 CodeCompleter->getCodeCompletionTUInfo(), 5880 CodeCompletionContext::CCC_Other); 5881 Results.EnterNewScope(); 5882 AddObjCStatementResults(Results, false); 5883 AddObjCExpressionResults(Results, false); 5884 Results.ExitScope(); 5885 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5886 Results.data(), Results.size()); 5887 } 5888 5889 void Sema::CodeCompleteObjCAtExpression(Scope *S) { 5890 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5891 CodeCompleter->getCodeCompletionTUInfo(), 5892 CodeCompletionContext::CCC_Other); 5893 Results.EnterNewScope(); 5894 AddObjCExpressionResults(Results, false); 5895 Results.ExitScope(); 5896 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5897 Results.data(), Results.size()); 5898 } 5899 5900 /// Determine whether the addition of the given flag to an Objective-C 5901 /// property's attributes will cause a conflict. 5902 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { 5903 // Check if we've already added this flag. 5904 if (Attributes & NewFlag) 5905 return true; 5906 5907 Attributes |= NewFlag; 5908 5909 // Check for collisions with "readonly". 5910 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && 5911 (Attributes & ObjCDeclSpec::DQ_PR_readwrite)) 5912 return true; 5913 5914 // Check for more than one of { assign, copy, retain, strong, weak }. 5915 unsigned AssignCopyRetMask = 5916 Attributes & 5917 (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_unsafe_unretained | 5918 ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain | 5919 ObjCDeclSpec::DQ_PR_strong | ObjCDeclSpec::DQ_PR_weak); 5920 if (AssignCopyRetMask && AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign && 5921 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained && 5922 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy && 5923 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain && 5924 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong && 5925 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak) 5926 return true; 5927 5928 return false; 5929 } 5930 5931 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { 5932 if (!CodeCompleter) 5933 return; 5934 5935 unsigned Attributes = ODS.getPropertyAttributes(); 5936 5937 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5938 CodeCompleter->getCodeCompletionTUInfo(), 5939 CodeCompletionContext::CCC_Other); 5940 Results.EnterNewScope(); 5941 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly)) 5942 Results.AddResult(CodeCompletionResult("readonly")); 5943 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign)) 5944 Results.AddResult(CodeCompletionResult("assign")); 5945 if (!ObjCPropertyFlagConflicts(Attributes, 5946 ObjCDeclSpec::DQ_PR_unsafe_unretained)) 5947 Results.AddResult(CodeCompletionResult("unsafe_unretained")); 5948 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite)) 5949 Results.AddResult(CodeCompletionResult("readwrite")); 5950 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain)) 5951 Results.AddResult(CodeCompletionResult("retain")); 5952 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong)) 5953 Results.AddResult(CodeCompletionResult("strong")); 5954 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy)) 5955 Results.AddResult(CodeCompletionResult("copy")); 5956 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic)) 5957 Results.AddResult(CodeCompletionResult("nonatomic")); 5958 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic)) 5959 Results.AddResult(CodeCompletionResult("atomic")); 5960 5961 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC. 5962 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC) 5963 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak)) 5964 Results.AddResult(CodeCompletionResult("weak")); 5965 5966 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) { 5967 CodeCompletionBuilder Setter(Results.getAllocator(), 5968 Results.getCodeCompletionTUInfo()); 5969 Setter.AddTypedTextChunk("setter"); 5970 Setter.AddTextChunk("="); 5971 Setter.AddPlaceholderChunk("method"); 5972 Results.AddResult(CodeCompletionResult(Setter.TakeString())); 5973 } 5974 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) { 5975 CodeCompletionBuilder Getter(Results.getAllocator(), 5976 Results.getCodeCompletionTUInfo()); 5977 Getter.AddTypedTextChunk("getter"); 5978 Getter.AddTextChunk("="); 5979 Getter.AddPlaceholderChunk("method"); 5980 Results.AddResult(CodeCompletionResult(Getter.TakeString())); 5981 } 5982 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) { 5983 Results.AddResult(CodeCompletionResult("nonnull")); 5984 Results.AddResult(CodeCompletionResult("nullable")); 5985 Results.AddResult(CodeCompletionResult("null_unspecified")); 5986 Results.AddResult(CodeCompletionResult("null_resettable")); 5987 } 5988 Results.ExitScope(); 5989 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5990 Results.data(), Results.size()); 5991 } 5992 5993 /// Describes the kind of Objective-C method that we want to find 5994 /// via code completion. 5995 enum ObjCMethodKind { 5996 MK_Any, ///< Any kind of method, provided it means other specified criteria. 5997 MK_ZeroArgSelector, ///< Zero-argument (unary) selector. 5998 MK_OneArgSelector ///< One-argument selector. 5999 }; 6000 6001 static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind, 6002 ArrayRef<IdentifierInfo *> SelIdents, 6003 bool AllowSameLength = true) { 6004 unsigned NumSelIdents = SelIdents.size(); 6005 if (NumSelIdents > Sel.getNumArgs()) 6006 return false; 6007 6008 switch (WantKind) { 6009 case MK_Any: 6010 break; 6011 case MK_ZeroArgSelector: 6012 return Sel.isUnarySelector(); 6013 case MK_OneArgSelector: 6014 return Sel.getNumArgs() == 1; 6015 } 6016 6017 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) 6018 return false; 6019 6020 for (unsigned I = 0; I != NumSelIdents; ++I) 6021 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) 6022 return false; 6023 6024 return true; 6025 } 6026 6027 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, 6028 ObjCMethodKind WantKind, 6029 ArrayRef<IdentifierInfo *> SelIdents, 6030 bool AllowSameLength = true) { 6031 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents, 6032 AllowSameLength); 6033 } 6034 6035 /// A set of selectors, which is used to avoid introducing multiple 6036 /// completions with the same selector into the result set. 6037 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; 6038 6039 /// Add all of the Objective-C methods in the given Objective-C 6040 /// container to the set of results. 6041 /// 6042 /// The container will be a class, protocol, category, or implementation of 6043 /// any of the above. This mether will recurse to include methods from 6044 /// the superclasses of classes along with their categories, protocols, and 6045 /// implementations. 6046 /// 6047 /// \param Container the container in which we'll look to find methods. 6048 /// 6049 /// \param WantInstanceMethods Whether to add instance methods (only); if 6050 /// false, this routine will add factory methods (only). 6051 /// 6052 /// \param CurContext the context in which we're performing the lookup that 6053 /// finds methods. 6054 /// 6055 /// \param AllowSameLength Whether we allow a method to be added to the list 6056 /// when it has the same number of parameters as we have selector identifiers. 6057 /// 6058 /// \param Results the structure into which we'll add results. 6059 static void AddObjCMethods(ObjCContainerDecl *Container, 6060 bool WantInstanceMethods, ObjCMethodKind WantKind, 6061 ArrayRef<IdentifierInfo *> SelIdents, 6062 DeclContext *CurContext, 6063 VisitedSelectorSet &Selectors, bool AllowSameLength, 6064 ResultBuilder &Results, bool InOriginalClass = true, 6065 bool IsRootClass = false) { 6066 typedef CodeCompletionResult Result; 6067 Container = getContainerDef(Container); 6068 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container); 6069 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass()); 6070 for (ObjCMethodDecl *M : Container->methods()) { 6071 // The instance methods on the root class can be messaged via the 6072 // metaclass. 6073 if (M->isInstanceMethod() == WantInstanceMethods || 6074 (IsRootClass && !WantInstanceMethods)) { 6075 // Check whether the selector identifiers we've been given are a 6076 // subset of the identifiers for this particular method. 6077 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength)) 6078 continue; 6079 6080 if (!Selectors.insert(M->getSelector()).second) 6081 continue; 6082 6083 Result R = Result(M, Results.getBasePriority(M), nullptr); 6084 R.StartParameter = SelIdents.size(); 6085 R.AllParametersAreInformative = (WantKind != MK_Any); 6086 if (!InOriginalClass) 6087 setInBaseClass(R); 6088 Results.MaybeAddResult(R, CurContext); 6089 } 6090 } 6091 6092 // Visit the protocols of protocols. 6093 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 6094 if (Protocol->hasDefinition()) { 6095 const ObjCList<ObjCProtocolDecl> &Protocols = 6096 Protocol->getReferencedProtocols(); 6097 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6098 E = Protocols.end(); 6099 I != E; ++I) 6100 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 6101 Selectors, AllowSameLength, Results, false, IsRootClass); 6102 } 6103 } 6104 6105 if (!IFace || !IFace->hasDefinition()) 6106 return; 6107 6108 // Add methods in protocols. 6109 for (ObjCProtocolDecl *I : IFace->protocols()) 6110 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext, 6111 Selectors, AllowSameLength, Results, false, IsRootClass); 6112 6113 // Add methods in categories. 6114 for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) { 6115 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, 6116 CurContext, Selectors, AllowSameLength, Results, 6117 InOriginalClass, IsRootClass); 6118 6119 // Add a categories protocol methods. 6120 const ObjCList<ObjCProtocolDecl> &Protocols = 6121 CatDecl->getReferencedProtocols(); 6122 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6123 E = Protocols.end(); 6124 I != E; ++I) 6125 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 6126 Selectors, AllowSameLength, Results, false, IsRootClass); 6127 6128 // Add methods in category implementations. 6129 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) 6130 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 6131 Selectors, AllowSameLength, Results, InOriginalClass, 6132 IsRootClass); 6133 } 6134 6135 // Add methods in superclass. 6136 // Avoid passing in IsRootClass since root classes won't have super classes. 6137 if (IFace->getSuperClass()) 6138 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, 6139 SelIdents, CurContext, Selectors, AllowSameLength, Results, 6140 /*IsRootClass=*/false); 6141 6142 // Add methods in our implementation, if any. 6143 if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 6144 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 6145 Selectors, AllowSameLength, Results, InOriginalClass, 6146 IsRootClass); 6147 } 6148 6149 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) { 6150 // Try to find the interface where getters might live. 6151 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 6152 if (!Class) { 6153 if (ObjCCategoryDecl *Category = 6154 dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 6155 Class = Category->getClassInterface(); 6156 6157 if (!Class) 6158 return; 6159 } 6160 6161 // Find all of the potential getters. 6162 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6163 CodeCompleter->getCodeCompletionTUInfo(), 6164 CodeCompletionContext::CCC_Other); 6165 Results.EnterNewScope(); 6166 6167 VisitedSelectorSet Selectors; 6168 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors, 6169 /*AllowSameLength=*/true, Results); 6170 Results.ExitScope(); 6171 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6172 Results.data(), Results.size()); 6173 } 6174 6175 void Sema::CodeCompleteObjCPropertySetter(Scope *S) { 6176 // Try to find the interface where setters might live. 6177 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 6178 if (!Class) { 6179 if (ObjCCategoryDecl *Category = 6180 dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 6181 Class = Category->getClassInterface(); 6182 6183 if (!Class) 6184 return; 6185 } 6186 6187 // Find all of the potential getters. 6188 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6189 CodeCompleter->getCodeCompletionTUInfo(), 6190 CodeCompletionContext::CCC_Other); 6191 Results.EnterNewScope(); 6192 6193 VisitedSelectorSet Selectors; 6194 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext, Selectors, 6195 /*AllowSameLength=*/true, Results); 6196 6197 Results.ExitScope(); 6198 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6199 Results.data(), Results.size()); 6200 } 6201 6202 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 6203 bool IsParameter) { 6204 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6205 CodeCompleter->getCodeCompletionTUInfo(), 6206 CodeCompletionContext::CCC_Type); 6207 Results.EnterNewScope(); 6208 6209 // Add context-sensitive, Objective-C parameter-passing keywords. 6210 bool AddedInOut = false; 6211 if ((DS.getObjCDeclQualifier() & 6212 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { 6213 Results.AddResult("in"); 6214 Results.AddResult("inout"); 6215 AddedInOut = true; 6216 } 6217 if ((DS.getObjCDeclQualifier() & 6218 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { 6219 Results.AddResult("out"); 6220 if (!AddedInOut) 6221 Results.AddResult("inout"); 6222 } 6223 if ((DS.getObjCDeclQualifier() & 6224 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | 6225 ObjCDeclSpec::DQ_Oneway)) == 0) { 6226 Results.AddResult("bycopy"); 6227 Results.AddResult("byref"); 6228 Results.AddResult("oneway"); 6229 } 6230 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) { 6231 Results.AddResult("nonnull"); 6232 Results.AddResult("nullable"); 6233 Results.AddResult("null_unspecified"); 6234 } 6235 6236 // If we're completing the return type of an Objective-C method and the 6237 // identifier IBAction refers to a macro, provide a completion item for 6238 // an action, e.g., 6239 // IBAction)<#selector#>:(id)sender 6240 if (DS.getObjCDeclQualifier() == 0 && !IsParameter && 6241 PP.isMacroDefined("IBAction")) { 6242 CodeCompletionBuilder Builder(Results.getAllocator(), 6243 Results.getCodeCompletionTUInfo(), 6244 CCP_CodePattern, CXAvailability_Available); 6245 Builder.AddTypedTextChunk("IBAction"); 6246 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6247 Builder.AddPlaceholderChunk("selector"); 6248 Builder.AddChunk(CodeCompletionString::CK_Colon); 6249 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6250 Builder.AddTextChunk("id"); 6251 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6252 Builder.AddTextChunk("sender"); 6253 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 6254 } 6255 6256 // If we're completing the return type, provide 'instancetype'. 6257 if (!IsParameter) { 6258 Results.AddResult(CodeCompletionResult("instancetype")); 6259 } 6260 6261 // Add various builtin type names and specifiers. 6262 AddOrdinaryNameResults(PCC_Type, S, *this, Results); 6263 Results.ExitScope(); 6264 6265 // Add the various type names 6266 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 6267 CodeCompletionDeclConsumer Consumer(Results, CurContext); 6268 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 6269 CodeCompleter->includeGlobals(), 6270 CodeCompleter->loadExternal()); 6271 6272 if (CodeCompleter->includeMacros()) 6273 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 6274 6275 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6276 Results.data(), Results.size()); 6277 } 6278 6279 /// When we have an expression with type "id", we may assume 6280 /// that it has some more-specific class type based on knowledge of 6281 /// common uses of Objective-C. This routine returns that class type, 6282 /// or NULL if no better result could be determined. 6283 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { 6284 auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E); 6285 if (!Msg) 6286 return nullptr; 6287 6288 Selector Sel = Msg->getSelector(); 6289 if (Sel.isNull()) 6290 return nullptr; 6291 6292 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0); 6293 if (!Id) 6294 return nullptr; 6295 6296 ObjCMethodDecl *Method = Msg->getMethodDecl(); 6297 if (!Method) 6298 return nullptr; 6299 6300 // Determine the class that we're sending the message to. 6301 ObjCInterfaceDecl *IFace = nullptr; 6302 switch (Msg->getReceiverKind()) { 6303 case ObjCMessageExpr::Class: 6304 if (const ObjCObjectType *ObjType = 6305 Msg->getClassReceiver()->getAs<ObjCObjectType>()) 6306 IFace = ObjType->getInterface(); 6307 break; 6308 6309 case ObjCMessageExpr::Instance: { 6310 QualType T = Msg->getInstanceReceiver()->getType(); 6311 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) 6312 IFace = Ptr->getInterfaceDecl(); 6313 break; 6314 } 6315 6316 case ObjCMessageExpr::SuperInstance: 6317 case ObjCMessageExpr::SuperClass: 6318 break; 6319 } 6320 6321 if (!IFace) 6322 return nullptr; 6323 6324 ObjCInterfaceDecl *Super = IFace->getSuperClass(); 6325 if (Method->isInstanceMethod()) 6326 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 6327 .Case("retain", IFace) 6328 .Case("strong", IFace) 6329 .Case("autorelease", IFace) 6330 .Case("copy", IFace) 6331 .Case("copyWithZone", IFace) 6332 .Case("mutableCopy", IFace) 6333 .Case("mutableCopyWithZone", IFace) 6334 .Case("awakeFromCoder", IFace) 6335 .Case("replacementObjectFromCoder", IFace) 6336 .Case("class", IFace) 6337 .Case("classForCoder", IFace) 6338 .Case("superclass", Super) 6339 .Default(nullptr); 6340 6341 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 6342 .Case("new", IFace) 6343 .Case("alloc", IFace) 6344 .Case("allocWithZone", IFace) 6345 .Case("class", IFace) 6346 .Case("superclass", Super) 6347 .Default(nullptr); 6348 } 6349 6350 // Add a special completion for a message send to "super", which fills in the 6351 // most likely case of forwarding all of our arguments to the superclass 6352 // function. 6353 /// 6354 /// \param S The semantic analysis object. 6355 /// 6356 /// \param NeedSuperKeyword Whether we need to prefix this completion with 6357 /// the "super" keyword. Otherwise, we just need to provide the arguments. 6358 /// 6359 /// \param SelIdents The identifiers in the selector that have already been 6360 /// provided as arguments for a send to "super". 6361 /// 6362 /// \param Results The set of results to augment. 6363 /// 6364 /// \returns the Objective-C method declaration that would be invoked by 6365 /// this "super" completion. If NULL, no completion was added. 6366 static ObjCMethodDecl * 6367 AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword, 6368 ArrayRef<IdentifierInfo *> SelIdents, 6369 ResultBuilder &Results) { 6370 ObjCMethodDecl *CurMethod = S.getCurMethodDecl(); 6371 if (!CurMethod) 6372 return nullptr; 6373 6374 ObjCInterfaceDecl *Class = CurMethod->getClassInterface(); 6375 if (!Class) 6376 return nullptr; 6377 6378 // Try to find a superclass method with the same selector. 6379 ObjCMethodDecl *SuperMethod = nullptr; 6380 while ((Class = Class->getSuperClass()) && !SuperMethod) { 6381 // Check in the class 6382 SuperMethod = Class->getMethod(CurMethod->getSelector(), 6383 CurMethod->isInstanceMethod()); 6384 6385 // Check in categories or class extensions. 6386 if (!SuperMethod) { 6387 for (const auto *Cat : Class->known_categories()) { 6388 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(), 6389 CurMethod->isInstanceMethod()))) 6390 break; 6391 } 6392 } 6393 } 6394 6395 if (!SuperMethod) 6396 return nullptr; 6397 6398 // Check whether the superclass method has the same signature. 6399 if (CurMethod->param_size() != SuperMethod->param_size() || 6400 CurMethod->isVariadic() != SuperMethod->isVariadic()) 6401 return nullptr; 6402 6403 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(), 6404 CurPEnd = CurMethod->param_end(), 6405 SuperP = SuperMethod->param_begin(); 6406 CurP != CurPEnd; ++CurP, ++SuperP) { 6407 // Make sure the parameter types are compatible. 6408 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), 6409 (*SuperP)->getType())) 6410 return nullptr; 6411 6412 // Make sure we have a parameter name to forward! 6413 if (!(*CurP)->getIdentifier()) 6414 return nullptr; 6415 } 6416 6417 // We have a superclass method. Now, form the send-to-super completion. 6418 CodeCompletionBuilder Builder(Results.getAllocator(), 6419 Results.getCodeCompletionTUInfo()); 6420 6421 // Give this completion a return type. 6422 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod, 6423 Results.getCompletionContext().getBaseType(), Builder); 6424 6425 // If we need the "super" keyword, add it (plus some spacing). 6426 if (NeedSuperKeyword) { 6427 Builder.AddTypedTextChunk("super"); 6428 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6429 } 6430 6431 Selector Sel = CurMethod->getSelector(); 6432 if (Sel.isUnarySelector()) { 6433 if (NeedSuperKeyword) 6434 Builder.AddTextChunk( 6435 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 6436 else 6437 Builder.AddTypedTextChunk( 6438 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 6439 } else { 6440 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(); 6441 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { 6442 if (I > SelIdents.size()) 6443 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6444 6445 if (I < SelIdents.size()) 6446 Builder.AddInformativeChunk( 6447 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 6448 else if (NeedSuperKeyword || I > SelIdents.size()) { 6449 Builder.AddTextChunk( 6450 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 6451 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 6452 (*CurP)->getIdentifier()->getName())); 6453 } else { 6454 Builder.AddTypedTextChunk( 6455 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 6456 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 6457 (*CurP)->getIdentifier()->getName())); 6458 } 6459 } 6460 } 6461 6462 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod, 6463 CCP_SuperCompletion)); 6464 return SuperMethod; 6465 } 6466 6467 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) { 6468 typedef CodeCompletionResult Result; 6469 ResultBuilder Results( 6470 *this, CodeCompleter->getAllocator(), 6471 CodeCompleter->getCodeCompletionTUInfo(), 6472 CodeCompletionContext::CCC_ObjCMessageReceiver, 6473 getLangOpts().CPlusPlus11 6474 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture 6475 : &ResultBuilder::IsObjCMessageReceiver); 6476 6477 CodeCompletionDeclConsumer Consumer(Results, CurContext); 6478 Results.EnterNewScope(); 6479 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 6480 CodeCompleter->includeGlobals(), 6481 CodeCompleter->loadExternal()); 6482 6483 // If we are in an Objective-C method inside a class that has a superclass, 6484 // add "super" as an option. 6485 if (ObjCMethodDecl *Method = getCurMethodDecl()) 6486 if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) 6487 if (Iface->getSuperClass()) { 6488 Results.AddResult(Result("super")); 6489 6490 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results); 6491 } 6492 6493 if (getLangOpts().CPlusPlus11) 6494 addThisCompletion(*this, Results); 6495 6496 Results.ExitScope(); 6497 6498 if (CodeCompleter->includeMacros()) 6499 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 6500 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6501 Results.data(), Results.size()); 6502 } 6503 6504 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 6505 ArrayRef<IdentifierInfo *> SelIdents, 6506 bool AtArgumentExpression) { 6507 ObjCInterfaceDecl *CDecl = nullptr; 6508 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 6509 // Figure out which interface we're in. 6510 CDecl = CurMethod->getClassInterface(); 6511 if (!CDecl) 6512 return; 6513 6514 // Find the superclass of this class. 6515 CDecl = CDecl->getSuperClass(); 6516 if (!CDecl) 6517 return; 6518 6519 if (CurMethod->isInstanceMethod()) { 6520 // We are inside an instance method, which means that the message 6521 // send [super ...] is actually calling an instance method on the 6522 // current object. 6523 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents, 6524 AtArgumentExpression, CDecl); 6525 } 6526 6527 // Fall through to send to the superclass in CDecl. 6528 } else { 6529 // "super" may be the name of a type or variable. Figure out which 6530 // it is. 6531 IdentifierInfo *Super = getSuperIdentifier(); 6532 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, LookupOrdinaryName); 6533 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { 6534 // "super" names an interface. Use it. 6535 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) { 6536 if (const ObjCObjectType *Iface = 6537 Context.getTypeDeclType(TD)->getAs<ObjCObjectType>()) 6538 CDecl = Iface->getInterface(); 6539 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) { 6540 // "super" names an unresolved type; we can't be more specific. 6541 } else { 6542 // Assume that "super" names some kind of value and parse that way. 6543 CXXScopeSpec SS; 6544 SourceLocation TemplateKWLoc; 6545 UnqualifiedId id; 6546 id.setIdentifier(Super, SuperLoc); 6547 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id, 6548 /*HasTrailingLParen=*/false, 6549 /*IsAddressOfOperand=*/false); 6550 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(), 6551 SelIdents, AtArgumentExpression); 6552 } 6553 6554 // Fall through 6555 } 6556 6557 ParsedType Receiver; 6558 if (CDecl) 6559 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl)); 6560 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, 6561 AtArgumentExpression, 6562 /*IsSuper=*/true); 6563 } 6564 6565 /// Given a set of code-completion results for the argument of a message 6566 /// send, determine the preferred type (if any) for that argument expression. 6567 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, 6568 unsigned NumSelIdents) { 6569 typedef CodeCompletionResult Result; 6570 ASTContext &Context = Results.getSema().Context; 6571 6572 QualType PreferredType; 6573 unsigned BestPriority = CCP_Unlikely * 2; 6574 Result *ResultsData = Results.data(); 6575 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 6576 Result &R = ResultsData[I]; 6577 if (R.Kind == Result::RK_Declaration && 6578 isa<ObjCMethodDecl>(R.Declaration)) { 6579 if (R.Priority <= BestPriority) { 6580 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration); 6581 if (NumSelIdents <= Method->param_size()) { 6582 QualType MyPreferredType = 6583 Method->parameters()[NumSelIdents - 1]->getType(); 6584 if (R.Priority < BestPriority || PreferredType.isNull()) { 6585 BestPriority = R.Priority; 6586 PreferredType = MyPreferredType; 6587 } else if (!Context.hasSameUnqualifiedType(PreferredType, 6588 MyPreferredType)) { 6589 PreferredType = QualType(); 6590 } 6591 } 6592 } 6593 } 6594 } 6595 6596 return PreferredType; 6597 } 6598 6599 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 6600 ParsedType Receiver, 6601 ArrayRef<IdentifierInfo *> SelIdents, 6602 bool AtArgumentExpression, bool IsSuper, 6603 ResultBuilder &Results) { 6604 typedef CodeCompletionResult Result; 6605 ObjCInterfaceDecl *CDecl = nullptr; 6606 6607 // If the given name refers to an interface type, retrieve the 6608 // corresponding declaration. 6609 if (Receiver) { 6610 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr); 6611 if (!T.isNull()) 6612 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) 6613 CDecl = Interface->getInterface(); 6614 } 6615 6616 // Add all of the factory methods in this Objective-C class, its protocols, 6617 // superclasses, categories, implementation, etc. 6618 Results.EnterNewScope(); 6619 6620 // If this is a send-to-super, try to add the special "super" send 6621 // completion. 6622 if (IsSuper) { 6623 if (ObjCMethodDecl *SuperMethod = 6624 AddSuperSendCompletion(SemaRef, false, SelIdents, Results)) 6625 Results.Ignore(SuperMethod); 6626 } 6627 6628 // If we're inside an Objective-C method definition, prefer its selector to 6629 // others. 6630 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) 6631 Results.setPreferredSelector(CurMethod->getSelector()); 6632 6633 VisitedSelectorSet Selectors; 6634 if (CDecl) 6635 AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext, 6636 Selectors, AtArgumentExpression, Results); 6637 else { 6638 // We're messaging "id" as a type; provide all class/factory methods. 6639 6640 // If we have an external source, load the entire class method 6641 // pool from the AST file. 6642 if (SemaRef.getExternalSource()) { 6643 for (uint32_t I = 0, 6644 N = SemaRef.getExternalSource()->GetNumExternalSelectors(); 6645 I != N; ++I) { 6646 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I); 6647 if (Sel.isNull() || SemaRef.MethodPool.count(Sel)) 6648 continue; 6649 6650 SemaRef.ReadMethodPool(Sel); 6651 } 6652 } 6653 6654 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(), 6655 MEnd = SemaRef.MethodPool.end(); 6656 M != MEnd; ++M) { 6657 for (ObjCMethodList *MethList = &M->second.second; 6658 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 6659 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 6660 continue; 6661 6662 Result R(MethList->getMethod(), 6663 Results.getBasePriority(MethList->getMethod()), nullptr); 6664 R.StartParameter = SelIdents.size(); 6665 R.AllParametersAreInformative = false; 6666 Results.MaybeAddResult(R, SemaRef.CurContext); 6667 } 6668 } 6669 } 6670 6671 Results.ExitScope(); 6672 } 6673 6674 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 6675 ArrayRef<IdentifierInfo *> SelIdents, 6676 bool AtArgumentExpression, 6677 bool IsSuper) { 6678 6679 QualType T = this->GetTypeFromParser(Receiver); 6680 6681 ResultBuilder Results( 6682 *this, CodeCompleter->getAllocator(), 6683 CodeCompleter->getCodeCompletionTUInfo(), 6684 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T, 6685 SelIdents)); 6686 6687 AddClassMessageCompletions(*this, S, Receiver, SelIdents, 6688 AtArgumentExpression, IsSuper, Results); 6689 6690 // If we're actually at the argument expression (rather than prior to the 6691 // selector), we're actually performing code completion for an expression. 6692 // Determine whether we have a single, best method. If so, we can 6693 // code-complete the expression using the corresponding parameter type as 6694 // our preferred type, improving completion results. 6695 if (AtArgumentExpression) { 6696 QualType PreferredType = 6697 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); 6698 if (PreferredType.isNull()) 6699 CodeCompleteOrdinaryName(S, PCC_Expression); 6700 else 6701 CodeCompleteExpression(S, PreferredType); 6702 return; 6703 } 6704 6705 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6706 Results.data(), Results.size()); 6707 } 6708 6709 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 6710 ArrayRef<IdentifierInfo *> SelIdents, 6711 bool AtArgumentExpression, 6712 ObjCInterfaceDecl *Super) { 6713 typedef CodeCompletionResult Result; 6714 6715 Expr *RecExpr = static_cast<Expr *>(Receiver); 6716 6717 // If necessary, apply function/array conversion to the receiver. 6718 // C99 6.7.5.3p[7,8]. 6719 if (RecExpr) { 6720 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr); 6721 if (Conv.isInvalid()) // conversion failed. bail. 6722 return; 6723 RecExpr = Conv.get(); 6724 } 6725 QualType ReceiverType = RecExpr 6726 ? RecExpr->getType() 6727 : Super ? Context.getObjCObjectPointerType( 6728 Context.getObjCInterfaceType(Super)) 6729 : Context.getObjCIdType(); 6730 6731 // If we're messaging an expression with type "id" or "Class", check 6732 // whether we know something special about the receiver that allows 6733 // us to assume a more-specific receiver type. 6734 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) { 6735 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) { 6736 if (ReceiverType->isObjCClassType()) 6737 return CodeCompleteObjCClassMessage( 6738 S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents, 6739 AtArgumentExpression, Super); 6740 6741 ReceiverType = 6742 Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace)); 6743 } 6744 } else if (RecExpr && getLangOpts().CPlusPlus) { 6745 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr); 6746 if (Conv.isUsable()) { 6747 RecExpr = Conv.get(); 6748 ReceiverType = RecExpr->getType(); 6749 } 6750 } 6751 6752 // Build the set of methods we can see. 6753 ResultBuilder Results( 6754 *this, CodeCompleter->getAllocator(), 6755 CodeCompleter->getCodeCompletionTUInfo(), 6756 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage, 6757 ReceiverType, SelIdents)); 6758 6759 Results.EnterNewScope(); 6760 6761 // If this is a send-to-super, try to add the special "super" send 6762 // completion. 6763 if (Super) { 6764 if (ObjCMethodDecl *SuperMethod = 6765 AddSuperSendCompletion(*this, false, SelIdents, Results)) 6766 Results.Ignore(SuperMethod); 6767 } 6768 6769 // If we're inside an Objective-C method definition, prefer its selector to 6770 // others. 6771 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) 6772 Results.setPreferredSelector(CurMethod->getSelector()); 6773 6774 // Keep track of the selectors we've already added. 6775 VisitedSelectorSet Selectors; 6776 6777 // Handle messages to Class. This really isn't a message to an instance 6778 // method, so we treat it the same way we would treat a message send to a 6779 // class method. 6780 if (ReceiverType->isObjCClassType() || 6781 ReceiverType->isObjCQualifiedClassType()) { 6782 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 6783 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) 6784 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext, 6785 Selectors, AtArgumentExpression, Results); 6786 } 6787 } 6788 // Handle messages to a qualified ID ("id<foo>"). 6789 else if (const ObjCObjectPointerType *QualID = 6790 ReceiverType->getAsObjCQualifiedIdType()) { 6791 // Search protocols for instance methods. 6792 for (auto *I : QualID->quals()) 6793 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors, 6794 AtArgumentExpression, Results); 6795 } 6796 // Handle messages to a pointer to interface type. 6797 else if (const ObjCObjectPointerType *IFacePtr = 6798 ReceiverType->getAsObjCInterfacePointerType()) { 6799 // Search the class, its superclasses, etc., for instance methods. 6800 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, 6801 CurContext, Selectors, AtArgumentExpression, Results); 6802 6803 // Search protocols for instance methods. 6804 for (auto *I : IFacePtr->quals()) 6805 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors, 6806 AtArgumentExpression, Results); 6807 } 6808 // Handle messages to "id". 6809 else if (ReceiverType->isObjCIdType()) { 6810 // We're messaging "id", so provide all instance methods we know 6811 // about as code-completion results. 6812 6813 // If we have an external source, load the entire class method 6814 // pool from the AST file. 6815 if (ExternalSource) { 6816 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 6817 I != N; ++I) { 6818 Selector Sel = ExternalSource->GetExternalSelector(I); 6819 if (Sel.isNull() || MethodPool.count(Sel)) 6820 continue; 6821 6822 ReadMethodPool(Sel); 6823 } 6824 } 6825 6826 for (GlobalMethodPool::iterator M = MethodPool.begin(), 6827 MEnd = MethodPool.end(); 6828 M != MEnd; ++M) { 6829 for (ObjCMethodList *MethList = &M->second.first; 6830 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 6831 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 6832 continue; 6833 6834 if (!Selectors.insert(MethList->getMethod()->getSelector()).second) 6835 continue; 6836 6837 Result R(MethList->getMethod(), 6838 Results.getBasePriority(MethList->getMethod()), nullptr); 6839 R.StartParameter = SelIdents.size(); 6840 R.AllParametersAreInformative = false; 6841 Results.MaybeAddResult(R, CurContext); 6842 } 6843 } 6844 } 6845 Results.ExitScope(); 6846 6847 // If we're actually at the argument expression (rather than prior to the 6848 // selector), we're actually performing code completion for an expression. 6849 // Determine whether we have a single, best method. If so, we can 6850 // code-complete the expression using the corresponding parameter type as 6851 // our preferred type, improving completion results. 6852 if (AtArgumentExpression) { 6853 QualType PreferredType = 6854 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); 6855 if (PreferredType.isNull()) 6856 CodeCompleteOrdinaryName(S, PCC_Expression); 6857 else 6858 CodeCompleteExpression(S, PreferredType); 6859 return; 6860 } 6861 6862 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6863 Results.data(), Results.size()); 6864 } 6865 6866 void Sema::CodeCompleteObjCForCollection(Scope *S, 6867 DeclGroupPtrTy IterationVar) { 6868 CodeCompleteExpressionData Data; 6869 Data.ObjCCollection = true; 6870 6871 if (IterationVar.getAsOpaquePtr()) { 6872 DeclGroupRef DG = IterationVar.get(); 6873 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { 6874 if (*I) 6875 Data.IgnoreDecls.push_back(*I); 6876 } 6877 } 6878 6879 CodeCompleteExpression(S, Data); 6880 } 6881 6882 void Sema::CodeCompleteObjCSelector(Scope *S, 6883 ArrayRef<IdentifierInfo *> SelIdents) { 6884 // If we have an external source, load the entire class method 6885 // pool from the AST file. 6886 if (ExternalSource) { 6887 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N; 6888 ++I) { 6889 Selector Sel = ExternalSource->GetExternalSelector(I); 6890 if (Sel.isNull() || MethodPool.count(Sel)) 6891 continue; 6892 6893 ReadMethodPool(Sel); 6894 } 6895 } 6896 6897 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6898 CodeCompleter->getCodeCompletionTUInfo(), 6899 CodeCompletionContext::CCC_SelectorName); 6900 Results.EnterNewScope(); 6901 for (GlobalMethodPool::iterator M = MethodPool.begin(), 6902 MEnd = MethodPool.end(); 6903 M != MEnd; ++M) { 6904 6905 Selector Sel = M->first; 6906 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents)) 6907 continue; 6908 6909 CodeCompletionBuilder Builder(Results.getAllocator(), 6910 Results.getCodeCompletionTUInfo()); 6911 if (Sel.isUnarySelector()) { 6912 Builder.AddTypedTextChunk( 6913 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 6914 Results.AddResult(Builder.TakeString()); 6915 continue; 6916 } 6917 6918 std::string Accumulator; 6919 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { 6920 if (I == SelIdents.size()) { 6921 if (!Accumulator.empty()) { 6922 Builder.AddInformativeChunk( 6923 Builder.getAllocator().CopyString(Accumulator)); 6924 Accumulator.clear(); 6925 } 6926 } 6927 6928 Accumulator += Sel.getNameForSlot(I); 6929 Accumulator += ':'; 6930 } 6931 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator)); 6932 Results.AddResult(Builder.TakeString()); 6933 } 6934 Results.ExitScope(); 6935 6936 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6937 Results.data(), Results.size()); 6938 } 6939 6940 /// Add all of the protocol declarations that we find in the given 6941 /// (translation unit) context. 6942 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, 6943 bool OnlyForwardDeclarations, 6944 ResultBuilder &Results) { 6945 typedef CodeCompletionResult Result; 6946 6947 for (const auto *D : Ctx->decls()) { 6948 // Record any protocols we find. 6949 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D)) 6950 if (!OnlyForwardDeclarations || !Proto->hasDefinition()) 6951 Results.AddResult( 6952 Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext, 6953 nullptr, false); 6954 } 6955 } 6956 6957 void Sema::CodeCompleteObjCProtocolReferences( 6958 ArrayRef<IdentifierLocPair> Protocols) { 6959 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6960 CodeCompleter->getCodeCompletionTUInfo(), 6961 CodeCompletionContext::CCC_ObjCProtocolName); 6962 6963 if (CodeCompleter->includeGlobals()) { 6964 Results.EnterNewScope(); 6965 6966 // Tell the result set to ignore all of the protocols we have 6967 // already seen. 6968 // FIXME: This doesn't work when caching code-completion results. 6969 for (const IdentifierLocPair &Pair : Protocols) 6970 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, Pair.second)) 6971 Results.Ignore(Protocol); 6972 6973 // Add all protocols. 6974 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false, 6975 Results); 6976 6977 Results.ExitScope(); 6978 } 6979 6980 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6981 Results.data(), Results.size()); 6982 } 6983 6984 void Sema::CodeCompleteObjCProtocolDecl(Scope *) { 6985 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6986 CodeCompleter->getCodeCompletionTUInfo(), 6987 CodeCompletionContext::CCC_ObjCProtocolName); 6988 6989 if (CodeCompleter->includeGlobals()) { 6990 Results.EnterNewScope(); 6991 6992 // Add all protocols. 6993 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true, 6994 Results); 6995 6996 Results.ExitScope(); 6997 } 6998 6999 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7000 Results.data(), Results.size()); 7001 } 7002 7003 /// Add all of the Objective-C interface declarations that we find in 7004 /// the given (translation unit) context. 7005 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, 7006 bool OnlyForwardDeclarations, 7007 bool OnlyUnimplemented, 7008 ResultBuilder &Results) { 7009 typedef CodeCompletionResult Result; 7010 7011 for (const auto *D : Ctx->decls()) { 7012 // Record any interfaces we find. 7013 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D)) 7014 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) && 7015 (!OnlyUnimplemented || !Class->getImplementation())) 7016 Results.AddResult( 7017 Result(Class, Results.getBasePriority(Class), nullptr), CurContext, 7018 nullptr, false); 7019 } 7020 } 7021 7022 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { 7023 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7024 CodeCompleter->getCodeCompletionTUInfo(), 7025 CodeCompletionContext::CCC_ObjCInterfaceName); 7026 Results.EnterNewScope(); 7027 7028 if (CodeCompleter->includeGlobals()) { 7029 // Add all classes. 7030 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 7031 false, Results); 7032 } 7033 7034 Results.ExitScope(); 7035 7036 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7037 Results.data(), Results.size()); 7038 } 7039 7040 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, 7041 SourceLocation ClassNameLoc) { 7042 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7043 CodeCompleter->getCodeCompletionTUInfo(), 7044 CodeCompletionContext::CCC_ObjCInterfaceName); 7045 Results.EnterNewScope(); 7046 7047 // Make sure that we ignore the class we're currently defining. 7048 NamedDecl *CurClass = 7049 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 7050 if (CurClass && isa<ObjCInterfaceDecl>(CurClass)) 7051 Results.Ignore(CurClass); 7052 7053 if (CodeCompleter->includeGlobals()) { 7054 // Add all classes. 7055 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 7056 false, Results); 7057 } 7058 7059 Results.ExitScope(); 7060 7061 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7062 Results.data(), Results.size()); 7063 } 7064 7065 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { 7066 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7067 CodeCompleter->getCodeCompletionTUInfo(), 7068 CodeCompletionContext::CCC_ObjCImplementation); 7069 Results.EnterNewScope(); 7070 7071 if (CodeCompleter->includeGlobals()) { 7072 // Add all unimplemented classes. 7073 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 7074 true, Results); 7075 } 7076 7077 Results.ExitScope(); 7078 7079 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7080 Results.data(), Results.size()); 7081 } 7082 7083 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, 7084 IdentifierInfo *ClassName, 7085 SourceLocation ClassNameLoc) { 7086 typedef CodeCompletionResult Result; 7087 7088 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7089 CodeCompleter->getCodeCompletionTUInfo(), 7090 CodeCompletionContext::CCC_ObjCCategoryName); 7091 7092 // Ignore any categories we find that have already been implemented by this 7093 // interface. 7094 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 7095 NamedDecl *CurClass = 7096 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 7097 if (ObjCInterfaceDecl *Class = 7098 dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) { 7099 for (const auto *Cat : Class->visible_categories()) 7100 CategoryNames.insert(Cat->getIdentifier()); 7101 } 7102 7103 // Add all of the categories we know about. 7104 Results.EnterNewScope(); 7105 TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 7106 for (const auto *D : TU->decls()) 7107 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D)) 7108 if (CategoryNames.insert(Category->getIdentifier()).second) 7109 Results.AddResult( 7110 Result(Category, Results.getBasePriority(Category), nullptr), 7111 CurContext, nullptr, false); 7112 Results.ExitScope(); 7113 7114 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7115 Results.data(), Results.size()); 7116 } 7117 7118 void Sema::CodeCompleteObjCImplementationCategory(Scope *S, 7119 IdentifierInfo *ClassName, 7120 SourceLocation ClassNameLoc) { 7121 typedef CodeCompletionResult Result; 7122 7123 // Find the corresponding interface. If we couldn't find the interface, the 7124 // program itself is ill-formed. However, we'll try to be helpful still by 7125 // providing the list of all of the categories we know about. 7126 NamedDecl *CurClass = 7127 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 7128 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); 7129 if (!Class) 7130 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); 7131 7132 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7133 CodeCompleter->getCodeCompletionTUInfo(), 7134 CodeCompletionContext::CCC_ObjCCategoryName); 7135 7136 // Add all of the categories that have have corresponding interface 7137 // declarations in this class and any of its superclasses, except for 7138 // already-implemented categories in the class itself. 7139 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 7140 Results.EnterNewScope(); 7141 bool IgnoreImplemented = true; 7142 while (Class) { 7143 for (const auto *Cat : Class->visible_categories()) { 7144 if ((!IgnoreImplemented || !Cat->getImplementation()) && 7145 CategoryNames.insert(Cat->getIdentifier()).second) 7146 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr), 7147 CurContext, nullptr, false); 7148 } 7149 7150 Class = Class->getSuperClass(); 7151 IgnoreImplemented = false; 7152 } 7153 Results.ExitScope(); 7154 7155 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7156 Results.data(), Results.size()); 7157 } 7158 7159 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) { 7160 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other); 7161 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7162 CodeCompleter->getCodeCompletionTUInfo(), CCContext); 7163 7164 // Figure out where this @synthesize lives. 7165 ObjCContainerDecl *Container = 7166 dyn_cast_or_null<ObjCContainerDecl>(CurContext); 7167 if (!Container || (!isa<ObjCImplementationDecl>(Container) && 7168 !isa<ObjCCategoryImplDecl>(Container))) 7169 return; 7170 7171 // Ignore any properties that have already been implemented. 7172 Container = getContainerDef(Container); 7173 for (const auto *D : Container->decls()) 7174 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D)) 7175 Results.Ignore(PropertyImpl->getPropertyDecl()); 7176 7177 // Add any properties that we find. 7178 AddedPropertiesSet AddedProperties; 7179 Results.EnterNewScope(); 7180 if (ObjCImplementationDecl *ClassImpl = 7181 dyn_cast<ObjCImplementationDecl>(Container)) 7182 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false, 7183 /*AllowNullaryMethods=*/false, CurContext, 7184 AddedProperties, Results); 7185 else 7186 AddObjCProperties(CCContext, 7187 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), 7188 false, /*AllowNullaryMethods=*/false, CurContext, 7189 AddedProperties, Results); 7190 Results.ExitScope(); 7191 7192 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7193 Results.data(), Results.size()); 7194 } 7195 7196 void Sema::CodeCompleteObjCPropertySynthesizeIvar( 7197 Scope *S, IdentifierInfo *PropertyName) { 7198 typedef CodeCompletionResult Result; 7199 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7200 CodeCompleter->getCodeCompletionTUInfo(), 7201 CodeCompletionContext::CCC_Other); 7202 7203 // Figure out where this @synthesize lives. 7204 ObjCContainerDecl *Container = 7205 dyn_cast_or_null<ObjCContainerDecl>(CurContext); 7206 if (!Container || (!isa<ObjCImplementationDecl>(Container) && 7207 !isa<ObjCCategoryImplDecl>(Container))) 7208 return; 7209 7210 // Figure out which interface we're looking into. 7211 ObjCInterfaceDecl *Class = nullptr; 7212 if (ObjCImplementationDecl *ClassImpl = 7213 dyn_cast<ObjCImplementationDecl>(Container)) 7214 Class = ClassImpl->getClassInterface(); 7215 else 7216 Class = cast<ObjCCategoryImplDecl>(Container) 7217 ->getCategoryDecl() 7218 ->getClassInterface(); 7219 7220 // Determine the type of the property we're synthesizing. 7221 QualType PropertyType = Context.getObjCIdType(); 7222 if (Class) { 7223 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration( 7224 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 7225 PropertyType = 7226 Property->getType().getNonReferenceType().getUnqualifiedType(); 7227 7228 // Give preference to ivars 7229 Results.setPreferredType(PropertyType); 7230 } 7231 } 7232 7233 // Add all of the instance variables in this class and its superclasses. 7234 Results.EnterNewScope(); 7235 bool SawSimilarlyNamedIvar = false; 7236 std::string NameWithPrefix; 7237 NameWithPrefix += '_'; 7238 NameWithPrefix += PropertyName->getName(); 7239 std::string NameWithSuffix = PropertyName->getName().str(); 7240 NameWithSuffix += '_'; 7241 for (; Class; Class = Class->getSuperClass()) { 7242 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar; 7243 Ivar = Ivar->getNextIvar()) { 7244 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr), 7245 CurContext, nullptr, false); 7246 7247 // Determine whether we've seen an ivar with a name similar to the 7248 // property. 7249 if ((PropertyName == Ivar->getIdentifier() || 7250 NameWithPrefix == Ivar->getName() || 7251 NameWithSuffix == Ivar->getName())) { 7252 SawSimilarlyNamedIvar = true; 7253 7254 // Reduce the priority of this result by one, to give it a slight 7255 // advantage over other results whose names don't match so closely. 7256 if (Results.size() && 7257 Results.data()[Results.size() - 1].Kind == 7258 CodeCompletionResult::RK_Declaration && 7259 Results.data()[Results.size() - 1].Declaration == Ivar) 7260 Results.data()[Results.size() - 1].Priority--; 7261 } 7262 } 7263 } 7264 7265 if (!SawSimilarlyNamedIvar) { 7266 // Create ivar result _propName, that the user can use to synthesize 7267 // an ivar of the appropriate type. 7268 unsigned Priority = CCP_MemberDeclaration + 1; 7269 typedef CodeCompletionResult Result; 7270 CodeCompletionAllocator &Allocator = Results.getAllocator(); 7271 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(), 7272 Priority, CXAvailability_Available); 7273 7274 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 7275 Builder.AddResultTypeChunk( 7276 GetCompletionTypeString(PropertyType, Context, Policy, Allocator)); 7277 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix)); 7278 Results.AddResult( 7279 Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl)); 7280 } 7281 7282 Results.ExitScope(); 7283 7284 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7285 Results.data(), Results.size()); 7286 } 7287 7288 // Mapping from selectors to the methods that implement that selector, along 7289 // with the "in original class" flag. 7290 typedef llvm::DenseMap<Selector, 7291 llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>> 7292 KnownMethodsMap; 7293 7294 /// Find all of the methods that reside in the given container 7295 /// (and its superclasses, protocols, etc.) that meet the given 7296 /// criteria. Insert those methods into the map of known methods, 7297 /// indexed by selector so they can be easily found. 7298 static void FindImplementableMethods(ASTContext &Context, 7299 ObjCContainerDecl *Container, 7300 Optional<bool> WantInstanceMethods, 7301 QualType ReturnType, 7302 KnownMethodsMap &KnownMethods, 7303 bool InOriginalClass = true) { 7304 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) { 7305 // Make sure we have a definition; that's what we'll walk. 7306 if (!IFace->hasDefinition()) 7307 return; 7308 7309 IFace = IFace->getDefinition(); 7310 Container = IFace; 7311 7312 const ObjCList<ObjCProtocolDecl> &Protocols = 7313 IFace->getReferencedProtocols(); 7314 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 7315 E = Protocols.end(); 7316 I != E; ++I) 7317 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 7318 KnownMethods, InOriginalClass); 7319 7320 // Add methods from any class extensions and categories. 7321 for (auto *Cat : IFace->visible_categories()) { 7322 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType, 7323 KnownMethods, false); 7324 } 7325 7326 // Visit the superclass. 7327 if (IFace->getSuperClass()) 7328 FindImplementableMethods(Context, IFace->getSuperClass(), 7329 WantInstanceMethods, ReturnType, KnownMethods, 7330 false); 7331 } 7332 7333 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 7334 // Recurse into protocols. 7335 const ObjCList<ObjCProtocolDecl> &Protocols = 7336 Category->getReferencedProtocols(); 7337 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 7338 E = Protocols.end(); 7339 I != E; ++I) 7340 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 7341 KnownMethods, InOriginalClass); 7342 7343 // If this category is the original class, jump to the interface. 7344 if (InOriginalClass && Category->getClassInterface()) 7345 FindImplementableMethods(Context, Category->getClassInterface(), 7346 WantInstanceMethods, ReturnType, KnownMethods, 7347 false); 7348 } 7349 7350 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 7351 // Make sure we have a definition; that's what we'll walk. 7352 if (!Protocol->hasDefinition()) 7353 return; 7354 Protocol = Protocol->getDefinition(); 7355 Container = Protocol; 7356 7357 // Recurse into protocols. 7358 const ObjCList<ObjCProtocolDecl> &Protocols = 7359 Protocol->getReferencedProtocols(); 7360 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 7361 E = Protocols.end(); 7362 I != E; ++I) 7363 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 7364 KnownMethods, false); 7365 } 7366 7367 // Add methods in this container. This operation occurs last because 7368 // we want the methods from this container to override any methods 7369 // we've previously seen with the same selector. 7370 for (auto *M : Container->methods()) { 7371 if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) { 7372 if (!ReturnType.isNull() && 7373 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType())) 7374 continue; 7375 7376 KnownMethods[M->getSelector()] = 7377 KnownMethodsMap::mapped_type(M, InOriginalClass); 7378 } 7379 } 7380 } 7381 7382 /// Add the parenthesized return or parameter type chunk to a code 7383 /// completion string. 7384 static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals, 7385 ASTContext &Context, 7386 const PrintingPolicy &Policy, 7387 CodeCompletionBuilder &Builder) { 7388 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7389 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type); 7390 if (!Quals.empty()) 7391 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals)); 7392 Builder.AddTextChunk( 7393 GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator())); 7394 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7395 } 7396 7397 /// Determine whether the given class is or inherits from a class by 7398 /// the given name. 7399 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) { 7400 if (!Class) 7401 return false; 7402 7403 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name) 7404 return true; 7405 7406 return InheritsFromClassNamed(Class->getSuperClass(), Name); 7407 } 7408 7409 /// Add code completions for Objective-C Key-Value Coding (KVC) and 7410 /// Key-Value Observing (KVO). 7411 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, 7412 bool IsInstanceMethod, 7413 QualType ReturnType, ASTContext &Context, 7414 VisitedSelectorSet &KnownSelectors, 7415 ResultBuilder &Results) { 7416 IdentifierInfo *PropName = Property->getIdentifier(); 7417 if (!PropName || PropName->getLength() == 0) 7418 return; 7419 7420 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 7421 7422 // Builder that will create each code completion. 7423 typedef CodeCompletionResult Result; 7424 CodeCompletionAllocator &Allocator = Results.getAllocator(); 7425 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 7426 7427 // The selector table. 7428 SelectorTable &Selectors = Context.Selectors; 7429 7430 // The property name, copied into the code completion allocation region 7431 // on demand. 7432 struct KeyHolder { 7433 CodeCompletionAllocator &Allocator; 7434 StringRef Key; 7435 const char *CopiedKey; 7436 7437 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key) 7438 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {} 7439 7440 operator const char *() { 7441 if (CopiedKey) 7442 return CopiedKey; 7443 7444 return CopiedKey = Allocator.CopyString(Key); 7445 } 7446 } Key(Allocator, PropName->getName()); 7447 7448 // The uppercased name of the property name. 7449 std::string UpperKey = PropName->getName(); 7450 if (!UpperKey.empty()) 7451 UpperKey[0] = toUppercase(UpperKey[0]); 7452 7453 bool ReturnTypeMatchesProperty = 7454 ReturnType.isNull() || 7455 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(), 7456 Property->getType()); 7457 bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType(); 7458 7459 // Add the normal accessor -(type)key. 7460 if (IsInstanceMethod && 7461 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second && 7462 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) { 7463 if (ReturnType.isNull()) 7464 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, 7465 Builder); 7466 7467 Builder.AddTypedTextChunk(Key); 7468 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7469 CXCursor_ObjCInstanceMethodDecl)); 7470 } 7471 7472 // If we have an integral or boolean property (or the user has provided 7473 // an integral or boolean return type), add the accessor -(type)isKey. 7474 if (IsInstanceMethod && 7475 ((!ReturnType.isNull() && 7476 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) || 7477 (ReturnType.isNull() && (Property->getType()->isIntegerType() || 7478 Property->getType()->isBooleanType())))) { 7479 std::string SelectorName = (Twine("is") + UpperKey).str(); 7480 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7481 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7482 .second) { 7483 if (ReturnType.isNull()) { 7484 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7485 Builder.AddTextChunk("BOOL"); 7486 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7487 } 7488 7489 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 7490 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7491 CXCursor_ObjCInstanceMethodDecl)); 7492 } 7493 } 7494 7495 // Add the normal mutator. 7496 if (IsInstanceMethod && ReturnTypeMatchesVoid && 7497 !Property->getSetterMethodDecl()) { 7498 std::string SelectorName = (Twine("set") + UpperKey).str(); 7499 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7500 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7501 if (ReturnType.isNull()) { 7502 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7503 Builder.AddTextChunk("void"); 7504 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7505 } 7506 7507 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 7508 Builder.AddTypedTextChunk(":"); 7509 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, 7510 Builder); 7511 Builder.AddTextChunk(Key); 7512 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7513 CXCursor_ObjCInstanceMethodDecl)); 7514 } 7515 } 7516 7517 // Indexed and unordered accessors 7518 unsigned IndexedGetterPriority = CCP_CodePattern; 7519 unsigned IndexedSetterPriority = CCP_CodePattern; 7520 unsigned UnorderedGetterPriority = CCP_CodePattern; 7521 unsigned UnorderedSetterPriority = CCP_CodePattern; 7522 if (const auto *ObjCPointer = 7523 Property->getType()->getAs<ObjCObjectPointerType>()) { 7524 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) { 7525 // If this interface type is not provably derived from a known 7526 // collection, penalize the corresponding completions. 7527 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) { 7528 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 7529 if (!InheritsFromClassNamed(IFace, "NSArray")) 7530 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 7531 } 7532 7533 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) { 7534 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 7535 if (!InheritsFromClassNamed(IFace, "NSSet")) 7536 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 7537 } 7538 } 7539 } else { 7540 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 7541 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 7542 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 7543 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 7544 } 7545 7546 // Add -(NSUInteger)countOf<key> 7547 if (IsInstanceMethod && 7548 (ReturnType.isNull() || ReturnType->isIntegerType())) { 7549 std::string SelectorName = (Twine("countOf") + UpperKey).str(); 7550 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7551 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7552 .second) { 7553 if (ReturnType.isNull()) { 7554 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7555 Builder.AddTextChunk("NSUInteger"); 7556 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7557 } 7558 7559 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 7560 Results.AddResult( 7561 Result(Builder.TakeString(), 7562 std::min(IndexedGetterPriority, UnorderedGetterPriority), 7563 CXCursor_ObjCInstanceMethodDecl)); 7564 } 7565 } 7566 7567 // Indexed getters 7568 // Add -(id)objectInKeyAtIndex:(NSUInteger)index 7569 if (IsInstanceMethod && 7570 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 7571 std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str(); 7572 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7573 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7574 if (ReturnType.isNull()) { 7575 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7576 Builder.AddTextChunk("id"); 7577 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7578 } 7579 7580 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7581 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7582 Builder.AddTextChunk("NSUInteger"); 7583 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7584 Builder.AddTextChunk("index"); 7585 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 7586 CXCursor_ObjCInstanceMethodDecl)); 7587 } 7588 } 7589 7590 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes 7591 if (IsInstanceMethod && 7592 (ReturnType.isNull() || 7593 (ReturnType->isObjCObjectPointerType() && 7594 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 7595 ReturnType->getAs<ObjCObjectPointerType>() 7596 ->getInterfaceDecl() 7597 ->getName() == "NSArray"))) { 7598 std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str(); 7599 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7600 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7601 if (ReturnType.isNull()) { 7602 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7603 Builder.AddTextChunk("NSArray *"); 7604 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7605 } 7606 7607 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7608 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7609 Builder.AddTextChunk("NSIndexSet *"); 7610 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7611 Builder.AddTextChunk("indexes"); 7612 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 7613 CXCursor_ObjCInstanceMethodDecl)); 7614 } 7615 } 7616 7617 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange 7618 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7619 std::string SelectorName = (Twine("get") + UpperKey).str(); 7620 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 7621 &Context.Idents.get("range")}; 7622 7623 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7624 if (ReturnType.isNull()) { 7625 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7626 Builder.AddTextChunk("void"); 7627 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7628 } 7629 7630 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7631 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7632 Builder.AddPlaceholderChunk("object-type"); 7633 Builder.AddTextChunk(" **"); 7634 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7635 Builder.AddTextChunk("buffer"); 7636 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7637 Builder.AddTypedTextChunk("range:"); 7638 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7639 Builder.AddTextChunk("NSRange"); 7640 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7641 Builder.AddTextChunk("inRange"); 7642 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 7643 CXCursor_ObjCInstanceMethodDecl)); 7644 } 7645 } 7646 7647 // Mutable indexed accessors 7648 7649 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index 7650 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7651 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str(); 7652 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"), 7653 &Context.Idents.get(SelectorName)}; 7654 7655 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7656 if (ReturnType.isNull()) { 7657 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7658 Builder.AddTextChunk("void"); 7659 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7660 } 7661 7662 Builder.AddTypedTextChunk("insertObject:"); 7663 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7664 Builder.AddPlaceholderChunk("object-type"); 7665 Builder.AddTextChunk(" *"); 7666 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7667 Builder.AddTextChunk("object"); 7668 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7669 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7670 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7671 Builder.AddPlaceholderChunk("NSUInteger"); 7672 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7673 Builder.AddTextChunk("index"); 7674 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7675 CXCursor_ObjCInstanceMethodDecl)); 7676 } 7677 } 7678 7679 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes 7680 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7681 std::string SelectorName = (Twine("insert") + UpperKey).str(); 7682 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 7683 &Context.Idents.get("atIndexes")}; 7684 7685 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7686 if (ReturnType.isNull()) { 7687 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7688 Builder.AddTextChunk("void"); 7689 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7690 } 7691 7692 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7693 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7694 Builder.AddTextChunk("NSArray *"); 7695 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7696 Builder.AddTextChunk("array"); 7697 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7698 Builder.AddTypedTextChunk("atIndexes:"); 7699 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7700 Builder.AddPlaceholderChunk("NSIndexSet *"); 7701 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7702 Builder.AddTextChunk("indexes"); 7703 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7704 CXCursor_ObjCInstanceMethodDecl)); 7705 } 7706 } 7707 7708 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index 7709 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7710 std::string SelectorName = 7711 (Twine("removeObjectFrom") + UpperKey + "AtIndex").str(); 7712 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7713 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7714 if (ReturnType.isNull()) { 7715 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7716 Builder.AddTextChunk("void"); 7717 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7718 } 7719 7720 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7721 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7722 Builder.AddTextChunk("NSUInteger"); 7723 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7724 Builder.AddTextChunk("index"); 7725 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7726 CXCursor_ObjCInstanceMethodDecl)); 7727 } 7728 } 7729 7730 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes 7731 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7732 std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str(); 7733 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7734 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7735 if (ReturnType.isNull()) { 7736 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7737 Builder.AddTextChunk("void"); 7738 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7739 } 7740 7741 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7742 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7743 Builder.AddTextChunk("NSIndexSet *"); 7744 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7745 Builder.AddTextChunk("indexes"); 7746 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7747 CXCursor_ObjCInstanceMethodDecl)); 7748 } 7749 } 7750 7751 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object 7752 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7753 std::string SelectorName = 7754 (Twine("replaceObjectIn") + UpperKey + "AtIndex").str(); 7755 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 7756 &Context.Idents.get("withObject")}; 7757 7758 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7759 if (ReturnType.isNull()) { 7760 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7761 Builder.AddTextChunk("void"); 7762 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7763 } 7764 7765 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7766 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7767 Builder.AddPlaceholderChunk("NSUInteger"); 7768 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7769 Builder.AddTextChunk("index"); 7770 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7771 Builder.AddTypedTextChunk("withObject:"); 7772 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7773 Builder.AddTextChunk("id"); 7774 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7775 Builder.AddTextChunk("object"); 7776 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7777 CXCursor_ObjCInstanceMethodDecl)); 7778 } 7779 } 7780 7781 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array 7782 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7783 std::string SelectorName1 = 7784 (Twine("replace") + UpperKey + "AtIndexes").str(); 7785 std::string SelectorName2 = (Twine("with") + UpperKey).str(); 7786 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1), 7787 &Context.Idents.get(SelectorName2)}; 7788 7789 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7790 if (ReturnType.isNull()) { 7791 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7792 Builder.AddTextChunk("void"); 7793 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7794 } 7795 7796 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":")); 7797 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7798 Builder.AddPlaceholderChunk("NSIndexSet *"); 7799 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7800 Builder.AddTextChunk("indexes"); 7801 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7802 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":")); 7803 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7804 Builder.AddTextChunk("NSArray *"); 7805 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7806 Builder.AddTextChunk("array"); 7807 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7808 CXCursor_ObjCInstanceMethodDecl)); 7809 } 7810 } 7811 7812 // Unordered getters 7813 // - (NSEnumerator *)enumeratorOfKey 7814 if (IsInstanceMethod && 7815 (ReturnType.isNull() || 7816 (ReturnType->isObjCObjectPointerType() && 7817 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 7818 ReturnType->getAs<ObjCObjectPointerType>() 7819 ->getInterfaceDecl() 7820 ->getName() == "NSEnumerator"))) { 7821 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str(); 7822 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7823 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7824 .second) { 7825 if (ReturnType.isNull()) { 7826 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7827 Builder.AddTextChunk("NSEnumerator *"); 7828 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7829 } 7830 7831 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 7832 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 7833 CXCursor_ObjCInstanceMethodDecl)); 7834 } 7835 } 7836 7837 // - (type *)memberOfKey:(type *)object 7838 if (IsInstanceMethod && 7839 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 7840 std::string SelectorName = (Twine("memberOf") + UpperKey).str(); 7841 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7842 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7843 if (ReturnType.isNull()) { 7844 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7845 Builder.AddPlaceholderChunk("object-type"); 7846 Builder.AddTextChunk(" *"); 7847 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7848 } 7849 7850 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7851 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7852 if (ReturnType.isNull()) { 7853 Builder.AddPlaceholderChunk("object-type"); 7854 Builder.AddTextChunk(" *"); 7855 } else { 7856 Builder.AddTextChunk(GetCompletionTypeString( 7857 ReturnType, Context, Policy, Builder.getAllocator())); 7858 } 7859 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7860 Builder.AddTextChunk("object"); 7861 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 7862 CXCursor_ObjCInstanceMethodDecl)); 7863 } 7864 } 7865 7866 // Mutable unordered accessors 7867 // - (void)addKeyObject:(type *)object 7868 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7869 std::string SelectorName = 7870 (Twine("add") + UpperKey + Twine("Object")).str(); 7871 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7872 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7873 if (ReturnType.isNull()) { 7874 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7875 Builder.AddTextChunk("void"); 7876 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7877 } 7878 7879 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7880 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7881 Builder.AddPlaceholderChunk("object-type"); 7882 Builder.AddTextChunk(" *"); 7883 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7884 Builder.AddTextChunk("object"); 7885 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7886 CXCursor_ObjCInstanceMethodDecl)); 7887 } 7888 } 7889 7890 // - (void)addKey:(NSSet *)objects 7891 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7892 std::string SelectorName = (Twine("add") + UpperKey).str(); 7893 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7894 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7895 if (ReturnType.isNull()) { 7896 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7897 Builder.AddTextChunk("void"); 7898 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7899 } 7900 7901 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7902 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7903 Builder.AddTextChunk("NSSet *"); 7904 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7905 Builder.AddTextChunk("objects"); 7906 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7907 CXCursor_ObjCInstanceMethodDecl)); 7908 } 7909 } 7910 7911 // - (void)removeKeyObject:(type *)object 7912 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7913 std::string SelectorName = 7914 (Twine("remove") + UpperKey + Twine("Object")).str(); 7915 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7916 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7917 if (ReturnType.isNull()) { 7918 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7919 Builder.AddTextChunk("void"); 7920 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7921 } 7922 7923 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7924 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7925 Builder.AddPlaceholderChunk("object-type"); 7926 Builder.AddTextChunk(" *"); 7927 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7928 Builder.AddTextChunk("object"); 7929 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7930 CXCursor_ObjCInstanceMethodDecl)); 7931 } 7932 } 7933 7934 // - (void)removeKey:(NSSet *)objects 7935 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7936 std::string SelectorName = (Twine("remove") + UpperKey).str(); 7937 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7938 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7939 if (ReturnType.isNull()) { 7940 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7941 Builder.AddTextChunk("void"); 7942 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7943 } 7944 7945 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7946 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7947 Builder.AddTextChunk("NSSet *"); 7948 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7949 Builder.AddTextChunk("objects"); 7950 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7951 CXCursor_ObjCInstanceMethodDecl)); 7952 } 7953 } 7954 7955 // - (void)intersectKey:(NSSet *)objects 7956 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7957 std::string SelectorName = (Twine("intersect") + UpperKey).str(); 7958 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7959 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7960 if (ReturnType.isNull()) { 7961 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7962 Builder.AddTextChunk("void"); 7963 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7964 } 7965 7966 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7967 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7968 Builder.AddTextChunk("NSSet *"); 7969 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7970 Builder.AddTextChunk("objects"); 7971 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7972 CXCursor_ObjCInstanceMethodDecl)); 7973 } 7974 } 7975 7976 // Key-Value Observing 7977 // + (NSSet *)keyPathsForValuesAffectingKey 7978 if (!IsInstanceMethod && 7979 (ReturnType.isNull() || 7980 (ReturnType->isObjCObjectPointerType() && 7981 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 7982 ReturnType->getAs<ObjCObjectPointerType>() 7983 ->getInterfaceDecl() 7984 ->getName() == "NSSet"))) { 7985 std::string SelectorName = 7986 (Twine("keyPathsForValuesAffecting") + UpperKey).str(); 7987 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7988 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7989 .second) { 7990 if (ReturnType.isNull()) { 7991 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7992 Builder.AddTextChunk("NSSet<NSString *> *"); 7993 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7994 } 7995 7996 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 7997 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7998 CXCursor_ObjCClassMethodDecl)); 7999 } 8000 } 8001 8002 // + (BOOL)automaticallyNotifiesObserversForKey 8003 if (!IsInstanceMethod && 8004 (ReturnType.isNull() || ReturnType->isIntegerType() || 8005 ReturnType->isBooleanType())) { 8006 std::string SelectorName = 8007 (Twine("automaticallyNotifiesObserversOf") + UpperKey).str(); 8008 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8009 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 8010 .second) { 8011 if (ReturnType.isNull()) { 8012 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8013 Builder.AddTextChunk("BOOL"); 8014 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8015 } 8016 8017 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 8018 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 8019 CXCursor_ObjCClassMethodDecl)); 8020 } 8021 } 8022 } 8023 8024 void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, 8025 ParsedType ReturnTy) { 8026 // Determine the return type of the method we're declaring, if 8027 // provided. 8028 QualType ReturnType = GetTypeFromParser(ReturnTy); 8029 Decl *IDecl = nullptr; 8030 if (CurContext->isObjCContainer()) { 8031 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 8032 IDecl = OCD; 8033 } 8034 // Determine where we should start searching for methods. 8035 ObjCContainerDecl *SearchDecl = nullptr; 8036 bool IsInImplementation = false; 8037 if (Decl *D = IDecl) { 8038 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { 8039 SearchDecl = Impl->getClassInterface(); 8040 IsInImplementation = true; 8041 } else if (ObjCCategoryImplDecl *CatImpl = 8042 dyn_cast<ObjCCategoryImplDecl>(D)) { 8043 SearchDecl = CatImpl->getCategoryDecl(); 8044 IsInImplementation = true; 8045 } else 8046 SearchDecl = dyn_cast<ObjCContainerDecl>(D); 8047 } 8048 8049 if (!SearchDecl && S) { 8050 if (DeclContext *DC = S->getEntity()) 8051 SearchDecl = dyn_cast<ObjCContainerDecl>(DC); 8052 } 8053 8054 if (!SearchDecl) { 8055 HandleCodeCompleteResults(this, CodeCompleter, 8056 CodeCompletionContext::CCC_Other, nullptr, 0); 8057 return; 8058 } 8059 8060 // Find all of the methods that we could declare/implement here. 8061 KnownMethodsMap KnownMethods; 8062 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType, 8063 KnownMethods); 8064 8065 // Add declarations or definitions for each of the known methods. 8066 typedef CodeCompletionResult Result; 8067 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8068 CodeCompleter->getCodeCompletionTUInfo(), 8069 CodeCompletionContext::CCC_Other); 8070 Results.EnterNewScope(); 8071 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 8072 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 8073 MEnd = KnownMethods.end(); 8074 M != MEnd; ++M) { 8075 ObjCMethodDecl *Method = M->second.getPointer(); 8076 CodeCompletionBuilder Builder(Results.getAllocator(), 8077 Results.getCodeCompletionTUInfo()); 8078 8079 // Add the '-'/'+' prefix if it wasn't provided yet. 8080 if (!IsInstanceMethod) { 8081 Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+"); 8082 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8083 } 8084 8085 // If the result type was not already provided, add it to the 8086 // pattern as (type). 8087 if (ReturnType.isNull()) { 8088 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context); 8089 AttributedType::stripOuterNullability(ResTy); 8090 AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context, 8091 Policy, Builder); 8092 } 8093 8094 Selector Sel = Method->getSelector(); 8095 8096 // Add the first part of the selector to the pattern. 8097 Builder.AddTypedTextChunk( 8098 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 8099 8100 // Add parameters to the pattern. 8101 unsigned I = 0; 8102 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 8103 PEnd = Method->param_end(); 8104 P != PEnd; (void)++P, ++I) { 8105 // Add the part of the selector name. 8106 if (I == 0) 8107 Builder.AddTypedTextChunk(":"); 8108 else if (I < Sel.getNumArgs()) { 8109 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8110 Builder.AddTypedTextChunk( 8111 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 8112 } else 8113 break; 8114 8115 // Add the parameter type. 8116 QualType ParamType; 8117 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 8118 ParamType = (*P)->getType(); 8119 else 8120 ParamType = (*P)->getOriginalType(); 8121 ParamType = ParamType.substObjCTypeArgs( 8122 Context, {}, ObjCSubstitutionContext::Parameter); 8123 AttributedType::stripOuterNullability(ParamType); 8124 AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(), Context, 8125 Policy, Builder); 8126 8127 if (IdentifierInfo *Id = (*P)->getIdentifier()) 8128 Builder.AddTextChunk(Builder.getAllocator().CopyString(Id->getName())); 8129 } 8130 8131 if (Method->isVariadic()) { 8132 if (Method->param_size() > 0) 8133 Builder.AddChunk(CodeCompletionString::CK_Comma); 8134 Builder.AddTextChunk("..."); 8135 } 8136 8137 if (IsInImplementation && Results.includeCodePatterns()) { 8138 // We will be defining the method here, so add a compound statement. 8139 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8140 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 8141 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 8142 if (!Method->getReturnType()->isVoidType()) { 8143 // If the result type is not void, add a return clause. 8144 Builder.AddTextChunk("return"); 8145 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8146 Builder.AddPlaceholderChunk("expression"); 8147 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 8148 } else 8149 Builder.AddPlaceholderChunk("statements"); 8150 8151 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 8152 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 8153 } 8154 8155 unsigned Priority = CCP_CodePattern; 8156 auto R = Result(Builder.TakeString(), Method, Priority); 8157 if (!M->second.getInt()) 8158 setInBaseClass(R); 8159 Results.AddResult(std::move(R)); 8160 } 8161 8162 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of 8163 // the properties in this class and its categories. 8164 if (Context.getLangOpts().ObjC) { 8165 SmallVector<ObjCContainerDecl *, 4> Containers; 8166 Containers.push_back(SearchDecl); 8167 8168 VisitedSelectorSet KnownSelectors; 8169 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 8170 MEnd = KnownMethods.end(); 8171 M != MEnd; ++M) 8172 KnownSelectors.insert(M->first); 8173 8174 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl); 8175 if (!IFace) 8176 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl)) 8177 IFace = Category->getClassInterface(); 8178 8179 if (IFace) 8180 for (auto *Cat : IFace->visible_categories()) 8181 Containers.push_back(Cat); 8182 8183 if (IsInstanceMethod) { 8184 for (unsigned I = 0, N = Containers.size(); I != N; ++I) 8185 for (auto *P : Containers[I]->instance_properties()) 8186 AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context, 8187 KnownSelectors, Results); 8188 } 8189 } 8190 8191 Results.ExitScope(); 8192 8193 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8194 Results.data(), Results.size()); 8195 } 8196 8197 void Sema::CodeCompleteObjCMethodDeclSelector( 8198 Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy, 8199 ArrayRef<IdentifierInfo *> SelIdents) { 8200 // If we have an external source, load the entire class method 8201 // pool from the AST file. 8202 if (ExternalSource) { 8203 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N; 8204 ++I) { 8205 Selector Sel = ExternalSource->GetExternalSelector(I); 8206 if (Sel.isNull() || MethodPool.count(Sel)) 8207 continue; 8208 8209 ReadMethodPool(Sel); 8210 } 8211 } 8212 8213 // Build the set of methods we can see. 8214 typedef CodeCompletionResult Result; 8215 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8216 CodeCompleter->getCodeCompletionTUInfo(), 8217 CodeCompletionContext::CCC_Other); 8218 8219 if (ReturnTy) 8220 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType()); 8221 8222 Results.EnterNewScope(); 8223 for (GlobalMethodPool::iterator M = MethodPool.begin(), 8224 MEnd = MethodPool.end(); 8225 M != MEnd; ++M) { 8226 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first 8227 : &M->second.second; 8228 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 8229 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 8230 continue; 8231 8232 if (AtParameterName) { 8233 // Suggest parameter names we've seen before. 8234 unsigned NumSelIdents = SelIdents.size(); 8235 if (NumSelIdents && 8236 NumSelIdents <= MethList->getMethod()->param_size()) { 8237 ParmVarDecl *Param = 8238 MethList->getMethod()->parameters()[NumSelIdents - 1]; 8239 if (Param->getIdentifier()) { 8240 CodeCompletionBuilder Builder(Results.getAllocator(), 8241 Results.getCodeCompletionTUInfo()); 8242 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 8243 Param->getIdentifier()->getName())); 8244 Results.AddResult(Builder.TakeString()); 8245 } 8246 } 8247 8248 continue; 8249 } 8250 8251 Result R(MethList->getMethod(), 8252 Results.getBasePriority(MethList->getMethod()), nullptr); 8253 R.StartParameter = SelIdents.size(); 8254 R.AllParametersAreInformative = false; 8255 R.DeclaringEntity = true; 8256 Results.MaybeAddResult(R, CurContext); 8257 } 8258 } 8259 8260 Results.ExitScope(); 8261 8262 if (!AtParameterName && !SelIdents.empty() && 8263 SelIdents.front()->getName().startswith("init")) { 8264 for (const auto &M : PP.macros()) { 8265 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER") 8266 continue; 8267 Results.EnterNewScope(); 8268 CodeCompletionBuilder Builder(Results.getAllocator(), 8269 Results.getCodeCompletionTUInfo()); 8270 Builder.AddTypedTextChunk( 8271 Builder.getAllocator().CopyString(M.first->getName())); 8272 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro, 8273 CXCursor_MacroDefinition)); 8274 Results.ExitScope(); 8275 } 8276 } 8277 8278 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8279 Results.data(), Results.size()); 8280 } 8281 8282 void Sema::CodeCompletePreprocessorDirective(bool InConditional) { 8283 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8284 CodeCompleter->getCodeCompletionTUInfo(), 8285 CodeCompletionContext::CCC_PreprocessorDirective); 8286 Results.EnterNewScope(); 8287 8288 // #if <condition> 8289 CodeCompletionBuilder Builder(Results.getAllocator(), 8290 Results.getCodeCompletionTUInfo()); 8291 Builder.AddTypedTextChunk("if"); 8292 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8293 Builder.AddPlaceholderChunk("condition"); 8294 Results.AddResult(Builder.TakeString()); 8295 8296 // #ifdef <macro> 8297 Builder.AddTypedTextChunk("ifdef"); 8298 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8299 Builder.AddPlaceholderChunk("macro"); 8300 Results.AddResult(Builder.TakeString()); 8301 8302 // #ifndef <macro> 8303 Builder.AddTypedTextChunk("ifndef"); 8304 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8305 Builder.AddPlaceholderChunk("macro"); 8306 Results.AddResult(Builder.TakeString()); 8307 8308 if (InConditional) { 8309 // #elif <condition> 8310 Builder.AddTypedTextChunk("elif"); 8311 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8312 Builder.AddPlaceholderChunk("condition"); 8313 Results.AddResult(Builder.TakeString()); 8314 8315 // #else 8316 Builder.AddTypedTextChunk("else"); 8317 Results.AddResult(Builder.TakeString()); 8318 8319 // #endif 8320 Builder.AddTypedTextChunk("endif"); 8321 Results.AddResult(Builder.TakeString()); 8322 } 8323 8324 // #include "header" 8325 Builder.AddTypedTextChunk("include"); 8326 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8327 Builder.AddTextChunk("\""); 8328 Builder.AddPlaceholderChunk("header"); 8329 Builder.AddTextChunk("\""); 8330 Results.AddResult(Builder.TakeString()); 8331 8332 // #include <header> 8333 Builder.AddTypedTextChunk("include"); 8334 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8335 Builder.AddTextChunk("<"); 8336 Builder.AddPlaceholderChunk("header"); 8337 Builder.AddTextChunk(">"); 8338 Results.AddResult(Builder.TakeString()); 8339 8340 // #define <macro> 8341 Builder.AddTypedTextChunk("define"); 8342 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8343 Builder.AddPlaceholderChunk("macro"); 8344 Results.AddResult(Builder.TakeString()); 8345 8346 // #define <macro>(<args>) 8347 Builder.AddTypedTextChunk("define"); 8348 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8349 Builder.AddPlaceholderChunk("macro"); 8350 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8351 Builder.AddPlaceholderChunk("args"); 8352 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8353 Results.AddResult(Builder.TakeString()); 8354 8355 // #undef <macro> 8356 Builder.AddTypedTextChunk("undef"); 8357 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8358 Builder.AddPlaceholderChunk("macro"); 8359 Results.AddResult(Builder.TakeString()); 8360 8361 // #line <number> 8362 Builder.AddTypedTextChunk("line"); 8363 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8364 Builder.AddPlaceholderChunk("number"); 8365 Results.AddResult(Builder.TakeString()); 8366 8367 // #line <number> "filename" 8368 Builder.AddTypedTextChunk("line"); 8369 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8370 Builder.AddPlaceholderChunk("number"); 8371 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8372 Builder.AddTextChunk("\""); 8373 Builder.AddPlaceholderChunk("filename"); 8374 Builder.AddTextChunk("\""); 8375 Results.AddResult(Builder.TakeString()); 8376 8377 // #error <message> 8378 Builder.AddTypedTextChunk("error"); 8379 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8380 Builder.AddPlaceholderChunk("message"); 8381 Results.AddResult(Builder.TakeString()); 8382 8383 // #pragma <arguments> 8384 Builder.AddTypedTextChunk("pragma"); 8385 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8386 Builder.AddPlaceholderChunk("arguments"); 8387 Results.AddResult(Builder.TakeString()); 8388 8389 if (getLangOpts().ObjC) { 8390 // #import "header" 8391 Builder.AddTypedTextChunk("import"); 8392 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8393 Builder.AddTextChunk("\""); 8394 Builder.AddPlaceholderChunk("header"); 8395 Builder.AddTextChunk("\""); 8396 Results.AddResult(Builder.TakeString()); 8397 8398 // #import <header> 8399 Builder.AddTypedTextChunk("import"); 8400 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8401 Builder.AddTextChunk("<"); 8402 Builder.AddPlaceholderChunk("header"); 8403 Builder.AddTextChunk(">"); 8404 Results.AddResult(Builder.TakeString()); 8405 } 8406 8407 // #include_next "header" 8408 Builder.AddTypedTextChunk("include_next"); 8409 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8410 Builder.AddTextChunk("\""); 8411 Builder.AddPlaceholderChunk("header"); 8412 Builder.AddTextChunk("\""); 8413 Results.AddResult(Builder.TakeString()); 8414 8415 // #include_next <header> 8416 Builder.AddTypedTextChunk("include_next"); 8417 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8418 Builder.AddTextChunk("<"); 8419 Builder.AddPlaceholderChunk("header"); 8420 Builder.AddTextChunk(">"); 8421 Results.AddResult(Builder.TakeString()); 8422 8423 // #warning <message> 8424 Builder.AddTypedTextChunk("warning"); 8425 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8426 Builder.AddPlaceholderChunk("message"); 8427 Results.AddResult(Builder.TakeString()); 8428 8429 // Note: #ident and #sccs are such crazy anachronisms that we don't provide 8430 // completions for them. And __include_macros is a Clang-internal extension 8431 // that we don't want to encourage anyone to use. 8432 8433 // FIXME: we don't support #assert or #unassert, so don't suggest them. 8434 Results.ExitScope(); 8435 8436 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8437 Results.data(), Results.size()); 8438 } 8439 8440 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) { 8441 CodeCompleteOrdinaryName(S, S->getFnParent() ? Sema::PCC_RecoveryInFunction 8442 : Sema::PCC_Namespace); 8443 } 8444 8445 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) { 8446 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8447 CodeCompleter->getCodeCompletionTUInfo(), 8448 IsDefinition ? CodeCompletionContext::CCC_MacroName 8449 : CodeCompletionContext::CCC_MacroNameUse); 8450 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) { 8451 // Add just the names of macros, not their arguments. 8452 CodeCompletionBuilder Builder(Results.getAllocator(), 8453 Results.getCodeCompletionTUInfo()); 8454 Results.EnterNewScope(); 8455 for (Preprocessor::macro_iterator M = PP.macro_begin(), 8456 MEnd = PP.macro_end(); 8457 M != MEnd; ++M) { 8458 Builder.AddTypedTextChunk( 8459 Builder.getAllocator().CopyString(M->first->getName())); 8460 Results.AddResult(CodeCompletionResult( 8461 Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition)); 8462 } 8463 Results.ExitScope(); 8464 } else if (IsDefinition) { 8465 // FIXME: Can we detect when the user just wrote an include guard above? 8466 } 8467 8468 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8469 Results.data(), Results.size()); 8470 } 8471 8472 void Sema::CodeCompletePreprocessorExpression() { 8473 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8474 CodeCompleter->getCodeCompletionTUInfo(), 8475 CodeCompletionContext::CCC_PreprocessorExpression); 8476 8477 if (!CodeCompleter || CodeCompleter->includeMacros()) 8478 AddMacroResults(PP, Results, 8479 CodeCompleter ? CodeCompleter->loadExternal() : false, 8480 true); 8481 8482 // defined (<macro>) 8483 Results.EnterNewScope(); 8484 CodeCompletionBuilder Builder(Results.getAllocator(), 8485 Results.getCodeCompletionTUInfo()); 8486 Builder.AddTypedTextChunk("defined"); 8487 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8488 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8489 Builder.AddPlaceholderChunk("macro"); 8490 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8491 Results.AddResult(Builder.TakeString()); 8492 Results.ExitScope(); 8493 8494 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8495 Results.data(), Results.size()); 8496 } 8497 8498 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S, 8499 IdentifierInfo *Macro, 8500 MacroInfo *MacroInfo, 8501 unsigned Argument) { 8502 // FIXME: In the future, we could provide "overload" results, much like we 8503 // do for function calls. 8504 8505 // Now just ignore this. There will be another code-completion callback 8506 // for the expanded tokens. 8507 } 8508 8509 // This handles completion inside an #include filename, e.g. #include <foo/ba 8510 // We look for the directory "foo" under each directory on the include path, 8511 // list its files, and reassemble the appropriate #include. 8512 void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) { 8513 // RelDir should use /, but unescaped \ is possible on windows! 8514 // Our completions will normalize to / for simplicity, this case is rare. 8515 std::string RelDir = llvm::sys::path::convert_to_slash(Dir); 8516 // We need the native slashes for the actual file system interactions. 8517 SmallString<128> NativeRelDir = StringRef(RelDir); 8518 llvm::sys::path::native(NativeRelDir); 8519 llvm::vfs::FileSystem &FS = 8520 getSourceManager().getFileManager().getVirtualFileSystem(); 8521 8522 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8523 CodeCompleter->getCodeCompletionTUInfo(), 8524 CodeCompletionContext::CCC_IncludedFile); 8525 llvm::DenseSet<StringRef> SeenResults; // To deduplicate results. 8526 8527 // Helper: adds one file or directory completion result. 8528 auto AddCompletion = [&](StringRef Filename, bool IsDirectory) { 8529 SmallString<64> TypedChunk = Filename; 8530 // Directory completion is up to the slash, e.g. <sys/ 8531 TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"'); 8532 auto R = SeenResults.insert(TypedChunk); 8533 if (R.second) { // New completion 8534 const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk); 8535 *R.first = InternedTyped; // Avoid dangling StringRef. 8536 CodeCompletionBuilder Builder(CodeCompleter->getAllocator(), 8537 CodeCompleter->getCodeCompletionTUInfo()); 8538 Builder.AddTypedTextChunk(InternedTyped); 8539 // The result is a "Pattern", which is pretty opaque. 8540 // We may want to include the real filename to allow smart ranking. 8541 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 8542 } 8543 }; 8544 8545 // Helper: scans IncludeDir for nice files, and adds results for each. 8546 auto AddFilesFromIncludeDir = [&](StringRef IncludeDir, 8547 bool IsSystem, 8548 DirectoryLookup::LookupType_t LookupType) { 8549 llvm::SmallString<128> Dir = IncludeDir; 8550 if (!NativeRelDir.empty()) { 8551 if (LookupType == DirectoryLookup::LT_Framework) { 8552 // For a framework dir, #include <Foo/Bar/> actually maps to 8553 // a path of Foo.framework/Headers/Bar/. 8554 auto Begin = llvm::sys::path::begin(NativeRelDir); 8555 auto End = llvm::sys::path::end(NativeRelDir); 8556 8557 llvm::sys::path::append(Dir, *Begin + ".framework", "Headers"); 8558 llvm::sys::path::append(Dir, ++Begin, End); 8559 } else { 8560 llvm::sys::path::append(Dir, NativeRelDir); 8561 } 8562 } 8563 8564 std::error_code EC; 8565 unsigned Count = 0; 8566 for (auto It = FS.dir_begin(Dir, EC); 8567 !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) { 8568 if (++Count == 2500) // If we happen to hit a huge directory, 8569 break; // bail out early so we're not too slow. 8570 StringRef Filename = llvm::sys::path::filename(It->path()); 8571 switch (It->type()) { 8572 case llvm::sys::fs::file_type::directory_file: 8573 // All entries in a framework directory must have a ".framework" suffix, 8574 // but the suffix does not appear in the source code's include/import. 8575 if (LookupType == DirectoryLookup::LT_Framework && 8576 NativeRelDir.empty() && !Filename.consume_back(".framework")) 8577 break; 8578 8579 AddCompletion(Filename, /*IsDirectory=*/true); 8580 break; 8581 case llvm::sys::fs::file_type::regular_file: 8582 // Only files that really look like headers. (Except in system dirs). 8583 if (!IsSystem) { 8584 // Header extensions from Types.def, which we can't depend on here. 8585 if (!(Filename.endswith_lower(".h") || 8586 Filename.endswith_lower(".hh") || 8587 Filename.endswith_lower(".hpp") || 8588 Filename.endswith_lower(".inc"))) 8589 break; 8590 } 8591 AddCompletion(Filename, /*IsDirectory=*/false); 8592 break; 8593 default: 8594 break; 8595 } 8596 } 8597 }; 8598 8599 // Helper: adds results relative to IncludeDir, if possible. 8600 auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir, 8601 bool IsSystem) { 8602 switch (IncludeDir.getLookupType()) { 8603 case DirectoryLookup::LT_HeaderMap: 8604 // header maps are not (currently) enumerable. 8605 break; 8606 case DirectoryLookup::LT_NormalDir: 8607 AddFilesFromIncludeDir(IncludeDir.getDir()->getName(), IsSystem, 8608 DirectoryLookup::LT_NormalDir); 8609 break; 8610 case DirectoryLookup::LT_Framework: 8611 AddFilesFromIncludeDir(IncludeDir.getFrameworkDir()->getName(), IsSystem, 8612 DirectoryLookup::LT_Framework); 8613 break; 8614 } 8615 }; 8616 8617 // Finally with all our helpers, we can scan the include path. 8618 // Do this in standard order so deduplication keeps the right file. 8619 // (In case we decide to add more details to the results later). 8620 const auto &S = PP.getHeaderSearchInfo(); 8621 using llvm::make_range; 8622 if (!Angled) { 8623 // The current directory is on the include path for "quoted" includes. 8624 auto *CurFile = PP.getCurrentFileLexer()->getFileEntry(); 8625 if (CurFile && CurFile->getDir()) 8626 AddFilesFromIncludeDir(CurFile->getDir()->getName(), false, 8627 DirectoryLookup::LT_NormalDir); 8628 for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end())) 8629 AddFilesFromDirLookup(D, false); 8630 } 8631 for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end())) 8632 AddFilesFromDirLookup(D, false); 8633 for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end())) 8634 AddFilesFromDirLookup(D, true); 8635 8636 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8637 Results.data(), Results.size()); 8638 } 8639 8640 void Sema::CodeCompleteNaturalLanguage() { 8641 HandleCodeCompleteResults(this, CodeCompleter, 8642 CodeCompletionContext::CCC_NaturalLanguage, nullptr, 8643 0); 8644 } 8645 8646 void Sema::CodeCompleteAvailabilityPlatformName() { 8647 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8648 CodeCompleter->getCodeCompletionTUInfo(), 8649 CodeCompletionContext::CCC_Other); 8650 Results.EnterNewScope(); 8651 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"}; 8652 for (const char *Platform : llvm::makeArrayRef(Platforms)) { 8653 Results.AddResult(CodeCompletionResult(Platform)); 8654 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString( 8655 Twine(Platform) + "ApplicationExtension"))); 8656 } 8657 Results.ExitScope(); 8658 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8659 Results.data(), Results.size()); 8660 } 8661 8662 void Sema::GatherGlobalCodeCompletions( 8663 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, 8664 SmallVectorImpl<CodeCompletionResult> &Results) { 8665 ResultBuilder Builder(*this, Allocator, CCTUInfo, 8666 CodeCompletionContext::CCC_Recovery); 8667 if (!CodeCompleter || CodeCompleter->includeGlobals()) { 8668 CodeCompletionDeclConsumer Consumer(Builder, 8669 Context.getTranslationUnitDecl()); 8670 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName, 8671 Consumer, 8672 !CodeCompleter || CodeCompleter->loadExternal()); 8673 } 8674 8675 if (!CodeCompleter || CodeCompleter->includeMacros()) 8676 AddMacroResults(PP, Builder, 8677 CodeCompleter ? CodeCompleter->loadExternal() : false, 8678 true); 8679 8680 Results.clear(); 8681 Results.insert(Results.end(), Builder.data(), 8682 Builder.data() + Builder.size()); 8683 } 8684