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