clang  9.0.0svn
SemaCodeComplete.cpp
Go to the documentation of this file.
1 //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the code-completion semantic actions.
10 //
11 //===----------------------------------------------------------------------===//
12 #include "clang/AST/Decl.h"
13 #include "clang/AST/DeclBase.h"
14 #include "clang/AST/DeclCXX.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/ExprObjC.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Lex/HeaderSearch.h"
21 #include "clang/Lex/MacroInfo.h"
22 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/Lookup.h"
25 #include "clang/Sema/Overload.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/SmallBitVector.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/StringSwitch.h"
35 #include "llvm/ADT/Twine.h"
36 #include "llvm/ADT/iterator_range.h"
37 #include "llvm/Support/Path.h"
38 #include <list>
39 #include <map>
40 #include <vector>
41 
42 using namespace clang;
43 using namespace sema;
44 
45 namespace {
46 /// A container of code-completion results.
47 class ResultBuilder {
48 public:
49  /// The type of a name-lookup filter, which can be provided to the
50  /// name-lookup routines to specify which declarations should be included in
51  /// the result set (when it returns true) and which declarations should be
52  /// filtered out (returns false).
53  typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
54 
55  typedef CodeCompletionResult Result;
56 
57 private:
58  /// The actual results we have found.
59  std::vector<Result> Results;
60 
61  /// A record of all of the declarations we have found and placed
62  /// into the result set, used to ensure that no declaration ever gets into
63  /// the result set twice.
64  llvm::SmallPtrSet<const Decl *, 16> AllDeclsFound;
65 
66  typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
67 
68  /// An entry in the shadow map, which is optimized to store
69  /// a single (declaration, index) mapping (the common case) but
70  /// can also store a list of (declaration, index) mappings.
71  class ShadowMapEntry {
72  typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
73 
74  /// Contains either the solitary NamedDecl * or a vector
75  /// of (declaration, index) pairs.
76  llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector;
77 
78  /// When the entry contains a single declaration, this is
79  /// the index associated with that entry.
80  unsigned SingleDeclIndex;
81 
82  public:
83  ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) {}
84 
85  void Add(const NamedDecl *ND, unsigned Index) {
86  if (DeclOrVector.isNull()) {
87  // 0 - > 1 elements: just set the single element information.
88  DeclOrVector = ND;
89  SingleDeclIndex = Index;
90  return;
91  }
92 
93  if (const NamedDecl *PrevND =
94  DeclOrVector.dyn_cast<const NamedDecl *>()) {
95  // 1 -> 2 elements: create the vector of results and push in the
96  // existing declaration.
97  DeclIndexPairVector *Vec = new DeclIndexPairVector;
98  Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
99  DeclOrVector = Vec;
100  }
101 
102  // Add the new element to the end of the vector.
103  DeclOrVector.get<DeclIndexPairVector *>()->push_back(
104  DeclIndexPair(ND, Index));
105  }
106 
107  void Destroy() {
108  if (DeclIndexPairVector *Vec =
109  DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
110  delete Vec;
111  DeclOrVector = ((NamedDecl *)nullptr);
112  }
113  }
114 
115  // Iteration.
116  class iterator;
117  iterator begin() const;
118  iterator end() const;
119  };
120 
121  /// A mapping from declaration names to the declarations that have
122  /// this name within a particular scope and their index within the list of
123  /// results.
124  typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
125 
126  /// The semantic analysis object for which results are being
127  /// produced.
128  Sema &SemaRef;
129 
130  /// The allocator used to allocate new code-completion strings.
131  CodeCompletionAllocator &Allocator;
132 
133  CodeCompletionTUInfo &CCTUInfo;
134 
135  /// If non-NULL, a filter function used to remove any code-completion
136  /// results that are not desirable.
137  LookupFilter Filter;
138 
139  /// Whether we should allow declarations as
140  /// nested-name-specifiers that would otherwise be filtered out.
141  bool AllowNestedNameSpecifiers;
142 
143  /// If set, the type that we would prefer our resulting value
144  /// declarations to have.
145  ///
146  /// Closely matching the preferred type gives a boost to a result's
147  /// priority.
148  CanQualType PreferredType;
149 
150  /// A list of shadow maps, which is used to model name hiding at
151  /// different levels of, e.g., the inheritance hierarchy.
152  std::list<ShadowMap> ShadowMaps;
153 
154  /// If we're potentially referring to a C++ member function, the set
155  /// of qualifiers applied to the object type.
156  Qualifiers ObjectTypeQualifiers;
157 
158  /// Whether the \p ObjectTypeQualifiers field is active.
159  bool HasObjectTypeQualifiers;
160 
161  /// The selector that we prefer.
162  Selector PreferredSelector;
163 
164  /// The completion context in which we are gathering results.
165  CodeCompletionContext CompletionContext;
166 
167  /// If we are in an instance method definition, the \@implementation
168  /// object.
169  ObjCImplementationDecl *ObjCImplementation;
170 
171  void AdjustResultPriorityForDecl(Result &R);
172 
173  void MaybeAddConstructorResults(Result R);
174 
175 public:
176  explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
177  CodeCompletionTUInfo &CCTUInfo,
178  const CodeCompletionContext &CompletionContext,
179  LookupFilter Filter = nullptr)
180  : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
181  Filter(Filter), AllowNestedNameSpecifiers(false),
182  HasObjectTypeQualifiers(false), CompletionContext(CompletionContext),
183  ObjCImplementation(nullptr) {
184  // If this is an Objective-C instance method definition, dig out the
185  // corresponding implementation.
186  switch (CompletionContext.getKind()) {
192  if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
193  if (Method->isInstanceMethod())
194  if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
195  ObjCImplementation = Interface->getImplementation();
196  break;
197 
198  default:
199  break;
200  }
201  }
202 
203  /// Determine the priority for a reference to the given declaration.
204  unsigned getBasePriority(const NamedDecl *D);
205 
206  /// Whether we should include code patterns in the completion
207  /// results.
208  bool includeCodePatterns() const {
209  return SemaRef.CodeCompleter &&
211  }
212 
213  /// Set the filter used for code-completion results.
214  void setFilter(LookupFilter Filter) { this->Filter = Filter; }
215 
216  Result *data() { return Results.empty() ? nullptr : &Results.front(); }
217  unsigned size() const { return Results.size(); }
218  bool empty() const { return Results.empty(); }
219 
220  /// Specify the preferred type.
221  void setPreferredType(QualType T) {
222  PreferredType = SemaRef.Context.getCanonicalType(T);
223  }
224 
225  /// Set the cv-qualifiers on the object type, for us in filtering
226  /// calls to member functions.
227  ///
228  /// When there are qualifiers in this set, they will be used to filter
229  /// out member functions that aren't available (because there will be a
230  /// cv-qualifier mismatch) or prefer functions with an exact qualifier
231  /// match.
232  void setObjectTypeQualifiers(Qualifiers Quals) {
233  ObjectTypeQualifiers = Quals;
234  HasObjectTypeQualifiers = true;
235  }
236 
237  /// Set the preferred selector.
238  ///
239  /// When an Objective-C method declaration result is added, and that
240  /// method's selector matches this preferred selector, we give that method
241  /// a slight priority boost.
242  void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; }
243 
244  /// Retrieve the code-completion context for which results are
245  /// being collected.
246  const CodeCompletionContext &getCompletionContext() const {
247  return CompletionContext;
248  }
249 
250  /// Specify whether nested-name-specifiers are allowed.
251  void allowNestedNameSpecifiers(bool Allow = true) {
252  AllowNestedNameSpecifiers = Allow;
253  }
254 
255  /// Return the semantic analysis object for which we are collecting
256  /// code completion results.
257  Sema &getSema() const { return SemaRef; }
258 
259  /// Retrieve the allocator used to allocate code completion strings.
260  CodeCompletionAllocator &getAllocator() const { return Allocator; }
261 
262  CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
263 
264  /// Determine whether the given declaration is at all interesting
265  /// as a code-completion result.
266  ///
267  /// \param ND the declaration that we are inspecting.
268  ///
269  /// \param AsNestedNameSpecifier will be set true if this declaration is
270  /// only interesting when it is a nested-name-specifier.
271  bool isInterestingDecl(const NamedDecl *ND,
272  bool &AsNestedNameSpecifier) const;
273 
274  /// Check whether the result is hidden by the Hiding declaration.
275  ///
276  /// \returns true if the result is hidden and cannot be found, false if
277  /// the hidden result could still be found. When false, \p R may be
278  /// modified to describe how the result can be found (e.g., via extra
279  /// qualification).
280  bool CheckHiddenResult(Result &R, DeclContext *CurContext,
281  const NamedDecl *Hiding);
282 
283  /// Add a new result to this result set (if it isn't already in one
284  /// of the shadow maps), or replace an existing result (for, e.g., a
285  /// redeclaration).
286  ///
287  /// \param R the result to add (if it is unique).
288  ///
289  /// \param CurContext the context in which this result will be named.
290  void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
291 
292  /// Add a new result to this result set, where we already know
293  /// the hiding declaration (if any).
294  ///
295  /// \param R the result to add (if it is unique).
296  ///
297  /// \param CurContext the context in which this result will be named.
298  ///
299  /// \param Hiding the declaration that hides the result.
300  ///
301  /// \param InBaseClass whether the result was found in a base
302  /// class of the searched context.
303  void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
304  bool InBaseClass);
305 
306  /// Add a new non-declaration result to this result set.
307  void AddResult(Result R);
308 
309  /// Enter into a new scope.
310  void EnterNewScope();
311 
312  /// Exit from the current scope.
313  void ExitScope();
314 
315  /// Ignore this declaration, if it is seen again.
316  void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
317 
318  /// Add a visited context.
319  void addVisitedContext(DeclContext *Ctx) {
320  CompletionContext.addVisitedContext(Ctx);
321  }
322 
323  /// \name Name lookup predicates
324  ///
325  /// These predicates can be passed to the name lookup functions to filter the
326  /// results of name lookup. All of the predicates have the same type, so that
327  ///
328  //@{
329  bool IsOrdinaryName(const NamedDecl *ND) const;
330  bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
331  bool IsIntegralConstantValue(const NamedDecl *ND) const;
332  bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
333  bool IsNestedNameSpecifier(const NamedDecl *ND) const;
334  bool IsEnum(const NamedDecl *ND) const;
335  bool IsClassOrStruct(const NamedDecl *ND) const;
336  bool IsUnion(const NamedDecl *ND) const;
337  bool IsNamespace(const NamedDecl *ND) const;
338  bool IsNamespaceOrAlias(const NamedDecl *ND) const;
339  bool IsType(const NamedDecl *ND) const;
340  bool IsMember(const NamedDecl *ND) const;
341  bool IsObjCIvar(const NamedDecl *ND) const;
342  bool IsObjCMessageReceiver(const NamedDecl *ND) const;
343  bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
344  bool IsObjCCollection(const NamedDecl *ND) const;
345  bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
346  //@}
347 };
348 } // namespace
349 
351  if (isa<BlockDecl>(S.CurContext)) {
352  if (sema::BlockScopeInfo *BSI = S.getCurBlock()) {
353  ComputeType = nullptr;
354  Type = BSI->ReturnType;
355  ExpectedLoc = Tok;
356  }
357  } else if (const auto *Function = dyn_cast<FunctionDecl>(S.CurContext)) {
358  ComputeType = nullptr;
359  Type = Function->getReturnType();
360  ExpectedLoc = Tok;
361  } else if (const auto *Method = dyn_cast<ObjCMethodDecl>(S.CurContext)) {
362  ComputeType = nullptr;
363  Type = Method->getReturnType();
364  ExpectedLoc = Tok;
365  }
366 }
367 
369  auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
370  ComputeType = nullptr;
371  Type = VD ? VD->getType() : QualType();
372  ExpectedLoc = Tok;
373 }
374 
376  SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) {
377  this->ComputeType = ComputeType;
378  Type = QualType();
379  ExpectedLoc = Tok;
380 }
381 
383  SourceLocation LParLoc) {
384  // expected type for parenthesized expression does not change.
385  if (ExpectedLoc == LParLoc)
386  ExpectedLoc = Tok;
387 }
388 
390  tok::TokenKind Op) {
391  if (!LHS)
392  return QualType();
393 
394  QualType LHSType = LHS->getType();
395  if (LHSType->isPointerType()) {
396  if (Op == tok::plus || Op == tok::plusequal || Op == tok::minusequal)
397  return S.getASTContext().getPointerDiffType();
398  // Pointer difference is more common than subtracting an int from a pointer.
399  if (Op == tok::minus)
400  return LHSType;
401  }
402 
403  switch (Op) {
404  // No way to infer the type of RHS from LHS.
405  case tok::comma:
406  return QualType();
407  // Prefer the type of the left operand for all of these.
408  // Arithmetic operations.
409  case tok::plus:
410  case tok::plusequal:
411  case tok::minus:
412  case tok::minusequal:
413  case tok::percent:
414  case tok::percentequal:
415  case tok::slash:
416  case tok::slashequal:
417  case tok::star:
418  case tok::starequal:
419  // Assignment.
420  case tok::equal:
421  // Comparison operators.
422  case tok::equalequal:
423  case tok::exclaimequal:
424  case tok::less:
425  case tok::lessequal:
426  case tok::greater:
427  case tok::greaterequal:
428  case tok::spaceship:
429  return LHS->getType();
430  // Binary shifts are often overloaded, so don't try to guess those.
431  case tok::greatergreater:
432  case tok::greatergreaterequal:
433  case tok::lessless:
434  case tok::lesslessequal:
435  if (LHSType->isIntegralOrEnumerationType())
436  return S.getASTContext().IntTy;
437  return QualType();
438  // Logical operators, assume we want bool.
439  case tok::ampamp:
440  case tok::pipepipe:
441  case tok::caretcaret:
442  return S.getASTContext().BoolTy;
443  // Operators often used for bit manipulation are typically used with the type
444  // of the left argument.
445  case tok::pipe:
446  case tok::pipeequal:
447  case tok::caret:
448  case tok::caretequal:
449  case tok::amp:
450  case tok::ampequal:
451  if (LHSType->isIntegralOrEnumerationType())
452  return LHSType;
453  return QualType();
454  // RHS should be a pointer to a member of the 'LHS' type, but we can't give
455  // any particular type here.
456  case tok::periodstar:
457  case tok::arrowstar:
458  return QualType();
459  default:
460  // FIXME(ibiryukov): handle the missing op, re-add the assertion.
461  // assert(false && "unhandled binary op");
462  return QualType();
463  }
464 }
465 
466 /// Get preferred type for an argument of an unary expression. \p ContextType is
467 /// preferred type of the whole unary expression.
469  tok::TokenKind Op) {
470  switch (Op) {
471  case tok::exclaim:
472  return S.getASTContext().BoolTy;
473  case tok::amp:
474  if (!ContextType.isNull() && ContextType->isPointerType())
475  return ContextType->getPointeeType();
476  return QualType();
477  case tok::star:
478  if (ContextType.isNull())
479  return QualType();
480  return S.getASTContext().getPointerType(ContextType.getNonReferenceType());
481  case tok::plus:
482  case tok::minus:
483  case tok::tilde:
484  case tok::minusminus:
485  case tok::plusplus:
486  if (ContextType.isNull())
487  return S.getASTContext().IntTy;
488  // leave as is, these operators typically return the same type.
489  return ContextType;
490  case tok::kw___real:
491  case tok::kw___imag:
492  return QualType();
493  default:
494  assert(false && "unhandled unary op");
495  return QualType();
496  }
497 }
498 
500  tok::TokenKind Op) {
501  ComputeType = nullptr;
502  Type = getPreferredTypeOfBinaryRHS(S, LHS, Op);
503  ExpectedLoc = Tok;
504 }
505 
507  Expr *Base) {
508  if (!Base)
509  return;
510  // Do we have expected type for Base?
511  if (ExpectedLoc != Base->getBeginLoc())
512  return;
513  // Keep the expected type, only update the location.
514  ExpectedLoc = Tok;
515  return;
516 }
517 
519  tok::TokenKind OpKind,
520  SourceLocation OpLoc) {
521  ComputeType = nullptr;
522  Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind);
523  ExpectedLoc = Tok;
524 }
525 
527  Expr *LHS) {
528  ComputeType = nullptr;
529  Type = S.getASTContext().IntTy;
530  ExpectedLoc = Tok;
531 }
532 
534  QualType CastType) {
535  ComputeType = nullptr;
536  Type = !CastType.isNull() ? CastType.getCanonicalType() : QualType();
537  ExpectedLoc = Tok;
538 }
539 
541  ComputeType = nullptr;
542  Type = S.getASTContext().BoolTy;
543  ExpectedLoc = Tok;
544 }
545 
547  llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
548  unsigned SingleDeclIndex;
549 
550 public:
551  typedef DeclIndexPair value_type;
552  typedef value_type reference;
554  typedef std::input_iterator_tag iterator_category;
555 
556  class pointer {
557  DeclIndexPair Value;
558 
559  public:
560  pointer(const DeclIndexPair &Value) : Value(Value) {}
561 
562  const DeclIndexPair *operator->() const { return &Value; }
563  };
564 
565  iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
566 
567  iterator(const NamedDecl *SingleDecl, unsigned Index)
568  : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {}
569 
570  iterator(const DeclIndexPair *Iterator)
571  : DeclOrIterator(Iterator), SingleDeclIndex(0) {}
572 
574  if (DeclOrIterator.is<const NamedDecl *>()) {
575  DeclOrIterator = (NamedDecl *)nullptr;
576  SingleDeclIndex = 0;
577  return *this;
578  }
579 
580  const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair *>();
581  ++I;
582  DeclOrIterator = I;
583  return *this;
584  }
585 
586  /*iterator operator++(int) {
587  iterator tmp(*this);
588  ++(*this);
589  return tmp;
590  }*/
591 
592  reference operator*() const {
593  if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
594  return reference(ND, SingleDeclIndex);
595 
596  return *DeclOrIterator.get<const DeclIndexPair *>();
597  }
598 
599  pointer operator->() const { return pointer(**this); }
600 
601  friend bool operator==(const iterator &X, const iterator &Y) {
602  return X.DeclOrIterator.getOpaqueValue() ==
603  Y.DeclOrIterator.getOpaqueValue() &&
604  X.SingleDeclIndex == Y.SingleDeclIndex;
605  }
606 
607  friend bool operator!=(const iterator &X, const iterator &Y) {
608  return !(X == Y);
609  }
610 };
611 
613 ResultBuilder::ShadowMapEntry::begin() const {
614  if (DeclOrVector.isNull())
615  return iterator();
616 
617  if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
618  return iterator(ND, SingleDeclIndex);
619 
620  return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
621 }
622 
624 ResultBuilder::ShadowMapEntry::end() const {
625  if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
626  return iterator();
627 
628  return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
629 }
630 
631 /// Compute the qualification required to get from the current context
632 /// (\p CurContext) to the target context (\p TargetContext).
633 ///
634 /// \param Context the AST context in which the qualification will be used.
635 ///
636 /// \param CurContext the context where an entity is being named, which is
637 /// typically based on the current scope.
638 ///
639 /// \param TargetContext the context in which the named entity actually
640 /// resides.
641 ///
642 /// \returns a nested name specifier that refers into the target context, or
643 /// NULL if no qualification is needed.
644 static NestedNameSpecifier *
645 getRequiredQualification(ASTContext &Context, const DeclContext *CurContext,
646  const DeclContext *TargetContext) {
648 
649  for (const DeclContext *CommonAncestor = TargetContext;
650  CommonAncestor && !CommonAncestor->Encloses(CurContext);
651  CommonAncestor = CommonAncestor->getLookupParent()) {
652  if (CommonAncestor->isTransparentContext() ||
653  CommonAncestor->isFunctionOrMethod())
654  continue;
655 
656  TargetParents.push_back(CommonAncestor);
657  }
658 
659  NestedNameSpecifier *Result = nullptr;
660  while (!TargetParents.empty()) {
661  const DeclContext *Parent = TargetParents.pop_back_val();
662 
663  if (const auto *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
664  if (!Namespace->getIdentifier())
665  continue;
666 
667  Result = NestedNameSpecifier::Create(Context, Result, Namespace);
668  } else if (const auto *TD = dyn_cast<TagDecl>(Parent))
670  Context, Result, false, Context.getTypeDeclType(TD).getTypePtr());
671  }
672  return Result;
673 }
674 
675 /// Determine whether \p Id is a name reserved for the implementation (C99
676 /// 7.1.3, C++ [lib.global.names]).
677 static bool isReservedName(const IdentifierInfo *Id,
678  bool doubleUnderscoreOnly = false) {
679  if (Id->getLength() < 2)
680  return false;
681  const char *Name = Id->getNameStart();
682  return Name[0] == '_' &&
683  (Name[1] == '_' ||
684  (Name[1] >= 'A' && Name[1] <= 'Z' && !doubleUnderscoreOnly));
685 }
686 
687 // Some declarations have reserved names that we don't want to ever show.
688 // Filter out names reserved for the implementation if they come from a
689 // system header.
690 static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
691  const IdentifierInfo *Id = ND->getIdentifier();
692  if (!Id)
693  return false;
694 
695  // Ignore reserved names for compiler provided decls.
696  if (isReservedName(Id) && ND->getLocation().isInvalid())
697  return true;
698 
699  // For system headers ignore only double-underscore names.
700  // This allows for system headers providing private symbols with a single
701  // underscore.
702  if (isReservedName(Id, /*doubleUnderscoreOnly=*/true) &&
703  SemaRef.SourceMgr.isInSystemHeader(
704  SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
705  return true;
706 
707  return false;
708 }
709 
710 bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
711  bool &AsNestedNameSpecifier) const {
712  AsNestedNameSpecifier = false;
713 
714  auto *Named = ND;
715  ND = ND->getUnderlyingDecl();
716 
717  // Skip unnamed entities.
718  if (!ND->getDeclName())
719  return false;
720 
721  // Friend declarations and declarations introduced due to friends are never
722  // added as results.
724  return false;
725 
726  // Class template (partial) specializations are never added as results.
727  if (isa<ClassTemplateSpecializationDecl>(ND) ||
728  isa<ClassTemplatePartialSpecializationDecl>(ND))
729  return false;
730 
731  // Using declarations themselves are never added as results.
732  if (isa<UsingDecl>(ND))
733  return false;
734 
735  if (shouldIgnoreDueToReservedName(ND, SemaRef))
736  return false;
737 
738  if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
739  (isa<NamespaceDecl>(ND) && Filter != &ResultBuilder::IsNamespace &&
740  Filter != &ResultBuilder::IsNamespaceOrAlias && Filter != nullptr))
741  AsNestedNameSpecifier = true;
742 
743  // Filter out any unwanted results.
744  if (Filter && !(this->*Filter)(Named)) {
745  // Check whether it is interesting as a nested-name-specifier.
746  if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
747  IsNestedNameSpecifier(ND) &&
748  (Filter != &ResultBuilder::IsMember ||
749  (isa<CXXRecordDecl>(ND) &&
750  cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
751  AsNestedNameSpecifier = true;
752  return true;
753  }
754 
755  return false;
756  }
757  // ... then it must be interesting!
758  return true;
759 }
760 
761 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
762  const NamedDecl *Hiding) {
763  // In C, there is no way to refer to a hidden name.
764  // FIXME: This isn't true; we can find a tag name hidden by an ordinary
765  // name if we introduce the tag type.
766  if (!SemaRef.getLangOpts().CPlusPlus)
767  return true;
768 
769  const DeclContext *HiddenCtx =
770  R.Declaration->getDeclContext()->getRedeclContext();
771 
772  // There is no way to qualify a name declared in a function or method.
773  if (HiddenCtx->isFunctionOrMethod())
774  return true;
775 
776  if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
777  return true;
778 
779  // We can refer to the result with the appropriate qualification. Do it.
780  R.Hidden = true;
781  R.QualifierIsInformative = false;
782 
783  if (!R.Qualifier)
784  R.Qualifier = getRequiredQualification(SemaRef.Context, CurContext,
785  R.Declaration->getDeclContext());
786  return false;
787 }
788 
789 /// A simplified classification of types used to determine whether two
790 /// types are "similar enough" when adjusting priorities.
792  switch (T->getTypeClass()) {
793  case Type::Builtin:
794  switch (cast<BuiltinType>(T)->getKind()) {
795  case BuiltinType::Void:
796  return STC_Void;
797 
798  case BuiltinType::NullPtr:
799  return STC_Pointer;
800 
801  case BuiltinType::Overload:
802  case BuiltinType::Dependent:
803  return STC_Other;
804 
805  case BuiltinType::ObjCId:
806  case BuiltinType::ObjCClass:
807  case BuiltinType::ObjCSel:
808  return STC_ObjectiveC;
809 
810  default:
811  return STC_Arithmetic;
812  }
813 
814  case Type::Complex:
815  return STC_Arithmetic;
816 
817  case Type::Pointer:
818  return STC_Pointer;
819 
820  case Type::BlockPointer:
821  return STC_Block;
822 
823  case Type::LValueReference:
824  case Type::RValueReference:
826 
827  case Type::ConstantArray:
828  case Type::IncompleteArray:
829  case Type::VariableArray:
830  case Type::DependentSizedArray:
831  return STC_Array;
832 
833  case Type::DependentSizedExtVector:
834  case Type::Vector:
835  case Type::ExtVector:
836  return STC_Arithmetic;
837 
838  case Type::FunctionProto:
839  case Type::FunctionNoProto:
840  return STC_Function;
841 
842  case Type::Record:
843  return STC_Record;
844 
845  case Type::Enum:
846  return STC_Arithmetic;
847 
848  case Type::ObjCObject:
849  case Type::ObjCInterface:
850  case Type::ObjCObjectPointer:
851  return STC_ObjectiveC;
852 
853  default:
854  return STC_Other;
855  }
856 }
857 
858 /// Get the type that a given expression will have if this declaration
859 /// is used as an expression in its "typical" code-completion form.
861  ND = ND->getUnderlyingDecl();
862 
863  if (const auto *Type = dyn_cast<TypeDecl>(ND))
864  return C.getTypeDeclType(Type);
865  if (const auto *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
866  return C.getObjCInterfaceType(Iface);
867 
868  QualType T;
869  if (const FunctionDecl *Function = ND->getAsFunction())
870  T = Function->getCallResultType();
871  else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND))
872  T = Method->getSendResultType();
873  else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND))
874  T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
875  else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND))
876  T = Property->getType();
877  else if (const auto *Value = dyn_cast<ValueDecl>(ND))
878  T = Value->getType();
879 
880  if (T.isNull())
881  return QualType();
882 
883  // Dig through references, function pointers, and block pointers to
884  // get down to the likely type of an expression when the entity is
885  // used.
886  do {
887  if (const auto *Ref = T->getAs<ReferenceType>()) {
888  T = Ref->getPointeeType();
889  continue;
890  }
891 
892  if (const auto *Pointer = T->getAs<PointerType>()) {
893  if (Pointer->getPointeeType()->isFunctionType()) {
894  T = Pointer->getPointeeType();
895  continue;
896  }
897 
898  break;
899  }
900 
901  if (const auto *Block = T->getAs<BlockPointerType>()) {
902  T = Block->getPointeeType();
903  continue;
904  }
905 
906  if (const auto *Function = T->getAs<FunctionType>()) {
907  T = Function->getReturnType();
908  continue;
909  }
910 
911  break;
912  } while (true);
913 
914  return T;
915 }
916 
917 unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
918  if (!ND)
919  return CCP_Unlikely;
920 
921  // Context-based decisions.
922  const DeclContext *LexicalDC = ND->getLexicalDeclContext();
923  if (LexicalDC->isFunctionOrMethod()) {
924  // _cmd is relatively rare
925  if (const auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
926  if (ImplicitParam->getIdentifier() &&
927  ImplicitParam->getIdentifier()->isStr("_cmd"))
928  return CCP_ObjC_cmd;
929 
930  return CCP_LocalDeclaration;
931  }
932 
933  const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
934  if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
935  // Explicit destructor calls are very rare.
936  if (isa<CXXDestructorDecl>(ND))
937  return CCP_Unlikely;
938  // Explicit operator and conversion function calls are also very rare.
939  auto DeclNameKind = ND->getDeclName().getNameKind();
940  if (DeclNameKind == DeclarationName::CXXOperatorName ||
941  DeclNameKind == DeclarationName::CXXLiteralOperatorName ||
943  return CCP_Unlikely;
944  return CCP_MemberDeclaration;
945  }
946 
947  // Content-based decisions.
948  if (isa<EnumConstantDecl>(ND))
949  return CCP_Constant;
950 
951  // Use CCP_Type for type declarations unless we're in a statement, Objective-C
952  // message receiver, or parenthesized expression context. There, it's as
953  // likely that the user will want to write a type as other declarations.
954  if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
955  !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
956  CompletionContext.getKind() ==
958  CompletionContext.getKind() ==
960  return CCP_Type;
961 
962  return CCP_Declaration;
963 }
964 
965 void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
966  // If this is an Objective-C method declaration whose selector matches our
967  // preferred selector, give it a priority boost.
968  if (!PreferredSelector.isNull())
969  if (const auto *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
970  if (PreferredSelector == Method->getSelector())
971  R.Priority += CCD_SelectorMatch;
972 
973  // If we have a preferred type, adjust the priority for results with exactly-
974  // matching or nearly-matching types.
975  if (!PreferredType.isNull()) {
976  QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
977  if (!T.isNull()) {
978  CanQualType TC = SemaRef.Context.getCanonicalType(T);
979  // Check for exactly-matching types (modulo qualifiers).
980  if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
981  R.Priority /= CCF_ExactTypeMatch;
982  // Check for nearly-matching types, based on classification of each.
983  else if ((getSimplifiedTypeClass(PreferredType) ==
984  getSimplifiedTypeClass(TC)) &&
985  !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
986  R.Priority /= CCF_SimilarTypeMatch;
987  }
988  }
989 }
990 
992  const CXXRecordDecl *Record) {
993  QualType RecordTy = Context.getTypeDeclType(Record);
994  DeclarationName ConstructorName =
996  Context.getCanonicalType(RecordTy));
997  return Record->lookup(ConstructorName);
998 }
999 
1000 void ResultBuilder::MaybeAddConstructorResults(Result R) {
1001  if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
1002  !CompletionContext.wantConstructorResults())
1003  return;
1004 
1005  const NamedDecl *D = R.Declaration;
1006  const CXXRecordDecl *Record = nullptr;
1007  if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
1008  Record = ClassTemplate->getTemplatedDecl();
1009  else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
1010  // Skip specializations and partial specializations.
1011  if (isa<ClassTemplateSpecializationDecl>(Record))
1012  return;
1013  } else {
1014  // There are no constructors here.
1015  return;
1016  }
1017 
1018  Record = Record->getDefinition();
1019  if (!Record)
1020  return;
1021 
1022  for (NamedDecl *Ctor : getConstructors(SemaRef.Context, Record)) {
1023  R.Declaration = Ctor;
1024  R.CursorKind = getCursorKindForDecl(R.Declaration);
1025  Results.push_back(R);
1026  }
1027 }
1028 
1029 static bool isConstructor(const Decl *ND) {
1030  if (const auto *Tmpl = dyn_cast<FunctionTemplateDecl>(ND))
1031  ND = Tmpl->getTemplatedDecl();
1032  return isa<CXXConstructorDecl>(ND);
1033 }
1034 
1035 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
1036  assert(!ShadowMaps.empty() && "Must enter into a results scope");
1037 
1038  if (R.Kind != Result::RK_Declaration) {
1039  // For non-declaration results, just add the result.
1040  Results.push_back(R);
1041  return;
1042  }
1043 
1044  // Look through using declarations.
1045  if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1046  CodeCompletionResult Result(Using->getTargetDecl(),
1047  getBasePriority(Using->getTargetDecl()),
1048  R.Qualifier);
1049  Result.ShadowDecl = Using;
1050  MaybeAddResult(Result, CurContext);
1051  return;
1052  }
1053 
1054  const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
1055  unsigned IDNS = CanonDecl->getIdentifierNamespace();
1056 
1057  bool AsNestedNameSpecifier = false;
1058  if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1059  return;
1060 
1061  // C++ constructors are never found by name lookup.
1062  if (isConstructor(R.Declaration))
1063  return;
1064 
1065  ShadowMap &SMap = ShadowMaps.back();
1066  ShadowMapEntry::iterator I, IEnd;
1067  ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
1068  if (NamePos != SMap.end()) {
1069  I = NamePos->second.begin();
1070  IEnd = NamePos->second.end();
1071  }
1072 
1073  for (; I != IEnd; ++I) {
1074  const NamedDecl *ND = I->first;
1075  unsigned Index = I->second;
1076  if (ND->getCanonicalDecl() == CanonDecl) {
1077  // This is a redeclaration. Always pick the newer declaration.
1078  Results[Index].Declaration = R.Declaration;
1079 
1080  // We're done.
1081  return;
1082  }
1083  }
1084 
1085  // This is a new declaration in this scope. However, check whether this
1086  // declaration name is hidden by a similarly-named declaration in an outer
1087  // scope.
1088  std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
1089  --SMEnd;
1090  for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
1091  ShadowMapEntry::iterator I, IEnd;
1092  ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
1093  if (NamePos != SM->end()) {
1094  I = NamePos->second.begin();
1095  IEnd = NamePos->second.end();
1096  }
1097  for (; I != IEnd; ++I) {
1098  // A tag declaration does not hide a non-tag declaration.
1099  if (I->first->hasTagIdentifierNamespace() &&
1102  continue;
1103 
1104  // Protocols are in distinct namespaces from everything else.
1105  if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) ||
1106  (IDNS & Decl::IDNS_ObjCProtocol)) &&
1107  I->first->getIdentifierNamespace() != IDNS)
1108  continue;
1109 
1110  // The newly-added result is hidden by an entry in the shadow map.
1111  if (CheckHiddenResult(R, CurContext, I->first))
1112  return;
1113 
1114  break;
1115  }
1116  }
1117 
1118  // Make sure that any given declaration only shows up in the result set once.
1119  if (!AllDeclsFound.insert(CanonDecl).second)
1120  return;
1121 
1122  // If the filter is for nested-name-specifiers, then this result starts a
1123  // nested-name-specifier.
1124  if (AsNestedNameSpecifier) {
1125  R.StartsNestedNameSpecifier = true;
1126  R.Priority = CCP_NestedNameSpecifier;
1127  } else
1128  AdjustResultPriorityForDecl(R);
1129 
1130  // If this result is supposed to have an informative qualifier, add one.
1131  if (R.QualifierIsInformative && !R.Qualifier &&
1132  !R.StartsNestedNameSpecifier) {
1133  const DeclContext *Ctx = R.Declaration->getDeclContext();
1134  if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1135  R.Qualifier =
1136  NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1137  else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
1138  R.Qualifier = NestedNameSpecifier::Create(
1139  SemaRef.Context, nullptr, false,
1140  SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1141  else
1142  R.QualifierIsInformative = false;
1143  }
1144 
1145  // Insert this result into the set of results and into the current shadow
1146  // map.
1147  SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
1148  Results.push_back(R);
1149 
1150  if (!AsNestedNameSpecifier)
1151  MaybeAddConstructorResults(R);
1152 }
1153 
1156  R.InBaseClass = true;
1157 }
1158 
1159 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
1160  NamedDecl *Hiding, bool InBaseClass = false) {
1161  if (R.Kind != Result::RK_Declaration) {
1162  // For non-declaration results, just add the result.
1163  Results.push_back(R);
1164  return;
1165  }
1166 
1167  // Look through using declarations.
1168  if (const auto *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1169  CodeCompletionResult Result(Using->getTargetDecl(),
1170  getBasePriority(Using->getTargetDecl()),
1171  R.Qualifier);
1172  Result.ShadowDecl = Using;
1173  AddResult(Result, CurContext, Hiding);
1174  return;
1175  }
1176 
1177  bool AsNestedNameSpecifier = false;
1178  if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1179  return;
1180 
1181  // C++ constructors are never found by name lookup.
1182  if (isConstructor(R.Declaration))
1183  return;
1184 
1185  if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
1186  return;
1187 
1188  // Make sure that any given declaration only shows up in the result set once.
1189  if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
1190  return;
1191 
1192  // If the filter is for nested-name-specifiers, then this result starts a
1193  // nested-name-specifier.
1194  if (AsNestedNameSpecifier) {
1195  R.StartsNestedNameSpecifier = true;
1196  R.Priority = CCP_NestedNameSpecifier;
1197  } else if (Filter == &ResultBuilder::IsMember && !R.Qualifier &&
1198  InBaseClass &&
1199  isa<CXXRecordDecl>(
1200  R.Declaration->getDeclContext()->getRedeclContext()))
1201  R.QualifierIsInformative = true;
1202 
1203  // If this result is supposed to have an informative qualifier, add one.
1204  if (R.QualifierIsInformative && !R.Qualifier &&
1205  !R.StartsNestedNameSpecifier) {
1206  const DeclContext *Ctx = R.Declaration->getDeclContext();
1207  if (const auto *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1208  R.Qualifier =
1209  NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1210  else if (const auto *Tag = dyn_cast<TagDecl>(Ctx))
1211  R.Qualifier = NestedNameSpecifier::Create(
1212  SemaRef.Context, nullptr, false,
1213  SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1214  else
1215  R.QualifierIsInformative = false;
1216  }
1217 
1218  // Adjust the priority if this result comes from a base class.
1219  if (InBaseClass)
1220  setInBaseClass(R);
1221 
1222  AdjustResultPriorityForDecl(R);
1223 
1224  if (HasObjectTypeQualifiers)
1225  if (const auto *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
1226  if (Method->isInstance()) {
1227  Qualifiers MethodQuals = Method->getMethodQualifiers();
1228  if (ObjectTypeQualifiers == MethodQuals)
1229  R.Priority += CCD_ObjectQualifierMatch;
1230  else if (ObjectTypeQualifiers - MethodQuals) {
1231  // The method cannot be invoked, because doing so would drop
1232  // qualifiers.
1233  return;
1234  }
1235  }
1236 
1237  // Insert this result into the set of results.
1238  Results.push_back(R);
1239 
1240  if (!AsNestedNameSpecifier)
1241  MaybeAddConstructorResults(R);
1242 }
1243 
1244 void ResultBuilder::AddResult(Result R) {
1245  assert(R.Kind != Result::RK_Declaration &&
1246  "Declaration results need more context");
1247  Results.push_back(R);
1248 }
1249 
1250 /// Enter into a new scope.
1251 void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1252 
1253 /// Exit from the current scope.
1254 void ResultBuilder::ExitScope() {
1255  for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1256  EEnd = ShadowMaps.back().end();
1257  E != EEnd; ++E)
1258  E->second.Destroy();
1259 
1260  ShadowMaps.pop_back();
1261 }
1262 
1263 /// Determines whether this given declaration will be found by
1264 /// ordinary name lookup.
1265 bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1266  ND = ND->getUnderlyingDecl();
1267 
1268  // If name lookup finds a local extern declaration, then we are in a
1269  // context where it behaves like an ordinary name.
1270  unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1271  if (SemaRef.getLangOpts().CPlusPlus)
1273  else if (SemaRef.getLangOpts().ObjC) {
1274  if (isa<ObjCIvarDecl>(ND))
1275  return true;
1276  }
1277 
1278  return ND->getIdentifierNamespace() & IDNS;
1279 }
1280 
1281 /// Determines whether this given declaration will be found by
1282 /// ordinary name lookup but is not a type name.
1283 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1284  ND = ND->getUnderlyingDecl();
1285  if (isa<TypeDecl>(ND))
1286  return false;
1287  // Objective-C interfaces names are not filtered by this method because they
1288  // can be used in a class property expression. We can still filter out
1289  // @class declarations though.
1290  if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
1291  if (!ID->getDefinition())
1292  return false;
1293  }
1294 
1295  unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1296  if (SemaRef.getLangOpts().CPlusPlus)
1298  else if (SemaRef.getLangOpts().ObjC) {
1299  if (isa<ObjCIvarDecl>(ND))
1300  return true;
1301  }
1302 
1303  return ND->getIdentifierNamespace() & IDNS;
1304 }
1305 
1306 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1307  if (!IsOrdinaryNonTypeName(ND))
1308  return 0;
1309 
1310  if (const auto *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1311  if (VD->getType()->isIntegralOrEnumerationType())
1312  return true;
1313 
1314  return false;
1315 }
1316 
1317 /// Determines whether this given declaration will be found by
1318 /// ordinary name lookup.
1319 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1320  ND = ND->getUnderlyingDecl();
1321 
1322  unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1323  if (SemaRef.getLangOpts().CPlusPlus)
1325 
1326  return (ND->getIdentifierNamespace() & IDNS) && !isa<ValueDecl>(ND) &&
1327  !isa<FunctionTemplateDecl>(ND) && !isa<ObjCPropertyDecl>(ND);
1328 }
1329 
1330 /// Determines whether the given declaration is suitable as the
1331 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1332 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1333  // Allow us to find class templates, too.
1334  if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1335  ND = ClassTemplate->getTemplatedDecl();
1336 
1337  return SemaRef.isAcceptableNestedNameSpecifier(ND);
1338 }
1339 
1340 /// Determines whether the given declaration is an enumeration.
1341 bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1342  return isa<EnumDecl>(ND);
1343 }
1344 
1345 /// Determines whether the given declaration is a class or struct.
1346 bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1347  // Allow us to find class templates, too.
1348  if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1349  ND = ClassTemplate->getTemplatedDecl();
1350 
1351  // For purposes of this check, interfaces match too.
1352  if (const auto *RD = dyn_cast<RecordDecl>(ND))
1353  return RD->getTagKind() == TTK_Class || RD->getTagKind() == TTK_Struct ||
1354  RD->getTagKind() == TTK_Interface;
1355 
1356  return false;
1357 }
1358 
1359 /// Determines whether the given declaration is a union.
1360 bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1361  // Allow us to find class templates, too.
1362  if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1363  ND = ClassTemplate->getTemplatedDecl();
1364 
1365  if (const auto *RD = dyn_cast<RecordDecl>(ND))
1366  return RD->getTagKind() == TTK_Union;
1367 
1368  return false;
1369 }
1370 
1371 /// Determines whether the given declaration is a namespace.
1372 bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1373  return isa<NamespaceDecl>(ND);
1374 }
1375 
1376 /// Determines whether the given declaration is a namespace or
1377 /// namespace alias.
1378 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1379  return isa<NamespaceDecl>(ND->getUnderlyingDecl());
1380 }
1381 
1382 /// Determines whether the given declaration is a type.
1383 bool ResultBuilder::IsType(const NamedDecl *ND) const {
1384  ND = ND->getUnderlyingDecl();
1385  return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1386 }
1387 
1388 /// Determines which members of a class should be visible via
1389 /// "." or "->". Only value declarations, nested name specifiers, and
1390 /// using declarations thereof should show up.
1391 bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1392  ND = ND->getUnderlyingDecl();
1393  return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1394  isa<ObjCPropertyDecl>(ND);
1395 }
1396 
1398  T = C.getCanonicalType(T);
1399  switch (T->getTypeClass()) {
1400  case Type::ObjCObject:
1401  case Type::ObjCInterface:
1402  case Type::ObjCObjectPointer:
1403  return true;
1404 
1405  case Type::Builtin:
1406  switch (cast<BuiltinType>(T)->getKind()) {
1407  case BuiltinType::ObjCId:
1408  case BuiltinType::ObjCClass:
1409  case BuiltinType::ObjCSel:
1410  return true;
1411 
1412  default:
1413  break;
1414  }
1415  return false;
1416 
1417  default:
1418  break;
1419  }
1420 
1421  if (!C.getLangOpts().CPlusPlus)
1422  return false;
1423 
1424  // FIXME: We could perform more analysis here to determine whether a
1425  // particular class type has any conversions to Objective-C types. For now,
1426  // just accept all class types.
1427  return T->isDependentType() || T->isRecordType();
1428 }
1429 
1430 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1431  QualType T = getDeclUsageType(SemaRef.Context, ND);
1432  if (T.isNull())
1433  return false;
1434 
1435  T = SemaRef.Context.getBaseElementType(T);
1436  return isObjCReceiverType(SemaRef.Context, T);
1437 }
1438 
1439 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
1440  const NamedDecl *ND) const {
1441  if (IsObjCMessageReceiver(ND))
1442  return true;
1443 
1444  const auto *Var = dyn_cast<VarDecl>(ND);
1445  if (!Var)
1446  return false;
1447 
1448  return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1449 }
1450 
1451 bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1452  if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1453  (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1454  return false;
1455 
1456  QualType T = getDeclUsageType(SemaRef.Context, ND);
1457  if (T.isNull())
1458  return false;
1459 
1460  T = SemaRef.Context.getBaseElementType(T);
1461  return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1462  T->isObjCIdType() ||
1463  (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1464 }
1465 
1466 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1467  return false;
1468 }
1469 
1470 /// Determines whether the given declaration is an Objective-C
1471 /// instance variable.
1472 bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1473  return isa<ObjCIvarDecl>(ND);
1474 }
1475 
1476 namespace {
1477 
1478 /// Visible declaration consumer that adds a code-completion result
1479 /// for each visible declaration.
1480 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1481  ResultBuilder &Results;
1482  DeclContext *InitialLookupCtx;
1483  // NamingClass and BaseType are used for access-checking. See
1484  // Sema::IsSimplyAccessible for details.
1485  CXXRecordDecl *NamingClass;
1486  QualType BaseType;
1487  std::vector<FixItHint> FixIts;
1488 
1489 public:
1490  CodeCompletionDeclConsumer(
1491  ResultBuilder &Results, DeclContext *InitialLookupCtx,
1492  QualType BaseType = QualType(),
1493  std::vector<FixItHint> FixIts = std::vector<FixItHint>())
1494  : Results(Results), InitialLookupCtx(InitialLookupCtx),
1495  FixIts(std::move(FixIts)) {
1496  NamingClass = llvm::dyn_cast<CXXRecordDecl>(InitialLookupCtx);
1497  // If BaseType was not provided explicitly, emulate implicit 'this->'.
1498  if (BaseType.isNull()) {
1499  auto ThisType = Results.getSema().getCurrentThisType();
1500  if (!ThisType.isNull()) {
1501  assert(ThisType->isPointerType());
1502  BaseType = ThisType->getPointeeType();
1503  if (!NamingClass)
1504  NamingClass = BaseType->getAsCXXRecordDecl();
1505  }
1506  }
1507  this->BaseType = BaseType;
1508  }
1509 
1510  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1511  bool InBaseClass) override {
1512  ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1513  false, IsAccessible(ND, Ctx), FixIts);
1514  Results.AddResult(Result, InitialLookupCtx, Hiding, InBaseClass);
1515  }
1516 
1517  void EnteredContext(DeclContext *Ctx) override {
1518  Results.addVisitedContext(Ctx);
1519  }
1520 
1521 private:
1522  bool IsAccessible(NamedDecl *ND, DeclContext *Ctx) {
1523  // Naming class to use for access check. In most cases it was provided
1524  // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)),
1525  // for unqualified lookup we fallback to the \p Ctx in which we found the
1526  // member.
1527  auto *NamingClass = this->NamingClass;
1528  QualType BaseType = this->BaseType;
1529  if (auto *Cls = llvm::dyn_cast_or_null<CXXRecordDecl>(Ctx)) {
1530  if (!NamingClass)
1531  NamingClass = Cls;
1532  // When we emulate implicit 'this->' in an unqualified lookup, we might
1533  // end up with an invalid naming class. In that case, we avoid emulating
1534  // 'this->' qualifier to satisfy preconditions of the access checking.
1535  if (NamingClass->getCanonicalDecl() != Cls->getCanonicalDecl() &&
1536  !NamingClass->isDerivedFrom(Cls)) {
1537  NamingClass = Cls;
1538  BaseType = QualType();
1539  }
1540  } else {
1541  // The decl was found outside the C++ class, so only ObjC access checks
1542  // apply. Those do not rely on NamingClass and BaseType, so we clear them
1543  // out.
1544  NamingClass = nullptr;
1545  BaseType = QualType();
1546  }
1547  return Results.getSema().IsSimplyAccessible(ND, NamingClass, BaseType);
1548  }
1549 };
1550 } // namespace
1551 
1552 /// Add type specifiers for the current language as keyword results.
1553 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1554  ResultBuilder &Results) {
1555  typedef CodeCompletionResult Result;
1556  Results.AddResult(Result("short", CCP_Type));
1557  Results.AddResult(Result("long", CCP_Type));
1558  Results.AddResult(Result("signed", CCP_Type));
1559  Results.AddResult(Result("unsigned", CCP_Type));
1560  Results.AddResult(Result("void", CCP_Type));
1561  Results.AddResult(Result("char", CCP_Type));
1562  Results.AddResult(Result("int", CCP_Type));
1563  Results.AddResult(Result("float", CCP_Type));
1564  Results.AddResult(Result("double", CCP_Type));
1565  Results.AddResult(Result("enum", CCP_Type));
1566  Results.AddResult(Result("struct", CCP_Type));
1567  Results.AddResult(Result("union", CCP_Type));
1568  Results.AddResult(Result("const", CCP_Type));
1569  Results.AddResult(Result("volatile", CCP_Type));
1570 
1571  if (LangOpts.C99) {
1572  // C99-specific
1573  Results.AddResult(Result("_Complex", CCP_Type));
1574  Results.AddResult(Result("_Imaginary", CCP_Type));
1575  Results.AddResult(Result("_Bool", CCP_Type));
1576  Results.AddResult(Result("restrict", CCP_Type));
1577  }
1578 
1579  CodeCompletionBuilder Builder(Results.getAllocator(),
1580  Results.getCodeCompletionTUInfo());
1581  if (LangOpts.CPlusPlus) {
1582  // C++-specific
1583  Results.AddResult(
1584  Result("bool", CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0)));
1585  Results.AddResult(Result("class", CCP_Type));
1586  Results.AddResult(Result("wchar_t", CCP_Type));
1587 
1588  // typename qualified-id
1589  Builder.AddTypedTextChunk("typename");
1590  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1591  Builder.AddPlaceholderChunk("qualifier");
1592  Builder.AddTextChunk("::");
1593  Builder.AddPlaceholderChunk("name");
1594  Results.AddResult(Result(Builder.TakeString()));
1595 
1596  if (LangOpts.CPlusPlus11) {
1597  Results.AddResult(Result("auto", CCP_Type));
1598  Results.AddResult(Result("char16_t", CCP_Type));
1599  Results.AddResult(Result("char32_t", CCP_Type));
1600 
1601  Builder.AddTypedTextChunk("decltype");
1602  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1603  Builder.AddPlaceholderChunk("expression");
1604  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1605  Results.AddResult(Result(Builder.TakeString()));
1606  }
1607  } else
1608  Results.AddResult(Result("__auto_type", CCP_Type));
1609 
1610  // GNU keywords
1611  if (LangOpts.GNUKeywords) {
1612  // FIXME: Enable when we actually support decimal floating point.
1613  // Results.AddResult(Result("_Decimal32"));
1614  // Results.AddResult(Result("_Decimal64"));
1615  // Results.AddResult(Result("_Decimal128"));
1616 
1617  Builder.AddTypedTextChunk("typeof");
1618  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1619  Builder.AddPlaceholderChunk("expression");
1620  Results.AddResult(Result(Builder.TakeString()));
1621 
1622  Builder.AddTypedTextChunk("typeof");
1623  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1624  Builder.AddPlaceholderChunk("type");
1625  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1626  Results.AddResult(Result(Builder.TakeString()));
1627  }
1628 
1629  // Nullability
1630  Results.AddResult(Result("_Nonnull", CCP_Type));
1631  Results.AddResult(Result("_Null_unspecified", CCP_Type));
1632  Results.AddResult(Result("_Nullable", CCP_Type));
1633 }
1634 
1636  const LangOptions &LangOpts,
1637  ResultBuilder &Results) {
1638  typedef CodeCompletionResult Result;
1639  // Note: we don't suggest either "auto" or "register", because both
1640  // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1641  // in C++0x as a type specifier.
1642  Results.AddResult(Result("extern"));
1643  Results.AddResult(Result("static"));
1644 
1645  if (LangOpts.CPlusPlus11) {
1646  CodeCompletionAllocator &Allocator = Results.getAllocator();
1647  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1648 
1649  // alignas
1650  Builder.AddTypedTextChunk("alignas");
1651  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1652  Builder.AddPlaceholderChunk("expression");
1653  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1654  Results.AddResult(Result(Builder.TakeString()));
1655 
1656  Results.AddResult(Result("constexpr"));
1657  Results.AddResult(Result("thread_local"));
1658  }
1659 }
1660 
1662  const LangOptions &LangOpts,
1663  ResultBuilder &Results) {
1664  typedef CodeCompletionResult Result;
1665  switch (CCC) {
1666  case Sema::PCC_Class:
1668  if (LangOpts.CPlusPlus) {
1669  Results.AddResult(Result("explicit"));
1670  Results.AddResult(Result("friend"));
1671  Results.AddResult(Result("mutable"));
1672  Results.AddResult(Result("virtual"));
1673  }
1674  LLVM_FALLTHROUGH;
1675 
1678  case Sema::PCC_Namespace:
1679  case Sema::PCC_Template:
1680  if (LangOpts.CPlusPlus || LangOpts.C99)
1681  Results.AddResult(Result("inline"));
1682  break;
1683 
1685  case Sema::PCC_Expression:
1686  case Sema::PCC_Statement:
1687  case Sema::PCC_ForInit:
1688  case Sema::PCC_Condition:
1690  case Sema::PCC_Type:
1693  break;
1694  }
1695 }
1696 
1697 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1698 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1699 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1700  ResultBuilder &Results, bool NeedAt);
1701 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1702  ResultBuilder &Results, bool NeedAt);
1703 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1704  ResultBuilder &Results, bool NeedAt);
1705 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1706 
1707 static void AddTypedefResult(ResultBuilder &Results) {
1708  CodeCompletionBuilder Builder(Results.getAllocator(),
1709  Results.getCodeCompletionTUInfo());
1710  Builder.AddTypedTextChunk("typedef");
1711  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1712  Builder.AddPlaceholderChunk("type");
1713  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1714  Builder.AddPlaceholderChunk("name");
1715  Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1716 }
1717 
1719  const LangOptions &LangOpts) {
1720  switch (CCC) {
1721  case Sema::PCC_Namespace:
1722  case Sema::PCC_Class:
1724  case Sema::PCC_Template:
1726  case Sema::PCC_Statement:
1728  case Sema::PCC_Type:
1731  return true;
1732 
1733  case Sema::PCC_Expression:
1734  case Sema::PCC_Condition:
1735  return LangOpts.CPlusPlus;
1736 
1739  return false;
1740 
1741  case Sema::PCC_ForInit:
1742  return LangOpts.CPlusPlus || LangOpts.ObjC || LangOpts.C99;
1743  }
1744 
1745  llvm_unreachable("Invalid ParserCompletionContext!");
1746 }
1747 
1749  const Preprocessor &PP) {
1750  PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1751  Policy.AnonymousTagLocations = false;
1752  Policy.SuppressStrongLifetime = true;
1753  Policy.SuppressUnwrittenScope = true;
1754  Policy.SuppressScope = true;
1755  return Policy;
1756 }
1757 
1758 /// Retrieve a printing policy suitable for code completion.
1760  return getCompletionPrintingPolicy(S.Context, S.PP);
1761 }
1762 
1763 /// Retrieve the string representation of the given type as a string
1764 /// that has the appropriate lifetime for code completion.
1765 ///
1766 /// This routine provides a fast path where we provide constant strings for
1767 /// common type names.
1768 static const char *GetCompletionTypeString(QualType T, ASTContext &Context,
1769  const PrintingPolicy &Policy,
1770  CodeCompletionAllocator &Allocator) {
1771  if (!T.getLocalQualifiers()) {
1772  // Built-in type names are constant strings.
1773  if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1774  return BT->getNameAsCString(Policy);
1775 
1776  // Anonymous tag types are constant strings.
1777  if (const TagType *TagT = dyn_cast<TagType>(T))
1778  if (TagDecl *Tag = TagT->getDecl())
1779  if (!Tag->hasNameForLinkage()) {
1780  switch (Tag->getTagKind()) {
1781  case TTK_Struct:
1782  return "struct <anonymous>";
1783  case TTK_Interface:
1784  return "__interface <anonymous>";
1785  case TTK_Class:
1786  return "class <anonymous>";
1787  case TTK_Union:
1788  return "union <anonymous>";
1789  case TTK_Enum:
1790  return "enum <anonymous>";
1791  }
1792  }
1793  }
1794 
1795  // Slow path: format the type as a string.
1796  std::string Result;
1797  T.getAsStringInternal(Result, Policy);
1798  return Allocator.CopyString(Result);
1799 }
1800 
1801 /// Add a completion for "this", if we're in a member function.
1802 static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1803  QualType ThisTy = S.getCurrentThisType();
1804  if (ThisTy.isNull())
1805  return;
1806 
1807  CodeCompletionAllocator &Allocator = Results.getAllocator();
1808  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1810  Builder.AddResultTypeChunk(
1811  GetCompletionTypeString(ThisTy, S.Context, Policy, Allocator));
1812  Builder.AddTypedTextChunk("this");
1813  Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1814 }
1815 
1817  ResultBuilder &Results,
1818  const LangOptions &LangOpts) {
1819  if (!LangOpts.CPlusPlus11)
1820  return;
1821 
1822  Builder.AddTypedTextChunk("static_assert");
1824  Builder.AddPlaceholderChunk("expression");
1826  Builder.AddPlaceholderChunk("message");
1828  Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1829 }
1830 
1831 static void printOverrideString(llvm::raw_ostream &OS,
1832  CodeCompletionString *CCS) {
1833  for (const auto &C : *CCS) {
1834  if (C.Kind == CodeCompletionString::CK_Optional)
1835  printOverrideString(OS, C.Optional);
1836  else
1837  OS << C.Text;
1838  // Add a space after return type.
1840  OS << ' ';
1841  }
1842 }
1843 
1844 static void AddOverrideResults(ResultBuilder &Results,
1845  const CodeCompletionContext &CCContext,
1846  CodeCompletionBuilder &Builder) {
1847  Sema &S = Results.getSema();
1848  const auto *CR = llvm::dyn_cast<CXXRecordDecl>(S.CurContext);
1849  // If not inside a class/struct/union return empty.
1850  if (!CR)
1851  return;
1852  // First store overrides within current class.
1853  // These are stored by name to make querying fast in the later step.
1854  llvm::StringMap<std::vector<FunctionDecl *>> Overrides;
1855  for (auto *Method : CR->methods()) {
1856  if (!Method->isVirtual() || !Method->getIdentifier())
1857  continue;
1858  Overrides[Method->getName()].push_back(Method);
1859  }
1860 
1861  for (const auto &Base : CR->bases()) {
1862  const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
1863  if (!BR)
1864  continue;
1865  for (auto *Method : BR->methods()) {
1866  if (!Method->isVirtual() || !Method->getIdentifier())
1867  continue;
1868  const auto it = Overrides.find(Method->getName());
1869  bool IsOverriden = false;
1870  if (it != Overrides.end()) {
1871  for (auto *MD : it->second) {
1872  // If the method in current body is not an overload of this virtual
1873  // function, then it overrides this one.
1874  if (!S.IsOverload(MD, Method, false)) {
1875  IsOverriden = true;
1876  break;
1877  }
1878  }
1879  }
1880  if (!IsOverriden) {
1881  // Generates a new CodeCompletionResult by taking this function and
1882  // converting it into an override declaration with only one chunk in the
1883  // final CodeCompletionString as a TypedTextChunk.
1884  std::string OverrideSignature;
1885  llvm::raw_string_ostream OS(OverrideSignature);
1886  CodeCompletionResult CCR(Method, 0);
1887  PrintingPolicy Policy =
1889  auto *CCS = CCR.createCodeCompletionStringForOverride(
1890  S.getPreprocessor(), S.getASTContext(), Builder,
1891  /*IncludeBriefComments=*/false, CCContext, Policy);
1892  Results.AddResult(CodeCompletionResult(CCS, Method, CCP_CodePattern));
1893  }
1894  }
1895  }
1896 }
1897 
1898 /// Add language constructs that show up for "ordinary" names.
1900  Sema &SemaRef, ResultBuilder &Results) {
1901  CodeCompletionAllocator &Allocator = Results.getAllocator();
1902  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1903 
1904  typedef CodeCompletionResult Result;
1905  switch (CCC) {
1906  case Sema::PCC_Namespace:
1907  if (SemaRef.getLangOpts().CPlusPlus) {
1908  if (Results.includeCodePatterns()) {
1909  // namespace <identifier> { declarations }
1910  Builder.AddTypedTextChunk("namespace");
1911  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1912  Builder.AddPlaceholderChunk("identifier");
1913  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1914  Builder.AddPlaceholderChunk("declarations");
1915  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1916  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1917  Results.AddResult(Result(Builder.TakeString()));
1918  }
1919 
1920  // namespace identifier = identifier ;
1921  Builder.AddTypedTextChunk("namespace");
1922  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1923  Builder.AddPlaceholderChunk("name");
1924  Builder.AddChunk(CodeCompletionString::CK_Equal);
1925  Builder.AddPlaceholderChunk("namespace");
1926  Results.AddResult(Result(Builder.TakeString()));
1927 
1928  // Using directives
1929  Builder.AddTypedTextChunk("using");
1930  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1931  Builder.AddTextChunk("namespace");
1932  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1933  Builder.AddPlaceholderChunk("identifier");
1934  Results.AddResult(Result(Builder.TakeString()));
1935 
1936  // asm(string-literal)
1937  Builder.AddTypedTextChunk("asm");
1938  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1939  Builder.AddPlaceholderChunk("string-literal");
1940  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1941  Results.AddResult(Result(Builder.TakeString()));
1942 
1943  if (Results.includeCodePatterns()) {
1944  // Explicit template instantiation
1945  Builder.AddTypedTextChunk("template");
1946  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1947  Builder.AddPlaceholderChunk("declaration");
1948  Results.AddResult(Result(Builder.TakeString()));
1949  } else {
1950  Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
1951  }
1952  }
1953 
1954  if (SemaRef.getLangOpts().ObjC)
1955  AddObjCTopLevelResults(Results, true);
1956 
1957  AddTypedefResult(Results);
1958  LLVM_FALLTHROUGH;
1959 
1960  case Sema::PCC_Class:
1961  if (SemaRef.getLangOpts().CPlusPlus) {
1962  // Using declaration
1963  Builder.AddTypedTextChunk("using");
1964  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1965  Builder.AddPlaceholderChunk("qualifier");
1966  Builder.AddTextChunk("::");
1967  Builder.AddPlaceholderChunk("name");
1968  Results.AddResult(Result(Builder.TakeString()));
1969 
1970  // using typename qualifier::name (only in a dependent context)
1971  if (SemaRef.CurContext->isDependentContext()) {
1972  Builder.AddTypedTextChunk("using");
1973  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1974  Builder.AddTextChunk("typename");
1975  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1976  Builder.AddPlaceholderChunk("qualifier");
1977  Builder.AddTextChunk("::");
1978  Builder.AddPlaceholderChunk("name");
1979  Results.AddResult(Result(Builder.TakeString()));
1980  }
1981 
1982  AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
1983 
1984  if (CCC == Sema::PCC_Class) {
1985  AddTypedefResult(Results);
1986 
1987  bool IsNotInheritanceScope =
1989  // public:
1990  Builder.AddTypedTextChunk("public");
1991  if (IsNotInheritanceScope && Results.includeCodePatterns())
1992  Builder.AddChunk(CodeCompletionString::CK_Colon);
1993  Results.AddResult(Result(Builder.TakeString()));
1994 
1995  // protected:
1996  Builder.AddTypedTextChunk("protected");
1997  if (IsNotInheritanceScope && Results.includeCodePatterns())
1998  Builder.AddChunk(CodeCompletionString::CK_Colon);
1999  Results.AddResult(Result(Builder.TakeString()));
2000 
2001  // private:
2002  Builder.AddTypedTextChunk("private");
2003  if (IsNotInheritanceScope && Results.includeCodePatterns())
2004  Builder.AddChunk(CodeCompletionString::CK_Colon);
2005  Results.AddResult(Result(Builder.TakeString()));
2006 
2007  // FIXME: This adds override results only if we are at the first word of
2008  // the declaration/definition. Also call this from other sides to have
2009  // more use-cases.
2011  Builder);
2012  }
2013  }
2014  LLVM_FALLTHROUGH;
2015 
2016  case Sema::PCC_Template:
2018  if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
2019  // template < parameters >
2020  Builder.AddTypedTextChunk("template");
2021  Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2022  Builder.AddPlaceholderChunk("parameters");
2023  Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2024  Results.AddResult(Result(Builder.TakeString()));
2025  } else {
2026  Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2027  }
2028 
2029  AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2030  AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2031  break;
2032 
2034  AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
2035  AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2036  AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2037  break;
2038 
2040  AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
2041  AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2042  AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2043  break;
2044 
2046  AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
2047  break;
2048 
2050  case Sema::PCC_Statement: {
2051  AddTypedefResult(Results);
2052 
2053  if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
2054  SemaRef.getLangOpts().CXXExceptions) {
2055  Builder.AddTypedTextChunk("try");
2056  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2057  Builder.AddPlaceholderChunk("statements");
2058  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2059  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2060  Builder.AddTextChunk("catch");
2061  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2062  Builder.AddPlaceholderChunk("declaration");
2063  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2064  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2065  Builder.AddPlaceholderChunk("statements");
2066  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2067  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2068  Results.AddResult(Result(Builder.TakeString()));
2069  }
2070  if (SemaRef.getLangOpts().ObjC)
2071  AddObjCStatementResults(Results, true);
2072 
2073  if (Results.includeCodePatterns()) {
2074  // if (condition) { statements }
2075  Builder.AddTypedTextChunk("if");
2076  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2077  if (SemaRef.getLangOpts().CPlusPlus)
2078  Builder.AddPlaceholderChunk("condition");
2079  else
2080  Builder.AddPlaceholderChunk("expression");
2081  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2082  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2083  Builder.AddPlaceholderChunk("statements");
2084  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2085  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2086  Results.AddResult(Result(Builder.TakeString()));
2087 
2088  // switch (condition) { }
2089  Builder.AddTypedTextChunk("switch");
2090  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2091  if (SemaRef.getLangOpts().CPlusPlus)
2092  Builder.AddPlaceholderChunk("condition");
2093  else
2094  Builder.AddPlaceholderChunk("expression");
2095  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2096  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2097  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2098  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2099  Results.AddResult(Result(Builder.TakeString()));
2100  }
2101 
2102  // Switch-specific statements.
2103  if (SemaRef.getCurFunction() &&
2104  !SemaRef.getCurFunction()->SwitchStack.empty()) {
2105  // case expression:
2106  Builder.AddTypedTextChunk("case");
2107  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2108  Builder.AddPlaceholderChunk("expression");
2109  Builder.AddChunk(CodeCompletionString::CK_Colon);
2110  Results.AddResult(Result(Builder.TakeString()));
2111 
2112  // default:
2113  Builder.AddTypedTextChunk("default");
2114  Builder.AddChunk(CodeCompletionString::CK_Colon);
2115  Results.AddResult(Result(Builder.TakeString()));
2116  }
2117 
2118  if (Results.includeCodePatterns()) {
2119  /// while (condition) { statements }
2120  Builder.AddTypedTextChunk("while");
2121  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2122  if (SemaRef.getLangOpts().CPlusPlus)
2123  Builder.AddPlaceholderChunk("condition");
2124  else
2125  Builder.AddPlaceholderChunk("expression");
2126  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2127  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2128  Builder.AddPlaceholderChunk("statements");
2129  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2130  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2131  Results.AddResult(Result(Builder.TakeString()));
2132 
2133  // do { statements } while ( expression );
2134  Builder.AddTypedTextChunk("do");
2135  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2136  Builder.AddPlaceholderChunk("statements");
2137  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2138  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2139  Builder.AddTextChunk("while");
2140  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2141  Builder.AddPlaceholderChunk("expression");
2142  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2143  Results.AddResult(Result(Builder.TakeString()));
2144 
2145  // for ( for-init-statement ; condition ; expression ) { statements }
2146  Builder.AddTypedTextChunk("for");
2147  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2148  if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
2149  Builder.AddPlaceholderChunk("init-statement");
2150  else
2151  Builder.AddPlaceholderChunk("init-expression");
2152  Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2153  Builder.AddPlaceholderChunk("condition");
2154  Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2155  Builder.AddPlaceholderChunk("inc-expression");
2156  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2157  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2158  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2159  Builder.AddPlaceholderChunk("statements");
2160  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2161  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2162  Results.AddResult(Result(Builder.TakeString()));
2163  }
2164 
2165  if (S->getContinueParent()) {
2166  // continue ;
2167  Builder.AddTypedTextChunk("continue");
2168  Results.AddResult(Result(Builder.TakeString()));
2169  }
2170 
2171  if (S->getBreakParent()) {
2172  // break ;
2173  Builder.AddTypedTextChunk("break");
2174  Results.AddResult(Result(Builder.TakeString()));
2175  }
2176 
2177  // "return expression ;" or "return ;", depending on whether we
2178  // know the function is void or not.
2179  bool isVoid = false;
2180  if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
2181  isVoid = Function->getReturnType()->isVoidType();
2182  else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
2183  isVoid = Method->getReturnType()->isVoidType();
2184  else if (SemaRef.getCurBlock() &&
2185  !SemaRef.getCurBlock()->ReturnType.isNull())
2186  isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
2187  Builder.AddTypedTextChunk("return");
2188  if (!isVoid) {
2189  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2190  Builder.AddPlaceholderChunk("expression");
2191  }
2192  Results.AddResult(Result(Builder.TakeString()));
2193 
2194  // goto identifier ;
2195  Builder.AddTypedTextChunk("goto");
2196  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2197  Builder.AddPlaceholderChunk("label");
2198  Results.AddResult(Result(Builder.TakeString()));
2199 
2200  // Using directives
2201  Builder.AddTypedTextChunk("using");
2202  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2203  Builder.AddTextChunk("namespace");
2204  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2205  Builder.AddPlaceholderChunk("identifier");
2206  Results.AddResult(Result(Builder.TakeString()));
2207 
2208  AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2209  }
2210  LLVM_FALLTHROUGH;
2211 
2212  // Fall through (for statement expressions).
2213  case Sema::PCC_ForInit:
2214  case Sema::PCC_Condition:
2215  AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2216  // Fall through: conditions and statements can have expressions.
2217  LLVM_FALLTHROUGH;
2218 
2220  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2222  // (__bridge <type>)<expression>
2223  Builder.AddTypedTextChunk("__bridge");
2224  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2225  Builder.AddPlaceholderChunk("type");
2226  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2227  Builder.AddPlaceholderChunk("expression");
2228  Results.AddResult(Result(Builder.TakeString()));
2229 
2230  // (__bridge_transfer <Objective-C type>)<expression>
2231  Builder.AddTypedTextChunk("__bridge_transfer");
2232  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2233  Builder.AddPlaceholderChunk("Objective-C type");
2234  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2235  Builder.AddPlaceholderChunk("expression");
2236  Results.AddResult(Result(Builder.TakeString()));
2237 
2238  // (__bridge_retained <CF type>)<expression>
2239  Builder.AddTypedTextChunk("__bridge_retained");
2240  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2241  Builder.AddPlaceholderChunk("CF type");
2242  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2243  Builder.AddPlaceholderChunk("expression");
2244  Results.AddResult(Result(Builder.TakeString()));
2245  }
2246  // Fall through
2247  LLVM_FALLTHROUGH;
2248 
2249  case Sema::PCC_Expression: {
2250  if (SemaRef.getLangOpts().CPlusPlus) {
2251  // 'this', if we're in a non-static member function.
2252  addThisCompletion(SemaRef, Results);
2253 
2254  // true
2255  Builder.AddResultTypeChunk("bool");
2256  Builder.AddTypedTextChunk("true");
2257  Results.AddResult(Result(Builder.TakeString()));
2258 
2259  // false
2260  Builder.AddResultTypeChunk("bool");
2261  Builder.AddTypedTextChunk("false");
2262  Results.AddResult(Result(Builder.TakeString()));
2263 
2264  if (SemaRef.getLangOpts().RTTI) {
2265  // dynamic_cast < type-id > ( expression )
2266  Builder.AddTypedTextChunk("dynamic_cast");
2267  Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2268  Builder.AddPlaceholderChunk("type");
2269  Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2270  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2271  Builder.AddPlaceholderChunk("expression");
2272  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2273  Results.AddResult(Result(Builder.TakeString()));
2274  }
2275 
2276  // static_cast < type-id > ( expression )
2277  Builder.AddTypedTextChunk("static_cast");
2278  Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2279  Builder.AddPlaceholderChunk("type");
2280  Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2281  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2282  Builder.AddPlaceholderChunk("expression");
2283  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2284  Results.AddResult(Result(Builder.TakeString()));
2285 
2286  // reinterpret_cast < type-id > ( expression )
2287  Builder.AddTypedTextChunk("reinterpret_cast");
2288  Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2289  Builder.AddPlaceholderChunk("type");
2290  Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2291  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2292  Builder.AddPlaceholderChunk("expression");
2293  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2294  Results.AddResult(Result(Builder.TakeString()));
2295 
2296  // const_cast < type-id > ( expression )
2297  Builder.AddTypedTextChunk("const_cast");
2298  Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2299  Builder.AddPlaceholderChunk("type");
2300  Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2301  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2302  Builder.AddPlaceholderChunk("expression");
2303  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2304  Results.AddResult(Result(Builder.TakeString()));
2305 
2306  if (SemaRef.getLangOpts().RTTI) {
2307  // typeid ( expression-or-type )
2308  Builder.AddResultTypeChunk("std::type_info");
2309  Builder.AddTypedTextChunk("typeid");
2310  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2311  Builder.AddPlaceholderChunk("expression-or-type");
2312  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2313  Results.AddResult(Result(Builder.TakeString()));
2314  }
2315 
2316  // new T ( ... )
2317  Builder.AddTypedTextChunk("new");
2318  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2319  Builder.AddPlaceholderChunk("type");
2320  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2321  Builder.AddPlaceholderChunk("expressions");
2322  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2323  Results.AddResult(Result(Builder.TakeString()));
2324 
2325  // new T [ ] ( ... )
2326  Builder.AddTypedTextChunk("new");
2327  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2328  Builder.AddPlaceholderChunk("type");
2329  Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2330  Builder.AddPlaceholderChunk("size");
2331  Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2332  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2333  Builder.AddPlaceholderChunk("expressions");
2334  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2335  Results.AddResult(Result(Builder.TakeString()));
2336 
2337  // delete expression
2338  Builder.AddResultTypeChunk("void");
2339  Builder.AddTypedTextChunk("delete");
2340  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2341  Builder.AddPlaceholderChunk("expression");
2342  Results.AddResult(Result(Builder.TakeString()));
2343 
2344  // delete [] expression
2345  Builder.AddResultTypeChunk("void");
2346  Builder.AddTypedTextChunk("delete");
2347  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2348  Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2349  Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2350  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2351  Builder.AddPlaceholderChunk("expression");
2352  Results.AddResult(Result(Builder.TakeString()));
2353 
2354  if (SemaRef.getLangOpts().CXXExceptions) {
2355  // throw expression
2356  Builder.AddResultTypeChunk("void");
2357  Builder.AddTypedTextChunk("throw");
2358  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2359  Builder.AddPlaceholderChunk("expression");
2360  Results.AddResult(Result(Builder.TakeString()));
2361  }
2362 
2363  // FIXME: Rethrow?
2364 
2365  if (SemaRef.getLangOpts().CPlusPlus11) {
2366  // nullptr
2367  Builder.AddResultTypeChunk("std::nullptr_t");
2368  Builder.AddTypedTextChunk("nullptr");
2369  Results.AddResult(Result(Builder.TakeString()));
2370 
2371  // alignof
2372  Builder.AddResultTypeChunk("size_t");
2373  Builder.AddTypedTextChunk("alignof");
2374  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2375  Builder.AddPlaceholderChunk("type");
2376  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2377  Results.AddResult(Result(Builder.TakeString()));
2378 
2379  // noexcept
2380  Builder.AddResultTypeChunk("bool");
2381  Builder.AddTypedTextChunk("noexcept");
2382  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2383  Builder.AddPlaceholderChunk("expression");
2384  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2385  Results.AddResult(Result(Builder.TakeString()));
2386 
2387  // sizeof... expression
2388  Builder.AddResultTypeChunk("size_t");
2389  Builder.AddTypedTextChunk("sizeof...");
2390  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2391  Builder.AddPlaceholderChunk("parameter-pack");
2392  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2393  Results.AddResult(Result(Builder.TakeString()));
2394  }
2395  }
2396 
2397  if (SemaRef.getLangOpts().ObjC) {
2398  // Add "super", if we're in an Objective-C class with a superclass.
2399  if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2400  // The interface can be NULL.
2401  if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2402  if (ID->getSuperClass()) {
2403  std::string SuperType;
2404  SuperType = ID->getSuperClass()->getNameAsString();
2405  if (Method->isInstanceMethod())
2406  SuperType += " *";
2407 
2408  Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2409  Builder.AddTypedTextChunk("super");
2410  Results.AddResult(Result(Builder.TakeString()));
2411  }
2412  }
2413 
2414  AddObjCExpressionResults(Results, true);
2415  }
2416 
2417  if (SemaRef.getLangOpts().C11) {
2418  // _Alignof
2419  Builder.AddResultTypeChunk("size_t");
2420  if (SemaRef.PP.isMacroDefined("alignof"))
2421  Builder.AddTypedTextChunk("alignof");
2422  else
2423  Builder.AddTypedTextChunk("_Alignof");
2424  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2425  Builder.AddPlaceholderChunk("type");
2426  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2427  Results.AddResult(Result(Builder.TakeString()));
2428  }
2429 
2430  // sizeof expression
2431  Builder.AddResultTypeChunk("size_t");
2432  Builder.AddTypedTextChunk("sizeof");
2433  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2434  Builder.AddPlaceholderChunk("expression-or-type");
2435  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2436  Results.AddResult(Result(Builder.TakeString()));
2437  break;
2438  }
2439 
2440  case Sema::PCC_Type:
2442  break;
2443  }
2444 
2445  if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2446  AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2447 
2448  if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
2449  Results.AddResult(Result("operator"));
2450 }
2451 
2452 /// If the given declaration has an associated type, add it as a result
2453 /// type chunk.
2454 static void AddResultTypeChunk(ASTContext &Context,
2455  const PrintingPolicy &Policy,
2456  const NamedDecl *ND, QualType BaseType,
2457  CodeCompletionBuilder &Result) {
2458  if (!ND)
2459  return;
2460 
2461  // Skip constructors and conversion functions, which have their return types
2462  // built into their names.
2463  if (isConstructor(ND) || isa<CXXConversionDecl>(ND))
2464  return;
2465 
2466  // Determine the type of the declaration (if it has a type).
2467  QualType T;
2468  if (const FunctionDecl *Function = ND->getAsFunction())
2469  T = Function->getReturnType();
2470  else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2471  if (!BaseType.isNull())
2472  T = Method->getSendResultType(BaseType);
2473  else
2474  T = Method->getReturnType();
2475  } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) {
2476  T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2478  } else if (isa<UnresolvedUsingValueDecl>(ND)) {
2479  /* Do nothing: ignore unresolved using declarations*/
2480  } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2481  if (!BaseType.isNull())
2482  T = Ivar->getUsageType(BaseType);
2483  else
2484  T = Ivar->getType();
2485  } else if (const auto *Value = dyn_cast<ValueDecl>(ND)) {
2486  T = Value->getType();
2487  } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2488  if (!BaseType.isNull())
2489  T = Property->getUsageType(BaseType);
2490  else
2491  T = Property->getType();
2492  }
2493 
2494  if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2495  return;
2496 
2497  Result.AddResultTypeChunk(
2498  GetCompletionTypeString(T, Context, Policy, Result.getAllocator()));
2499 }
2500 
2502  const NamedDecl *FunctionOrMethod,
2503  CodeCompletionBuilder &Result) {
2504  if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2505  if (Sentinel->getSentinel() == 0) {
2506  if (PP.getLangOpts().ObjC && PP.isMacroDefined("nil"))
2507  Result.AddTextChunk(", nil");
2508  else if (PP.isMacroDefined("NULL"))
2509  Result.AddTextChunk(", NULL");
2510  else
2511  Result.AddTextChunk(", (void*)0");
2512  }
2513 }
2514 
2515 static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2516  QualType &Type) {
2517  std::string Result;
2518  if (ObjCQuals & Decl::OBJC_TQ_In)
2519  Result += "in ";
2520  else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2521  Result += "inout ";
2522  else if (ObjCQuals & Decl::OBJC_TQ_Out)
2523  Result += "out ";
2524  if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2525  Result += "bycopy ";
2526  else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2527  Result += "byref ";
2528  if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2529  Result += "oneway ";
2530  if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2531  if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2532  switch (*nullability) {
2534  Result += "nonnull ";
2535  break;
2536 
2538  Result += "nullable ";
2539  break;
2540 
2542  Result += "null_unspecified ";
2543  break;
2544  }
2545  }
2546  }
2547  return Result;
2548 }
2549 
2550 /// Tries to find the most appropriate type location for an Objective-C
2551 /// block placeholder.
2552 ///
2553 /// This function ignores things like typedefs and qualifiers in order to
2554 /// present the most relevant and accurate block placeholders in code completion
2555 /// results.
2557  FunctionTypeLoc &Block,
2558  FunctionProtoTypeLoc &BlockProto,
2559  bool SuppressBlock = false) {
2560  if (!TSInfo)
2561  return;
2562  TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2563  while (true) {
2564  // Look through typedefs.
2565  if (!SuppressBlock) {
2566  if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2567  if (TypeSourceInfo *InnerTSInfo =
2568  TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2569  TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2570  continue;
2571  }
2572  }
2573 
2574  // Look through qualified types
2575  if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2576  TL = QualifiedTL.getUnqualifiedLoc();
2577  continue;
2578  }
2579 
2580  if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2581  TL = AttrTL.getModifiedLoc();
2582  continue;
2583  }
2584  }
2585 
2586  // Try to get the function prototype behind the block pointer type,
2587  // then we're done.
2588  if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2589  TL = BlockPtr.getPointeeLoc().IgnoreParens();
2590  Block = TL.getAs<FunctionTypeLoc>();
2591  BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2592  }
2593  break;
2594  }
2595 }
2596 
2597 static std::string
2599  FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2600  bool SuppressBlockName = false,
2601  bool SuppressBlock = false,
2602  Optional<ArrayRef<QualType>> ObjCSubsts = None);
2603 
2604 static std::string
2606  bool SuppressName = false, bool SuppressBlock = false,
2607  Optional<ArrayRef<QualType>> ObjCSubsts = None) {
2608  // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
2609  // It would be better to pass in the param Type, which is usually avaliable.
2610  // But this case is rare, so just pretend we fell back to int as elsewhere.
2611  if (!Param)
2612  return "int";
2613  bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2614  if (Param->getType()->isDependentType() ||
2615  !Param->getType()->isBlockPointerType()) {
2616  // The argument for a dependent or non-block parameter is a placeholder
2617  // containing that parameter's type.
2618  std::string Result;
2619 
2620  if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2621  Result = Param->getIdentifier()->getName();
2622 
2623  QualType Type = Param->getType();
2624  if (ObjCSubsts)
2625  Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2627  if (ObjCMethodParam) {
2628  Result =
2629  "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type);
2630  Result += Type.getAsString(Policy) + ")";
2631  if (Param->getIdentifier() && !SuppressName)
2632  Result += Param->getIdentifier()->getName();
2633  } else {
2634  Type.getAsStringInternal(Result, Policy);
2635  }
2636  return Result;
2637  }
2638 
2639  // The argument for a block pointer parameter is a block literal with
2640  // the appropriate type.
2641  FunctionTypeLoc Block;
2642  FunctionProtoTypeLoc BlockProto;
2643  findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2644  SuppressBlock);
2645  // Try to retrieve the block type information from the property if this is a
2646  // parameter in a setter.
2647  if (!Block && ObjCMethodParam &&
2648  cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2649  if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2650  ->findPropertyDecl(/*CheckOverrides=*/false))
2651  findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2652  SuppressBlock);
2653  }
2654 
2655  if (!Block) {
2656  // We were unable to find a FunctionProtoTypeLoc with parameter names
2657  // for the block; just use the parameter type as a placeholder.
2658  std::string Result;
2659  if (!ObjCMethodParam && Param->getIdentifier())
2660  Result = Param->getIdentifier()->getName();
2661 
2662  QualType Type = Param->getType().getUnqualifiedType();
2663 
2664  if (ObjCMethodParam) {
2665  Result = Type.getAsString(Policy);
2666  std::string Quals =
2668  if (!Quals.empty())
2669  Result = "(" + Quals + " " + Result + ")";
2670  if (Result.back() != ')')
2671  Result += " ";
2672  if (Param->getIdentifier())
2673  Result += Param->getIdentifier()->getName();
2674  } else {
2675  Type.getAsStringInternal(Result, Policy);
2676  }
2677 
2678  return Result;
2679  }
2680 
2681  // We have the function prototype behind the block pointer type, as it was
2682  // written in the source.
2683  return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
2684  /*SuppressBlockName=*/false, SuppressBlock,
2685  ObjCSubsts);
2686 }
2687 
2688 /// Returns a placeholder string that corresponds to an Objective-C block
2689 /// declaration.
2690 ///
2691 /// \param BlockDecl A declaration with an Objective-C block type.
2692 ///
2693 /// \param Block The most relevant type location for that block type.
2694 ///
2695 /// \param SuppressBlockName Determines whether or not the name of the block
2696 /// declaration is included in the resulting string.
2697 static std::string
2698 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2699  FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2700  bool SuppressBlockName, bool SuppressBlock,
2701  Optional<ArrayRef<QualType>> ObjCSubsts) {
2702  std::string Result;
2703  QualType ResultType = Block.getTypePtr()->getReturnType();
2704  if (ObjCSubsts)
2705  ResultType =
2706  ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
2708  if (!ResultType->isVoidType() || SuppressBlock)
2709  ResultType.getAsStringInternal(Result, Policy);
2710 
2711  // Format the parameter list.
2712  std::string Params;
2713  if (!BlockProto || Block.getNumParams() == 0) {
2714  if (BlockProto && BlockProto.getTypePtr()->isVariadic())
2715  Params = "(...)";
2716  else
2717  Params = "(void)";
2718  } else {
2719  Params += "(";
2720  for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
2721  if (I)
2722  Params += ", ";
2723  Params += FormatFunctionParameter(Policy, Block.getParam(I),
2724  /*SuppressName=*/false,
2725  /*SuppressBlock=*/true, ObjCSubsts);
2726 
2727  if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
2728  Params += ", ...";
2729  }
2730  Params += ")";
2731  }
2732 
2733  if (SuppressBlock) {
2734  // Format as a parameter.
2735  Result = Result + " (^";
2736  if (!SuppressBlockName && BlockDecl->getIdentifier())
2737  Result += BlockDecl->getIdentifier()->getName();
2738  Result += ")";
2739  Result += Params;
2740  } else {
2741  // Format as a block literal argument.
2742  Result = '^' + Result;
2743  Result += Params;
2744 
2745  if (!SuppressBlockName && BlockDecl->getIdentifier())
2746  Result += BlockDecl->getIdentifier()->getName();
2747  }
2748 
2749  return Result;
2750 }
2751 
2752 static std::string GetDefaultValueString(const ParmVarDecl *Param,
2753  const SourceManager &SM,
2754  const LangOptions &LangOpts) {
2755  const SourceRange SrcRange = Param->getDefaultArgRange();
2756  CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
2757  bool Invalid = CharSrcRange.isInvalid();
2758  if (Invalid)
2759  return "";
2760  StringRef srcText =
2761  Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
2762  if (Invalid)
2763  return "";
2764 
2765  if (srcText.empty() || srcText == "=") {
2766  // Lexer can't determine the value.
2767  // This happens if the code is incorrect (for example class is forward
2768  // declared).
2769  return "";
2770  }
2771  std::string DefValue(srcText.str());
2772  // FIXME: remove this check if the Lexer::getSourceText value is fixed and
2773  // this value always has (or always does not have) '=' in front of it
2774  if (DefValue.at(0) != '=') {
2775  // If we don't have '=' in front of value.
2776  // Lexer returns built-in types values without '=' and user-defined types
2777  // values with it.
2778  return " = " + DefValue;
2779  }
2780  return " " + DefValue;
2781 }
2782 
2783 /// Add function parameter chunks to the given code completion string.
2785  const PrintingPolicy &Policy,
2786  const FunctionDecl *Function,
2787  CodeCompletionBuilder &Result,
2788  unsigned Start = 0,
2789  bool InOptional = false) {
2790  bool FirstParameter = true;
2791 
2792  for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
2793  const ParmVarDecl *Param = Function->getParamDecl(P);
2794 
2795  if (Param->hasDefaultArg() && !InOptional) {
2796  // When we see an optional default argument, put that argument and
2797  // the remaining default arguments into a new, optional string.
2798  CodeCompletionBuilder Opt(Result.getAllocator(),
2799  Result.getCodeCompletionTUInfo());
2800  if (!FirstParameter)
2802  AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
2803  Result.AddOptionalChunk(Opt.TakeString());
2804  break;
2805  }
2806 
2807  if (FirstParameter)
2808  FirstParameter = false;
2809  else
2811 
2812  InOptional = false;
2813 
2814  // Format the placeholder string.
2815  std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
2816  if (Param->hasDefaultArg())
2817  PlaceholderStr +=
2819 
2820  if (Function->isVariadic() && P == N - 1)
2821  PlaceholderStr += ", ...";
2822 
2823  // Add the placeholder string.
2824  Result.AddPlaceholderChunk(
2825  Result.getAllocator().CopyString(PlaceholderStr));
2826  }
2827 
2828  if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>())
2829  if (Proto->isVariadic()) {
2830  if (Proto->getNumParams() == 0)
2831  Result.AddPlaceholderChunk("...");
2832 
2833  MaybeAddSentinel(PP, Function, Result);
2834  }
2835 }
2836 
2837 /// Add template parameter chunks to the given code completion string.
2839  ASTContext &Context, const PrintingPolicy &Policy,
2840  const TemplateDecl *Template, CodeCompletionBuilder &Result,
2841  unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) {
2842  bool FirstParameter = true;
2843 
2844  // Prefer to take the template parameter names from the first declaration of
2845  // the template.
2846  Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2847 
2848  TemplateParameterList *Params = Template->getTemplateParameters();
2849  TemplateParameterList::iterator PEnd = Params->end();
2850  if (MaxParameters)
2851  PEnd = Params->begin() + MaxParameters;
2852  for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd;
2853  ++P) {
2854  bool HasDefaultArg = false;
2855  std::string PlaceholderStr;
2856  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2857  if (TTP->wasDeclaredWithTypename())
2858  PlaceholderStr = "typename";
2859  else
2860  PlaceholderStr = "class";
2861 
2862  if (TTP->getIdentifier()) {
2863  PlaceholderStr += ' ';
2864  PlaceholderStr += TTP->getIdentifier()->getName();
2865  }
2866 
2867  HasDefaultArg = TTP->hasDefaultArgument();
2868  } else if (NonTypeTemplateParmDecl *NTTP =
2869  dyn_cast<NonTypeTemplateParmDecl>(*P)) {
2870  if (NTTP->getIdentifier())
2871  PlaceholderStr = NTTP->getIdentifier()->getName();
2872  NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
2873  HasDefaultArg = NTTP->hasDefaultArgument();
2874  } else {
2875  assert(isa<TemplateTemplateParmDecl>(*P));
2876  TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2877 
2878  // Since putting the template argument list into the placeholder would
2879  // be very, very long, we just use an abbreviation.
2880  PlaceholderStr = "template<...> class";
2881  if (TTP->getIdentifier()) {
2882  PlaceholderStr += ' ';
2883  PlaceholderStr += TTP->getIdentifier()->getName();
2884  }
2885 
2886  HasDefaultArg = TTP->hasDefaultArgument();
2887  }
2888 
2889  if (HasDefaultArg && !InDefaultArg) {
2890  // When we see an optional default argument, put that argument and
2891  // the remaining default arguments into a new, optional string.
2892  CodeCompletionBuilder Opt(Result.getAllocator(),
2893  Result.getCodeCompletionTUInfo());
2894  if (!FirstParameter)
2896  AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
2897  P - Params->begin(), true);
2898  Result.AddOptionalChunk(Opt.TakeString());
2899  break;
2900  }
2901 
2902  InDefaultArg = false;
2903 
2904  if (FirstParameter)
2905  FirstParameter = false;
2906  else
2908 
2909  // Add the placeholder string.
2910  Result.AddPlaceholderChunk(
2911  Result.getAllocator().CopyString(PlaceholderStr));
2912  }
2913 }
2914 
2915 /// Add a qualifier to the given code-completion string, if the
2916 /// provided nested-name-specifier is non-NULL.
2918  NestedNameSpecifier *Qualifier,
2919  bool QualifierIsInformative,
2920  ASTContext &Context,
2921  const PrintingPolicy &Policy) {
2922  if (!Qualifier)
2923  return;
2924 
2925  std::string PrintedNNS;
2926  {
2927  llvm::raw_string_ostream OS(PrintedNNS);
2928  Qualifier->print(OS, Policy);
2929  }
2930  if (QualifierIsInformative)
2931  Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
2932  else
2933  Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
2934 }
2935 
2936 static void
2938  const FunctionDecl *Function) {
2939  const auto *Proto = Function->getType()->getAs<FunctionProtoType>();
2940  if (!Proto || !Proto->getMethodQuals())
2941  return;
2942 
2943  // FIXME: Add ref-qualifier!
2944 
2945  // Handle single qualifiers without copying
2946  if (Proto->getMethodQuals().hasOnlyConst()) {
2947  Result.AddInformativeChunk(" const");
2948  return;
2949  }
2950 
2951  if (Proto->getMethodQuals().hasOnlyVolatile()) {
2952  Result.AddInformativeChunk(" volatile");
2953  return;
2954  }
2955 
2956  if (Proto->getMethodQuals().hasOnlyRestrict()) {
2957  Result.AddInformativeChunk(" restrict");
2958  return;
2959  }
2960 
2961  // Handle multiple qualifiers.
2962  std::string QualsStr;
2963  if (Proto->isConst())
2964  QualsStr += " const";
2965  if (Proto->isVolatile())
2966  QualsStr += " volatile";
2967  if (Proto->isRestrict())
2968  QualsStr += " restrict";
2969  Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
2970 }
2971 
2972 /// Add the name of the given declaration
2973 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2974  const NamedDecl *ND,
2975  CodeCompletionBuilder &Result) {
2976  DeclarationName Name = ND->getDeclName();
2977  if (!Name)
2978  return;
2979 
2980  switch (Name.getNameKind()) {
2982  const char *OperatorName = nullptr;
2983  switch (Name.getCXXOverloadedOperator()) {
2984  case OO_None:
2985  case OO_Conditional:
2987  OperatorName = "operator";
2988  break;
2989 
2990 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
2991  case OO_##Name: \
2992  OperatorName = "operator" Spelling; \
2993  break;
2994 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly)
2995 #include "clang/Basic/OperatorKinds.def"
2996 
2997  case OO_New:
2998  OperatorName = "operator new";
2999  break;
3000  case OO_Delete:
3001  OperatorName = "operator delete";
3002  break;
3003  case OO_Array_New:
3004  OperatorName = "operator new[]";
3005  break;
3006  case OO_Array_Delete:
3007  OperatorName = "operator delete[]";
3008  break;
3009  case OO_Call:
3010  OperatorName = "operator()";
3011  break;
3012  case OO_Subscript:
3013  OperatorName = "operator[]";
3014  break;
3015  }
3016  Result.AddTypedTextChunk(OperatorName);
3017  break;
3018  }
3019 
3024  Result.AddTypedTextChunk(
3025  Result.getAllocator().CopyString(ND->getNameAsString()));
3026  break;
3027 
3033  break;
3034 
3036  CXXRecordDecl *Record = nullptr;
3037  QualType Ty = Name.getCXXNameType();
3038  if (const auto *RecordTy = Ty->getAs<RecordType>())
3039  Record = cast<CXXRecordDecl>(RecordTy->getDecl());
3040  else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>())
3041  Record = InjectedTy->getDecl();
3042  else {
3043  Result.AddTypedTextChunk(
3044  Result.getAllocator().CopyString(ND->getNameAsString()));
3045  break;
3046  }
3047 
3048  Result.AddTypedTextChunk(
3049  Result.getAllocator().CopyString(Record->getNameAsString()));
3050  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
3052  AddTemplateParameterChunks(Context, Policy, Template, Result);
3054  }
3055  break;
3056  }
3057  }
3058 }
3059 
3061  Sema &S, const CodeCompletionContext &CCContext,
3062  CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3063  bool IncludeBriefComments) {
3064  return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
3065  CCTUInfo, IncludeBriefComments);
3066 }
3067 
3069  Preprocessor &PP, CodeCompletionAllocator &Allocator,
3070  CodeCompletionTUInfo &CCTUInfo) {
3071  assert(Kind == RK_Macro);
3072  CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3073  const MacroInfo *MI = PP.getMacroInfo(Macro);
3074  Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
3075 
3076  if (!MI || !MI->isFunctionLike())
3077  return Result.TakeString();
3078 
3079  // Format a function-like macro with placeholders for the arguments.
3081  MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
3082 
3083  // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
3084  if (MI->isC99Varargs()) {
3085  --AEnd;
3086 
3087  if (A == AEnd) {
3088  Result.AddPlaceholderChunk("...");
3089  }
3090  }
3091 
3092  for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
3093  if (A != MI->param_begin())
3095 
3096  if (MI->isVariadic() && (A + 1) == AEnd) {
3097  SmallString<32> Arg = (*A)->getName();
3098  if (MI->isC99Varargs())
3099  Arg += ", ...";
3100  else
3101  Arg += "...";
3102  Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3103  break;
3104  }
3105 
3106  // Non-variadic macros are simple.
3107  Result.AddPlaceholderChunk(
3108  Result.getAllocator().CopyString((*A)->getName()));
3109  }
3111  return Result.TakeString();
3112 }
3113 
3114 /// If possible, create a new code completion string for the given
3115 /// result.
3116 ///
3117 /// \returns Either a new, heap-allocated code completion string describing
3118 /// how to use this result, or NULL to indicate that the string or name of the
3119 /// result is all that is needed.
3121  ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext,
3122  CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3123  bool IncludeBriefComments) {
3124  if (Kind == RK_Macro)
3125  return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
3126 
3127  CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3128 
3129  PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
3130  if (Kind == RK_Pattern) {
3131  Pattern->Priority = Priority;
3132  Pattern->Availability = Availability;
3133 
3134  if (Declaration) {
3135  Result.addParentContext(Declaration->getDeclContext());
3136  Pattern->ParentName = Result.getParentName();
3137  if (const RawComment *RC =
3138  getPatternCompletionComment(Ctx, Declaration)) {
3139  Result.addBriefComment(RC->getBriefText(Ctx));
3140  Pattern->BriefComment = Result.getBriefComment();
3141  }
3142  }
3143 
3144  return Pattern;
3145  }
3146 
3147  if (Kind == RK_Keyword) {
3148  Result.AddTypedTextChunk(Keyword);
3149  return Result.TakeString();
3150  }
3151  assert(Kind == RK_Declaration && "Missed a result kind?");
3152  return createCodeCompletionStringForDecl(
3153  PP, Ctx, Result, IncludeBriefComments, CCContext, Policy);
3154 }
3155 
3158  Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3159  bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3160  PrintingPolicy &Policy) {
3161  std::string OverrideSignature;
3162  llvm::raw_string_ostream OS(OverrideSignature);
3163  auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result,
3164  /*IncludeBriefComments=*/false,
3165  CCContext, Policy);
3166  printOverrideString(OS, CCS);
3167  OS << " override";
3168  Result.AddTypedTextChunk(Result.getAllocator().CopyString(OS.str()));
3169  return Result.TakeString();
3170 }
3171 
3173  Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3174  bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3175  PrintingPolicy &Policy) {
3176  const NamedDecl *ND = Declaration;
3177  Result.addParentContext(ND->getDeclContext());
3178 
3179  if (IncludeBriefComments) {
3180  // Add documentation comment, if it exists.
3181  if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) {
3182  Result.addBriefComment(RC->getBriefText(Ctx));
3183  }
3184  }
3185 
3186  if (StartsNestedNameSpecifier) {
3187  Result.AddTypedTextChunk(
3188  Result.getAllocator().CopyString(ND->getNameAsString()));
3189  Result.AddTextChunk("::");
3190  return Result.TakeString();
3191  }
3192 
3193  for (const auto *I : ND->specific_attrs<AnnotateAttr>())
3194  Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
3195 
3196  AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
3197 
3198  if (const auto *Function = dyn_cast<FunctionDecl>(ND)) {
3199  AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3200  Ctx, Policy);
3201  AddTypedNameChunk(Ctx, Policy, ND, Result);
3203  AddFunctionParameterChunks(PP, Policy, Function, Result);
3205  AddFunctionTypeQualsToCompletionString(Result, Function);
3206  return Result.TakeString();
3207  }
3208 
3209  if (const FunctionTemplateDecl *FunTmpl =
3210  dyn_cast<FunctionTemplateDecl>(ND)) {
3211  AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3212  Ctx, Policy);
3213  FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3214  AddTypedNameChunk(Ctx, Policy, Function, Result);
3215 
3216  // Figure out which template parameters are deduced (or have default
3217  // arguments).
3218  llvm::SmallBitVector Deduced;
3219  Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
3220  unsigned LastDeducibleArgument;
3221  for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
3222  --LastDeducibleArgument) {
3223  if (!Deduced[LastDeducibleArgument - 1]) {
3224  // C++0x: Figure out if the template argument has a default. If so,
3225  // the user doesn't need to type this argument.
3226  // FIXME: We need to abstract template parameters better!
3227  bool HasDefaultArg = false;
3228  NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
3229  LastDeducibleArgument - 1);
3230  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3231  HasDefaultArg = TTP->hasDefaultArgument();
3232  else if (NonTypeTemplateParmDecl *NTTP =
3233  dyn_cast<NonTypeTemplateParmDecl>(Param))
3234  HasDefaultArg = NTTP->hasDefaultArgument();
3235  else {
3236  assert(isa<TemplateTemplateParmDecl>(Param));
3237  HasDefaultArg =
3238  cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
3239  }
3240 
3241  if (!HasDefaultArg)
3242  break;
3243  }
3244  }
3245 
3246  if (LastDeducibleArgument) {
3247  // Some of the function template arguments cannot be deduced from a
3248  // function call, so we introduce an explicit template argument list
3249  // containing all of the arguments up to the first deducible argument.
3251  AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
3252  LastDeducibleArgument);
3254  }
3255 
3256  // Add the function parameters
3258  AddFunctionParameterChunks(PP, Policy, Function, Result);
3260  AddFunctionTypeQualsToCompletionString(Result, Function);
3261  return Result.TakeString();
3262  }
3263 
3264  if (const auto *Template = dyn_cast<TemplateDecl>(ND)) {
3265  AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3266  Ctx, Policy);
3267  Result.AddTypedTextChunk(
3268  Result.getAllocator().CopyString(Template->getNameAsString()));
3270  AddTemplateParameterChunks(Ctx, Policy, Template, Result);
3272  return Result.TakeString();
3273  }
3274  if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
3275  Selector Sel = Method->getSelector();
3276  if (Sel.isUnarySelector()) {
3277  Result.AddTypedTextChunk(
3278  Result.getAllocator().CopyString(Sel.getNameForSlot(0)));
3279  return Result.TakeString();
3280  }
3281 
3282  std::string SelName = Sel.getNameForSlot(0).str();
3283  SelName += ':';
3284  if (StartParameter == 0)
3285  Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
3286  else {
3287  Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
3288 
3289  // If there is only one parameter, and we're past it, add an empty
3290  // typed-text chunk since there is nothing to type.
3291  if (Method->param_size() == 1)
3292  Result.AddTypedTextChunk("");
3293  }
3294  unsigned Idx = 0;
3295  for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
3296  PEnd = Method->param_end();
3297  P != PEnd; (void)++P, ++Idx) {
3298  if (Idx > 0) {
3299  std::string Keyword;
3300  if (Idx > StartParameter)
3302  if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
3303  Keyword += II->getName();
3304  Keyword += ":";
3305  if (Idx < StartParameter || AllParametersAreInformative)
3306  Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
3307  else
3308  Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
3309  }
3310 
3311  // If we're before the starting parameter, skip the placeholder.
3312  if (Idx < StartParameter)
3313  continue;
3314 
3315  std::string Arg;
3316  QualType ParamType = (*P)->getType();
3317  Optional<ArrayRef<QualType>> ObjCSubsts;
3318  if (!CCContext.getBaseType().isNull())
3319  ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
3320 
3321  if (ParamType->isBlockPointerType() && !DeclaringEntity)
3322  Arg = FormatFunctionParameter(Policy, *P, true,
3323  /*SuppressBlock=*/false, ObjCSubsts);
3324  else {
3325  if (ObjCSubsts)
3326  ParamType = ParamType.substObjCTypeArgs(
3327  Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter);
3328  Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
3329  ParamType);
3330  Arg += ParamType.getAsString(Policy) + ")";
3331  if (IdentifierInfo *II = (*P)->getIdentifier())
3332  if (DeclaringEntity || AllParametersAreInformative)
3333  Arg += II->getName();
3334  }
3335 
3336  if (Method->isVariadic() && (P + 1) == PEnd)
3337  Arg += ", ...";
3338 
3339  if (DeclaringEntity)
3340  Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
3341  else if (AllParametersAreInformative)
3342  Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
3343  else
3344  Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3345  }
3346 
3347  if (Method->isVariadic()) {
3348  if (Method->param_size() == 0) {
3349  if (DeclaringEntity)
3350  Result.AddTextChunk(", ...");
3351  else if (AllParametersAreInformative)
3352  Result.AddInformativeChunk(", ...");
3353  else
3354  Result.AddPlaceholderChunk(", ...");
3355  }
3356 
3357  MaybeAddSentinel(PP, Method, Result);
3358  }
3359 
3360  return Result.TakeString();
3361  }
3362 
3363  if (Qualifier)
3364  AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3365  Ctx, Policy);
3366 
3367  Result.AddTypedTextChunk(
3368  Result.getAllocator().CopyString(ND->getNameAsString()));
3369  return Result.TakeString();
3370 }
3371 
3373  const NamedDecl *ND) {
3374  if (!ND)
3375  return nullptr;
3376  if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND))
3377  return RC;
3378 
3379  // Try to find comment from a property for ObjC methods.
3380  const auto *M = dyn_cast<ObjCMethodDecl>(ND);
3381  if (!M)
3382  return nullptr;
3383  const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3384  if (!PDecl)
3385  return nullptr;
3386 
3387  return Ctx.getRawCommentForAnyRedecl(PDecl);
3388 }
3389 
3391  const NamedDecl *ND) {
3392  const auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND);
3393  if (!M || !M->isPropertyAccessor())
3394  return nullptr;
3395 
3396  // Provide code completion comment for self.GetterName where
3397  // GetterName is the getter method for a property with name
3398  // different from the property name (declared via a property
3399  // getter attribute.
3400  const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3401  if (!PDecl)
3402  return nullptr;
3403  if (PDecl->getGetterName() == M->getSelector() &&
3404  PDecl->getIdentifier() != M->getIdentifier()) {
3405  if (auto *RC = Ctx.getRawCommentForAnyRedecl(M))
3406  return RC;
3407  if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
3408  return RC;
3409  }
3410  return nullptr;
3411 }
3412 
3414  const ASTContext &Ctx,
3415  const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) {
3416  auto FDecl = Result.getFunction();
3417  if (!FDecl)
3418  return nullptr;
3419  if (ArgIndex < FDecl->getNumParams())
3420  return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex));
3421  return nullptr;
3422 }
3423 
3424 /// Add function overload parameter chunks to the given code completion
3425 /// string.
3427  const PrintingPolicy &Policy,
3428  const FunctionDecl *Function,
3429  const FunctionProtoType *Prototype,
3430  CodeCompletionBuilder &Result,
3431  unsigned CurrentArg, unsigned Start = 0,
3432  bool InOptional = false) {
3433  bool FirstParameter = true;
3434  unsigned NumParams =
3435  Function ? Function->getNumParams() : Prototype->getNumParams();
3436 
3437  for (unsigned P = Start; P != NumParams; ++P) {
3438  if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
3439  // When we see an optional default argument, put that argument and
3440  // the remaining default arguments into a new, optional string.
3441  CodeCompletionBuilder Opt(Result.getAllocator(),
3442  Result.getCodeCompletionTUInfo());
3443  if (!FirstParameter)
3445  // Optional sections are nested.
3446  AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
3447  CurrentArg, P, /*InOptional=*/true);
3448  Result.AddOptionalChunk(Opt.TakeString());
3449  return;
3450  }
3451 
3452  if (FirstParameter)
3453  FirstParameter = false;
3454  else
3456 
3457  InOptional = false;
3458 
3459  // Format the placeholder string.
3460  std::string Placeholder;
3461  if (Function) {
3462  const ParmVarDecl *Param = Function->getParamDecl(P);
3463  Placeholder = FormatFunctionParameter(Policy, Param);
3464  if (Param->hasDefaultArg())
3465  Placeholder += GetDefaultValueString(Param, Context.getSourceManager(),
3466  Context.getLangOpts());
3467  } else {
3468  Placeholder = Prototype->getParamType(P).getAsString(Policy);
3469  }
3470 
3471  if (P == CurrentArg)
3472  Result.AddCurrentParameterChunk(
3473  Result.getAllocator().CopyString(Placeholder));
3474  else
3475  Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3476  }
3477 
3478  if (Prototype && Prototype->isVariadic()) {
3479  CodeCompletionBuilder Opt(Result.getAllocator(),
3480  Result.getCodeCompletionTUInfo());
3481  if (!FirstParameter)
3483 
3484  if (CurrentArg < NumParams)
3485  Opt.AddPlaceholderChunk("...");
3486  else
3487  Opt.AddCurrentParameterChunk("...");
3488 
3489  Result.AddOptionalChunk(Opt.TakeString());
3490  }
3491 }
3492 
3495  unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator,
3496  CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments) const {
3498 
3499  // FIXME: Set priority, availability appropriately.
3500  CodeCompletionBuilder Result(Allocator, CCTUInfo, 1,
3502  FunctionDecl *FDecl = getFunction();
3503  const FunctionProtoType *Proto =
3504  dyn_cast<FunctionProtoType>(getFunctionType());
3505  if (!FDecl && !Proto) {
3506  // Function without a prototype. Just give the return type and a
3507  // highlighted ellipsis.
3508  const FunctionType *FT = getFunctionType();
3509  Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3510  FT->getReturnType().getAsString(Policy)));
3514  return Result.TakeString();
3515  }
3516 
3517  if (FDecl) {
3518  if (IncludeBriefComments) {
3519  if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg))
3520  Result.addBriefComment(RC->getBriefText(S.getASTContext()));
3521  }
3522  AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
3523  Result.AddTextChunk(
3524  Result.getAllocator().CopyString(FDecl->getNameAsString()));
3525  } else {
3526  Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3527  Proto->getReturnType().getAsString(Policy)));
3528  }
3529 
3531  AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
3532  CurrentArg);
3533  Result.AddChunk(CodeCompletionString::CK_RightParen);
3534 
3535  return Result.TakeString();
3536 }
3537 
3538 unsigned clang::getMacroUsagePriority(StringRef MacroName,
3539  const LangOptions &LangOpts,
3540  bool PreferredTypeIsPointer) {
3541  unsigned Priority = CCP_Macro;
3542 
3543  // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
3544  if (MacroName.equals("nil") || MacroName.equals("NULL") ||
3545  MacroName.equals("Nil")) {
3546  Priority = CCP_Constant;
3547  if (PreferredTypeIsPointer)
3548  Priority = Priority / CCF_SimilarTypeMatch;
3549  }
3550  // Treat "YES", "NO", "true", and "false" as constants.
3551  else if (MacroName.equals("YES") || MacroName.equals("NO") ||
3552  MacroName.equals("true") || MacroName.equals("false"))
3553  Priority = CCP_Constant;
3554  // Treat "bool" as a type.
3555  else if (MacroName.equals("bool"))
3556  Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0);
3557 
3558  return Priority;
3559 }
3560 
3562  if (!D)
3563  return CXCursor_UnexposedDecl;
3564 
3565  switch (D->getKind()) {
3566  case Decl::Enum:
3567  return CXCursor_EnumDecl;
3568  case Decl::EnumConstant:
3570  case Decl::Field:
3571  return CXCursor_FieldDecl;
3572  case Decl::Function:
3573  return CXCursor_FunctionDecl;
3574  case Decl::ObjCCategory:
3576  case Decl::ObjCCategoryImpl:
3578  case Decl::ObjCImplementation:
3580 
3581  case Decl::ObjCInterface:
3583  case Decl::ObjCIvar:
3584  return CXCursor_ObjCIvarDecl;
3585  case Decl::ObjCMethod:
3586  return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3589  case Decl::CXXMethod:
3590  return CXCursor_CXXMethod;
3591  case Decl::CXXConstructor:
3592  return CXCursor_Constructor;
3593  case Decl::CXXDestructor:
3594  return CXCursor_Destructor;
3595  case Decl::CXXConversion:
3597  case Decl::ObjCProperty:
3599  case Decl::ObjCProtocol:
3601  case Decl::ParmVar:
3602  return CXCursor_ParmDecl;
3603  case Decl::Typedef:
3604  return CXCursor_TypedefDecl;
3605  case Decl::TypeAlias:
3606  return CXCursor_TypeAliasDecl;
3607  case Decl::TypeAliasTemplate:
3609  case Decl::Var:
3610  return CXCursor_VarDecl;
3611  case Decl::Namespace:
3612  return CXCursor_Namespace;
3613  case Decl::NamespaceAlias:
3614  return CXCursor_NamespaceAlias;
3615  case Decl::TemplateTypeParm:
3617  case Decl::NonTypeTemplateParm:
3619  case Decl::TemplateTemplateParm:
3621  case Decl::FunctionTemplate:
3623  case Decl::ClassTemplate:
3624  return CXCursor_ClassTemplate;
3625  case Decl::AccessSpec:
3627  case Decl::ClassTemplatePartialSpecialization:
3629  case Decl::UsingDirective:
3630  return CXCursor_UsingDirective;
3631  case Decl::StaticAssert:
3632  return CXCursor_StaticAssert;
3633  case Decl::Friend:
3634  return CXCursor_FriendDecl;
3635  case Decl::TranslationUnit:
3636  return CXCursor_TranslationUnit;
3637 
3638  case Decl::Using:
3639  case Decl::UnresolvedUsingValue:
3640  case Decl::UnresolvedUsingTypename:
3642 
3643  case Decl::ObjCPropertyImpl:
3644  switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3646  return CXCursor_ObjCDynamicDecl;
3647 
3650  }
3651  llvm_unreachable("Unexpected Kind!");
3652 
3653  case Decl::Import:
3655 
3656  case Decl::ObjCTypeParam:
3658 
3659  default:
3660  if (const auto *TD = dyn_cast<TagDecl>(D)) {
3661  switch (TD->getTagKind()) {
3662  case TTK_Interface: // fall through
3663  case TTK_Struct:
3664  return CXCursor_StructDecl;
3665  case TTK_Class:
3666  return CXCursor_ClassDecl;
3667  case TTK_Union:
3668  return CXCursor_UnionDecl;
3669  case TTK_Enum:
3670  return CXCursor_EnumDecl;
3671  }
3672  }
3673  }
3674 
3675  return CXCursor_UnexposedDecl;
3676 }
3677 
3678 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
3679  bool LoadExternal, bool IncludeUndefined,
3680  bool TargetTypeIsPointer = false) {
3681  typedef CodeCompletionResult Result;
3682 
3683  Results.EnterNewScope();
3684 
3685  for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal),
3686  MEnd = PP.macro_end(LoadExternal);
3687  M != MEnd; ++M) {
3688  auto MD = PP.getMacroDefinition(M->first);
3689  if (IncludeUndefined || MD) {
3690  MacroInfo *MI = MD.getMacroInfo();
3691  if (MI && MI->isUsedForHeaderGuard())
3692  continue;
3693 
3694  Results.AddResult(
3695  Result(M->first, MI,
3696  getMacroUsagePriority(M->first->getName(), PP.getLangOpts(),
3697  TargetTypeIsPointer)));
3698  }
3699  }
3700 
3701  Results.ExitScope();
3702 }
3703 
3704 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3705  ResultBuilder &Results) {
3706  typedef CodeCompletionResult Result;
3707 
3708  Results.EnterNewScope();
3709 
3710  Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3711  Results.AddResult(Result("__FUNCTION__", CCP_Constant));
3712  if (LangOpts.C99 || LangOpts.CPlusPlus11)
3713  Results.AddResult(Result("__func__", CCP_Constant));
3714  Results.ExitScope();
3715 }
3716 
3718  CodeCompleteConsumer *CodeCompleter,
3719  CodeCompletionContext Context,
3720  CodeCompletionResult *Results,
3721  unsigned NumResults) {
3722  if (CodeCompleter)
3723  CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
3724 }
3725 
3726 static CodeCompletionContext
3728  switch (PCC) {
3729  case Sema::PCC_Namespace:
3731 
3732  case Sema::PCC_Class:
3734 
3737 
3740 
3743 
3744  case Sema::PCC_Template:
3746  if (S.CurContext->isFileContext())
3748  if (S.CurContext->isRecord())
3751 
3754 
3755  case Sema::PCC_ForInit:
3756  if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3757  S.getLangOpts().ObjC)
3759  else
3761 
3762  case Sema::PCC_Expression:
3764  case Sema::PCC_Condition:
3766  S.getASTContext().BoolTy);
3767 
3768  case Sema::PCC_Statement:
3770 
3771  case Sema::PCC_Type:
3773 
3776 
3779  }
3780 
3781  llvm_unreachable("Invalid ParserCompletionContext!");
3782 }
3783 
3784 /// If we're in a C++ virtual member function, add completion results
3785 /// that invoke the functions we override, since it's common to invoke the
3786 /// overridden function as well as adding new functionality.
3787 ///
3788 /// \param S The semantic analysis object for which we are generating results.
3789 ///
3790 /// \param InContext This context in which the nested-name-specifier preceding
3791 /// the code-completion point
3792 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3793  ResultBuilder &Results) {
3794  // Look through blocks.
3795  DeclContext *CurContext = S.CurContext;
3796  while (isa<BlockDecl>(CurContext))
3797  CurContext = CurContext->getParent();
3798 
3799  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3800  if (!Method || !Method->isVirtual())
3801  return;
3802 
3803  // We need to have names for all of the parameters, if we're going to
3804  // generate a forwarding call.
3805  for (auto P : Method->parameters())
3806  if (!P->getDeclName())
3807  return;
3808 
3810  for (const CXXMethodDecl *Overridden : Method->overridden_methods()) {
3811  CodeCompletionBuilder Builder(Results.getAllocator(),
3812  Results.getCodeCompletionTUInfo());
3813  if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3814  continue;
3815 
3816  // If we need a nested-name-specifier, add one now.
3817  if (!InContext) {
3819  S.Context, CurContext, Overridden->getDeclContext());
3820  if (NNS) {
3821  std::string Str;
3822  llvm::raw_string_ostream OS(Str);
3823  NNS->print(OS, Policy);
3824  Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
3825  }
3826  } else if (!InContext->Equals(Overridden->getDeclContext()))
3827  continue;
3828 
3829  Builder.AddTypedTextChunk(
3830  Results.getAllocator().CopyString(Overridden->getNameAsString()));
3831  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3832  bool FirstParam = true;
3833  for (auto P : Method->parameters()) {
3834  if (FirstParam)
3835  FirstParam = false;
3836  else
3837  Builder.AddChunk(CodeCompletionString::CK_Comma);
3838 
3839  Builder.AddPlaceholderChunk(
3840  Results.getAllocator().CopyString(P->getIdentifier()->getName()));
3841  }
3842  Builder.AddChunk(CodeCompletionString::CK_RightParen);
3843  Results.AddResult(CodeCompletionResult(
3844  Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod,
3845  CXAvailability_Available, Overridden));
3846  Results.Ignore(Overridden);
3847  }
3848 }
3849 
3851  ModuleIdPath Path) {
3852  typedef CodeCompletionResult Result;
3853  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3854  CodeCompleter->getCodeCompletionTUInfo(),
3856  Results.EnterNewScope();
3857 
3858  CodeCompletionAllocator &Allocator = Results.getAllocator();
3859  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
3860  typedef CodeCompletionResult Result;
3861  if (Path.empty()) {
3862  // Enumerate all top-level modules.
3863  SmallVector<Module *, 8> Modules;
3864  PP.getHeaderSearchInfo().collectAllModules(Modules);
3865  for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3866  Builder.AddTypedTextChunk(
3867  Builder.getAllocator().CopyString(Modules[I]->Name));
3868  Results.AddResult(Result(
3869  Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
3870  Modules[I]->isAvailable() ? CXAvailability_Available
3872  }
3873  } else if (getLangOpts().Modules) {
3874  // Load the named module.
3875  Module *Mod =
3876  PP.getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
3877  /*IsInclusionDirective=*/false);
3878  // Enumerate submodules.
3879  if (Mod) {
3880  for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3881  SubEnd = Mod->submodule_end();
3882  Sub != SubEnd; ++Sub) {
3883 
3884  Builder.AddTypedTextChunk(
3885  Builder.getAllocator().CopyString((*Sub)->Name));
3886  Results.AddResult(Result(
3887  Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
3888  (*Sub)->isAvailable() ? CXAvailability_Available
3890  }
3891  }
3892  }
3893  Results.ExitScope();
3894  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3895  Results.data(), Results.size());
3896 }
3897 
3899  ParserCompletionContext CompletionContext) {
3900  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3901  CodeCompleter->getCodeCompletionTUInfo(),
3902  mapCodeCompletionContext(*this, CompletionContext));
3903  Results.EnterNewScope();
3904 
3905  // Determine how to filter results, e.g., so that the names of
3906  // values (functions, enumerators, function templates, etc.) are
3907  // only allowed where we can have an expression.
3908  switch (CompletionContext) {
3909  case PCC_Namespace:
3910  case PCC_Class:
3911  case PCC_ObjCInterface:
3912  case PCC_ObjCImplementation:
3913  case PCC_ObjCInstanceVariableList:
3914  case PCC_Template:
3915  case PCC_MemberTemplate:
3916  case PCC_Type:
3917  case PCC_LocalDeclarationSpecifiers:
3918  Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3919  break;
3920 
3921  case PCC_Statement:
3922  case PCC_ParenthesizedExpression:
3923  case PCC_Expression:
3924  case PCC_ForInit:
3925  case PCC_Condition:
3926  if (WantTypesInContext(CompletionContext, getLangOpts()))
3927  Results.setFilter(&ResultBuilder::IsOrdinaryName);
3928  else
3929  Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3930 
3931  if (getLangOpts().CPlusPlus)
3932  MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
3933  break;
3934 
3935  case PCC_RecoveryInFunction:
3936  // Unfiltered
3937  break;
3938  }
3939 
3940  // If we are in a C++ non-static member function, check the qualifiers on
3941  // the member function to filter/prioritize the results list.
3942  auto ThisType = getCurrentThisType();
3943  if (!ThisType.isNull())
3944  Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers());
3945 
3946  CodeCompletionDeclConsumer Consumer(Results, CurContext);
3947  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3948  CodeCompleter->includeGlobals(),
3949  CodeCompleter->loadExternal());
3950 
3951  AddOrdinaryNameResults(CompletionContext, S, *this, Results);
3952  Results.ExitScope();
3953 
3954  switch (CompletionContext) {
3955  case PCC_ParenthesizedExpression:
3956  case PCC_Expression:
3957  case PCC_Statement:
3958  case PCC_RecoveryInFunction:
3959  if (S->getFnParent())
3960  AddPrettyFunctionResults(getLangOpts(), Results);
3961  break;
3962 
3963  case PCC_Namespace:
3964  case PCC_Class:
3965  case PCC_ObjCInterface:
3966  case PCC_ObjCImplementation:
3967  case PCC_ObjCInstanceVariableList:
3968  case PCC_Template:
3969  case PCC_MemberTemplate:
3970  case PCC_ForInit:
3971  case PCC_Condition:
3972  case PCC_Type:
3973  case PCC_LocalDeclarationSpecifiers:
3974  break;
3975  }
3976 
3977  if (CodeCompleter->includeMacros())
3978  AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
3979 
3980  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3981  Results.data(), Results.size());
3982 }
3983 
3984 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3985  ParsedType Receiver,
3986  ArrayRef<IdentifierInfo *> SelIdents,
3987  bool AtArgumentExpression, bool IsSuper,
3988  ResultBuilder &Results);
3989 
3991  bool AllowNonIdentifiers,
3992  bool AllowNestedNameSpecifiers) {
3993  typedef CodeCompletionResult Result;
3994  ResultBuilder Results(
3995  *this, CodeCompleter->getAllocator(),
3996  CodeCompleter->getCodeCompletionTUInfo(),
3997  AllowNestedNameSpecifiers
3998  // FIXME: Try to separate codepath leading here to deduce whether we
3999  // need an existing symbol or a new one.
4002  Results.EnterNewScope();
4003 
4004  // Type qualifiers can come after names.
4005  Results.AddResult(Result("const"));
4006  Results.AddResult(Result("volatile"));
4007  if (getLangOpts().C99)
4008  Results.AddResult(Result("restrict"));
4009 
4010  if (getLangOpts().CPlusPlus) {
4011  if (getLangOpts().CPlusPlus11 &&
4014  Results.AddResult("final");
4015 
4016  if (AllowNonIdentifiers) {
4017  Results.AddResult(Result("operator"));
4018  }
4019 
4020  // Add nested-name-specifiers.
4021  if (AllowNestedNameSpecifiers) {
4022  Results.allowNestedNameSpecifiers();
4023  Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
4024  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4025  LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
4026  CodeCompleter->includeGlobals(),
4027  CodeCompleter->loadExternal());
4028  Results.setFilter(nullptr);
4029  }
4030  }
4031  Results.ExitScope();
4032 
4033  // If we're in a context where we might have an expression (rather than a
4034  // declaration), and what we've seen so far is an Objective-C type that could
4035  // be a receiver of a class message, this may be a class message send with
4036  // the initial opening bracket '[' missing. Add appropriate completions.
4037  if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
4042  !DS.isTypeAltiVecVector() && S &&
4043  (S->getFlags() & Scope::DeclScope) != 0 &&
4046  0) {
4047  ParsedType T = DS.getRepAsType();
4048  if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
4049  AddClassMessageCompletions(*this, S, T, None, false, false, Results);
4050  }
4051 
4052  // Note that we intentionally suppress macro results here, since we do not
4053  // encourage using macros to produce the names of entities.
4054 
4055  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4056  Results.data(), Results.size());
4057 }
4058 
4061  bool IsParenthesized = false)
4062  : PreferredType(PreferredType), IntegralConstantExpression(false),
4063  ObjCCollection(false), IsParenthesized(IsParenthesized) {}
4064 
4070 };
4071 
4072 /// Perform code-completion in an expression context when we know what
4073 /// type we're looking for.
4075  const CodeCompleteExpressionData &Data) {
4076  ResultBuilder Results(
4077  *this, CodeCompleter->getAllocator(),
4078  CodeCompleter->getCodeCompletionTUInfo(),
4080  Data.IsParenthesized
4083  Data.PreferredType));
4084  auto PCC =
4085  Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression;
4086  if (Data.ObjCCollection)
4087  Results.setFilter(&ResultBuilder::IsObjCCollection);
4088  else if (Data.IntegralConstantExpression)
4089  Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
4090  else if (WantTypesInContext(PCC, getLangOpts()))
4091  Results.setFilter(&ResultBuilder::IsOrdinaryName);
4092  else
4093  Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4094 
4095  if (!Data.PreferredType.isNull())
4096  Results.setPreferredType(Data.PreferredType.getNonReferenceType());
4097 
4098  // Ignore any declarations that we were told that we don't care about.
4099  for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
4100  Results.Ignore(Data.IgnoreDecls[I]);
4101 
4102  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4103  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4104  CodeCompleter->includeGlobals(),
4105  CodeCompleter->loadExternal());
4106 
4107  Results.EnterNewScope();
4108  AddOrdinaryNameResults(PCC, S, *this, Results);
4109  Results.ExitScope();
4110 
4111  bool PreferredTypeIsPointer = false;
4112  if (!Data.PreferredType.isNull())
4113  PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() ||
4116 
4117  if (S->getFnParent() && !Data.ObjCCollection &&
4119  AddPrettyFunctionResults(getLangOpts(), Results);
4120 
4121  if (CodeCompleter->includeMacros())
4122  AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false,
4123  PreferredTypeIsPointer);
4124  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4125  Results.data(), Results.size());
4126 }
4127 
4129  bool IsParenthesized) {
4130  return CodeCompleteExpression(
4131  S, CodeCompleteExpressionData(PreferredType, IsParenthesized));
4132 }
4133 
4135  QualType PreferredType) {
4136  if (E.isInvalid())
4137  CodeCompleteExpression(S, PreferredType);
4138  else if (getLangOpts().ObjC)
4139  CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
4140 }
4141 
4142 /// The set of properties that have already been added, referenced by
4143 /// property name.
4144 typedef llvm::SmallPtrSet<IdentifierInfo *, 16> AddedPropertiesSet;
4145 
4146 /// Retrieve the container definition, if any?
4148  if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4149  if (Interface->hasDefinition())
4150  return Interface->getDefinition();
4151 
4152  return Interface;
4153  }
4154 
4155  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4156  if (Protocol->hasDefinition())
4157  return Protocol->getDefinition();
4158 
4159  return Protocol;
4160  }
4161  return Container;
4162 }
4163 
4164 /// Adds a block invocation code completion result for the given block
4165 /// declaration \p BD.
4166 static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
4167  CodeCompletionBuilder &Builder,
4168  const NamedDecl *BD,
4169  const FunctionTypeLoc &BlockLoc,
4170  const FunctionProtoTypeLoc &BlockProtoLoc) {
4171  Builder.AddResultTypeChunk(
4172  GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
4173  Policy, Builder.getAllocator()));
4174 
4175  AddTypedNameChunk(Context, Policy, BD, Builder);
4177 
4178  if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
4179  Builder.AddPlaceholderChunk("...");
4180  } else {
4181  for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
4182  if (I)
4184 
4185  // Format the placeholder string.
4186  std::string PlaceholderStr =
4187  FormatFunctionParameter(Policy, BlockLoc.getParam(I));
4188 
4189  if (I == N - 1 && BlockProtoLoc &&
4190  BlockProtoLoc.getTypePtr()->isVariadic())
4191  PlaceholderStr += ", ...";
4192 
4193  // Add the placeholder string.
4194  Builder.AddPlaceholderChunk(
4195  Builder.getAllocator().CopyString(PlaceholderStr));
4196  }
4197  }
4198 
4200 }
4201 
4202 static void
4204  ObjCContainerDecl *Container, bool AllowCategories,
4205  bool AllowNullaryMethods, DeclContext *CurContext,
4206  AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
4207  bool IsBaseExprStatement = false,
4208  bool IsClassProperty = false, bool InOriginalClass = true) {
4209  typedef CodeCompletionResult Result;
4210 
4211  // Retrieve the definition.
4212  Container = getContainerDef(Container);
4213 
4214  // Add properties in this container.
4215  const auto AddProperty = [&](const ObjCPropertyDecl *P) {
4216  if (!AddedProperties.insert(P->getIdentifier()).second)
4217  return;
4218 
4219  // FIXME: Provide block invocation completion for non-statement
4220  // expressions.
4221  if (!P->getType().getTypePtr()->isBlockPointerType() ||
4222  !IsBaseExprStatement) {
4223  Result R = Result(P, Results.getBasePriority(P), nullptr);
4224  if (!InOriginalClass)
4225  setInBaseClass(R);
4226  Results.MaybeAddResult(R, CurContext);
4227  return;
4228  }
4229 
4230  // Block setter and invocation completion is provided only when we are able
4231  // to find the FunctionProtoTypeLoc with parameter names for the block.
4232  FunctionTypeLoc BlockLoc;
4233  FunctionProtoTypeLoc BlockProtoLoc;
4234  findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
4235  BlockProtoLoc);
4236  if (!BlockLoc) {
4237  Result R = Result(P, Results.getBasePriority(P), nullptr);
4238  if (!InOriginalClass)
4239  setInBaseClass(R);
4240  Results.MaybeAddResult(R, CurContext);
4241  return;
4242  }
4243 
4244  // The default completion result for block properties should be the block
4245  // invocation completion when the base expression is a statement.
4246  CodeCompletionBuilder Builder(Results.getAllocator(),
4247  Results.getCodeCompletionTUInfo());
4248  AddObjCBlockCall(Container->getASTContext(),
4249  getCompletionPrintingPolicy(Results.getSema()), Builder, P,
4250  BlockLoc, BlockProtoLoc);
4251  Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P));
4252  if (!InOriginalClass)
4253  setInBaseClass(R);
4254  Results.MaybeAddResult(R, CurContext);
4255 
4256  // Provide additional block setter completion iff the base expression is a
4257  // statement and the block property is mutable.
4258  if (!P->isReadOnly()) {
4259  CodeCompletionBuilder Builder(Results.getAllocator(),
4260  Results.getCodeCompletionTUInfo());
4261  AddResultTypeChunk(Container->getASTContext(),
4262  getCompletionPrintingPolicy(Results.getSema()), P,
4263  CCContext.getBaseType(), Builder);
4264  Builder.AddTypedTextChunk(
4265  Results.getAllocator().CopyString(P->getName()));
4266  Builder.AddChunk(CodeCompletionString::CK_Equal);
4267 
4268  std::string PlaceholderStr = formatBlockPlaceholder(
4269  getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
4270  BlockProtoLoc, /*SuppressBlockName=*/true);
4271  // Add the placeholder string.
4272  Builder.AddPlaceholderChunk(
4273  Builder.getAllocator().CopyString(PlaceholderStr));
4274 
4275  // When completing blocks properties that return void the default
4276  // property completion result should show up before the setter,
4277  // otherwise the setter completion should show up before the default
4278  // property completion, as we normally want to use the result of the
4279  // call.
4280  Result R =
4281  Result(Builder.TakeString(), P,
4282  Results.getBasePriority(P) +
4283  (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
4286  if (!InOriginalClass)
4287  setInBaseClass(R);
4288  Results.MaybeAddResult(R, CurContext);
4289  }
4290  };
4291 
4292  if (IsClassProperty) {
4293  for (const auto *P : Container->class_properties())
4294  AddProperty(P);
4295  } else {
4296  for (const auto *P : Container->instance_properties())
4297  AddProperty(P);
4298  }
4299 
4300  // Add nullary methods or implicit class properties
4301  if (AllowNullaryMethods) {
4302  ASTContext &Context = Container->getASTContext();
4303  PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
4304  // Adds a method result
4305  const auto AddMethod = [&](const ObjCMethodDecl *M) {
4306  IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
4307  if (!Name)
4308  return;
4309  if (!AddedProperties.insert(Name).second)
4310  return;
4311  CodeCompletionBuilder Builder(Results.getAllocator(),
4312  Results.getCodeCompletionTUInfo());
4313  AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
4314  Builder.AddTypedTextChunk(
4315  Results.getAllocator().CopyString(Name->getName()));
4316  Result R = Result(Builder.TakeString(), M,
4318  if (!InOriginalClass)
4319  setInBaseClass(R);
4320  Results.MaybeAddResult(R, CurContext);
4321  };
4322 
4323  if (IsClassProperty) {
4324  for (const auto *M : Container->methods()) {
4325  // Gather the class method that can be used as implicit property
4326  // getters. Methods with arguments or methods that return void aren't
4327  // added to the results as they can't be used as a getter.
4328  if (!M->getSelector().isUnarySelector() ||
4329  M->getReturnType()->isVoidType() || M->isInstanceMethod())
4330  continue;
4331  AddMethod(M);
4332  }
4333  } else {
4334  for (auto *M : Container->methods()) {
4335  if (M->getSelector().isUnarySelector())
4336  AddMethod(M);
4337  }
4338  }
4339  }
4340 
4341  // Add properties in referenced protocols.
4342  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4343  for (auto *P : Protocol->protocols())
4344  AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
4345  CurContext, AddedProperties, Results,
4346  IsBaseExprStatement, IsClassProperty,
4347  /*InOriginalClass*/ false);
4348  } else if (ObjCInterfaceDecl *IFace =
4349  dyn_cast<ObjCInterfaceDecl>(Container)) {
4350  if (AllowCategories) {
4351  // Look through categories.
4352  for (auto *Cat : IFace->known_categories())
4353  AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
4354  CurContext, AddedProperties, Results,
4355  IsBaseExprStatement, IsClassProperty,
4356  InOriginalClass);
4357  }
4358 
4359  // Look through protocols.
4360  for (auto *I : IFace->all_referenced_protocols())
4361  AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
4362  CurContext, AddedProperties, Results,
4363  IsBaseExprStatement, IsClassProperty,
4364  /*InOriginalClass*/ false);
4365 
4366  // Look in the superclass.
4367  if (IFace->getSuperClass())
4368  AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
4369  AllowNullaryMethods, CurContext, AddedProperties,
4370  Results, IsBaseExprStatement, IsClassProperty,
4371  /*InOriginalClass*/ false);
4372  } else if (const auto *Category =
4373  dyn_cast<ObjCCategoryDecl>(Container)) {
4374  // Look through protocols.
4375  for (auto *P : Category->protocols())
4376  AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
4377  CurContext, AddedProperties, Results,
4378  IsBaseExprStatement, IsClassProperty,
4379  /*InOriginalClass*/ false);
4380  }
4381 }
4382 
4383 static void
4384 AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results,
4385  Scope *S, QualType BaseType, RecordDecl *RD,
4386  Optional<FixItHint> AccessOpFixIt) {
4387  // Indicate that we are performing a member access, and the cv-qualifiers
4388  // for the base object type.
4389  Results.setObjectTypeQualifiers(BaseType.getQualifiers());
4390 
4391  // Access to a C/C++ class, struct, or union.
4392  Results.allowNestedNameSpecifiers();
4393  std::vector<FixItHint> FixIts;
4394  if (AccessOpFixIt)
4395  FixIts.emplace_back(AccessOpFixIt.getValue());
4396  CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts));
4397  SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
4398  SemaRef.CodeCompleter->includeGlobals(),
4399  /*IncludeDependentBases=*/true,
4400  SemaRef.CodeCompleter->loadExternal());
4401 
4402  if (SemaRef.getLangOpts().CPlusPlus) {
4403  if (!Results.empty()) {
4404  // The "template" keyword can follow "->" or "." in the grammar.
4405  // However, we only want to suggest the template keyword if something
4406  // is dependent.
4407  bool IsDependent = BaseType->isDependentType();
4408  if (!IsDependent) {
4409  for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
4410  if (DeclContext *Ctx = DepScope->getEntity()) {
4411  IsDependent = Ctx->isDependentContext();
4412  break;
4413  }
4414  }
4415 
4416  if (IsDependent)
4417  Results.AddResult(CodeCompletionResult("template"));
4418  }
4419  }
4420 }
4421 
4423  Expr *OtherOpBase,
4424  SourceLocation OpLoc, bool IsArrow,
4425  bool IsBaseExprStatement,
4426  QualType PreferredType) {
4427  if (!Base || !CodeCompleter)
4428  return;
4429 
4430  ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
4431  if (ConvertedBase.isInvalid())
4432  return;
4433  QualType ConvertedBaseType = ConvertedBase.get()->getType();
4434 
4435  enum CodeCompletionContext::Kind contextKind;
4436 
4437  if (IsArrow) {
4438  if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>())
4439  ConvertedBaseType = Ptr->getPointeeType();
4440  }
4441 
4442  if (IsArrow) {
4444  } else {
4445  if (ConvertedBaseType->isObjCObjectPointerType() ||
4446  ConvertedBaseType->isObjCObjectOrInterfaceType()) {
4448  } else {
4450  }
4451  }
4452 
4453  CodeCompletionContext CCContext(contextKind, ConvertedBaseType);
4454  CCContext.setPreferredType(PreferredType);
4455  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4456  CodeCompleter->getCodeCompletionTUInfo(), CCContext,
4457  &ResultBuilder::IsMember);
4458 
4459  auto DoCompletion = [&](Expr *Base, bool IsArrow,
4460  Optional<FixItHint> AccessOpFixIt) -> bool {
4461  if (!Base)
4462  return false;
4463 
4464  ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
4465  if (ConvertedBase.isInvalid())
4466  return false;
4467  Base = ConvertedBase.get();
4468 
4469  QualType BaseType = Base->getType();
4470 
4471  if (IsArrow) {
4472  if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4473  BaseType = Ptr->getPointeeType();
4474  else if (BaseType->isObjCObjectPointerType())
4475  /*Do nothing*/;
4476  else
4477  return false;
4478  }
4479 
4480  if (const RecordType *Record = BaseType->getAs<RecordType>()) {
4481  AddRecordMembersCompletionResults(*this, Results, S, BaseType,
4482  Record->getDecl(),
4483  std::move(AccessOpFixIt));
4484  } else if (const auto *TST =
4485  BaseType->getAs<TemplateSpecializationType>()) {
4486  TemplateName TN = TST->getTemplateName();
4487  if (const auto *TD =
4488  dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) {
4489  CXXRecordDecl *RD = TD->getTemplatedDecl();
4490  AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD,
4491  std::move(AccessOpFixIt));
4492  }
4493  } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) {
4494  if (auto *RD = ICNT->getDecl())
4495  AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD,
4496  std::move(AccessOpFixIt));
4497  } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
4498  // Objective-C property reference.
4499  AddedPropertiesSet AddedProperties;
4500 
4501  if (const ObjCObjectPointerType *ObjCPtr =
4502  BaseType->getAsObjCInterfacePointerType()) {
4503  // Add property results based on our interface.
4504  assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
4505  AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
4506  /*AllowNullaryMethods=*/true, CurContext,
4507  AddedProperties, Results, IsBaseExprStatement);
4508  }
4509 
4510  // Add properties from the protocols in a qualified interface.
4511  for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals())
4512  AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
4513  CurContext, AddedProperties, Results,
4514  IsBaseExprStatement, /*IsClassProperty*/ false,
4515  /*InOriginalClass*/ false);
4516  } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
4517  (!IsArrow && BaseType->isObjCObjectType())) {
4518  // Objective-C instance variable access.
4519  ObjCInterfaceDecl *Class = nullptr;
4520  if (const ObjCObjectPointerType *ObjCPtr =
4521  BaseType->getAs<ObjCObjectPointerType>())
4522  Class = ObjCPtr->getInterfaceDecl();
4523  else
4524  Class = BaseType->getAs<ObjCObjectType>()->getInterface();
4525 
4526  // Add all ivars from this class and its superclasses.
4527  if (Class) {
4528  CodeCompletionDeclConsumer Consumer(Results, Class, BaseType);
4529  Results.setFilter(&ResultBuilder::IsObjCIvar);
4531  Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(),
4532  /*IncludeDependentBases=*/false, CodeCompleter->loadExternal());
4533  }
4534  }
4535 
4536  // FIXME: How do we cope with isa?
4537  return true;
4538  };
4539 
4540  Results.EnterNewScope();
4541 
4542  bool CompletionSucceded = DoCompletion(Base, IsArrow, None);
4543  if (CodeCompleter->includeFixIts()) {
4544  const CharSourceRange OpRange =
4545  CharSourceRange::getTokenRange(OpLoc, OpLoc);
4546  CompletionSucceded |= DoCompletion(
4547  OtherOpBase, !IsArrow,
4548  FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->"));
4549  }
4550 
4551  Results.ExitScope();
4552 
4553  if (!CompletionSucceded)
4554  return;
4555 
4556  // Hand off the results found for code completion.
4557  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4558  Results.data(), Results.size());
4559 }
4560 
4562  IdentifierInfo &ClassName,
4563  SourceLocation ClassNameLoc,
4564  bool IsBaseExprStatement) {
4565  IdentifierInfo *ClassNamePtr = &ClassName;
4566  ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
4567  if (!IFace)
4568  return;
4569  CodeCompletionContext CCContext(
4571  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4572  CodeCompleter->getCodeCompletionTUInfo(), CCContext,
4573  &ResultBuilder::IsMember);
4574  Results.EnterNewScope();
4575  AddedPropertiesSet AddedProperties;
4576  AddObjCProperties(CCContext, IFace, true,
4577  /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
4578  Results, IsBaseExprStatement,
4579  /*IsClassProperty=*/true);
4580  Results.ExitScope();
4581  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4582  Results.data(), Results.size());
4583 }
4584 
4585 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
4586  if (!CodeCompleter)
4587  return;
4588 
4589  ResultBuilder::LookupFilter Filter = nullptr;
4592  switch ((DeclSpec::TST)TagSpec) {
4593  case DeclSpec::TST_enum:
4594  Filter = &ResultBuilder::IsEnum;
4595  ContextKind = CodeCompletionContext::CCC_EnumTag;
4596  break;
4597 
4598  case DeclSpec::TST_union:
4599  Filter = &ResultBuilder::IsUnion;
4601  break;
4602 
4603  case DeclSpec::TST_struct:
4604  case DeclSpec::TST_class:
4606  Filter = &ResultBuilder::IsClassOrStruct;
4608  break;
4609 
4610  default:
4611  llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
4612  }
4613 
4614  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4615  CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
4616  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4617 
4618  // First pass: look for tags.
4619  Results.setFilter(Filter);
4620  LookupVisibleDecls(S, LookupTagName, Consumer,
4621  CodeCompleter->includeGlobals(),
4622  CodeCompleter->loadExternal());
4623 
4624  if (CodeCompleter->includeGlobals()) {
4625  // Second pass: look for nested name specifiers.
4626  Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
4627  LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
4628  CodeCompleter->includeGlobals(),
4629  CodeCompleter->loadExternal());
4630  }
4631 
4632  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4633  Results.data(), Results.size());
4634 }
4635 
4636 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
4637  const LangOptions &LangOpts) {
4638  if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
4639  Results.AddResult("const");
4641  Results.AddResult("volatile");
4642  if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
4643  Results.AddResult("restrict");
4644  if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
4645  Results.AddResult("_Atomic");
4646  if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
4647  Results.AddResult("__unaligned");
4648 }
4649 
4651  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4652  CodeCompleter->getCodeCompletionTUInfo(),
4654  Results.EnterNewScope();
4655  AddTypeQualifierResults(DS, Results, LangOpts);
4656  Results.ExitScope();
4657  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4658  Results.data(), Results.size());
4659 }
4660 
4662  const VirtSpecifiers *VS) {
4663  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4664  CodeCompleter->getCodeCompletionTUInfo(),
4666  Results.EnterNewScope();
4667  AddTypeQualifierResults(DS, Results, LangOpts);
4668  if (LangOpts.CPlusPlus11) {
4669  Results.AddResult("noexcept");
4671  !D.isCtorOrDtor() && !D.isStaticMember()) {
4672  if (!VS || !VS->isFinalSpecified())
4673  Results.AddResult("final");
4674  if (!VS || !VS->isOverrideSpecified())
4675  Results.AddResult("override");
4676  }
4677  }
4678  Results.ExitScope();
4679  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4680  Results.data(), Results.size());
4681 }
4682 
4684  CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
4685 }
4686 
4688  if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
4689  return;
4690 
4691  SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer();
4692  // Condition expression might be invalid, do not continue in this case.
4693  if (!Switch->getCond())
4694  return;
4695  QualType type = Switch->getCond()->IgnoreImplicit()->getType();
4696  if (!type->isEnumeralType()) {
4697  CodeCompleteExpressionData Data(type);
4698  Data.IntegralConstantExpression = true;
4699  CodeCompleteExpression(S, Data);
4700  return;
4701  }
4702 
4703  // Code-complete the cases of a switch statement over an enumeration type
4704  // by providing the list of
4705  EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
4706  if (EnumDecl *Def = Enum->getDefinition())
4707  Enum = Def;
4708 
4709  // Determine which enumerators we have already seen in the switch statement.
4710  // FIXME: Ideally, we would also be able to look *past* the code-completion
4711  // token, in case we are code-completing in the middle of the switch and not
4712  // at the end. However, we aren't able to do so at the moment.
4713  llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
4714  NestedNameSpecifier *Qualifier = nullptr;
4715  for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
4716  SC = SC->getNextSwitchCase()) {
4717  CaseStmt *Case = dyn_cast<CaseStmt>(SC);
4718  if (!Case)
4719  continue;
4720 
4721  Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
4722  if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal))
4723  if (auto *Enumerator =
4724  dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4725  // We look into the AST of the case statement to determine which
4726  // enumerator was named. Alternatively, we could compute the value of
4727  // the integral constant expression, then compare it against the
4728  // values of each enumerator. However, value-based approach would not
4729  // work as well with C++ templates where enumerators declared within a
4730  // template are type- and value-dependent.
4731  EnumeratorsSeen.insert(Enumerator);
4732 
4733  // If this is a qualified-id, keep track of the nested-name-specifier
4734  // so that we can reproduce it as part of code completion, e.g.,
4735  //
4736  // switch (TagD.getKind()) {
4737  // case TagDecl::TK_enum:
4738  // break;
4739  // case XXX
4740  //
4741  // At the XXX, our completions are TagDecl::TK_union,
4742  // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
4743  // TK_struct, and TK_class.
4744  Qualifier = DRE->getQualifier();
4745  }
4746  }
4747 
4748  if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
4749  // If there are no prior enumerators in C++, check whether we have to
4750  // qualify the names of the enumerators that we suggest, because they
4751  // may not be visible in this scope.
4752  Qualifier = getRequiredQualification(Context, CurContext, Enum);
4753  }
4754 
4755  // Add any enumerators that have not yet been mentioned.
4756  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4757  CodeCompleter->getCodeCompletionTUInfo(),
4759  Results.EnterNewScope();
4760  for (auto *E : Enum->enumerators()) {
4761  if (EnumeratorsSeen.count(E))
4762  continue;
4763 
4764  CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
4765  Results.AddResult(R, CurContext, nullptr, false);
4766  }
4767  Results.ExitScope();
4768 
4769  if (CodeCompleter->includeMacros()) {
4770  AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
4771  }
4772  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4773  Results.data(), Results.size());
4774 }
4775 
4776 static bool anyNullArguments(ArrayRef<Expr *> Args) {
4777  if (Args.size() && !Args.data())
4778  return true;
4779 
4780  for (unsigned I = 0; I != Args.size(); ++I)
4781  if (!Args[I])
4782  return true;
4783 
4784  return false;
4785 }
4786 
4788 
4790  Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results,
4791  OverloadCandidateSet &CandidateSet, SourceLocation Loc) {
4792  if (!CandidateSet.empty()) {
4793  // Sort the overload candidate set by placing the best overloads first.
4794  std::stable_sort(
4795  CandidateSet.begin(), CandidateSet.end(),
4796  [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
4797  return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
4798  CandidateSet.getKind());
4799  });
4800 
4801  // Add the remaining viable overload candidates as code-completion results.
4802  for (OverloadCandidate &Candidate : CandidateSet) {
4803  if (Candidate.Function && Candidate.Function->isDeleted())
4804  continue;
4805  if (Candidate.Viable)
4806  Results.push_back(ResultCandidate(Candidate.Function));
4807  }
4808  }
4809 }
4810 
4811 /// Get the type of the Nth parameter from a given set of overload
4812 /// candidates.
4813 static QualType getParamType(Sema &SemaRef,
4814  ArrayRef<ResultCandidate> Candidates, unsigned N) {
4815 
4816  // Given the overloads 'Candidates' for a function call matching all arguments
4817  // up to N, return the type of the Nth parameter if it is the same for all
4818  // overload candidates.
4819  QualType ParamType;
4820  for (auto &Candidate : Candidates) {
4821  if (const auto *FType = Candidate.getFunctionType())
4822  if (const auto *Proto = dyn_cast<FunctionProtoType>(FType))
4823  if (N < Proto->getNumParams()) {
4824  if (ParamType.isNull())
4825  ParamType = Proto->getParamType(N);
4826  else if (!SemaRef.Context.hasSameUnqualifiedType(
4827  ParamType.getNonReferenceType(),
4828  Proto->getParamType(N).getNonReferenceType()))
4829  // Otherwise return a default-constructed QualType.
4830  return QualType();
4831  }
4832  }
4833 
4834  return ParamType;
4835 }
4836 
4837 static QualType
4840  unsigned CurrentArg, SourceLocation OpenParLoc) {
4841  if (Candidates.empty())
4842  return QualType();
4844  SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc);
4845  return getParamType(SemaRef, Candidates, CurrentArg);
4846 }
4847 
4849  ArrayRef<Expr *> Args,
4850  SourceLocation OpenParLoc) {
4851  if (!CodeCompleter)
4852  return QualType();
4853 
4854  // FIXME: Provide support for variadic template functions.
4855  // Ignore type-dependent call expressions entirely.
4856  if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4858  return QualType();
4859  }
4860 
4861  // Build an overload candidate set based on the functions we find.
4862  SourceLocation Loc = Fn->getExprLoc();
4864 
4866 
4867  Expr *NakedFn = Fn->IgnoreParenCasts();
4868  if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
4869  AddOverloadedCallCandidates(ULE, Args, CandidateSet,
4870  /*PartialOverloading=*/true);
4871  else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4872  TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4873  if (UME->hasExplicitTemplateArgs()) {
4874  UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4875  TemplateArgs = &TemplateArgsBuffer;
4876  }
4877 
4878  // Add the base as first argument (use a nullptr if the base is implicit).
4879  SmallVector<Expr *, 12> ArgExprs(
4880  1, UME->isImplicitAccess() ? nullptr : UME->getBase());
4881  ArgExprs.append(Args.begin(), Args.end());
4882  UnresolvedSet<8> Decls;
4883  Decls.append(UME->decls_begin(), UME->decls_end());
4884  const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase();
4885  AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4886  /*SuppressUsedConversions=*/false,
4887  /*PartialOverloading=*/true, FirstArgumentIsBase);
4888  } else {
4889  FunctionDecl *FD = nullptr;
4890  if (auto *MCE = dyn_cast<MemberExpr>(NakedFn))
4891  FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4892  else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn))
4893  FD = dyn_cast<FunctionDecl>(DRE->getDecl());
4894  if (FD) { // We check whether it's a resolved function declaration.
4895  if (!getLangOpts().CPlusPlus ||
4896  !FD->getType()->getAs<FunctionProtoType>())
4897  Results.push_back(ResultCandidate(FD));
4898  else
4899  AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4900  Args, CandidateSet,
4901  /*SuppressUsedConversions=*/false,
4902  /*PartialOverloading=*/true);
4903 
4904  } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4905  // If expression's type is CXXRecordDecl, it may overload the function
4906  // call operator, so we check if it does and add them as candidates.
4907  // A complete type is needed to lookup for member function call operators.
4908  if (isCompleteType(Loc, NakedFn->getType())) {
4909  DeclarationName OpName =
4910  Context.DeclarationNames.getCXXOperatorName(OO_Call);
4911  LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4912  LookupQualifiedName(R, DC);
4913  R.suppressDiagnostics();
4914  SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4915  ArgExprs.append(Args.begin(), Args.end());
4916  AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4917  /*ExplicitArgs=*/nullptr,
4918  /*SuppressUsedConversions=*/false,
4919  /*PartialOverloading=*/true);
4920  }
4921  } else {
4922  // Lastly we check whether expression's type is function pointer or
4923  // function.
4924  QualType T = NakedFn->getType();
4925  if (!T->getPointeeType().isNull())
4926  T = T->getPointeeType();
4927 
4928  if (auto FP = T->getAs<FunctionProtoType>()) {
4929  if (!TooManyArguments(FP->getNumParams(), Args.size(),
4930  /*PartialOverloading=*/true) ||
4931  FP->isVariadic())
4932  Results.push_back(ResultCandidate(FP));
4933  } else if (auto FT = T->getAs<FunctionType>())
4934  // No prototype and declaration, it may be a K & R style function.
4935  Results.push_back(ResultCandidate(FT));
4936  }
4937  }
4938  mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4939  QualType ParamType =
4940  ProduceSignatureHelp(*this, S, Results, Args.size(), OpenParLoc);
4941  return !CandidateSet.empty() ? ParamType : QualType();
4942 }
4943 
4945  SourceLocation Loc,
4946  ArrayRef<Expr *> Args,
4947  SourceLocation OpenParLoc) {
4948  if (!CodeCompleter)
4949  return QualType();
4950 
4951  // A complete type is needed to lookup for constructors.
4952  CXXRecordDecl *RD =
4953  isCompleteType(Loc, Type) ? Type->getAsCXXRecordDecl() : nullptr;
4954  if (!RD)
4955  return Type;
4956 
4957  // FIXME: Provide support for member initializers.
4958  // FIXME: Provide support for variadic template constructors.
4959 
4961 
4962  for (NamedDecl *C : LookupConstructors(RD)) {
4963  if (auto *FD = dyn_cast<FunctionDecl>(C)) {
4964  AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), Args,
4965  CandidateSet,
4966  /*SuppressUsedConversions=*/false,
4967  /*PartialOverloading=*/true);
4968  } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4969  AddTemplateOverloadCandidate(
4970  FTD, DeclAccessPair::make(FTD, C->getAccess()),
4971  /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet,
4972  /*SuppressUsedConversions=*/false,
4973  /*PartialOverloading=*/true);
4974  }
4975  }
4976 
4978  mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4979  return ProduceSignatureHelp(*this, S, Results, Args.size(), OpenParLoc);
4980 }
4981 
4983  Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
4984  ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc) {
4985  if (!CodeCompleter)
4986  return QualType();
4987 
4988  CXXConstructorDecl *Constructor =
4989  dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4990  if (!Constructor)
4991  return QualType();
4992  // FIXME: Add support for Base class constructors as well.
4993  if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl(
4994  Constructor->getParent(), SS, TemplateTypeTy, II))
4995  return ProduceConstructorSignatureHelp(getCurScope(), MemberDecl->getType(),
4996  MemberDecl->getLocation(), ArgExprs,
4997  OpenParLoc);
4998  return QualType();
4999 }
5000 
5002  ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
5003  if (!VD) {
5004  CodeCompleteOrdinaryName(S, PCC_Expression);
5005  return;
5006  }
5007 
5009  Data.PreferredType = VD->getType();
5010  // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'.
5011  Data.IgnoreDecls.push_back(VD);
5012 
5013  CodeCompleteExpression(S, Data);
5014 }
5015 
5017  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5018  CodeCompleter->getCodeCompletionTUInfo(),
5019  mapCodeCompletionContext(*this, PCC_Statement));
5020  Results.setFilter(&ResultBuilder::IsOrdinaryName);
5021  Results.EnterNewScope();
5022 
5023  CodeCompletionDeclConsumer Consumer(Results, CurContext);
5024  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5025  CodeCompleter->includeGlobals(),
5026  CodeCompleter->loadExternal());
5027 
5028  AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
5029 
5030  // "else" block
5031  CodeCompletionBuilder Builder(Results.getAllocator(),
5032  Results.getCodeCompletionTUInfo());
5033  Builder.AddTypedTextChunk("else");
5034  if (Results.includeCodePatterns()) {
5035  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5036  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5037  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
5038  Builder.AddPlaceholderChunk("statements");
5039  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
5040  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5041  }
5042  Results.AddResult(Builder.TakeString());
5043 
5044  // "else if" block
5045  Builder.AddTypedTextChunk("else");
5046  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5047  Builder.AddTextChunk("if");
5048  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5049  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5050  if (getLangOpts().CPlusPlus)
5051  Builder.AddPlaceholderChunk("condition");
5052  else
5053  Builder.AddPlaceholderChunk("expression");
5054  Builder.AddChunk(CodeCompletionString::CK_RightParen);
5055  if (Results.includeCodePatterns()) {
5056  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5057  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5058  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
5059  Builder.AddPlaceholderChunk("statements");
5060  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
5061  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5062  }
5063  Results.AddResult(Builder.TakeString());
5064 
5065  Results.ExitScope();
5066 
5067  if (S->getFnParent())
5068  AddPrettyFunctionResults(getLangOpts(), Results);
5069 
5070  if (CodeCompleter->includeMacros())
5071  AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
5072 
5073  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5074  Results.data(), Results.size());
5075 }
5076 
5078  bool EnteringContext, QualType BaseType) {
5079  if (SS.isEmpty() || !CodeCompleter)
5080  return;
5081 
5082  // We want to keep the scope specifier even if it's invalid (e.g. the scope
5083  // "a::b::" is not corresponding to any context/namespace in the AST), since
5084  // it can be useful for global code completion which have information about
5085  // contexts/symbols that are not in the AST.
5086  if (SS.isInvalid()) {
5088  CC.setCXXScopeSpecifier(SS);
5089  // As SS is invalid, we try to collect accessible contexts from the current
5090  // scope with a dummy lookup so that the completion consumer can try to
5091  // guess what the specified scope is.
5092  ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(),
5093  CodeCompleter->getCodeCompletionTUInfo(), CC);
5094  if (S->getEntity()) {
5095  CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(),
5096  BaseType);
5097  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5098  /*IncludeGlobalScope=*/false,
5099  /*LoadExternal=*/false);
5100  }
5101  HandleCodeCompleteResults(this, CodeCompleter,
5102  DummyResults.getCompletionContext(), nullptr, 0);
5103  return;
5104  }
5105  // Always pretend to enter a context to ensure that a dependent type
5106  // resolves to a dependent record.
5107  DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true);
5108  if (!Ctx)
5109  return;
5110 
5111  // Try to instantiate any non-dependent declaration contexts before
5112  // we look in them.
5113  if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
5114  return;
5115 
5116  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5117  CodeCompleter->getCodeCompletionTUInfo(),
5119  Results.EnterNewScope();
5120 
5121  // The "template" keyword can follow "::" in the grammar, but only
5122  // put it into the grammar if the nested-name-specifier is dependent.
5123  NestedNameSpecifier *NNS = SS.getScopeRep();
5124  if (!Results.empty() && NNS->isDependent())
5125  Results.AddResult("template");
5126 
5127  // Add calls to overridden virtual functions, if there are any.
5128  //
5129  // FIXME: This isn't wonderful, because we don't know whether we're actually
5130  // in a context that permits expressions. This is a general issue with
5131  // qualified-id completions.
5132  if (!EnteringContext)
5133  MaybeAddOverrideCalls(*this, Ctx, Results);
5134  Results.ExitScope();
5135 
5136  if (CodeCompleter->includeNamespaceLevelDecls() ||
5137  (!Ctx->isNamespace() && !Ctx->isTranslationUnit())) {
5138  CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType);
5139  LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
5140  /*IncludeGlobalScope=*/true,
5141  /*IncludeDependentBases=*/true,
5142  CodeCompleter->loadExternal());
5143  }
5144 
5145  auto CC = Results.getCompletionContext();
5146  CC.setCXXScopeSpecifier(SS);
5147 
5148  HandleCodeCompleteResults(this, CodeCompleter, CC, Results.data(),
5149  Results.size());
5150 }
5151 
5153  if (!CodeCompleter)
5154  return;
5155 
5156  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5157  CodeCompleter->getCodeCompletionTUInfo(),
5158  // This can be both a using alias or using
5159  // declaration, in the former we expect a new name and a
5160  // symbol in the latter case.
5162  &ResultBuilder::IsNestedNameSpecifier);
5163  Results.EnterNewScope();
5164 
5165  // If we aren't in class scope, we could see the "namespace" keyword.
5166  if (!S->isClassScope())
5167  Results.AddResult(CodeCompletionResult("namespace"));
5168 
5169  // After "using", we can see anything that would start a
5170  // nested-name-specifier.
5171  CodeCompletionDeclConsumer Consumer(Results, CurContext);
5172  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5173  CodeCompleter->includeGlobals(),
5174  CodeCompleter->loadExternal());
5175  Results.ExitScope();
5176 
5177  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5178  Results.data(), Results.size());
5179 }
5180 
5182  if (!CodeCompleter)
5183  return;
5184 
5185  // After "using namespace", we expect to see a namespace name or namespace
5186  // alias.
5187  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5188  CodeCompleter->getCodeCompletionTUInfo(),
5190  &ResultBuilder::IsNamespaceOrAlias);
5191  Results.EnterNewScope();
5192  CodeCompletionDeclConsumer Consumer(Results, CurContext);
5193  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5194  CodeCompleter->includeGlobals(),
5195  CodeCompleter->loadExternal());
5196  Results.ExitScope();
5197  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5198  Results.data(), Results.size());
5199 }
5200 
5202  if (!CodeCompleter)
5203  return;
5204 
5205  DeclContext *Ctx = S->getEntity();
5206  if (!S->getParent())
5207  Ctx = Context.getTranslationUnitDecl();
5208 
5209  bool SuppressedGlobalResults =
5210  Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
5211 
5212  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5213  CodeCompleter->getCodeCompletionTUInfo(),
5214  SuppressedGlobalResults
5217  &ResultBuilder::IsNamespace);
5218 
5219  if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
5220  // We only want to see those namespaces that have already been defined
5221  // within this scope, because its likely that the user is creating an
5222  // extended namespace declaration. Keep track of the most recent
5223  // definition of each namespace.
5224  std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
5226  NS(Ctx->decls_begin()),
5227  NSEnd(Ctx->decls_end());
5228  NS != NSEnd; ++NS)
5229  OrigToLatest[NS->getOriginalNamespace()] = *NS;
5230 
5231  // Add the most recent definition (or extended definition) of each
5232  // namespace to the list of results.
5233  Results.EnterNewScope();
5234  for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
5235  NS = OrigToLatest.begin(),
5236  NSEnd = OrigToLatest.end();
5237  NS != NSEnd; ++NS)
5238  Results.AddResult(
5239  CodeCompletionResult(NS->second, Results.getBasePriority(NS->second),
5240  nullptr),
5241  CurContext, nullptr, false);
5242  Results.ExitScope();
5243  }
5244 
5245  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5246  Results.data(), Results.size());
5247 }
5248 
5250  if (!CodeCompleter)
5251  return;
5252 
5253  // After "namespace", we expect to see a namespace or alias.
5254  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5255  CodeCompleter->getCodeCompletionTUInfo(),
5257  &ResultBuilder::IsNamespaceOrAlias);
5258  CodeCompletionDeclConsumer Consumer(Results, CurContext);
5259  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5260  CodeCompleter->includeGlobals(),
5261  CodeCompleter->loadExternal());
5262  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5263  Results.data(), Results.size());
5264 }
5265 
5267  if (!CodeCompleter)
5268  return;
5269 
5270  typedef CodeCompletionResult Result;
5271  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5272  CodeCompleter->getCodeCompletionTUInfo(),
5274  &ResultBuilder::IsType);
5275  Results.EnterNewScope();
5276 
5277  // Add the names of overloadable operators.
5278 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
5279  if (std::strcmp(Spelling, "?")) \
5280  Results.AddResult(Result(Spelling));
5281 #include "clang/Basic/OperatorKinds.def"
5282 
5283  // Add any type names visible from the current scope
5284  Results.allowNestedNameSpecifiers();
5285  CodeCompletionDeclConsumer Consumer(Results, CurContext);
5286  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5287  CodeCompleter->includeGlobals(),
5288  CodeCompleter->loadExternal());
5289 
5290  // Add any type specifiers
5291  AddTypeSpecifierResults(getLangOpts(), Results);
5292  Results.ExitScope();
5293 
5294  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5295  Results.data(), Results.size());
5296 }
5297 
5299  Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) {
5300  if (!ConstructorD)
5301  return;
5302 
5303  AdjustDeclIfTemplate(ConstructorD);
5304 
5305  auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
5306  if (!Constructor)
5307  return;
5308 
5309  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5310  CodeCompleter->getCodeCompletionTUInfo(),
5312  Results.EnterNewScope();
5313 
5314  // Fill in any already-initialized fields or base classes.
5315  llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
5316  llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
5317  for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
5318  if (Initializers[I]->isBaseInitializer())
5319  InitializedBases.insert(Context.getCanonicalType(
5320  QualType(Initializers[I]->getBaseClass(), 0)));
5321  else
5322  InitializedFields.insert(
5323  cast<FieldDecl>(Initializers[I]->getAnyMember()));
5324  }
5325 
5326  // Add completions for base classes.
5328  bool SawLastInitializer = Initializers.empty();
5329  CXXRecordDecl *ClassDecl = Constructor->getParent();
5330 
5331  auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) {
5332  CodeCompletionBuilder Builder(Results.getAllocator(),
5333  Results.getCodeCompletionTUInfo());
5334  Builder.AddTypedTextChunk(Name);
5335  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5336  if (const auto *Function = dyn_cast<FunctionDecl>(ND))
5337  AddFunctionParameterChunks(PP, Policy, Function, Builder);
5338  else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND))
5339  AddFunctionParameterChunks(PP, Policy, FunTemplDecl->getTemplatedDecl(),
5340  Builder);
5341  Builder.AddChunk(CodeCompletionString::CK_RightParen);
5342  return Builder.TakeString();
5343  };
5344  auto AddDefaultCtorInit = [&](const char *Name, const char *Type,
5345  const NamedDecl *ND) {
5346  CodeCompletionBuilder Builder(Results.getAllocator(),
5347  Results.getCodeCompletionTUInfo());
5348  Builder.AddTypedTextChunk(Name);
5349  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5350  Builder.AddPlaceholderChunk(Type);
5351  Builder.AddChunk(CodeCompletionString::CK_RightParen);
5352  if (ND) {
5353  auto CCR = CodeCompletionResult(
5354  Builder.TakeString(), ND,
5355  SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration);
5356  if (isa<FieldDecl>(ND))
5358  return Results.AddResult(CCR);
5359  }
5360  return Results.AddResult(CodeCompletionResult(
5361  Builder.TakeString(),
5362  SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration));
5363  };
5364  auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority,
5365  const char *Name, const FieldDecl *FD) {
5366  if (!RD)
5367  return AddDefaultCtorInit(Name,
5368  FD ? Results.getAllocator().CopyString(
5369  FD->getType().getAsString(Policy))
5370  : Name,
5371  FD);
5372  auto Ctors = getConstructors(Context, RD);
5373  if (Ctors.begin() == Ctors.end())
5374  return AddDefaultCtorInit(Name, Name, RD);
5375  for (const NamedDecl *Ctor : Ctors) {
5376  auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority);
5377  CCR.CursorKind = getCursorKindForDecl(Ctor);
5378  Results.AddResult(CCR);
5379  }
5380  };
5381  auto AddBase = [&](const CXXBaseSpecifier &Base) {
5382  const char *BaseName =
5383  Results.getAllocator().CopyString(Base.getType().getAsString(Policy));
5384  const auto *RD = Base.getType()->getAsCXXRecordDecl();
5385  AddCtorsWithName(
5386  RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
5387  BaseName, nullptr);
5388  };
5389  auto AddField = [&](const FieldDecl *FD) {
5390  const char *FieldName =
5391  Results.getAllocator().CopyString(FD->getIdentifier()->getName());
5392  const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
5393  AddCtorsWithName(
5394  RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
5395  FieldName, FD);
5396  };
5397 
5398  for (const auto &Base : ClassDecl->bases()) {
5399  if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
5400  .second) {
5401  SawLastInitializer =
5402  !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
5403  Context.hasSameUnqualifiedType(
5404  Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
5405  continue;
5406  }
5407 
5408  AddBase(Base);
5409  SawLastInitializer = false;
5410  }
5411 
5412  // Add completions for virtual base classes.
5413  for (const auto &Base : ClassDecl->vbases()) {
5414  if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
5415  .second) {
5416  SawLastInitializer =
5417  !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
5418  Context.hasSameUnqualifiedType(
5419  Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
5420  continue;
5421  }
5422 
5423  AddBase(Base);
5424  SawLastInitializer = false;
5425  }
5426 
5427  // Add completions for members.
5428  for (auto *Field : ClassDecl->fields()) {
5429  if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
5430  .second) {
5431  SawLastInitializer = !Initializers.empty() &&
5432  Initializers.back()->isAnyMemberInitializer() &&
5433  Initializers.back()->getAnyMember() == Field;
5434  continue;
5435  }
5436 
5437  if (!Field->getDeclName())
5438  continue;
5439 
5440  AddField(Field);
5441  SawLastInitializer = false;
5442  }
5443  Results.ExitScope();
5444 
5445  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5446  Results.data(), Results.size());
5447 }
5448 
5449 /// Determine whether this scope denotes a namespace.
5450 static bool isNamespaceScope(Scope *S) {
5451  DeclContext *DC = S->getEntity();
5452  if (!DC)
5453  return false;
5454 
5455  return DC->isFileContext();
5456 }
5457 
5459  bool AfterAmpersand) {
5460  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5461  CodeCompleter->getCodeCompletionTUInfo(),
5463  Results.EnterNewScope();
5464 
5465  // Note what has already been captured.
5466  llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
5467  bool IncludedThis = false;
5468  for (const auto &C : Intro.Captures) {
5469  if (C.Kind == LCK_This) {
5470  IncludedThis = true;
5471  continue;
5472  }
5473 
5474  Known.insert(C.Id);
5475  }
5476 
5477  // Look for other capturable variables.
5478  for (; S && !isNamespaceScope(S); S = S->getParent()) {
5479  for (const auto *D : S->decls()) {
5480  const auto *Var = dyn_cast<VarDecl>(D);
5481  if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>())
5482  continue;
5483 
5484  if (Known.insert(Var->getIdentifier()).second)
5485  Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
5486  CurContext, nullptr, false);
5487  }
5488  }
5489 
5490  // Add 'this', if it would be valid.
5491  if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
5492  addThisCompletion(*this, Results);
5493 
5494  Results.ExitScope();
5495 
5496  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5497  Results.data(), Results.size());
5498 }
5499 
5500 /// Macro that optionally prepends an "@" to the string literal passed in via
5501 /// Keyword, depending on whether NeedAt is true or false.
5502 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword)
5503 
5504 static void AddObjCImplementationResults(const LangOptions &LangOpts,
5505  ResultBuilder &Results, bool NeedAt) {
5506  typedef CodeCompletionResult Result;
5507  // Since we have an implementation, we can end it.
5508  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
5509 
5510  CodeCompletionBuilder Builder(Results.getAllocator(),
5511  Results.getCodeCompletionTUInfo());
5512  if (LangOpts.ObjC) {
5513  // @dynamic
5514  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic"));
5515  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5516  Builder.AddPlaceholderChunk("property");
5517  Results.AddResult(Result(Builder.TakeString()));
5518 
5519  // @synthesize
5520  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize"));
5521  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5522  Builder.AddPlaceholderChunk("property");
5523  Results.AddResult(Result(Builder.TakeString()));
5524  }
5525 }
5526 
5527 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
5528  ResultBuilder &Results, bool NeedAt) {
5529  typedef CodeCompletionResult Result;
5530 
5531  // Since we have an interface or protocol, we can end it.
5532  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
5533 
5534  if (LangOpts.ObjC) {
5535  // @property
5536  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property")));
5537 
5538  // @required
5539  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required")));
5540 
5541  // @optional
5542  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional")));
5543  }
5544 }
5545 
5546 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
5547  typedef CodeCompletionResult Result;
5548  CodeCompletionBuilder Builder(Results.getAllocator(),
5549  Results.getCodeCompletionTUInfo());
5550 
5551  // @class name ;
5552  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class"));
5553  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5554  Builder.AddPlaceholderChunk("name");
5555  Results.AddResult(Result(Builder.TakeString()));
5556 
5557  if (Results.includeCodePatterns()) {
5558  // @interface name
5559  // FIXME: Could introduce the whole pattern, including superclasses and
5560  // such.
5561  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface"));
5562  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5563  Builder.AddPlaceholderChunk("class");
5564  Results.AddResult(Result(Builder.TakeString()));
5565 
5566  // @protocol name
5567  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
5568  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5569  Builder.AddPlaceholderChunk("protocol");
5570  Results.AddResult(Result(Builder.TakeString()));
5571 
5572  // @implementation name
5573  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation"));
5574  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5575  Builder.AddPlaceholderChunk("class");
5576  Results.AddResult(Result(Builder.TakeString()));
5577  }
5578 
5579  // @compatibility_alias name
5580  Builder.AddTypedTextChunk(
5581  OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias"));
5582  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5583  Builder.AddPlaceholderChunk("alias");
5584  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5585  Builder.AddPlaceholderChunk("class");
5586  Results.AddResult(Result(Builder.TakeString()));
5587 
5588  if (Results.getSema().getLangOpts().Modules) {
5589  // @import name
5590  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
5591  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5592  Builder.AddPlaceholderChunk("module");
5593  Results.AddResult(Result(Builder.TakeString()));
5594  }
5595 }
5596 
5598  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5599  CodeCompleter->getCodeCompletionTUInfo(),
5601  Results.EnterNewScope();
5602  if (isa<ObjCImplDecl>(CurContext))