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