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