SemaCodeComplete.cpp revision 205219
1//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
13#include "Sema.h"
14#include "Lookup.h"
15#include "clang/Sema/CodeCompleteConsumer.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ExprObjC.h"
18#include "clang/Lex/MacroInfo.h"
19#include "clang/Lex/Preprocessor.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/StringExtras.h"
22#include <list>
23#include <map>
24#include <vector>
25
26using namespace clang;
27
28namespace {
29  /// \brief A container of code-completion results.
30  class ResultBuilder {
31  public:
32    /// \brief The type of a name-lookup filter, which can be provided to the
33    /// name-lookup routines to specify which declarations should be included in
34    /// the result set (when it returns true) and which declarations should be
35    /// filtered out (returns false).
36    typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
37
38    typedef CodeCompleteConsumer::Result Result;
39
40  private:
41    /// \brief The actual results we have found.
42    std::vector<Result> Results;
43
44    /// \brief A record of all of the declarations we have found and placed
45    /// into the result set, used to ensure that no declaration ever gets into
46    /// the result set twice.
47    llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
48
49    typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
50
51    /// \brief An entry in the shadow map, which is optimized to store
52    /// a single (declaration, index) mapping (the common case) but
53    /// can also store a list of (declaration, index) mappings.
54    class ShadowMapEntry {
55      typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
56
57      /// \brief Contains either the solitary NamedDecl * or a vector
58      /// of (declaration, index) pairs.
59      llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
60
61      /// \brief When the entry contains a single declaration, this is
62      /// the index associated with that entry.
63      unsigned SingleDeclIndex;
64
65    public:
66      ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
67
68      void Add(NamedDecl *ND, unsigned Index) {
69        if (DeclOrVector.isNull()) {
70          // 0 - > 1 elements: just set the single element information.
71          DeclOrVector = ND;
72          SingleDeclIndex = Index;
73          return;
74        }
75
76        if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
77          // 1 -> 2 elements: create the vector of results and push in the
78          // existing declaration.
79          DeclIndexPairVector *Vec = new DeclIndexPairVector;
80          Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
81          DeclOrVector = Vec;
82        }
83
84        // Add the new element to the end of the vector.
85        DeclOrVector.get<DeclIndexPairVector*>()->push_back(
86                                                    DeclIndexPair(ND, Index));
87      }
88
89      void Destroy() {
90        if (DeclIndexPairVector *Vec
91              = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
92          delete Vec;
93          DeclOrVector = ((NamedDecl *)0);
94        }
95      }
96
97      // Iteration.
98      class iterator;
99      iterator begin() const;
100      iterator end() const;
101    };
102
103    /// \brief A mapping from declaration names to the declarations that have
104    /// this name within a particular scope and their index within the list of
105    /// results.
106    typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
107
108    /// \brief The semantic analysis object for which results are being
109    /// produced.
110    Sema &SemaRef;
111
112    /// \brief If non-NULL, a filter function used to remove any code-completion
113    /// results that are not desirable.
114    LookupFilter Filter;
115
116    /// \brief Whether we should allow declarations as
117    /// nested-name-specifiers that would otherwise be filtered out.
118    bool AllowNestedNameSpecifiers;
119
120    /// \brief A list of shadow maps, which is used to model name hiding at
121    /// different levels of, e.g., the inheritance hierarchy.
122    std::list<ShadowMap> ShadowMaps;
123
124  public:
125    explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
126      : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false) { }
127
128    /// \brief Set the filter used for code-completion results.
129    void setFilter(LookupFilter Filter) {
130      this->Filter = Filter;
131    }
132
133    typedef std::vector<Result>::iterator iterator;
134    iterator begin() { return Results.begin(); }
135    iterator end() { return Results.end(); }
136
137    Result *data() { return Results.empty()? 0 : &Results.front(); }
138    unsigned size() const { return Results.size(); }
139    bool empty() const { return Results.empty(); }
140
141    /// \brief Specify whether nested-name-specifiers are allowed.
142    void allowNestedNameSpecifiers(bool Allow = true) {
143      AllowNestedNameSpecifiers = Allow;
144    }
145
146    /// \brief Determine whether the given declaration is at all interesting
147    /// as a code-completion result.
148    ///
149    /// \param ND the declaration that we are inspecting.
150    ///
151    /// \param AsNestedNameSpecifier will be set true if this declaration is
152    /// only interesting when it is a nested-name-specifier.
153    bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
154
155    /// \brief Check whether the result is hidden by the Hiding declaration.
156    ///
157    /// \returns true if the result is hidden and cannot be found, false if
158    /// the hidden result could still be found. When false, \p R may be
159    /// modified to describe how the result can be found (e.g., via extra
160    /// qualification).
161    bool CheckHiddenResult(Result &R, DeclContext *CurContext,
162                           NamedDecl *Hiding);
163
164    /// \brief Add a new result to this result set (if it isn't already in one
165    /// of the shadow maps), or replace an existing result (for, e.g., a
166    /// redeclaration).
167    ///
168    /// \param CurContext the result to add (if it is unique).
169    ///
170    /// \param R the context in which this result will be named.
171    void MaybeAddResult(Result R, DeclContext *CurContext = 0);
172
173    /// \brief Add a new result to this result set, where we already know
174    /// the hiding declation (if any).
175    ///
176    /// \param R the result to add (if it is unique).
177    ///
178    /// \param CurContext the context in which this result will be named.
179    ///
180    /// \param Hiding the declaration that hides the result.
181    ///
182    /// \param InBaseClass whether the result was found in a base
183    /// class of the searched context.
184    void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
185                   bool InBaseClass);
186
187    /// \brief Add a new non-declaration result to this result set.
188    void AddResult(Result R);
189
190    /// \brief Enter into a new scope.
191    void EnterNewScope();
192
193    /// \brief Exit from the current scope.
194    void ExitScope();
195
196    /// \brief Ignore this declaration, if it is seen again.
197    void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
198
199    /// \name Name lookup predicates
200    ///
201    /// These predicates can be passed to the name lookup functions to filter the
202    /// results of name lookup. All of the predicates have the same type, so that
203    ///
204    //@{
205    bool IsOrdinaryName(NamedDecl *ND) const;
206    bool IsOrdinaryNonValueName(NamedDecl *ND) const;
207    bool IsNestedNameSpecifier(NamedDecl *ND) const;
208    bool IsEnum(NamedDecl *ND) const;
209    bool IsClassOrStruct(NamedDecl *ND) const;
210    bool IsUnion(NamedDecl *ND) const;
211    bool IsNamespace(NamedDecl *ND) const;
212    bool IsNamespaceOrAlias(NamedDecl *ND) const;
213    bool IsType(NamedDecl *ND) const;
214    bool IsMember(NamedDecl *ND) const;
215    bool IsObjCIvar(NamedDecl *ND) const;
216    //@}
217  };
218}
219
220class ResultBuilder::ShadowMapEntry::iterator {
221  llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
222  unsigned SingleDeclIndex;
223
224public:
225  typedef DeclIndexPair value_type;
226  typedef value_type reference;
227  typedef std::ptrdiff_t difference_type;
228  typedef std::input_iterator_tag iterator_category;
229
230  class pointer {
231    DeclIndexPair Value;
232
233  public:
234    pointer(const DeclIndexPair &Value) : Value(Value) { }
235
236    const DeclIndexPair *operator->() const {
237      return &Value;
238    }
239  };
240
241  iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
242
243  iterator(NamedDecl *SingleDecl, unsigned Index)
244    : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
245
246  iterator(const DeclIndexPair *Iterator)
247    : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
248
249  iterator &operator++() {
250    if (DeclOrIterator.is<NamedDecl *>()) {
251      DeclOrIterator = (NamedDecl *)0;
252      SingleDeclIndex = 0;
253      return *this;
254    }
255
256    const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
257    ++I;
258    DeclOrIterator = I;
259    return *this;
260  }
261
262  iterator operator++(int) {
263    iterator tmp(*this);
264    ++(*this);
265    return tmp;
266  }
267
268  reference operator*() const {
269    if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
270      return reference(ND, SingleDeclIndex);
271
272    return *DeclOrIterator.get<const DeclIndexPair*>();
273  }
274
275  pointer operator->() const {
276    return pointer(**this);
277  }
278
279  friend bool operator==(const iterator &X, const iterator &Y) {
280    return X.DeclOrIterator.getOpaqueValue()
281                                  == Y.DeclOrIterator.getOpaqueValue() &&
282      X.SingleDeclIndex == Y.SingleDeclIndex;
283  }
284
285  friend bool operator!=(const iterator &X, const iterator &Y) {
286    return !(X == Y);
287  }
288};
289
290ResultBuilder::ShadowMapEntry::iterator
291ResultBuilder::ShadowMapEntry::begin() const {
292  if (DeclOrVector.isNull())
293    return iterator();
294
295  if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
296    return iterator(ND, SingleDeclIndex);
297
298  return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
299}
300
301ResultBuilder::ShadowMapEntry::iterator
302ResultBuilder::ShadowMapEntry::end() const {
303  if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
304    return iterator();
305
306  return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
307}
308
309/// \brief Compute the qualification required to get from the current context
310/// (\p CurContext) to the target context (\p TargetContext).
311///
312/// \param Context the AST context in which the qualification will be used.
313///
314/// \param CurContext the context where an entity is being named, which is
315/// typically based on the current scope.
316///
317/// \param TargetContext the context in which the named entity actually
318/// resides.
319///
320/// \returns a nested name specifier that refers into the target context, or
321/// NULL if no qualification is needed.
322static NestedNameSpecifier *
323getRequiredQualification(ASTContext &Context,
324                         DeclContext *CurContext,
325                         DeclContext *TargetContext) {
326  llvm::SmallVector<DeclContext *, 4> TargetParents;
327
328  for (DeclContext *CommonAncestor = TargetContext;
329       CommonAncestor && !CommonAncestor->Encloses(CurContext);
330       CommonAncestor = CommonAncestor->getLookupParent()) {
331    if (CommonAncestor->isTransparentContext() ||
332        CommonAncestor->isFunctionOrMethod())
333      continue;
334
335    TargetParents.push_back(CommonAncestor);
336  }
337
338  NestedNameSpecifier *Result = 0;
339  while (!TargetParents.empty()) {
340    DeclContext *Parent = TargetParents.back();
341    TargetParents.pop_back();
342
343    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
344      Result = NestedNameSpecifier::Create(Context, Result, Namespace);
345    else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
346      Result = NestedNameSpecifier::Create(Context, Result,
347                                           false,
348                                     Context.getTypeDeclType(TD).getTypePtr());
349    else
350      assert(Parent->isTranslationUnit());
351  }
352  return Result;
353}
354
355bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
356                                      bool &AsNestedNameSpecifier) const {
357  AsNestedNameSpecifier = false;
358
359  ND = ND->getUnderlyingDecl();
360  unsigned IDNS = ND->getIdentifierNamespace();
361
362  // Skip unnamed entities.
363  if (!ND->getDeclName())
364    return false;
365
366  // Friend declarations and declarations introduced due to friends are never
367  // added as results.
368  if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
369    return false;
370
371  // Class template (partial) specializations are never added as results.
372  if (isa<ClassTemplateSpecializationDecl>(ND) ||
373      isa<ClassTemplatePartialSpecializationDecl>(ND))
374    return false;
375
376  // Using declarations themselves are never added as results.
377  if (isa<UsingDecl>(ND))
378    return false;
379
380  // Some declarations have reserved names that we don't want to ever show.
381  if (const IdentifierInfo *Id = ND->getIdentifier()) {
382    // __va_list_tag is a freak of nature. Find it and skip it.
383    if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
384      return false;
385
386    // Filter out names reserved for the implementation (C99 7.1.3,
387    // C++ [lib.global.names]). Users don't need to see those.
388    //
389    // FIXME: Add predicate for this.
390    if (Id->getLength() >= 2) {
391      const char *Name = Id->getNameStart();
392      if (Name[0] == '_' &&
393          (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
394        return false;
395    }
396  }
397
398  // C++ constructors are never found by name lookup.
399  if (isa<CXXConstructorDecl>(ND))
400    return false;
401
402  // Filter out any unwanted results.
403  if (Filter && !(this->*Filter)(ND)) {
404    // Check whether it is interesting as a nested-name-specifier.
405    if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
406        IsNestedNameSpecifier(ND) &&
407        (Filter != &ResultBuilder::IsMember ||
408         (isa<CXXRecordDecl>(ND) &&
409          cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
410      AsNestedNameSpecifier = true;
411      return true;
412    }
413
414    return false;
415  }
416
417  // ... then it must be interesting!
418  return true;
419}
420
421bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
422                                      NamedDecl *Hiding) {
423  // In C, there is no way to refer to a hidden name.
424  // FIXME: This isn't true; we can find a tag name hidden by an ordinary
425  // name if we introduce the tag type.
426  if (!SemaRef.getLangOptions().CPlusPlus)
427    return true;
428
429  DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext();
430
431  // There is no way to qualify a name declared in a function or method.
432  if (HiddenCtx->isFunctionOrMethod())
433    return true;
434
435  if (HiddenCtx == Hiding->getDeclContext()->getLookupContext())
436    return true;
437
438  // We can refer to the result with the appropriate qualification. Do it.
439  R.Hidden = true;
440  R.QualifierIsInformative = false;
441
442  if (!R.Qualifier)
443    R.Qualifier = getRequiredQualification(SemaRef.Context,
444                                           CurContext,
445                                           R.Declaration->getDeclContext());
446  return false;
447}
448
449void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
450  assert(!ShadowMaps.empty() && "Must enter into a results scope");
451
452  if (R.Kind != Result::RK_Declaration) {
453    // For non-declaration results, just add the result.
454    Results.push_back(R);
455    return;
456  }
457
458  // Look through using declarations.
459  if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
460    MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
461    return;
462  }
463
464  Decl *CanonDecl = R.Declaration->getCanonicalDecl();
465  unsigned IDNS = CanonDecl->getIdentifierNamespace();
466
467  bool AsNestedNameSpecifier = false;
468  if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
469    return;
470
471  ShadowMap &SMap = ShadowMaps.back();
472  ShadowMapEntry::iterator I, IEnd;
473  ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
474  if (NamePos != SMap.end()) {
475    I = NamePos->second.begin();
476    IEnd = NamePos->second.end();
477  }
478
479  for (; I != IEnd; ++I) {
480    NamedDecl *ND = I->first;
481    unsigned Index = I->second;
482    if (ND->getCanonicalDecl() == CanonDecl) {
483      // This is a redeclaration. Always pick the newer declaration.
484      Results[Index].Declaration = R.Declaration;
485
486      // We're done.
487      return;
488    }
489  }
490
491  // This is a new declaration in this scope. However, check whether this
492  // declaration name is hidden by a similarly-named declaration in an outer
493  // scope.
494  std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
495  --SMEnd;
496  for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
497    ShadowMapEntry::iterator I, IEnd;
498    ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
499    if (NamePos != SM->end()) {
500      I = NamePos->second.begin();
501      IEnd = NamePos->second.end();
502    }
503    for (; I != IEnd; ++I) {
504      // A tag declaration does not hide a non-tag declaration.
505      if (I->first->getIdentifierNamespace() == Decl::IDNS_Tag &&
506          (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
507                   Decl::IDNS_ObjCProtocol)))
508        continue;
509
510      // Protocols are in distinct namespaces from everything else.
511      if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
512           || (IDNS & Decl::IDNS_ObjCProtocol)) &&
513          I->first->getIdentifierNamespace() != IDNS)
514        continue;
515
516      // The newly-added result is hidden by an entry in the shadow map.
517      if (CheckHiddenResult(R, CurContext, I->first))
518        return;
519
520      break;
521    }
522  }
523
524  // Make sure that any given declaration only shows up in the result set once.
525  if (!AllDeclsFound.insert(CanonDecl))
526    return;
527
528  // If the filter is for nested-name-specifiers, then this result starts a
529  // nested-name-specifier.
530  if (AsNestedNameSpecifier)
531    R.StartsNestedNameSpecifier = true;
532
533  // If this result is supposed to have an informative qualifier, add one.
534  if (R.QualifierIsInformative && !R.Qualifier &&
535      !R.StartsNestedNameSpecifier) {
536    DeclContext *Ctx = R.Declaration->getDeclContext();
537    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
538      R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
539    else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
540      R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
541                             SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
542    else
543      R.QualifierIsInformative = false;
544  }
545
546  // Insert this result into the set of results and into the current shadow
547  // map.
548  SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
549  Results.push_back(R);
550}
551
552void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
553                              NamedDecl *Hiding, bool InBaseClass = false) {
554  if (R.Kind != Result::RK_Declaration) {
555    // For non-declaration results, just add the result.
556    Results.push_back(R);
557    return;
558  }
559
560  // Look through using declarations.
561  if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
562    AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
563    return;
564  }
565
566  bool AsNestedNameSpecifier = false;
567  if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
568    return;
569
570  if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
571    return;
572
573  // Make sure that any given declaration only shows up in the result set once.
574  if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
575    return;
576
577  // If the filter is for nested-name-specifiers, then this result starts a
578  // nested-name-specifier.
579  if (AsNestedNameSpecifier)
580    R.StartsNestedNameSpecifier = true;
581  else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
582           isa<CXXRecordDecl>(R.Declaration->getDeclContext()
583                                                  ->getLookupContext()))
584    R.QualifierIsInformative = true;
585
586  // If this result is supposed to have an informative qualifier, add one.
587  if (R.QualifierIsInformative && !R.Qualifier &&
588      !R.StartsNestedNameSpecifier) {
589    DeclContext *Ctx = R.Declaration->getDeclContext();
590    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
591      R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
592    else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
593      R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
594                            SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
595    else
596      R.QualifierIsInformative = false;
597  }
598
599  // Insert this result into the set of results.
600  Results.push_back(R);
601}
602
603void ResultBuilder::AddResult(Result R) {
604  assert(R.Kind != Result::RK_Declaration &&
605          "Declaration results need more context");
606  Results.push_back(R);
607}
608
609/// \brief Enter into a new scope.
610void ResultBuilder::EnterNewScope() {
611  ShadowMaps.push_back(ShadowMap());
612}
613
614/// \brief Exit from the current scope.
615void ResultBuilder::ExitScope() {
616  for (ShadowMap::iterator E = ShadowMaps.back().begin(),
617                        EEnd = ShadowMaps.back().end();
618       E != EEnd;
619       ++E)
620    E->second.Destroy();
621
622  ShadowMaps.pop_back();
623}
624
625/// \brief Determines whether this given declaration will be found by
626/// ordinary name lookup.
627bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
628  unsigned IDNS = Decl::IDNS_Ordinary;
629  if (SemaRef.getLangOptions().CPlusPlus)
630    IDNS |= Decl::IDNS_Tag;
631  else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
632    return true;
633
634  return ND->getIdentifierNamespace() & IDNS;
635}
636
637/// \brief Determines whether this given declaration will be found by
638/// ordinary name lookup.
639bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
640  unsigned IDNS = Decl::IDNS_Ordinary;
641  if (SemaRef.getLangOptions().CPlusPlus)
642    IDNS |= Decl::IDNS_Tag;
643
644  return (ND->getIdentifierNamespace() & IDNS) &&
645    !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND);
646}
647
648/// \brief Determines whether the given declaration is suitable as the
649/// start of a C++ nested-name-specifier, e.g., a class or namespace.
650bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
651  // Allow us to find class templates, too.
652  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
653    ND = ClassTemplate->getTemplatedDecl();
654
655  return SemaRef.isAcceptableNestedNameSpecifier(ND);
656}
657
658/// \brief Determines whether the given declaration is an enumeration.
659bool ResultBuilder::IsEnum(NamedDecl *ND) const {
660  return isa<EnumDecl>(ND);
661}
662
663/// \brief Determines whether the given declaration is a class or struct.
664bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
665  // Allow us to find class templates, too.
666  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
667    ND = ClassTemplate->getTemplatedDecl();
668
669  if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
670    return RD->getTagKind() == TagDecl::TK_class ||
671    RD->getTagKind() == TagDecl::TK_struct;
672
673  return false;
674}
675
676/// \brief Determines whether the given declaration is a union.
677bool ResultBuilder::IsUnion(NamedDecl *ND) const {
678  // Allow us to find class templates, too.
679  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
680    ND = ClassTemplate->getTemplatedDecl();
681
682  if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
683    return RD->getTagKind() == TagDecl::TK_union;
684
685  return false;
686}
687
688/// \brief Determines whether the given declaration is a namespace.
689bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
690  return isa<NamespaceDecl>(ND);
691}
692
693/// \brief Determines whether the given declaration is a namespace or
694/// namespace alias.
695bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
696  return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
697}
698
699/// \brief Determines whether the given declaration is a type.
700bool ResultBuilder::IsType(NamedDecl *ND) const {
701  return isa<TypeDecl>(ND);
702}
703
704/// \brief Determines which members of a class should be visible via
705/// "." or "->".  Only value declarations, nested name specifiers, and
706/// using declarations thereof should show up.
707bool ResultBuilder::IsMember(NamedDecl *ND) const {
708  if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
709    ND = Using->getTargetDecl();
710
711  return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
712    isa<ObjCPropertyDecl>(ND);
713}
714
715/// \rief Determines whether the given declaration is an Objective-C
716/// instance variable.
717bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
718  return isa<ObjCIvarDecl>(ND);
719}
720
721namespace {
722  /// \brief Visible declaration consumer that adds a code-completion result
723  /// for each visible declaration.
724  class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
725    ResultBuilder &Results;
726    DeclContext *CurContext;
727
728  public:
729    CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
730      : Results(Results), CurContext(CurContext) { }
731
732    virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
733      Results.AddResult(ND, CurContext, Hiding, InBaseClass);
734    }
735  };
736}
737
738/// \brief Add type specifiers for the current language as keyword results.
739static void AddTypeSpecifierResults(const LangOptions &LangOpts,
740                                    ResultBuilder &Results) {
741  typedef CodeCompleteConsumer::Result Result;
742  Results.AddResult(Result("short"));
743  Results.AddResult(Result("long"));
744  Results.AddResult(Result("signed"));
745  Results.AddResult(Result("unsigned"));
746  Results.AddResult(Result("void"));
747  Results.AddResult(Result("char"));
748  Results.AddResult(Result("int"));
749  Results.AddResult(Result("float"));
750  Results.AddResult(Result("double"));
751  Results.AddResult(Result("enum"));
752  Results.AddResult(Result("struct"));
753  Results.AddResult(Result("union"));
754  Results.AddResult(Result("const"));
755  Results.AddResult(Result("volatile"));
756
757  if (LangOpts.C99) {
758    // C99-specific
759    Results.AddResult(Result("_Complex"));
760    Results.AddResult(Result("_Imaginary"));
761    Results.AddResult(Result("_Bool"));
762    Results.AddResult(Result("restrict"));
763  }
764
765  if (LangOpts.CPlusPlus) {
766    // C++-specific
767    Results.AddResult(Result("bool"));
768    Results.AddResult(Result("class"));
769    Results.AddResult(Result("wchar_t"));
770
771    // typename qualified-id
772    CodeCompletionString *Pattern = new CodeCompletionString;
773    Pattern->AddTypedTextChunk("typename");
774    Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
775    Pattern->AddPlaceholderChunk("qualified-id");
776    Results.AddResult(Result(Pattern));
777
778    if (LangOpts.CPlusPlus0x) {
779      Results.AddResult(Result("auto"));
780      Results.AddResult(Result("char16_t"));
781      Results.AddResult(Result("char32_t"));
782      Results.AddResult(Result("decltype"));
783    }
784  }
785
786  // GNU extensions
787  if (LangOpts.GNUMode) {
788    // FIXME: Enable when we actually support decimal floating point.
789    //    Results.AddResult(Result("_Decimal32"));
790    //    Results.AddResult(Result("_Decimal64"));
791    //    Results.AddResult(Result("_Decimal128"));
792
793    CodeCompletionString *Pattern = new CodeCompletionString;
794    Pattern->AddTypedTextChunk("typeof");
795    Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
796    Pattern->AddPlaceholderChunk("expression-or-type");
797    Pattern->AddChunk(CodeCompletionString::CK_RightParen);
798    Results.AddResult(Result(Pattern));
799  }
800}
801
802static void AddStorageSpecifiers(Action::CodeCompletionContext CCC,
803                                 const LangOptions &LangOpts,
804                                 ResultBuilder &Results) {
805  typedef CodeCompleteConsumer::Result Result;
806  // Note: we don't suggest either "auto" or "register", because both
807  // are pointless as storage specifiers. Elsewhere, we suggest "auto"
808  // in C++0x as a type specifier.
809  Results.AddResult(Result("extern"));
810  Results.AddResult(Result("static"));
811}
812
813static void AddFunctionSpecifiers(Action::CodeCompletionContext CCC,
814                                  const LangOptions &LangOpts,
815                                  ResultBuilder &Results) {
816  typedef CodeCompleteConsumer::Result Result;
817  switch (CCC) {
818  case Action::CCC_Class:
819  case Action::CCC_MemberTemplate:
820    if (LangOpts.CPlusPlus) {
821      Results.AddResult(Result("explicit"));
822      Results.AddResult(Result("friend"));
823      Results.AddResult(Result("mutable"));
824      Results.AddResult(Result("virtual"));
825    }
826    // Fall through
827
828  case Action::CCC_ObjCInterface:
829  case Action::CCC_ObjCImplementation:
830  case Action::CCC_Namespace:
831  case Action::CCC_Template:
832    if (LangOpts.CPlusPlus || LangOpts.C99)
833      Results.AddResult(Result("inline"));
834    break;
835
836  case Action::CCC_ObjCInstanceVariableList:
837  case Action::CCC_Expression:
838  case Action::CCC_Statement:
839  case Action::CCC_ForInit:
840  case Action::CCC_Condition:
841    break;
842  }
843}
844
845static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
846static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
847static void AddObjCVisibilityResults(const LangOptions &LangOpts,
848                                     ResultBuilder &Results,
849                                     bool NeedAt);
850static void AddObjCImplementationResults(const LangOptions &LangOpts,
851                                         ResultBuilder &Results,
852                                         bool NeedAt);
853static void AddObjCInterfaceResults(const LangOptions &LangOpts,
854                                    ResultBuilder &Results,
855                                    bool NeedAt);
856static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
857
858/// \brief Add language constructs that show up for "ordinary" names.
859static void AddOrdinaryNameResults(Action::CodeCompletionContext CCC,
860                                   Scope *S,
861                                   Sema &SemaRef,
862                                   ResultBuilder &Results) {
863  typedef CodeCompleteConsumer::Result Result;
864  switch (CCC) {
865  case Action::CCC_Namespace:
866    if (SemaRef.getLangOptions().CPlusPlus) {
867      // namespace <identifier> { }
868      CodeCompletionString *Pattern = new CodeCompletionString;
869      Pattern->AddTypedTextChunk("namespace");
870      Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
871      Pattern->AddPlaceholderChunk("identifier");
872      Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
873      Pattern->AddPlaceholderChunk("declarations");
874      Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
875      Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
876      Results.AddResult(Result(Pattern));
877
878      // namespace identifier = identifier ;
879      Pattern = new CodeCompletionString;
880      Pattern->AddTypedTextChunk("namespace");
881      Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
882      Pattern->AddPlaceholderChunk("identifier");
883      Pattern->AddChunk(CodeCompletionString::CK_Equal);
884      Pattern->AddPlaceholderChunk("identifier");
885      Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
886      Results.AddResult(Result(Pattern));
887
888      // Using directives
889      Pattern = new CodeCompletionString;
890      Pattern->AddTypedTextChunk("using");
891      Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
892      Pattern->AddTextChunk("namespace");
893      Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
894      Pattern->AddPlaceholderChunk("identifier");
895      Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
896      Results.AddResult(Result(Pattern));
897
898      // asm(string-literal)
899      Pattern = new CodeCompletionString;
900      Pattern->AddTypedTextChunk("asm");
901      Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
902      Pattern->AddPlaceholderChunk("string-literal");
903      Pattern->AddChunk(CodeCompletionString::CK_RightParen);
904      Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
905      Results.AddResult(Result(Pattern));
906
907      // Explicit template instantiation
908      Pattern = new CodeCompletionString;
909      Pattern->AddTypedTextChunk("template");
910      Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
911      Pattern->AddPlaceholderChunk("declaration");
912      Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
913      Results.AddResult(Result(Pattern));
914    }
915
916    if (SemaRef.getLangOptions().ObjC1)
917      AddObjCTopLevelResults(Results, true);
918
919    // Fall through
920
921  case Action::CCC_Class:
922    Results.AddResult(Result("typedef"));
923    if (SemaRef.getLangOptions().CPlusPlus) {
924      // Using declaration
925      CodeCompletionString *Pattern = new CodeCompletionString;
926      Pattern->AddTypedTextChunk("using");
927      Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
928      Pattern->AddPlaceholderChunk("qualified-id");
929      Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
930      Results.AddResult(Result(Pattern));
931
932      // using typename qualified-id; (only in a dependent context)
933      if (SemaRef.CurContext->isDependentContext()) {
934        Pattern = new CodeCompletionString;
935        Pattern->AddTypedTextChunk("using");
936        Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
937        Pattern->AddTextChunk("typename");
938        Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
939        Pattern->AddPlaceholderChunk("qualified-id");
940        Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
941        Results.AddResult(Result(Pattern));
942      }
943
944      if (CCC == Action::CCC_Class) {
945        // public:
946        Pattern = new CodeCompletionString;
947        Pattern->AddTypedTextChunk("public");
948        Pattern->AddChunk(CodeCompletionString::CK_Colon);
949        Results.AddResult(Result(Pattern));
950
951        // protected:
952        Pattern = new CodeCompletionString;
953        Pattern->AddTypedTextChunk("protected");
954        Pattern->AddChunk(CodeCompletionString::CK_Colon);
955        Results.AddResult(Result(Pattern));
956
957        // private:
958        Pattern = new CodeCompletionString;
959        Pattern->AddTypedTextChunk("private");
960        Pattern->AddChunk(CodeCompletionString::CK_Colon);
961        Results.AddResult(Result(Pattern));
962      }
963    }
964    // Fall through
965
966  case Action::CCC_Template:
967  case Action::CCC_MemberTemplate:
968    if (SemaRef.getLangOptions().CPlusPlus) {
969      // template < parameters >
970      CodeCompletionString *Pattern = new CodeCompletionString;
971      Pattern->AddTypedTextChunk("template");
972      Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
973      Pattern->AddPlaceholderChunk("parameters");
974      Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
975      Results.AddResult(Result(Pattern));
976    }
977
978    AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
979    AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
980    break;
981
982  case Action::CCC_ObjCInterface:
983    AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
984    AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
985    AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
986    break;
987
988  case Action::CCC_ObjCImplementation:
989    AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
990    AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
991    AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
992    break;
993
994  case Action::CCC_ObjCInstanceVariableList:
995    AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
996    break;
997
998  case Action::CCC_Statement: {
999    Results.AddResult(Result("typedef"));
1000
1001    CodeCompletionString *Pattern = 0;
1002    if (SemaRef.getLangOptions().CPlusPlus) {
1003      Pattern = new CodeCompletionString;
1004      Pattern->AddTypedTextChunk("try");
1005      Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1006      Pattern->AddPlaceholderChunk("statements");
1007      Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1008      Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1009      Pattern->AddTextChunk("catch");
1010      Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1011      Pattern->AddPlaceholderChunk("declaration");
1012      Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1013      Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1014      Pattern->AddPlaceholderChunk("statements");
1015      Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1016      Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1017      Results.AddResult(Result(Pattern));
1018    }
1019    if (SemaRef.getLangOptions().ObjC1)
1020      AddObjCStatementResults(Results, true);
1021
1022    // if (condition) { statements }
1023    Pattern = new CodeCompletionString;
1024    Pattern->AddTypedTextChunk("if");
1025    Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1026    if (SemaRef.getLangOptions().CPlusPlus)
1027      Pattern->AddPlaceholderChunk("condition");
1028    else
1029      Pattern->AddPlaceholderChunk("expression");
1030    Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1031    Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1032    Pattern->AddPlaceholderChunk("statements");
1033    Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1034    Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1035    Results.AddResult(Result(Pattern));
1036
1037    // switch (condition) { }
1038    Pattern = new CodeCompletionString;
1039    Pattern->AddTypedTextChunk("switch");
1040    Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1041    if (SemaRef.getLangOptions().CPlusPlus)
1042      Pattern->AddPlaceholderChunk("condition");
1043    else
1044      Pattern->AddPlaceholderChunk("expression");
1045    Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1046    Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1047    Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1048    Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1049    Results.AddResult(Result(Pattern));
1050
1051    // Switch-specific statements.
1052    if (!SemaRef.getSwitchStack().empty()) {
1053      // case expression:
1054      Pattern = new CodeCompletionString;
1055      Pattern->AddTypedTextChunk("case");
1056      Pattern->AddPlaceholderChunk("expression");
1057      Pattern->AddChunk(CodeCompletionString::CK_Colon);
1058      Results.AddResult(Result(Pattern));
1059
1060      // default:
1061      Pattern = new CodeCompletionString;
1062      Pattern->AddTypedTextChunk("default");
1063      Pattern->AddChunk(CodeCompletionString::CK_Colon);
1064      Results.AddResult(Result(Pattern));
1065    }
1066
1067    /// while (condition) { statements }
1068    Pattern = new CodeCompletionString;
1069    Pattern->AddTypedTextChunk("while");
1070    Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1071    if (SemaRef.getLangOptions().CPlusPlus)
1072      Pattern->AddPlaceholderChunk("condition");
1073    else
1074      Pattern->AddPlaceholderChunk("expression");
1075    Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1076    Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1077    Pattern->AddPlaceholderChunk("statements");
1078    Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1079    Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1080    Results.AddResult(Result(Pattern));
1081
1082    // do { statements } while ( expression );
1083    Pattern = new CodeCompletionString;
1084    Pattern->AddTypedTextChunk("do");
1085    Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1086    Pattern->AddPlaceholderChunk("statements");
1087    Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1088    Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1089    Pattern->AddTextChunk("while");
1090    Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1091    Pattern->AddPlaceholderChunk("expression");
1092    Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1093    Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1094    Results.AddResult(Result(Pattern));
1095
1096    // for ( for-init-statement ; condition ; expression ) { statements }
1097    Pattern = new CodeCompletionString;
1098    Pattern->AddTypedTextChunk("for");
1099    Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1100    if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1101      Pattern->AddPlaceholderChunk("init-statement");
1102    else
1103      Pattern->AddPlaceholderChunk("init-expression");
1104    Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1105    Pattern->AddPlaceholderChunk("condition");
1106    Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1107    Pattern->AddPlaceholderChunk("inc-expression");
1108    Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1109    Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1110    Pattern->AddPlaceholderChunk("statements");
1111    Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1112    Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1113    Results.AddResult(Result(Pattern));
1114
1115    if (S->getContinueParent()) {
1116      // continue ;
1117      Pattern = new CodeCompletionString;
1118      Pattern->AddTypedTextChunk("continue");
1119      Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1120      Results.AddResult(Result(Pattern));
1121    }
1122
1123    if (S->getBreakParent()) {
1124      // break ;
1125      Pattern = new CodeCompletionString;
1126      Pattern->AddTypedTextChunk("break");
1127      Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1128      Results.AddResult(Result(Pattern));
1129    }
1130
1131    // "return expression ;" or "return ;", depending on whether we
1132    // know the function is void or not.
1133    bool isVoid = false;
1134    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1135      isVoid = Function->getResultType()->isVoidType();
1136    else if (ObjCMethodDecl *Method
1137                                 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1138      isVoid = Method->getResultType()->isVoidType();
1139    else if (SemaRef.getCurBlock() &&
1140             !SemaRef.getCurBlock()->ReturnType.isNull())
1141      isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
1142    Pattern = new CodeCompletionString;
1143    Pattern->AddTypedTextChunk("return");
1144    if (!isVoid) {
1145      Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1146      Pattern->AddPlaceholderChunk("expression");
1147    }
1148    Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1149    Results.AddResult(Result(Pattern));
1150
1151    // goto identifier ;
1152    Pattern = new CodeCompletionString;
1153    Pattern->AddTypedTextChunk("goto");
1154    Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1155    Pattern->AddPlaceholderChunk("identifier");
1156    Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1157    Results.AddResult(Result(Pattern));
1158
1159    // Using directives
1160    Pattern = new CodeCompletionString;
1161    Pattern->AddTypedTextChunk("using");
1162    Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1163    Pattern->AddTextChunk("namespace");
1164    Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1165    Pattern->AddPlaceholderChunk("identifier");
1166    Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1167    Results.AddResult(Result(Pattern));
1168  }
1169
1170  // Fall through (for statement expressions).
1171  case Action::CCC_ForInit:
1172  case Action::CCC_Condition:
1173    AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1174    // Fall through: conditions and statements can have expressions.
1175
1176  case Action::CCC_Expression: {
1177    CodeCompletionString *Pattern = 0;
1178    if (SemaRef.getLangOptions().CPlusPlus) {
1179      // 'this', if we're in a non-static member function.
1180      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1181        if (!Method->isStatic())
1182          Results.AddResult(Result("this"));
1183
1184      // true, false
1185      Results.AddResult(Result("true"));
1186      Results.AddResult(Result("false"));
1187
1188      // dynamic_cast < type-id > ( expression )
1189      Pattern = new CodeCompletionString;
1190      Pattern->AddTypedTextChunk("dynamic_cast");
1191      Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1192      Pattern->AddPlaceholderChunk("type-id");
1193      Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1194      Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1195      Pattern->AddPlaceholderChunk("expression");
1196      Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1197      Results.AddResult(Result(Pattern));
1198
1199      // static_cast < type-id > ( expression )
1200      Pattern = new CodeCompletionString;
1201      Pattern->AddTypedTextChunk("static_cast");
1202      Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1203      Pattern->AddPlaceholderChunk("type-id");
1204      Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1205      Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1206      Pattern->AddPlaceholderChunk("expression");
1207      Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1208      Results.AddResult(Result(Pattern));
1209
1210      // reinterpret_cast < type-id > ( expression )
1211      Pattern = new CodeCompletionString;
1212      Pattern->AddTypedTextChunk("reinterpret_cast");
1213      Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1214      Pattern->AddPlaceholderChunk("type-id");
1215      Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1216      Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1217      Pattern->AddPlaceholderChunk("expression");
1218      Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1219      Results.AddResult(Result(Pattern));
1220
1221      // const_cast < type-id > ( expression )
1222      Pattern = new CodeCompletionString;
1223      Pattern->AddTypedTextChunk("const_cast");
1224      Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1225      Pattern->AddPlaceholderChunk("type-id");
1226      Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1227      Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1228      Pattern->AddPlaceholderChunk("expression");
1229      Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1230      Results.AddResult(Result(Pattern));
1231
1232      // typeid ( expression-or-type )
1233      Pattern = new CodeCompletionString;
1234      Pattern->AddTypedTextChunk("typeid");
1235      Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1236      Pattern->AddPlaceholderChunk("expression-or-type");
1237      Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1238      Results.AddResult(Result(Pattern));
1239
1240      // new T ( ... )
1241      Pattern = new CodeCompletionString;
1242      Pattern->AddTypedTextChunk("new");
1243      Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1244      Pattern->AddPlaceholderChunk("type-id");
1245      Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1246      Pattern->AddPlaceholderChunk("expressions");
1247      Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1248      Results.AddResult(Result(Pattern));
1249
1250      // new T [ ] ( ... )
1251      Pattern = new CodeCompletionString;
1252      Pattern->AddTypedTextChunk("new");
1253      Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1254      Pattern->AddPlaceholderChunk("type-id");
1255      Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1256      Pattern->AddPlaceholderChunk("size");
1257      Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1258      Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1259      Pattern->AddPlaceholderChunk("expressions");
1260      Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1261      Results.AddResult(Result(Pattern));
1262
1263      // delete expression
1264      Pattern = new CodeCompletionString;
1265      Pattern->AddTypedTextChunk("delete");
1266      Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1267      Pattern->AddPlaceholderChunk("expression");
1268      Results.AddResult(Result(Pattern));
1269
1270      // delete [] expression
1271      Pattern = new CodeCompletionString;
1272      Pattern->AddTypedTextChunk("delete");
1273      Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1274      Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1275      Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1276      Pattern->AddPlaceholderChunk("expression");
1277      Results.AddResult(Result(Pattern));
1278
1279      // throw expression
1280      Pattern = new CodeCompletionString;
1281      Pattern->AddTypedTextChunk("throw");
1282      Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1283      Pattern->AddPlaceholderChunk("expression");
1284      Results.AddResult(Result(Pattern));
1285    }
1286
1287    if (SemaRef.getLangOptions().ObjC1) {
1288      // Add "super", if we're in an Objective-C class with a superclass.
1289      if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
1290        if (Method->getClassInterface()->getSuperClass())
1291          Results.AddResult(Result("super"));
1292
1293      AddObjCExpressionResults(Results, true);
1294    }
1295
1296    // sizeof expression
1297    Pattern = new CodeCompletionString;
1298    Pattern->AddTypedTextChunk("sizeof");
1299    Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1300    Pattern->AddPlaceholderChunk("expression-or-type");
1301    Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1302    Results.AddResult(Result(Pattern));
1303    break;
1304  }
1305  }
1306
1307  AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
1308
1309  if (SemaRef.getLangOptions().CPlusPlus)
1310    Results.AddResult(Result("operator"));
1311}
1312
1313/// \brief If the given declaration has an associated type, add it as a result
1314/// type chunk.
1315static void AddResultTypeChunk(ASTContext &Context,
1316                               NamedDecl *ND,
1317                               CodeCompletionString *Result) {
1318  if (!ND)
1319    return;
1320
1321  // Determine the type of the declaration (if it has a type).
1322  QualType T;
1323  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1324    T = Function->getResultType();
1325  else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1326    T = Method->getResultType();
1327  else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1328    T = FunTmpl->getTemplatedDecl()->getResultType();
1329  else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1330    T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1331  else if (isa<UnresolvedUsingValueDecl>(ND)) {
1332    /* Do nothing: ignore unresolved using declarations*/
1333  } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1334    T = Value->getType();
1335  else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1336    T = Property->getType();
1337
1338  if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1339    return;
1340
1341  std::string TypeStr;
1342  T.getAsStringInternal(TypeStr, Context.PrintingPolicy);
1343  Result->AddResultTypeChunk(TypeStr);
1344}
1345
1346/// \brief Add function parameter chunks to the given code completion string.
1347static void AddFunctionParameterChunks(ASTContext &Context,
1348                                       FunctionDecl *Function,
1349                                       CodeCompletionString *Result) {
1350  typedef CodeCompletionString::Chunk Chunk;
1351
1352  CodeCompletionString *CCStr = Result;
1353
1354  for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1355    ParmVarDecl *Param = Function->getParamDecl(P);
1356
1357    if (Param->hasDefaultArg()) {
1358      // When we see an optional default argument, put that argument and
1359      // the remaining default arguments into a new, optional string.
1360      CodeCompletionString *Opt = new CodeCompletionString;
1361      CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1362      CCStr = Opt;
1363    }
1364
1365    if (P != 0)
1366      CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1367
1368    // Format the placeholder string.
1369    std::string PlaceholderStr;
1370    if (Param->getIdentifier())
1371      PlaceholderStr = Param->getIdentifier()->getName();
1372
1373    Param->getType().getAsStringInternal(PlaceholderStr,
1374                                         Context.PrintingPolicy);
1375
1376    // Add the placeholder string.
1377    CCStr->AddPlaceholderChunk(PlaceholderStr);
1378  }
1379
1380  if (const FunctionProtoType *Proto
1381        = Function->getType()->getAs<FunctionProtoType>())
1382    if (Proto->isVariadic())
1383      CCStr->AddPlaceholderChunk(", ...");
1384}
1385
1386/// \brief Add template parameter chunks to the given code completion string.
1387static void AddTemplateParameterChunks(ASTContext &Context,
1388                                       TemplateDecl *Template,
1389                                       CodeCompletionString *Result,
1390                                       unsigned MaxParameters = 0) {
1391  typedef CodeCompletionString::Chunk Chunk;
1392
1393  CodeCompletionString *CCStr = Result;
1394  bool FirstParameter = true;
1395
1396  TemplateParameterList *Params = Template->getTemplateParameters();
1397  TemplateParameterList::iterator PEnd = Params->end();
1398  if (MaxParameters)
1399    PEnd = Params->begin() + MaxParameters;
1400  for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1401    bool HasDefaultArg = false;
1402    std::string PlaceholderStr;
1403    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1404      if (TTP->wasDeclaredWithTypename())
1405        PlaceholderStr = "typename";
1406      else
1407        PlaceholderStr = "class";
1408
1409      if (TTP->getIdentifier()) {
1410        PlaceholderStr += ' ';
1411        PlaceholderStr += TTP->getIdentifier()->getName();
1412      }
1413
1414      HasDefaultArg = TTP->hasDefaultArgument();
1415    } else if (NonTypeTemplateParmDecl *NTTP
1416               = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1417      if (NTTP->getIdentifier())
1418        PlaceholderStr = NTTP->getIdentifier()->getName();
1419      NTTP->getType().getAsStringInternal(PlaceholderStr,
1420                                          Context.PrintingPolicy);
1421      HasDefaultArg = NTTP->hasDefaultArgument();
1422    } else {
1423      assert(isa<TemplateTemplateParmDecl>(*P));
1424      TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1425
1426      // Since putting the template argument list into the placeholder would
1427      // be very, very long, we just use an abbreviation.
1428      PlaceholderStr = "template<...> class";
1429      if (TTP->getIdentifier()) {
1430        PlaceholderStr += ' ';
1431        PlaceholderStr += TTP->getIdentifier()->getName();
1432      }
1433
1434      HasDefaultArg = TTP->hasDefaultArgument();
1435    }
1436
1437    if (HasDefaultArg) {
1438      // When we see an optional default argument, put that argument and
1439      // the remaining default arguments into a new, optional string.
1440      CodeCompletionString *Opt = new CodeCompletionString;
1441      CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1442      CCStr = Opt;
1443    }
1444
1445    if (FirstParameter)
1446      FirstParameter = false;
1447    else
1448      CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1449
1450    // Add the placeholder string.
1451    CCStr->AddPlaceholderChunk(PlaceholderStr);
1452  }
1453}
1454
1455/// \brief Add a qualifier to the given code-completion string, if the
1456/// provided nested-name-specifier is non-NULL.
1457static void
1458AddQualifierToCompletionString(CodeCompletionString *Result,
1459                               NestedNameSpecifier *Qualifier,
1460                               bool QualifierIsInformative,
1461                               ASTContext &Context) {
1462  if (!Qualifier)
1463    return;
1464
1465  std::string PrintedNNS;
1466  {
1467    llvm::raw_string_ostream OS(PrintedNNS);
1468    Qualifier->print(OS, Context.PrintingPolicy);
1469  }
1470  if (QualifierIsInformative)
1471    Result->AddInformativeChunk(PrintedNNS);
1472  else
1473    Result->AddTextChunk(PrintedNNS);
1474}
1475
1476static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1477                                                   FunctionDecl *Function) {
1478  const FunctionProtoType *Proto
1479    = Function->getType()->getAs<FunctionProtoType>();
1480  if (!Proto || !Proto->getTypeQuals())
1481    return;
1482
1483  std::string QualsStr;
1484  if (Proto->getTypeQuals() & Qualifiers::Const)
1485    QualsStr += " const";
1486  if (Proto->getTypeQuals() & Qualifiers::Volatile)
1487    QualsStr += " volatile";
1488  if (Proto->getTypeQuals() & Qualifiers::Restrict)
1489    QualsStr += " restrict";
1490  Result->AddInformativeChunk(QualsStr);
1491}
1492
1493/// \brief If possible, create a new code completion string for the given
1494/// result.
1495///
1496/// \returns Either a new, heap-allocated code completion string describing
1497/// how to use this result, or NULL to indicate that the string or name of the
1498/// result is all that is needed.
1499CodeCompletionString *
1500CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
1501  typedef CodeCompletionString::Chunk Chunk;
1502
1503  if (Kind == RK_Pattern)
1504    return Pattern->Clone();
1505
1506  CodeCompletionString *Result = new CodeCompletionString;
1507
1508  if (Kind == RK_Keyword) {
1509    Result->AddTypedTextChunk(Keyword);
1510    return Result;
1511  }
1512
1513  if (Kind == RK_Macro) {
1514    MacroInfo *MI = S.PP.getMacroInfo(Macro);
1515    assert(MI && "Not a macro?");
1516
1517    Result->AddTypedTextChunk(Macro->getName());
1518
1519    if (!MI->isFunctionLike())
1520      return Result;
1521
1522    // Format a function-like macro with placeholders for the arguments.
1523    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1524    for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
1525         A != AEnd; ++A) {
1526      if (A != MI->arg_begin())
1527        Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1528
1529      if (!MI->isVariadic() || A != AEnd - 1) {
1530        // Non-variadic argument.
1531        Result->AddPlaceholderChunk((*A)->getName());
1532        continue;
1533      }
1534
1535      // Variadic argument; cope with the different between GNU and C99
1536      // variadic macros, providing a single placeholder for the rest of the
1537      // arguments.
1538      if ((*A)->isStr("__VA_ARGS__"))
1539        Result->AddPlaceholderChunk("...");
1540      else {
1541        std::string Arg = (*A)->getName();
1542        Arg += "...";
1543        Result->AddPlaceholderChunk(Arg);
1544      }
1545    }
1546    Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1547    return Result;
1548  }
1549
1550  assert(Kind == RK_Declaration && "Missed a macro kind?");
1551  NamedDecl *ND = Declaration;
1552
1553  if (StartsNestedNameSpecifier) {
1554    Result->AddTypedTextChunk(ND->getNameAsString());
1555    Result->AddTextChunk("::");
1556    return Result;
1557  }
1558
1559  AddResultTypeChunk(S.Context, ND, Result);
1560
1561  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
1562    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1563                                   S.Context);
1564    Result->AddTypedTextChunk(Function->getNameAsString());
1565    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1566    AddFunctionParameterChunks(S.Context, Function, Result);
1567    Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1568    AddFunctionTypeQualsToCompletionString(Result, Function);
1569    return Result;
1570  }
1571
1572  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
1573    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1574                                   S.Context);
1575    FunctionDecl *Function = FunTmpl->getTemplatedDecl();
1576    Result->AddTypedTextChunk(Function->getNameAsString());
1577
1578    // Figure out which template parameters are deduced (or have default
1579    // arguments).
1580    llvm::SmallVector<bool, 16> Deduced;
1581    S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
1582    unsigned LastDeducibleArgument;
1583    for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
1584         --LastDeducibleArgument) {
1585      if (!Deduced[LastDeducibleArgument - 1]) {
1586        // C++0x: Figure out if the template argument has a default. If so,
1587        // the user doesn't need to type this argument.
1588        // FIXME: We need to abstract template parameters better!
1589        bool HasDefaultArg = false;
1590        NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
1591                                                                      LastDeducibleArgument - 1);
1592        if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1593          HasDefaultArg = TTP->hasDefaultArgument();
1594        else if (NonTypeTemplateParmDecl *NTTP
1595                 = dyn_cast<NonTypeTemplateParmDecl>(Param))
1596          HasDefaultArg = NTTP->hasDefaultArgument();
1597        else {
1598          assert(isa<TemplateTemplateParmDecl>(Param));
1599          HasDefaultArg
1600            = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
1601        }
1602
1603        if (!HasDefaultArg)
1604          break;
1605      }
1606    }
1607
1608    if (LastDeducibleArgument) {
1609      // Some of the function template arguments cannot be deduced from a
1610      // function call, so we introduce an explicit template argument list
1611      // containing all of the arguments up to the first deducible argument.
1612      Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
1613      AddTemplateParameterChunks(S.Context, FunTmpl, Result,
1614                                 LastDeducibleArgument);
1615      Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
1616    }
1617
1618    // Add the function parameters
1619    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1620    AddFunctionParameterChunks(S.Context, Function, Result);
1621    Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1622    AddFunctionTypeQualsToCompletionString(Result, Function);
1623    return Result;
1624  }
1625
1626  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
1627    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1628                                   S.Context);
1629    Result->AddTypedTextChunk(Template->getNameAsString());
1630    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
1631    AddTemplateParameterChunks(S.Context, Template, Result);
1632    Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
1633    return Result;
1634  }
1635
1636  if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
1637    Selector Sel = Method->getSelector();
1638    if (Sel.isUnarySelector()) {
1639      Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
1640      return Result;
1641    }
1642
1643    std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
1644    SelName += ':';
1645    if (StartParameter == 0)
1646      Result->AddTypedTextChunk(SelName);
1647    else {
1648      Result->AddInformativeChunk(SelName);
1649
1650      // If there is only one parameter, and we're past it, add an empty
1651      // typed-text chunk since there is nothing to type.
1652      if (Method->param_size() == 1)
1653        Result->AddTypedTextChunk("");
1654    }
1655    unsigned Idx = 0;
1656    for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
1657                                     PEnd = Method->param_end();
1658         P != PEnd; (void)++P, ++Idx) {
1659      if (Idx > 0) {
1660        std::string Keyword;
1661        if (Idx > StartParameter)
1662          Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1663        if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
1664          Keyword += II->getName().str();
1665        Keyword += ":";
1666        if (Idx < StartParameter || AllParametersAreInformative) {
1667          Result->AddInformativeChunk(Keyword);
1668        } else if (Idx == StartParameter)
1669          Result->AddTypedTextChunk(Keyword);
1670        else
1671          Result->AddTextChunk(Keyword);
1672      }
1673
1674      // If we're before the starting parameter, skip the placeholder.
1675      if (Idx < StartParameter)
1676        continue;
1677
1678      std::string Arg;
1679      (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
1680      Arg = "(" + Arg + ")";
1681      if (IdentifierInfo *II = (*P)->getIdentifier())
1682        Arg += II->getName().str();
1683      if (AllParametersAreInformative)
1684        Result->AddInformativeChunk(Arg);
1685      else
1686        Result->AddPlaceholderChunk(Arg);
1687    }
1688
1689    if (Method->isVariadic()) {
1690      if (AllParametersAreInformative)
1691        Result->AddInformativeChunk(", ...");
1692      else
1693        Result->AddPlaceholderChunk(", ...");
1694    }
1695
1696    return Result;
1697  }
1698
1699  if (Qualifier)
1700    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1701                                   S.Context);
1702
1703  Result->AddTypedTextChunk(ND->getNameAsString());
1704  return Result;
1705}
1706
1707CodeCompletionString *
1708CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
1709                                                          unsigned CurrentArg,
1710                                                               Sema &S) const {
1711  typedef CodeCompletionString::Chunk Chunk;
1712
1713  CodeCompletionString *Result = new CodeCompletionString;
1714  FunctionDecl *FDecl = getFunction();
1715  AddResultTypeChunk(S.Context, FDecl, Result);
1716  const FunctionProtoType *Proto
1717    = dyn_cast<FunctionProtoType>(getFunctionType());
1718  if (!FDecl && !Proto) {
1719    // Function without a prototype. Just give the return type and a
1720    // highlighted ellipsis.
1721    const FunctionType *FT = getFunctionType();
1722    Result->AddTextChunk(
1723            FT->getResultType().getAsString(S.Context.PrintingPolicy));
1724    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1725    Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1726    Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1727    return Result;
1728  }
1729
1730  if (FDecl)
1731    Result->AddTextChunk(FDecl->getNameAsString());
1732  else
1733    Result->AddTextChunk(
1734         Proto->getResultType().getAsString(S.Context.PrintingPolicy));
1735
1736  Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1737  unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
1738  for (unsigned I = 0; I != NumParams; ++I) {
1739    if (I)
1740      Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1741
1742    std::string ArgString;
1743    QualType ArgType;
1744
1745    if (FDecl) {
1746      ArgString = FDecl->getParamDecl(I)->getNameAsString();
1747      ArgType = FDecl->getParamDecl(I)->getOriginalType();
1748    } else {
1749      ArgType = Proto->getArgType(I);
1750    }
1751
1752    ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
1753
1754    if (I == CurrentArg)
1755      Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
1756                             ArgString));
1757    else
1758      Result->AddTextChunk(ArgString);
1759  }
1760
1761  if (Proto && Proto->isVariadic()) {
1762    Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1763    if (CurrentArg < NumParams)
1764      Result->AddTextChunk("...");
1765    else
1766      Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1767  }
1768  Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1769
1770  return Result;
1771}
1772
1773namespace {
1774  struct SortCodeCompleteResult {
1775    typedef CodeCompleteConsumer::Result Result;
1776
1777    bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
1778      Selector XSel = X.getObjCSelector();
1779      Selector YSel = Y.getObjCSelector();
1780      if (!XSel.isNull() && !YSel.isNull()) {
1781        // We are comparing two selectors.
1782        unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
1783        if (N == 0)
1784          ++N;
1785        for (unsigned I = 0; I != N; ++I) {
1786          IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
1787          IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
1788          if (!XId || !YId)
1789            return XId && !YId;
1790
1791          switch (XId->getName().compare_lower(YId->getName())) {
1792          case -1: return true;
1793          case 1: return false;
1794          default: break;
1795          }
1796        }
1797
1798        return XSel.getNumArgs() < YSel.getNumArgs();
1799      }
1800
1801      // For non-selectors, order by kind.
1802      if (X.getNameKind() != Y.getNameKind())
1803        return X.getNameKind() < Y.getNameKind();
1804
1805      // Order identifiers by comparison of their lowercased names.
1806      if (IdentifierInfo *XId = X.getAsIdentifierInfo())
1807        return XId->getName().compare_lower(
1808                                     Y.getAsIdentifierInfo()->getName()) < 0;
1809
1810      // Order overloaded operators by the order in which they appear
1811      // in our list of operators.
1812      if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
1813        return XOp < Y.getCXXOverloadedOperator();
1814
1815      // Order C++0x user-defined literal operators lexically by their
1816      // lowercased suffixes.
1817      if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
1818        return XLit->getName().compare_lower(
1819                                  Y.getCXXLiteralIdentifier()->getName()) < 0;
1820
1821      // The only stable ordering we have is to turn the name into a
1822      // string and then compare the lower-case strings. This is
1823      // inefficient, but thankfully does not happen too often.
1824      return llvm::StringRef(X.getAsString()).compare_lower(
1825                                                 Y.getAsString()) < 0;
1826    }
1827
1828    /// \brief Retrieve the name that should be used to order a result.
1829    ///
1830    /// If the name needs to be constructed as a string, that string will be
1831    /// saved into Saved and the returned StringRef will refer to it.
1832    static llvm::StringRef getOrderedName(const Result &R,
1833                                          std::string &Saved) {
1834      switch (R.Kind) {
1835      case Result::RK_Keyword:
1836        return R.Keyword;
1837
1838      case Result::RK_Pattern:
1839        return R.Pattern->getTypedText();
1840
1841      case Result::RK_Macro:
1842        return R.Macro->getName();
1843
1844      case Result::RK_Declaration:
1845        // Handle declarations below.
1846        break;
1847      }
1848
1849      DeclarationName Name = R.Declaration->getDeclName();
1850
1851      // If the name is a simple identifier (by far the common case), or a
1852      // zero-argument selector, just return a reference to that identifier.
1853      if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
1854        return Id->getName();
1855      if (Name.isObjCZeroArgSelector())
1856        if (IdentifierInfo *Id
1857                          = Name.getObjCSelector().getIdentifierInfoForSlot(0))
1858          return Id->getName();
1859
1860      Saved = Name.getAsString();
1861      return Saved;
1862    }
1863
1864    bool operator()(const Result &X, const Result &Y) const {
1865      std::string XSaved, YSaved;
1866      llvm::StringRef XStr = getOrderedName(X, XSaved);
1867      llvm::StringRef YStr = getOrderedName(Y, YSaved);
1868      int cmp = XStr.compare_lower(YStr);
1869      if (cmp)
1870        return cmp < 0;
1871
1872      // Non-hidden names precede hidden names.
1873      if (X.Hidden != Y.Hidden)
1874        return !X.Hidden;
1875
1876      // Non-nested-name-specifiers precede nested-name-specifiers.
1877      if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1878        return !X.StartsNestedNameSpecifier;
1879
1880      return false;
1881    }
1882  };
1883}
1884
1885static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results) {
1886  Results.EnterNewScope();
1887  for (Preprocessor::macro_iterator M = PP.macro_begin(),
1888                                 MEnd = PP.macro_end();
1889       M != MEnd; ++M)
1890    Results.AddResult(M->first);
1891  Results.ExitScope();
1892}
1893
1894static void HandleCodeCompleteResults(Sema *S,
1895                                      CodeCompleteConsumer *CodeCompleter,
1896                                     CodeCompleteConsumer::Result *Results,
1897                                     unsigned NumResults) {
1898  std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1899
1900  if (CodeCompleter)
1901    CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
1902
1903  for (unsigned I = 0; I != NumResults; ++I)
1904    Results[I].Destroy();
1905}
1906
1907void Sema::CodeCompleteOrdinaryName(Scope *S,
1908                                    CodeCompletionContext CompletionContext) {
1909  typedef CodeCompleteConsumer::Result Result;
1910  ResultBuilder Results(*this);
1911
1912  // Determine how to filter results, e.g., so that the names of
1913  // values (functions, enumerators, function templates, etc.) are
1914  // only allowed where we can have an expression.
1915  switch (CompletionContext) {
1916  case CCC_Namespace:
1917  case CCC_Class:
1918  case CCC_ObjCInterface:
1919  case CCC_ObjCImplementation:
1920  case CCC_ObjCInstanceVariableList:
1921  case CCC_Template:
1922  case CCC_MemberTemplate:
1923    Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
1924    break;
1925
1926  case CCC_Expression:
1927  case CCC_Statement:
1928  case CCC_ForInit:
1929  case CCC_Condition:
1930    Results.setFilter(&ResultBuilder::IsOrdinaryName);
1931    break;
1932  }
1933
1934  CodeCompletionDeclConsumer Consumer(Results, CurContext);
1935  LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
1936
1937  Results.EnterNewScope();
1938  AddOrdinaryNameResults(CompletionContext, S, *this, Results);
1939  Results.ExitScope();
1940
1941  if (CodeCompleter->includeMacros())
1942    AddMacroResults(PP, Results);
1943  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1944}
1945
1946static void AddObjCProperties(ObjCContainerDecl *Container,
1947                              bool AllowCategories,
1948                              DeclContext *CurContext,
1949                              ResultBuilder &Results) {
1950  typedef CodeCompleteConsumer::Result Result;
1951
1952  // Add properties in this container.
1953  for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
1954                                     PEnd = Container->prop_end();
1955       P != PEnd;
1956       ++P)
1957    Results.MaybeAddResult(Result(*P, 0), CurContext);
1958
1959  // Add properties in referenced protocols.
1960  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
1961    for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
1962                                          PEnd = Protocol->protocol_end();
1963         P != PEnd; ++P)
1964      AddObjCProperties(*P, AllowCategories, CurContext, Results);
1965  } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
1966    if (AllowCategories) {
1967      // Look through categories.
1968      for (ObjCCategoryDecl *Category = IFace->getCategoryList();
1969           Category; Category = Category->getNextClassCategory())
1970        AddObjCProperties(Category, AllowCategories, CurContext, Results);
1971    }
1972
1973    // Look through protocols.
1974    for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
1975                                              E = IFace->protocol_end();
1976         I != E; ++I)
1977      AddObjCProperties(*I, AllowCategories, CurContext, Results);
1978
1979    // Look in the superclass.
1980    if (IFace->getSuperClass())
1981      AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
1982                        Results);
1983  } else if (const ObjCCategoryDecl *Category
1984                                    = dyn_cast<ObjCCategoryDecl>(Container)) {
1985    // Look through protocols.
1986    for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
1987                                           PEnd = Category->protocol_end();
1988         P != PEnd; ++P)
1989      AddObjCProperties(*P, AllowCategories, CurContext, Results);
1990  }
1991}
1992
1993void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1994                                           SourceLocation OpLoc,
1995                                           bool IsArrow) {
1996  if (!BaseE || !CodeCompleter)
1997    return;
1998
1999  typedef CodeCompleteConsumer::Result Result;
2000
2001  Expr *Base = static_cast<Expr *>(BaseE);
2002  QualType BaseType = Base->getType();
2003
2004  if (IsArrow) {
2005    if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2006      BaseType = Ptr->getPointeeType();
2007    else if (BaseType->isObjCObjectPointerType())
2008    /*Do nothing*/ ;
2009    else
2010      return;
2011  }
2012
2013  ResultBuilder Results(*this, &ResultBuilder::IsMember);
2014  Results.EnterNewScope();
2015  if (const RecordType *Record = BaseType->getAs<RecordType>()) {
2016    // Access to a C/C++ class, struct, or union.
2017    Results.allowNestedNameSpecifiers();
2018    CodeCompletionDeclConsumer Consumer(Results, CurContext);
2019    LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer);
2020
2021    if (getLangOptions().CPlusPlus) {
2022      if (!Results.empty()) {
2023        // The "template" keyword can follow "->" or "." in the grammar.
2024        // However, we only want to suggest the template keyword if something
2025        // is dependent.
2026        bool IsDependent = BaseType->isDependentType();
2027        if (!IsDependent) {
2028          for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2029            if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2030              IsDependent = Ctx->isDependentContext();
2031              break;
2032            }
2033        }
2034
2035        if (IsDependent)
2036          Results.AddResult(Result("template"));
2037      }
2038    }
2039  } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2040    // Objective-C property reference.
2041
2042    // Add property results based on our interface.
2043    const ObjCObjectPointerType *ObjCPtr
2044      = BaseType->getAsObjCInterfacePointerType();
2045    assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
2046    AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
2047
2048    // Add properties from the protocols in a qualified interface.
2049    for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2050                                              E = ObjCPtr->qual_end();
2051         I != E; ++I)
2052      AddObjCProperties(*I, true, CurContext, Results);
2053  } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2054             (!IsArrow && BaseType->isObjCInterfaceType())) {
2055    // Objective-C instance variable access.
2056    ObjCInterfaceDecl *Class = 0;
2057    if (const ObjCObjectPointerType *ObjCPtr
2058                                    = BaseType->getAs<ObjCObjectPointerType>())
2059      Class = ObjCPtr->getInterfaceDecl();
2060    else
2061      Class = BaseType->getAs<ObjCInterfaceType>()->getDecl();
2062
2063    // Add all ivars from this class and its superclasses.
2064    if (Class) {
2065      CodeCompletionDeclConsumer Consumer(Results, CurContext);
2066      Results.setFilter(&ResultBuilder::IsObjCIvar);
2067      LookupVisibleDecls(Class, LookupMemberName, Consumer);
2068    }
2069  }
2070
2071  // FIXME: How do we cope with isa?
2072
2073  Results.ExitScope();
2074
2075  // Add macros
2076  if (CodeCompleter->includeMacros())
2077    AddMacroResults(PP, Results);
2078
2079  // Hand off the results found for code completion.
2080  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2081}
2082
2083void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2084  if (!CodeCompleter)
2085    return;
2086
2087  typedef CodeCompleteConsumer::Result Result;
2088  ResultBuilder::LookupFilter Filter = 0;
2089  switch ((DeclSpec::TST)TagSpec) {
2090  case DeclSpec::TST_enum:
2091    Filter = &ResultBuilder::IsEnum;
2092    break;
2093
2094  case DeclSpec::TST_union:
2095    Filter = &ResultBuilder::IsUnion;
2096    break;
2097
2098  case DeclSpec::TST_struct:
2099  case DeclSpec::TST_class:
2100    Filter = &ResultBuilder::IsClassOrStruct;
2101    break;
2102
2103  default:
2104    assert(false && "Unknown type specifier kind in CodeCompleteTag");
2105    return;
2106  }
2107
2108  ResultBuilder Results(*this, Filter);
2109  Results.allowNestedNameSpecifiers();
2110  CodeCompletionDeclConsumer Consumer(Results, CurContext);
2111  LookupVisibleDecls(S, LookupTagName, Consumer);
2112
2113  if (CodeCompleter->includeMacros())
2114    AddMacroResults(PP, Results);
2115  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2116}
2117
2118void Sema::CodeCompleteCase(Scope *S) {
2119  if (getSwitchStack().empty() || !CodeCompleter)
2120    return;
2121
2122  SwitchStmt *Switch = getSwitchStack().back();
2123  if (!Switch->getCond()->getType()->isEnumeralType())
2124    return;
2125
2126  // Code-complete the cases of a switch statement over an enumeration type
2127  // by providing the list of
2128  EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2129
2130  // Determine which enumerators we have already seen in the switch statement.
2131  // FIXME: Ideally, we would also be able to look *past* the code-completion
2132  // token, in case we are code-completing in the middle of the switch and not
2133  // at the end. However, we aren't able to do so at the moment.
2134  llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
2135  NestedNameSpecifier *Qualifier = 0;
2136  for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2137       SC = SC->getNextSwitchCase()) {
2138    CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2139    if (!Case)
2140      continue;
2141
2142    Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2143    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2144      if (EnumConstantDecl *Enumerator
2145            = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2146        // We look into the AST of the case statement to determine which
2147        // enumerator was named. Alternatively, we could compute the value of
2148        // the integral constant expression, then compare it against the
2149        // values of each enumerator. However, value-based approach would not
2150        // work as well with C++ templates where enumerators declared within a
2151        // template are type- and value-dependent.
2152        EnumeratorsSeen.insert(Enumerator);
2153
2154        // If this is a qualified-id, keep track of the nested-name-specifier
2155        // so that we can reproduce it as part of code completion, e.g.,
2156        //
2157        //   switch (TagD.getKind()) {
2158        //     case TagDecl::TK_enum:
2159        //       break;
2160        //     case XXX
2161        //
2162        // At the XXX, our completions are TagDecl::TK_union,
2163        // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2164        // TK_struct, and TK_class.
2165        Qualifier = DRE->getQualifier();
2166      }
2167  }
2168
2169  if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2170    // If there are no prior enumerators in C++, check whether we have to
2171    // qualify the names of the enumerators that we suggest, because they
2172    // may not be visible in this scope.
2173    Qualifier = getRequiredQualification(Context, CurContext,
2174                                         Enum->getDeclContext());
2175
2176    // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2177  }
2178
2179  // Add any enumerators that have not yet been mentioned.
2180  ResultBuilder Results(*this);
2181  Results.EnterNewScope();
2182  for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2183                                  EEnd = Enum->enumerator_end();
2184       E != EEnd; ++E) {
2185    if (EnumeratorsSeen.count(*E))
2186      continue;
2187
2188    Results.AddResult(CodeCompleteConsumer::Result(*E, Qualifier),
2189                      CurContext, 0, false);
2190  }
2191  Results.ExitScope();
2192
2193  if (CodeCompleter->includeMacros())
2194    AddMacroResults(PP, Results);
2195  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2196}
2197
2198namespace {
2199  struct IsBetterOverloadCandidate {
2200    Sema &S;
2201    SourceLocation Loc;
2202
2203  public:
2204    explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
2205      : S(S), Loc(Loc) { }
2206
2207    bool
2208    operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
2209      return S.isBetterOverloadCandidate(X, Y, Loc);
2210    }
2211  };
2212}
2213
2214void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2215                            ExprTy **ArgsIn, unsigned NumArgs) {
2216  if (!CodeCompleter)
2217    return;
2218
2219  // When we're code-completing for a call, we fall back to ordinary
2220  // name code-completion whenever we can't produce specific
2221  // results. We may want to revisit this strategy in the future,
2222  // e.g., by merging the two kinds of results.
2223
2224  Expr *Fn = (Expr *)FnIn;
2225  Expr **Args = (Expr **)ArgsIn;
2226
2227  // Ignore type-dependent call expressions entirely.
2228  if (Fn->isTypeDependent() ||
2229      Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2230    CodeCompleteOrdinaryName(S, CCC_Expression);
2231    return;
2232  }
2233
2234  // Build an overload candidate set based on the functions we find.
2235  SourceLocation Loc = Fn->getExprLoc();
2236  OverloadCandidateSet CandidateSet(Loc);
2237
2238  // FIXME: What if we're calling something that isn't a function declaration?
2239  // FIXME: What if we're calling a pseudo-destructor?
2240  // FIXME: What if we're calling a member function?
2241
2242  typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
2243  llvm::SmallVector<ResultCandidate, 8> Results;
2244
2245  Expr *NakedFn = Fn->IgnoreParenCasts();
2246  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
2247    AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
2248                                /*PartialOverloading=*/ true);
2249  else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
2250    FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
2251    if (FDecl) {
2252      if (!FDecl->getType()->getAs<FunctionProtoType>())
2253        Results.push_back(ResultCandidate(FDecl));
2254      else
2255        // FIXME: access?
2256        AddOverloadCandidate(FDecl, AS_none, Args, NumArgs, CandidateSet,
2257                             false, false, /*PartialOverloading*/ true);
2258    }
2259  }
2260
2261  if (!CandidateSet.empty()) {
2262    // Sort the overload candidate set by placing the best overloads first.
2263    std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
2264                     IsBetterOverloadCandidate(*this, Loc));
2265
2266    // Add the remaining viable overload candidates as code-completion reslults.
2267    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2268                                     CandEnd = CandidateSet.end();
2269         Cand != CandEnd; ++Cand) {
2270      if (Cand->Viable)
2271        Results.push_back(ResultCandidate(Cand->Function));
2272    }
2273  }
2274
2275  if (Results.empty())
2276    CodeCompleteOrdinaryName(S, CCC_Expression);
2277  else
2278    CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
2279                                             Results.size());
2280}
2281
2282void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
2283                                   bool EnteringContext) {
2284  if (!SS.getScopeRep() || !CodeCompleter)
2285    return;
2286
2287  DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
2288  if (!Ctx)
2289    return;
2290
2291  // Try to instantiate any non-dependent declaration contexts before
2292  // we look in them.
2293  if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS))
2294    return;
2295
2296  ResultBuilder Results(*this);
2297  CodeCompletionDeclConsumer Consumer(Results, CurContext);
2298  LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
2299
2300  // The "template" keyword can follow "::" in the grammar, but only
2301  // put it into the grammar if the nested-name-specifier is dependent.
2302  NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
2303  if (!Results.empty() && NNS->isDependent())
2304    Results.AddResult("template");
2305
2306  if (CodeCompleter->includeMacros())
2307    AddMacroResults(PP, Results);
2308  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2309}
2310
2311void Sema::CodeCompleteUsing(Scope *S) {
2312  if (!CodeCompleter)
2313    return;
2314
2315  ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
2316  Results.EnterNewScope();
2317
2318  // If we aren't in class scope, we could see the "namespace" keyword.
2319  if (!S->isClassScope())
2320    Results.AddResult(CodeCompleteConsumer::Result("namespace"));
2321
2322  // After "using", we can see anything that would start a
2323  // nested-name-specifier.
2324  CodeCompletionDeclConsumer Consumer(Results, CurContext);
2325  LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2326  Results.ExitScope();
2327
2328  if (CodeCompleter->includeMacros())
2329    AddMacroResults(PP, Results);
2330  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2331}
2332
2333void Sema::CodeCompleteUsingDirective(Scope *S) {
2334  if (!CodeCompleter)
2335    return;
2336
2337  // After "using namespace", we expect to see a namespace name or namespace
2338  // alias.
2339  ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
2340  Results.EnterNewScope();
2341  CodeCompletionDeclConsumer Consumer(Results, CurContext);
2342  LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2343  Results.ExitScope();
2344  if (CodeCompleter->includeMacros())
2345    AddMacroResults(PP, Results);
2346  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2347}
2348
2349void Sema::CodeCompleteNamespaceDecl(Scope *S)  {
2350  if (!CodeCompleter)
2351    return;
2352
2353  ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
2354  DeclContext *Ctx = (DeclContext *)S->getEntity();
2355  if (!S->getParent())
2356    Ctx = Context.getTranslationUnitDecl();
2357
2358  if (Ctx && Ctx->isFileContext()) {
2359    // We only want to see those namespaces that have already been defined
2360    // within this scope, because its likely that the user is creating an
2361    // extended namespace declaration. Keep track of the most recent
2362    // definition of each namespace.
2363    std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
2364    for (DeclContext::specific_decl_iterator<NamespaceDecl>
2365         NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
2366         NS != NSEnd; ++NS)
2367      OrigToLatest[NS->getOriginalNamespace()] = *NS;
2368
2369    // Add the most recent definition (or extended definition) of each
2370    // namespace to the list of results.
2371    Results.EnterNewScope();
2372    for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
2373         NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
2374         NS != NSEnd; ++NS)
2375      Results.AddResult(CodeCompleteConsumer::Result(NS->second, 0),
2376                        CurContext, 0, false);
2377    Results.ExitScope();
2378  }
2379
2380  if (CodeCompleter->includeMacros())
2381    AddMacroResults(PP, Results);
2382  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2383}
2384
2385void Sema::CodeCompleteNamespaceAliasDecl(Scope *S)  {
2386  if (!CodeCompleter)
2387    return;
2388
2389  // After "namespace", we expect to see a namespace or alias.
2390  ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
2391  CodeCompletionDeclConsumer Consumer(Results, CurContext);
2392  LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2393  if (CodeCompleter->includeMacros())
2394    AddMacroResults(PP, Results);
2395  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2396}
2397
2398void Sema::CodeCompleteOperatorName(Scope *S) {
2399  if (!CodeCompleter)
2400    return;
2401
2402  typedef CodeCompleteConsumer::Result Result;
2403  ResultBuilder Results(*this, &ResultBuilder::IsType);
2404  Results.EnterNewScope();
2405
2406  // Add the names of overloadable operators.
2407#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly)      \
2408  if (std::strcmp(Spelling, "?"))                                                  \
2409    Results.AddResult(Result(Spelling));
2410#include "clang/Basic/OperatorKinds.def"
2411
2412  // Add any type names visible from the current scope
2413  Results.allowNestedNameSpecifiers();
2414  CodeCompletionDeclConsumer Consumer(Results, CurContext);
2415  LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2416
2417  // Add any type specifiers
2418  AddTypeSpecifierResults(getLangOptions(), Results);
2419  Results.ExitScope();
2420
2421  if (CodeCompleter->includeMacros())
2422    AddMacroResults(PP, Results);
2423  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2424}
2425
2426// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
2427// true or false.
2428#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
2429static void AddObjCImplementationResults(const LangOptions &LangOpts,
2430                                         ResultBuilder &Results,
2431                                         bool NeedAt) {
2432  typedef CodeCompleteConsumer::Result Result;
2433  // Since we have an implementation, we can end it.
2434  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
2435
2436  CodeCompletionString *Pattern = 0;
2437  if (LangOpts.ObjC2) {
2438    // @dynamic
2439    Pattern = new CodeCompletionString;
2440    Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
2441    Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2442    Pattern->AddPlaceholderChunk("property");
2443    Results.AddResult(Result(Pattern));
2444
2445    // @synthesize
2446    Pattern = new CodeCompletionString;
2447    Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
2448    Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2449    Pattern->AddPlaceholderChunk("property");
2450    Results.AddResult(Result(Pattern));
2451  }
2452}
2453
2454static void AddObjCInterfaceResults(const LangOptions &LangOpts,
2455                                    ResultBuilder &Results,
2456                                    bool NeedAt) {
2457  typedef CodeCompleteConsumer::Result Result;
2458
2459  // Since we have an interface or protocol, we can end it.
2460  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
2461
2462  if (LangOpts.ObjC2) {
2463    // @property
2464    Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
2465
2466    // @required
2467    Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
2468
2469    // @optional
2470    Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
2471  }
2472}
2473
2474static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
2475  typedef CodeCompleteConsumer::Result Result;
2476  CodeCompletionString *Pattern = 0;
2477
2478  // @class name ;
2479  Pattern = new CodeCompletionString;
2480  Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
2481  Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2482  Pattern->AddPlaceholderChunk("identifier");
2483  Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
2484  Results.AddResult(Result(Pattern));
2485
2486  // @interface name
2487  // FIXME: Could introduce the whole pattern, including superclasses and
2488  // such.
2489  Pattern = new CodeCompletionString;
2490  Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
2491  Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2492  Pattern->AddPlaceholderChunk("class");
2493  Results.AddResult(Result(Pattern));
2494
2495  // @protocol name
2496  Pattern = new CodeCompletionString;
2497  Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
2498  Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2499  Pattern->AddPlaceholderChunk("protocol");
2500  Results.AddResult(Result(Pattern));
2501
2502  // @implementation name
2503  Pattern = new CodeCompletionString;
2504  Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
2505  Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2506  Pattern->AddPlaceholderChunk("class");
2507  Results.AddResult(Result(Pattern));
2508
2509  // @compatibility_alias name
2510  Pattern = new CodeCompletionString;
2511  Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
2512  Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2513  Pattern->AddPlaceholderChunk("alias");
2514  Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2515  Pattern->AddPlaceholderChunk("class");
2516  Results.AddResult(Result(Pattern));
2517}
2518
2519void Sema::CodeCompleteObjCAtDirective(Scope *S, DeclPtrTy ObjCImpDecl,
2520                                       bool InInterface) {
2521  typedef CodeCompleteConsumer::Result Result;
2522  ResultBuilder Results(*this);
2523  Results.EnterNewScope();
2524  if (ObjCImpDecl)
2525    AddObjCImplementationResults(getLangOptions(), Results, false);
2526  else if (InInterface)
2527    AddObjCInterfaceResults(getLangOptions(), Results, false);
2528  else
2529    AddObjCTopLevelResults(Results, false);
2530  Results.ExitScope();
2531  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2532}
2533
2534static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
2535  typedef CodeCompleteConsumer::Result Result;
2536  CodeCompletionString *Pattern = 0;
2537
2538  // @encode ( type-name )
2539  Pattern = new CodeCompletionString;
2540  Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
2541  Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2542  Pattern->AddPlaceholderChunk("type-name");
2543  Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2544  Results.AddResult(Result(Pattern));
2545
2546  // @protocol ( protocol-name )
2547  Pattern = new CodeCompletionString;
2548  Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
2549  Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2550  Pattern->AddPlaceholderChunk("protocol-name");
2551  Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2552  Results.AddResult(Result(Pattern));
2553
2554  // @selector ( selector )
2555  Pattern = new CodeCompletionString;
2556  Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
2557  Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2558  Pattern->AddPlaceholderChunk("selector");
2559  Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2560  Results.AddResult(Result(Pattern));
2561}
2562
2563static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
2564  typedef CodeCompleteConsumer::Result Result;
2565  CodeCompletionString *Pattern = 0;
2566
2567  // @try { statements } @catch ( declaration ) { statements } @finally
2568  //   { statements }
2569  Pattern = new CodeCompletionString;
2570  Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
2571  Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2572  Pattern->AddPlaceholderChunk("statements");
2573  Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2574  Pattern->AddTextChunk("@catch");
2575  Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2576  Pattern->AddPlaceholderChunk("parameter");
2577  Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2578  Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2579  Pattern->AddPlaceholderChunk("statements");
2580  Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2581  Pattern->AddTextChunk("@finally");
2582  Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2583  Pattern->AddPlaceholderChunk("statements");
2584  Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2585  Results.AddResult(Result(Pattern));
2586
2587  // @throw
2588  Pattern = new CodeCompletionString;
2589  Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
2590  Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2591  Pattern->AddPlaceholderChunk("expression");
2592  Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
2593  Results.AddResult(Result(Pattern));
2594
2595  // @synchronized ( expression ) { statements }
2596  Pattern = new CodeCompletionString;
2597  Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
2598  Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2599  Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2600  Pattern->AddPlaceholderChunk("expression");
2601  Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2602  Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2603  Pattern->AddPlaceholderChunk("statements");
2604  Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2605  Results.AddResult(Result(Pattern));
2606}
2607
2608static void AddObjCVisibilityResults(const LangOptions &LangOpts,
2609                                     ResultBuilder &Results,
2610                                     bool NeedAt) {
2611  typedef CodeCompleteConsumer::Result Result;
2612  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
2613  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
2614  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
2615  if (LangOpts.ObjC2)
2616    Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
2617}
2618
2619void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
2620  ResultBuilder Results(*this);
2621  Results.EnterNewScope();
2622  AddObjCVisibilityResults(getLangOptions(), Results, false);
2623  Results.ExitScope();
2624  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2625}
2626
2627void Sema::CodeCompleteObjCAtStatement(Scope *S) {
2628  ResultBuilder Results(*this);
2629  Results.EnterNewScope();
2630  AddObjCStatementResults(Results, false);
2631  AddObjCExpressionResults(Results, false);
2632  Results.ExitScope();
2633  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2634}
2635
2636void Sema::CodeCompleteObjCAtExpression(Scope *S) {
2637  ResultBuilder Results(*this);
2638  Results.EnterNewScope();
2639  AddObjCExpressionResults(Results, false);
2640  Results.ExitScope();
2641  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2642}
2643
2644/// \brief Determine whether the addition of the given flag to an Objective-C
2645/// property's attributes will cause a conflict.
2646static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
2647  // Check if we've already added this flag.
2648  if (Attributes & NewFlag)
2649    return true;
2650
2651  Attributes |= NewFlag;
2652
2653  // Check for collisions with "readonly".
2654  if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
2655      (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
2656                     ObjCDeclSpec::DQ_PR_assign |
2657                     ObjCDeclSpec::DQ_PR_copy |
2658                     ObjCDeclSpec::DQ_PR_retain)))
2659    return true;
2660
2661  // Check for more than one of { assign, copy, retain }.
2662  unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
2663                                             ObjCDeclSpec::DQ_PR_copy |
2664                                             ObjCDeclSpec::DQ_PR_retain);
2665  if (AssignCopyRetMask &&
2666      AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
2667      AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
2668      AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
2669    return true;
2670
2671  return false;
2672}
2673
2674void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
2675  if (!CodeCompleter)
2676    return;
2677
2678  unsigned Attributes = ODS.getPropertyAttributes();
2679
2680  typedef CodeCompleteConsumer::Result Result;
2681  ResultBuilder Results(*this);
2682  Results.EnterNewScope();
2683  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
2684    Results.AddResult(CodeCompleteConsumer::Result("readonly"));
2685  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
2686    Results.AddResult(CodeCompleteConsumer::Result("assign"));
2687  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
2688    Results.AddResult(CodeCompleteConsumer::Result("readwrite"));
2689  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
2690    Results.AddResult(CodeCompleteConsumer::Result("retain"));
2691  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
2692    Results.AddResult(CodeCompleteConsumer::Result("copy"));
2693  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
2694    Results.AddResult(CodeCompleteConsumer::Result("nonatomic"));
2695  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
2696    CodeCompletionString *Setter = new CodeCompletionString;
2697    Setter->AddTypedTextChunk("setter");
2698    Setter->AddTextChunk(" = ");
2699    Setter->AddPlaceholderChunk("method");
2700    Results.AddResult(CodeCompleteConsumer::Result(Setter));
2701  }
2702  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
2703    CodeCompletionString *Getter = new CodeCompletionString;
2704    Getter->AddTypedTextChunk("getter");
2705    Getter->AddTextChunk(" = ");
2706    Getter->AddPlaceholderChunk("method");
2707    Results.AddResult(CodeCompleteConsumer::Result(Getter));
2708  }
2709  Results.ExitScope();
2710  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2711}
2712
2713/// \brief Descripts the kind of Objective-C method that we want to find
2714/// via code completion.
2715enum ObjCMethodKind {
2716  MK_Any, //< Any kind of method, provided it means other specified criteria.
2717  MK_ZeroArgSelector, //< Zero-argument (unary) selector.
2718  MK_OneArgSelector //< One-argument selector.
2719};
2720
2721static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
2722                                   ObjCMethodKind WantKind,
2723                                   IdentifierInfo **SelIdents,
2724                                   unsigned NumSelIdents) {
2725  Selector Sel = Method->getSelector();
2726  if (NumSelIdents > Sel.getNumArgs())
2727    return false;
2728
2729  switch (WantKind) {
2730  case MK_Any:             break;
2731  case MK_ZeroArgSelector: return Sel.isUnarySelector();
2732  case MK_OneArgSelector:  return Sel.getNumArgs() == 1;
2733  }
2734
2735  for (unsigned I = 0; I != NumSelIdents; ++I)
2736    if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
2737      return false;
2738
2739  return true;
2740}
2741
2742/// \brief Add all of the Objective-C methods in the given Objective-C
2743/// container to the set of results.
2744///
2745/// The container will be a class, protocol, category, or implementation of
2746/// any of the above. This mether will recurse to include methods from
2747/// the superclasses of classes along with their categories, protocols, and
2748/// implementations.
2749///
2750/// \param Container the container in which we'll look to find methods.
2751///
2752/// \param WantInstance whether to add instance methods (only); if false, this
2753/// routine will add factory methods (only).
2754///
2755/// \param CurContext the context in which we're performing the lookup that
2756/// finds methods.
2757///
2758/// \param Results the structure into which we'll add results.
2759static void AddObjCMethods(ObjCContainerDecl *Container,
2760                           bool WantInstanceMethods,
2761                           ObjCMethodKind WantKind,
2762                           IdentifierInfo **SelIdents,
2763                           unsigned NumSelIdents,
2764                           DeclContext *CurContext,
2765                           ResultBuilder &Results) {
2766  typedef CodeCompleteConsumer::Result Result;
2767  for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
2768                                       MEnd = Container->meth_end();
2769       M != MEnd; ++M) {
2770    if ((*M)->isInstanceMethod() == WantInstanceMethods) {
2771      // Check whether the selector identifiers we've been given are a
2772      // subset of the identifiers for this particular method.
2773      if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
2774        continue;
2775
2776      Result R = Result(*M, 0);
2777      R.StartParameter = NumSelIdents;
2778      R.AllParametersAreInformative = (WantKind != MK_Any);
2779      Results.MaybeAddResult(R, CurContext);
2780    }
2781  }
2782
2783  ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
2784  if (!IFace)
2785    return;
2786
2787  // Add methods in protocols.
2788  const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
2789  for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
2790                                            E = Protocols.end();
2791       I != E; ++I)
2792    AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
2793                   CurContext, Results);
2794
2795  // Add methods in categories.
2796  for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
2797       CatDecl = CatDecl->getNextClassCategory()) {
2798    AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
2799                   NumSelIdents, CurContext, Results);
2800
2801    // Add a categories protocol methods.
2802    const ObjCList<ObjCProtocolDecl> &Protocols
2803      = CatDecl->getReferencedProtocols();
2804    for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
2805                                              E = Protocols.end();
2806         I != E; ++I)
2807      AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
2808                     NumSelIdents, CurContext, Results);
2809
2810    // Add methods in category implementations.
2811    if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
2812      AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
2813                     NumSelIdents, CurContext, Results);
2814  }
2815
2816  // Add methods in superclass.
2817  if (IFace->getSuperClass())
2818    AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
2819                   SelIdents, NumSelIdents, CurContext, Results);
2820
2821  // Add methods in our implementation, if any.
2822  if (ObjCImplementationDecl *Impl = IFace->getImplementation())
2823    AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
2824                   NumSelIdents, CurContext, Results);
2825}
2826
2827
2828void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
2829                                          DeclPtrTy *Methods,
2830                                          unsigned NumMethods) {
2831  typedef CodeCompleteConsumer::Result Result;
2832
2833  // Try to find the interface where getters might live.
2834  ObjCInterfaceDecl *Class
2835    = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
2836  if (!Class) {
2837    if (ObjCCategoryDecl *Category
2838          = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
2839      Class = Category->getClassInterface();
2840
2841    if (!Class)
2842      return;
2843  }
2844
2845  // Find all of the potential getters.
2846  ResultBuilder Results(*this);
2847  Results.EnterNewScope();
2848
2849  // FIXME: We need to do this because Objective-C methods don't get
2850  // pushed into DeclContexts early enough. Argh!
2851  for (unsigned I = 0; I != NumMethods; ++I) {
2852    if (ObjCMethodDecl *Method
2853            = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
2854      if (Method->isInstanceMethod() &&
2855          isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
2856        Result R = Result(Method, 0);
2857        R.AllParametersAreInformative = true;
2858        Results.MaybeAddResult(R, CurContext);
2859      }
2860  }
2861
2862  AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
2863  Results.ExitScope();
2864  HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
2865}
2866
2867void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
2868                                          DeclPtrTy *Methods,
2869                                          unsigned NumMethods) {
2870  typedef CodeCompleteConsumer::Result Result;
2871
2872  // Try to find the interface where setters might live.
2873  ObjCInterfaceDecl *Class
2874    = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
2875  if (!Class) {
2876    if (ObjCCategoryDecl *Category
2877          = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
2878      Class = Category->getClassInterface();
2879
2880    if (!Class)
2881      return;
2882  }
2883
2884  // Find all of the potential getters.
2885  ResultBuilder Results(*this);
2886  Results.EnterNewScope();
2887
2888  // FIXME: We need to do this because Objective-C methods don't get
2889  // pushed into DeclContexts early enough. Argh!
2890  for (unsigned I = 0; I != NumMethods; ++I) {
2891    if (ObjCMethodDecl *Method
2892            = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
2893      if (Method->isInstanceMethod() &&
2894          isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
2895        Result R = Result(Method, 0);
2896        R.AllParametersAreInformative = true;
2897        Results.MaybeAddResult(R, CurContext);
2898      }
2899  }
2900
2901  AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
2902
2903  Results.ExitScope();
2904  HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
2905}
2906
2907void Sema::CodeCompleteObjCClassMessage(Scope *S, IdentifierInfo *FName,
2908                                        SourceLocation FNameLoc,
2909                                        IdentifierInfo **SelIdents,
2910                                        unsigned NumSelIdents) {
2911  typedef CodeCompleteConsumer::Result Result;
2912  ObjCInterfaceDecl *CDecl = 0;
2913
2914  if (FName->isStr("super")) {
2915    // We're sending a message to "super".
2916    if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
2917      // Figure out which interface we're in.
2918      CDecl = CurMethod->getClassInterface();
2919      if (!CDecl)
2920        return;
2921
2922      // Find the superclass of this class.
2923      CDecl = CDecl->getSuperClass();
2924      if (!CDecl)
2925        return;
2926
2927      if (CurMethod->isInstanceMethod()) {
2928        // We are inside an instance method, which means that the message
2929        // send [super ...] is actually calling an instance method on the
2930        // current object. Build the super expression and handle this like
2931        // an instance method.
2932        QualType SuperTy = Context.getObjCInterfaceType(CDecl);
2933        SuperTy = Context.getObjCObjectPointerType(SuperTy);
2934        OwningExprResult Super
2935          = Owned(new (Context) ObjCSuperExpr(FNameLoc, SuperTy));
2936        return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
2937                                               SelIdents, NumSelIdents);
2938      }
2939
2940      // Okay, we're calling a factory method in our superclass.
2941    }
2942  }
2943
2944  // If the given name refers to an interface type, retrieve the
2945  // corresponding declaration.
2946  if (!CDecl)
2947    if (TypeTy *Ty = getTypeName(*FName, FNameLoc, S, 0, false)) {
2948      QualType T = GetTypeFromParser(Ty, 0);
2949      if (!T.isNull())
2950        if (const ObjCInterfaceType *Interface = T->getAs<ObjCInterfaceType>())
2951          CDecl = Interface->getDecl();
2952    }
2953
2954  if (!CDecl && FName->isStr("super")) {
2955    // "super" may be the name of a variable, in which case we are
2956    // probably calling an instance method.
2957    CXXScopeSpec SS;
2958    UnqualifiedId id;
2959    id.setIdentifier(FName, FNameLoc);
2960    OwningExprResult Super = ActOnIdExpression(S, SS, id, false, false);
2961    return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
2962                                           SelIdents, NumSelIdents);
2963  }
2964
2965  // Add all of the factory methods in this Objective-C class, its protocols,
2966  // superclasses, categories, implementation, etc.
2967  ResultBuilder Results(*this);
2968  Results.EnterNewScope();
2969  AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
2970                 Results);
2971  Results.ExitScope();
2972
2973  // This also suppresses remaining diagnostics.
2974  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2975}
2976
2977void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
2978                                           IdentifierInfo **SelIdents,
2979                                           unsigned NumSelIdents) {
2980  typedef CodeCompleteConsumer::Result Result;
2981
2982  Expr *RecExpr = static_cast<Expr *>(Receiver);
2983
2984  // If necessary, apply function/array conversion to the receiver.
2985  // C99 6.7.5.3p[7,8].
2986  DefaultFunctionArrayLvalueConversion(RecExpr);
2987  QualType ReceiverType = RecExpr->getType();
2988
2989  if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType()) {
2990    // FIXME: We're messaging 'id'. Do we actually want to look up every method
2991    // in the universe?
2992    return;
2993  }
2994
2995  // Build the set of methods we can see.
2996  ResultBuilder Results(*this);
2997  Results.EnterNewScope();
2998
2999  // Handle messages to Class. This really isn't a message to an instance
3000  // method, so we treat it the same way we would treat a message send to a
3001  // class method.
3002  if (ReceiverType->isObjCClassType() ||
3003      ReceiverType->isObjCQualifiedClassType()) {
3004    if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3005      if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
3006        AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
3007                       CurContext, Results);
3008    }
3009  }
3010  // Handle messages to a qualified ID ("id<foo>").
3011  else if (const ObjCObjectPointerType *QualID
3012             = ReceiverType->getAsObjCQualifiedIdType()) {
3013    // Search protocols for instance methods.
3014    for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
3015                                              E = QualID->qual_end();
3016         I != E; ++I)
3017      AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3018                     Results);
3019  }
3020  // Handle messages to a pointer to interface type.
3021  else if (const ObjCObjectPointerType *IFacePtr
3022                              = ReceiverType->getAsObjCInterfacePointerType()) {
3023    // Search the class, its superclasses, etc., for instance methods.
3024    AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
3025                   NumSelIdents, CurContext, Results);
3026
3027    // Search protocols for instance methods.
3028    for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
3029         E = IFacePtr->qual_end();
3030         I != E; ++I)
3031      AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3032                     Results);
3033  }
3034
3035  Results.ExitScope();
3036  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3037}
3038
3039/// \brief Add all of the protocol declarations that we find in the given
3040/// (translation unit) context.
3041static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
3042                               bool OnlyForwardDeclarations,
3043                               ResultBuilder &Results) {
3044  typedef CodeCompleteConsumer::Result Result;
3045
3046  for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3047                               DEnd = Ctx->decls_end();
3048       D != DEnd; ++D) {
3049    // Record any protocols we find.
3050    if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
3051      if (!OnlyForwardDeclarations || Proto->isForwardDecl())
3052        Results.AddResult(Result(Proto, 0), CurContext, 0, false);
3053
3054    // Record any forward-declared protocols we find.
3055    if (ObjCForwardProtocolDecl *Forward
3056          = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
3057      for (ObjCForwardProtocolDecl::protocol_iterator
3058             P = Forward->protocol_begin(),
3059             PEnd = Forward->protocol_end();
3060           P != PEnd; ++P)
3061        if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
3062          Results.AddResult(Result(*P, 0), CurContext, 0, false);
3063    }
3064  }
3065}
3066
3067void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
3068                                              unsigned NumProtocols) {
3069  ResultBuilder Results(*this);
3070  Results.EnterNewScope();
3071
3072  // Tell the result set to ignore all of the protocols we have
3073  // already seen.
3074  for (unsigned I = 0; I != NumProtocols; ++I)
3075    if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first))
3076      Results.Ignore(Protocol);
3077
3078  // Add all protocols.
3079  AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
3080                     Results);
3081
3082  Results.ExitScope();
3083  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3084}
3085
3086void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
3087  ResultBuilder Results(*this);
3088  Results.EnterNewScope();
3089
3090  // Add all protocols.
3091  AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
3092                     Results);
3093
3094  Results.ExitScope();
3095  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3096}
3097
3098/// \brief Add all of the Objective-C interface declarations that we find in
3099/// the given (translation unit) context.
3100static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
3101                                bool OnlyForwardDeclarations,
3102                                bool OnlyUnimplemented,
3103                                ResultBuilder &Results) {
3104  typedef CodeCompleteConsumer::Result Result;
3105
3106  for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3107                               DEnd = Ctx->decls_end();
3108       D != DEnd; ++D) {
3109    // Record any interfaces we find.
3110    if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
3111      if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
3112          (!OnlyUnimplemented || !Class->getImplementation()))
3113        Results.AddResult(Result(Class, 0), CurContext, 0, false);
3114
3115    // Record any forward-declared interfaces we find.
3116    if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
3117      for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
3118           C != CEnd; ++C)
3119        if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
3120            (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
3121          Results.AddResult(Result(C->getInterface(), 0), CurContext,
3122                            0, false);
3123    }
3124  }
3125}
3126
3127void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
3128  ResultBuilder Results(*this);
3129  Results.EnterNewScope();
3130
3131  // Add all classes.
3132  AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
3133                      false, Results);
3134
3135  Results.ExitScope();
3136  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3137}
3138
3139void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName) {
3140  ResultBuilder Results(*this);
3141  Results.EnterNewScope();
3142
3143  // Make sure that we ignore the class we're currently defining.
3144  NamedDecl *CurClass
3145    = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
3146  if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
3147    Results.Ignore(CurClass);
3148
3149  // Add all classes.
3150  AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3151                      false, Results);
3152
3153  Results.ExitScope();
3154  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3155}
3156
3157void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
3158  ResultBuilder Results(*this);
3159  Results.EnterNewScope();
3160
3161  // Add all unimplemented classes.
3162  AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3163                      true, Results);
3164
3165  Results.ExitScope();
3166  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3167}
3168
3169void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
3170                                             IdentifierInfo *ClassName) {
3171  typedef CodeCompleteConsumer::Result Result;
3172
3173  ResultBuilder Results(*this);
3174
3175  // Ignore any categories we find that have already been implemented by this
3176  // interface.
3177  llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3178  NamedDecl *CurClass
3179    = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
3180  if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
3181    for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3182         Category = Category->getNextClassCategory())
3183      CategoryNames.insert(Category->getIdentifier());
3184
3185  // Add all of the categories we know about.
3186  Results.EnterNewScope();
3187  TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3188  for (DeclContext::decl_iterator D = TU->decls_begin(),
3189                               DEnd = TU->decls_end();
3190       D != DEnd; ++D)
3191    if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
3192      if (CategoryNames.insert(Category->getIdentifier()))
3193        Results.AddResult(Result(Category, 0), CurContext, 0, false);
3194  Results.ExitScope();
3195
3196  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3197}
3198
3199void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
3200                                                  IdentifierInfo *ClassName) {
3201  typedef CodeCompleteConsumer::Result Result;
3202
3203  // Find the corresponding interface. If we couldn't find the interface, the
3204  // program itself is ill-formed. However, we'll try to be helpful still by
3205  // providing the list of all of the categories we know about.
3206  NamedDecl *CurClass
3207    = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
3208  ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
3209  if (!Class)
3210    return CodeCompleteObjCInterfaceCategory(S, ClassName);
3211
3212  ResultBuilder Results(*this);
3213
3214  // Add all of the categories that have have corresponding interface
3215  // declarations in this class and any of its superclasses, except for
3216  // already-implemented categories in the class itself.
3217  llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3218  Results.EnterNewScope();
3219  bool IgnoreImplemented = true;
3220  while (Class) {
3221    for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3222         Category = Category->getNextClassCategory())
3223      if ((!IgnoreImplemented || !Category->getImplementation()) &&
3224          CategoryNames.insert(Category->getIdentifier()))
3225        Results.AddResult(Result(Category, 0), CurContext, 0, false);
3226
3227    Class = Class->getSuperClass();
3228    IgnoreImplemented = false;
3229  }
3230  Results.ExitScope();
3231
3232  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3233}
3234
3235void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
3236  typedef CodeCompleteConsumer::Result Result;
3237  ResultBuilder Results(*this);
3238
3239  // Figure out where this @synthesize lives.
3240  ObjCContainerDecl *Container
3241    = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3242  if (!Container ||
3243      (!isa<ObjCImplementationDecl>(Container) &&
3244       !isa<ObjCCategoryImplDecl>(Container)))
3245    return;
3246
3247  // Ignore any properties that have already been implemented.
3248  for (DeclContext::decl_iterator D = Container->decls_begin(),
3249                               DEnd = Container->decls_end();
3250       D != DEnd; ++D)
3251    if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
3252      Results.Ignore(PropertyImpl->getPropertyDecl());
3253
3254  // Add any properties that we find.
3255  Results.EnterNewScope();
3256  if (ObjCImplementationDecl *ClassImpl
3257        = dyn_cast<ObjCImplementationDecl>(Container))
3258    AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
3259                      Results);
3260  else
3261    AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
3262                      false, CurContext, Results);
3263  Results.ExitScope();
3264
3265  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3266}
3267
3268void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
3269                                                  IdentifierInfo *PropertyName,
3270                                                  DeclPtrTy ObjCImpDecl) {
3271  typedef CodeCompleteConsumer::Result Result;
3272  ResultBuilder Results(*this);
3273
3274  // Figure out where this @synthesize lives.
3275  ObjCContainerDecl *Container
3276    = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3277  if (!Container ||
3278      (!isa<ObjCImplementationDecl>(Container) &&
3279       !isa<ObjCCategoryImplDecl>(Container)))
3280    return;
3281
3282  // Figure out which interface we're looking into.
3283  ObjCInterfaceDecl *Class = 0;
3284  if (ObjCImplementationDecl *ClassImpl
3285                                 = dyn_cast<ObjCImplementationDecl>(Container))
3286    Class = ClassImpl->getClassInterface();
3287  else
3288    Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
3289                                                          ->getClassInterface();
3290
3291  // Add all of the instance variables in this class and its superclasses.
3292  Results.EnterNewScope();
3293  for(; Class; Class = Class->getSuperClass()) {
3294    // FIXME: We could screen the type of each ivar for compatibility with
3295    // the property, but is that being too paternal?
3296    for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
3297                                       IVarEnd = Class->ivar_end();
3298         IVar != IVarEnd; ++IVar)
3299      Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
3300  }
3301  Results.ExitScope();
3302
3303  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3304}
3305