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