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