SemaCodeComplete.cpp revision e213bc51ec27cc46986ddfe81dee750f7a1592e8
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 "clang/Sema/CodeCompleteConsumer.h"
15#include "clang/AST/ExprCXX.h"
16#include "clang/AST/ExprObjC.h"
17#include "clang/Lex/MacroInfo.h"
18#include "clang/Lex/Preprocessor.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/StringExtras.h"
21#include <list>
22#include <map>
23#include <vector>
24
25using namespace clang;
26
27namespace {
28  /// \brief A container of code-completion results.
29  class ResultBuilder {
30  public:
31    /// \brief The type of a name-lookup filter, which can be provided to the
32    /// name-lookup routines to specify which declarations should be included in
33    /// the result set (when it returns true) and which declarations should be
34    /// filtered out (returns false).
35    typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
36
37    typedef CodeCompleteConsumer::Result Result;
38
39  private:
40    /// \brief The actual results we have found.
41    std::vector<Result> Results;
42
43    /// \brief A record of all of the declarations we have found and placed
44    /// into the result set, used to ensure that no declaration ever gets into
45    /// the result set twice.
46    llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
47
48    typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
49
50    /// \brief An entry in the shadow map, which is optimized to store
51    /// a single (declaration, index) mapping (the common case) but
52    /// can also store a list of (declaration, index) mappings.
53    class ShadowMapEntry {
54      typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
55
56      /// \brief Contains either the solitary NamedDecl * or a vector
57      /// of (declaration, index) pairs.
58      llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
59
60      /// \brief When the entry contains a single declaration, this is
61      /// the index associated with that entry.
62      unsigned SingleDeclIndex;
63
64    public:
65      ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
66
67      void Add(NamedDecl *ND, unsigned Index) {
68        if (DeclOrVector.isNull()) {
69          // 0 - > 1 elements: just set the single element information.
70          DeclOrVector = ND;
71          SingleDeclIndex = Index;
72          return;
73        }
74
75        if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
76          // 1 -> 2 elements: create the vector of results and push in the
77          // existing declaration.
78          DeclIndexPairVector *Vec = new DeclIndexPairVector;
79          Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
80          DeclOrVector = Vec;
81        }
82
83        // Add the new element to the end of the vector.
84        DeclOrVector.get<DeclIndexPairVector*>()->push_back(
85                                                    DeclIndexPair(ND, Index));
86      }
87
88      void Destroy() {
89        if (DeclIndexPairVector *Vec
90              = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
91          delete Vec;
92          DeclOrVector = ((NamedDecl *)0);
93        }
94      }
95
96      // Iteration.
97      class iterator;
98      iterator begin() const;
99      iterator end() const;
100    };
101
102    /// \brief A mapping from declaration names to the declarations that have
103    /// this name within a particular scope and their index within the list of
104    /// results.
105    typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
106
107    /// \brief The semantic analysis object for which results are being
108    /// produced.
109    Sema &SemaRef;
110
111    /// \brief If non-NULL, a filter function used to remove any code-completion
112    /// results that are not desirable.
113    LookupFilter Filter;
114
115    /// \brief A list of shadow maps, which is used to model name hiding at
116    /// different levels of, e.g., the inheritance hierarchy.
117    std::list<ShadowMap> ShadowMaps;
118
119  public:
120    explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
121      : SemaRef(SemaRef), Filter(Filter) { }
122
123    /// \brief Set the filter used for code-completion results.
124    void setFilter(LookupFilter Filter) {
125      this->Filter = Filter;
126    }
127
128    typedef std::vector<Result>::iterator iterator;
129    iterator begin() { return Results.begin(); }
130    iterator end() { return Results.end(); }
131
132    Result *data() { return Results.empty()? 0 : &Results.front(); }
133    unsigned size() const { return Results.size(); }
134    bool empty() const { return Results.empty(); }
135
136    /// \brief Add a new result to this result set (if it isn't already in one
137    /// of the shadow maps), or replace an existing result (for, e.g., a
138    /// redeclaration).
139    ///
140    /// \param R the result to add (if it is unique).
141    ///
142    /// \param R the context in which this result will be named.
143    void MaybeAddResult(Result R, DeclContext *CurContext = 0);
144
145    /// \brief Enter into a new scope.
146    void EnterNewScope();
147
148    /// \brief Exit from the current scope.
149    void ExitScope();
150
151    /// \brief Ignore this declaration, if it is seen again.
152    void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
153
154    /// \name Name lookup predicates
155    ///
156    /// These predicates can be passed to the name lookup functions to filter the
157    /// results of name lookup. All of the predicates have the same type, so that
158    ///
159    //@{
160    bool IsOrdinaryName(NamedDecl *ND) const;
161    bool IsNestedNameSpecifier(NamedDecl *ND) const;
162    bool IsEnum(NamedDecl *ND) const;
163    bool IsClassOrStruct(NamedDecl *ND) const;
164    bool IsUnion(NamedDecl *ND) const;
165    bool IsNamespace(NamedDecl *ND) const;
166    bool IsNamespaceOrAlias(NamedDecl *ND) const;
167    bool IsType(NamedDecl *ND) const;
168    bool IsMember(NamedDecl *ND) const;
169    //@}
170  };
171}
172
173class ResultBuilder::ShadowMapEntry::iterator {
174  llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
175  unsigned SingleDeclIndex;
176
177public:
178  typedef DeclIndexPair value_type;
179  typedef value_type reference;
180  typedef std::ptrdiff_t difference_type;
181  typedef std::input_iterator_tag iterator_category;
182
183  class pointer {
184    DeclIndexPair Value;
185
186  public:
187    pointer(const DeclIndexPair &Value) : Value(Value) { }
188
189    const DeclIndexPair *operator->() const {
190      return &Value;
191    }
192  };
193
194  iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
195
196  iterator(NamedDecl *SingleDecl, unsigned Index)
197    : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
198
199  iterator(const DeclIndexPair *Iterator)
200    : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
201
202  iterator &operator++() {
203    if (DeclOrIterator.is<NamedDecl *>()) {
204      DeclOrIterator = (NamedDecl *)0;
205      SingleDeclIndex = 0;
206      return *this;
207    }
208
209    const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
210    ++I;
211    DeclOrIterator = I;
212    return *this;
213  }
214
215  iterator operator++(int) {
216    iterator tmp(*this);
217    ++(*this);
218    return tmp;
219  }
220
221  reference operator*() const {
222    if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
223      return reference(ND, SingleDeclIndex);
224
225    return *DeclOrIterator.get<DeclIndexPair*>();
226  }
227
228  pointer operator->() const {
229    return pointer(**this);
230  }
231
232  friend bool operator==(const iterator &X, const iterator &Y) {
233    return X.DeclOrIterator == Y.DeclOrIterator &&
234      X.SingleDeclIndex == Y.SingleDeclIndex;
235  }
236
237  friend bool operator!=(const iterator &X, const iterator &Y) {
238    return X.DeclOrIterator != Y.DeclOrIterator ||
239      X.SingleDeclIndex != Y.SingleDeclIndex;
240  }
241};
242
243namespace llvm {
244  template<>
245  struct DenseMapInfo<ResultBuilder::ShadowMapEntry> {
246    static bool isPod() { return false; }
247  };
248}
249
250ResultBuilder::ShadowMapEntry::iterator
251ResultBuilder::ShadowMapEntry::begin() const {
252  if (DeclOrVector.isNull())
253    return iterator();
254
255  if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
256    return iterator(ND, SingleDeclIndex);
257
258  return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
259}
260
261ResultBuilder::ShadowMapEntry::iterator
262ResultBuilder::ShadowMapEntry::end() const {
263  if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
264    return iterator();
265
266  return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
267}
268
269/// \brief Determines whether the given hidden result could be found with
270/// some extra work, e.g., by qualifying the name.
271///
272/// \param Hidden the declaration that is hidden by the currenly \p Visible
273/// declaration.
274///
275/// \param Visible the declaration with the same name that is already visible.
276///
277/// \returns true if the hidden result can be found by some mechanism,
278/// false otherwise.
279static bool canHiddenResultBeFound(const LangOptions &LangOpts,
280                                   NamedDecl *Hidden, NamedDecl *Visible) {
281  // In C, there is no way to refer to a hidden name.
282  if (!LangOpts.CPlusPlus)
283    return false;
284
285  DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
286
287  // There is no way to qualify a name declared in a function or method.
288  if (HiddenCtx->isFunctionOrMethod())
289    return false;
290
291  return HiddenCtx != Visible->getDeclContext()->getLookupContext();
292}
293
294/// \brief Compute the qualification required to get from the current context
295/// (\p CurContext) to the target context (\p TargetContext).
296///
297/// \param Context the AST context in which the qualification will be used.
298///
299/// \param CurContext the context where an entity is being named, which is
300/// typically based on the current scope.
301///
302/// \param TargetContext the context in which the named entity actually
303/// resides.
304///
305/// \returns a nested name specifier that refers into the target context, or
306/// NULL if no qualification is needed.
307static NestedNameSpecifier *
308getRequiredQualification(ASTContext &Context,
309                         DeclContext *CurContext,
310                         DeclContext *TargetContext) {
311  llvm::SmallVector<DeclContext *, 4> TargetParents;
312
313  for (DeclContext *CommonAncestor = TargetContext;
314       CommonAncestor && !CommonAncestor->Encloses(CurContext);
315       CommonAncestor = CommonAncestor->getLookupParent()) {
316    if (CommonAncestor->isTransparentContext() ||
317        CommonAncestor->isFunctionOrMethod())
318      continue;
319
320    TargetParents.push_back(CommonAncestor);
321  }
322
323  NestedNameSpecifier *Result = 0;
324  while (!TargetParents.empty()) {
325    DeclContext *Parent = TargetParents.back();
326    TargetParents.pop_back();
327
328    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
329      Result = NestedNameSpecifier::Create(Context, Result, Namespace);
330    else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
331      Result = NestedNameSpecifier::Create(Context, Result,
332                                           false,
333                                     Context.getTypeDeclType(TD).getTypePtr());
334    else
335      assert(Parent->isTranslationUnit());
336  }
337  return Result;
338}
339
340void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
341  assert(!ShadowMaps.empty() && "Must enter into a results scope");
342
343  if (R.Kind != Result::RK_Declaration) {
344    // For non-declaration results, just add the result.
345    Results.push_back(R);
346    return;
347  }
348
349  // Skip unnamed entities.
350  if (!R.Declaration->getDeclName())
351    return;
352
353  // Look through using declarations.
354  if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration))
355    MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
356                   CurContext);
357
358  Decl *CanonDecl = R.Declaration->getCanonicalDecl();
359  unsigned IDNS = CanonDecl->getIdentifierNamespace();
360
361  // Friend declarations and declarations introduced due to friends are never
362  // added as results.
363  if (isa<FriendDecl>(CanonDecl) ||
364      (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
365    return;
366
367  if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
368    // __va_list_tag is a freak of nature. Find it and skip it.
369    if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
370      return;
371
372    // Filter out names reserved for the implementation (C99 7.1.3,
373    // C++ [lib.global.names]). Users don't need to see those.
374    //
375    // FIXME: Add predicate for this.
376    if (Id->getLength() >= 2) {
377      const char *Name = Id->getNameStart();
378      if (Name[0] == '_' &&
379          (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
380        return;
381    }
382  }
383
384  // C++ constructors are never found by name lookup.
385  if (isa<CXXConstructorDecl>(CanonDecl))
386    return;
387
388  // Filter out any unwanted results.
389  if (Filter && !(this->*Filter)(R.Declaration))
390    return;
391
392  ShadowMap &SMap = ShadowMaps.back();
393  ShadowMapEntry::iterator I, IEnd;
394  ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
395  if (NamePos != SMap.end()) {
396    I = NamePos->second.begin();
397    IEnd = NamePos->second.end();
398  }
399
400  for (; I != IEnd; ++I) {
401    NamedDecl *ND = I->first;
402    unsigned Index = I->second;
403    if (ND->getCanonicalDecl() == CanonDecl) {
404      // This is a redeclaration. Always pick the newer declaration.
405      Results[Index].Declaration = R.Declaration;
406
407      // Pick the best rank of the two.
408      Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
409
410      // We're done.
411      return;
412    }
413  }
414
415  // This is a new declaration in this scope. However, check whether this
416  // declaration name is hidden by a similarly-named declaration in an outer
417  // scope.
418  std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
419  --SMEnd;
420  for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
421    ShadowMapEntry::iterator I, IEnd;
422    ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
423    if (NamePos != SM->end()) {
424      I = NamePos->second.begin();
425      IEnd = NamePos->second.end();
426    }
427    for (; I != IEnd; ++I) {
428      // A tag declaration does not hide a non-tag declaration.
429      if (I->first->getIdentifierNamespace() == Decl::IDNS_Tag &&
430          (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
431                   Decl::IDNS_ObjCProtocol)))
432        continue;
433
434      // Protocols are in distinct namespaces from everything else.
435      if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
436           || (IDNS & Decl::IDNS_ObjCProtocol)) &&
437          I->first->getIdentifierNamespace() != IDNS)
438        continue;
439
440      // The newly-added result is hidden by an entry in the shadow map.
441      if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
442                                 I->first)) {
443        // Note that this result was hidden.
444        R.Hidden = true;
445        R.QualifierIsInformative = false;
446
447        if (!R.Qualifier)
448          R.Qualifier = getRequiredQualification(SemaRef.Context,
449                                                 CurContext,
450                                              R.Declaration->getDeclContext());
451      } else {
452        // This result was hidden and cannot be found; don't bother adding
453        // it.
454        return;
455      }
456
457      break;
458    }
459  }
460
461  // Make sure that any given declaration only shows up in the result set once.
462  if (!AllDeclsFound.insert(CanonDecl))
463    return;
464
465  // If the filter is for nested-name-specifiers, then this result starts a
466  // nested-name-specifier.
467  if ((Filter == &ResultBuilder::IsNestedNameSpecifier) ||
468      (Filter == &ResultBuilder::IsMember &&
469       isa<CXXRecordDecl>(R.Declaration) &&
470       cast<CXXRecordDecl>(R.Declaration)->isInjectedClassName()))
471    R.StartsNestedNameSpecifier = true;
472
473  // If this result is supposed to have an informative qualifier, add one.
474  if (R.QualifierIsInformative && !R.Qualifier &&
475      !R.StartsNestedNameSpecifier) {
476    DeclContext *Ctx = R.Declaration->getDeclContext();
477    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
478      R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
479    else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
480      R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
481                             SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
482    else
483      R.QualifierIsInformative = false;
484  }
485
486  // Insert this result into the set of results and into the current shadow
487  // map.
488  SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
489  Results.push_back(R);
490}
491
492/// \brief Enter into a new scope.
493void ResultBuilder::EnterNewScope() {
494  ShadowMaps.push_back(ShadowMap());
495}
496
497/// \brief Exit from the current scope.
498void ResultBuilder::ExitScope() {
499  for (ShadowMap::iterator E = ShadowMaps.back().begin(),
500                        EEnd = ShadowMaps.back().end();
501       E != EEnd;
502       ++E)
503    E->second.Destroy();
504
505  ShadowMaps.pop_back();
506}
507
508/// \brief Determines whether this given declaration will be found by
509/// ordinary name lookup.
510bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
511  unsigned IDNS = Decl::IDNS_Ordinary;
512  if (SemaRef.getLangOptions().CPlusPlus)
513    IDNS |= Decl::IDNS_Tag;
514
515  return ND->getIdentifierNamespace() & IDNS;
516}
517
518/// \brief Determines whether the given declaration is suitable as the
519/// start of a C++ nested-name-specifier, e.g., a class or namespace.
520bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
521  // Allow us to find class templates, too.
522  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
523    ND = ClassTemplate->getTemplatedDecl();
524
525  return SemaRef.isAcceptableNestedNameSpecifier(ND);
526}
527
528/// \brief Determines whether the given declaration is an enumeration.
529bool ResultBuilder::IsEnum(NamedDecl *ND) const {
530  return isa<EnumDecl>(ND);
531}
532
533/// \brief Determines whether the given declaration is a class or struct.
534bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
535  // Allow us to find class templates, too.
536  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
537    ND = ClassTemplate->getTemplatedDecl();
538
539  if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
540    return RD->getTagKind() == TagDecl::TK_class ||
541    RD->getTagKind() == TagDecl::TK_struct;
542
543  return false;
544}
545
546/// \brief Determines whether the given declaration is a union.
547bool ResultBuilder::IsUnion(NamedDecl *ND) const {
548  // Allow us to find class templates, too.
549  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
550    ND = ClassTemplate->getTemplatedDecl();
551
552  if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
553    return RD->getTagKind() == TagDecl::TK_union;
554
555  return false;
556}
557
558/// \brief Determines whether the given declaration is a namespace.
559bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
560  return isa<NamespaceDecl>(ND);
561}
562
563/// \brief Determines whether the given declaration is a namespace or
564/// namespace alias.
565bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
566  return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
567}
568
569/// \brief Brief determines whether the given declaration is a namespace or
570/// namespace alias.
571bool ResultBuilder::IsType(NamedDecl *ND) const {
572  return isa<TypeDecl>(ND);
573}
574
575/// \brief Since every declaration found within a class is a member that we
576/// care about, always returns true. This predicate exists mostly to
577/// communicate to the result builder that we are performing a lookup for
578/// member access.
579bool ResultBuilder::IsMember(NamedDecl *ND) const {
580  return true;
581}
582
583// Find the next outer declaration context corresponding to this scope.
584static DeclContext *findOuterContext(Scope *S) {
585  for (S = S->getParent(); S; S = S->getParent())
586    if (S->getEntity())
587      return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
588
589  return 0;
590}
591
592/// \brief Collect the results of searching for members within the given
593/// declaration context.
594///
595/// \param Ctx the declaration context from which we will gather results.
596///
597/// \param Rank the rank given to results in this declaration context.
598///
599/// \param Visited the set of declaration contexts that have already been
600/// visited. Declaration contexts will only be visited once.
601///
602/// \param Results the result set that will be extended with any results
603/// found within this declaration context (and, for a C++ class, its bases).
604///
605/// \param InBaseClass whether we are in a base class.
606///
607/// \returns the next higher rank value, after considering all of the
608/// names within this declaration context.
609static unsigned CollectMemberLookupResults(DeclContext *Ctx,
610                                           unsigned Rank,
611                                           DeclContext *CurContext,
612                                 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
613                                           ResultBuilder &Results,
614                                           bool InBaseClass = false) {
615  // Make sure we don't visit the same context twice.
616  if (!Visited.insert(Ctx->getPrimaryContext()))
617    return Rank;
618
619  // Enumerate all of the results in this context.
620  typedef CodeCompleteConsumer::Result Result;
621  Results.EnterNewScope();
622  for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
623       CurCtx = CurCtx->getNextContext()) {
624    for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
625                                 DEnd = CurCtx->decls_end();
626         D != DEnd; ++D) {
627      if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
628        Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
629
630      // Visit transparent contexts inside this context.
631      if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
632        if (InnerCtx->isTransparentContext())
633          CollectMemberLookupResults(InnerCtx, Rank, CurContext, Visited,
634                                     Results, InBaseClass);
635      }
636    }
637  }
638
639  // Traverse the contexts of inherited classes.
640  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
641    for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
642                                         BEnd = Record->bases_end();
643         B != BEnd; ++B) {
644      QualType BaseType = B->getType();
645
646      // Don't look into dependent bases, because name lookup can't look
647      // there anyway.
648      if (BaseType->isDependentType())
649        continue;
650
651      const RecordType *Record = BaseType->getAs<RecordType>();
652      if (!Record)
653        continue;
654
655      // FIXME: It would be nice to be able to determine whether referencing
656      // a particular member would be ambiguous. For example, given
657      //
658      //   struct A { int member; };
659      //   struct B { int member; };
660      //   struct C : A, B { };
661      //
662      //   void f(C *c) { c->### }
663      // accessing 'member' would result in an ambiguity. However, code
664      // completion could be smart enough to qualify the member with the
665      // base class, e.g.,
666      //
667      //   c->B::member
668      //
669      // or
670      //
671      //   c->A::member
672
673      // Collect results from this base class (and its bases).
674      CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
675                                 Results, /*InBaseClass=*/true);
676    }
677  }
678
679  // FIXME: Look into base classes in Objective-C!
680
681  Results.ExitScope();
682  return Rank + 1;
683}
684
685/// \brief Collect the results of searching for members within the given
686/// declaration context.
687///
688/// \param Ctx the declaration context from which we will gather results.
689///
690/// \param InitialRank the initial rank given to results in this declaration
691/// context. Larger rank values will be used for, e.g., members found in
692/// base classes.
693///
694/// \param Results the result set that will be extended with any results
695/// found within this declaration context (and, for a C++ class, its bases).
696///
697/// \returns the next higher rank value, after considering all of the
698/// names within this declaration context.
699static unsigned CollectMemberLookupResults(DeclContext *Ctx,
700                                           unsigned InitialRank,
701                                           DeclContext *CurContext,
702                                           ResultBuilder &Results) {
703  llvm::SmallPtrSet<DeclContext *, 16> Visited;
704  return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
705                                    Results);
706}
707
708/// \brief Collect the results of searching for declarations within the given
709/// scope and its parent scopes.
710///
711/// \param S the scope in which we will start looking for declarations.
712///
713/// \param InitialRank the initial rank given to results in this scope.
714/// Larger rank values will be used for results found in parent scopes.
715///
716/// \param CurContext the context from which lookup results will be found.
717///
718/// \param Results the builder object that will receive each result.
719static unsigned CollectLookupResults(Scope *S,
720                                     TranslationUnitDecl *TranslationUnit,
721                                     unsigned InitialRank,
722                                     DeclContext *CurContext,
723                                     ResultBuilder &Results) {
724  if (!S)
725    return InitialRank;
726
727  // FIXME: Using directives!
728
729  unsigned NextRank = InitialRank;
730  Results.EnterNewScope();
731  if (S->getEntity() &&
732      !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
733    // Look into this scope's declaration context, along with any of its
734    // parent lookup contexts (e.g., enclosing classes), up to the point
735    // where we hit the context stored in the next outer scope.
736    DeclContext *Ctx = (DeclContext *)S->getEntity();
737    DeclContext *OuterCtx = findOuterContext(S);
738
739    for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
740         Ctx = Ctx->getLookupParent()) {
741      if (Ctx->isFunctionOrMethod())
742        continue;
743
744      NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
745                                            Results);
746    }
747  } else if (!S->getParent()) {
748    // Look into the translation unit scope. We walk through the translation
749    // unit's declaration context, because the Scope itself won't have all of
750    // the declarations if we loaded a precompiled header.
751    // FIXME: We would like the translation unit's Scope object to point to the
752    // translation unit, so we don't need this special "if" branch. However,
753    // doing so would force the normal C++ name-lookup code to look into the
754    // translation unit decl when the IdentifierInfo chains would suffice.
755    // Once we fix that problem (which is part of a more general "don't look
756    // in DeclContexts unless we have to" optimization), we can eliminate the
757    // TranslationUnit parameter entirely.
758    NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
759                                          CurContext, Results);
760  } else {
761    // Walk through the declarations in this Scope.
762    for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
763         D != DEnd; ++D) {
764      if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
765        Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
766                               CurContext);
767    }
768
769    NextRank = NextRank + 1;
770  }
771
772  // Lookup names in the parent scope.
773  NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
774                                  CurContext, Results);
775  Results.ExitScope();
776
777  return NextRank;
778}
779
780/// \brief Add type specifiers for the current language as keyword results.
781static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
782                                    ResultBuilder &Results) {
783  typedef CodeCompleteConsumer::Result Result;
784  Results.MaybeAddResult(Result("short", Rank));
785  Results.MaybeAddResult(Result("long", Rank));
786  Results.MaybeAddResult(Result("signed", Rank));
787  Results.MaybeAddResult(Result("unsigned", Rank));
788  Results.MaybeAddResult(Result("void", Rank));
789  Results.MaybeAddResult(Result("char", Rank));
790  Results.MaybeAddResult(Result("int", Rank));
791  Results.MaybeAddResult(Result("float", Rank));
792  Results.MaybeAddResult(Result("double", Rank));
793  Results.MaybeAddResult(Result("enum", Rank));
794  Results.MaybeAddResult(Result("struct", Rank));
795  Results.MaybeAddResult(Result("union", Rank));
796
797  if (LangOpts.C99) {
798    // C99-specific
799    Results.MaybeAddResult(Result("_Complex", Rank));
800    Results.MaybeAddResult(Result("_Imaginary", Rank));
801    Results.MaybeAddResult(Result("_Bool", Rank));
802  }
803
804  if (LangOpts.CPlusPlus) {
805    // C++-specific
806    Results.MaybeAddResult(Result("bool", Rank));
807    Results.MaybeAddResult(Result("class", Rank));
808    Results.MaybeAddResult(Result("typename", Rank));
809    Results.MaybeAddResult(Result("wchar_t", Rank));
810
811    if (LangOpts.CPlusPlus0x) {
812      Results.MaybeAddResult(Result("char16_t", Rank));
813      Results.MaybeAddResult(Result("char32_t", Rank));
814      Results.MaybeAddResult(Result("decltype", Rank));
815    }
816  }
817
818  // GNU extensions
819  if (LangOpts.GNUMode) {
820    // FIXME: Enable when we actually support decimal floating point.
821    //    Results.MaybeAddResult(Result("_Decimal32", Rank));
822    //    Results.MaybeAddResult(Result("_Decimal64", Rank));
823    //    Results.MaybeAddResult(Result("_Decimal128", Rank));
824    Results.MaybeAddResult(Result("typeof", Rank));
825  }
826}
827
828/// \brief Add function parameter chunks to the given code completion string.
829static void AddFunctionParameterChunks(ASTContext &Context,
830                                       FunctionDecl *Function,
831                                       CodeCompletionString *Result) {
832  typedef CodeCompletionString::Chunk Chunk;
833
834  CodeCompletionString *CCStr = Result;
835
836  for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
837    ParmVarDecl *Param = Function->getParamDecl(P);
838
839    if (Param->hasDefaultArg()) {
840      // When we see an optional default argument, put that argument and
841      // the remaining default arguments into a new, optional string.
842      CodeCompletionString *Opt = new CodeCompletionString;
843      CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
844      CCStr = Opt;
845    }
846
847    if (P != 0)
848      CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
849
850    // Format the placeholder string.
851    std::string PlaceholderStr;
852    if (Param->getIdentifier())
853      PlaceholderStr = Param->getIdentifier()->getName();
854
855    Param->getType().getAsStringInternal(PlaceholderStr,
856                                         Context.PrintingPolicy);
857
858    // Add the placeholder string.
859    CCStr->AddPlaceholderChunk(PlaceholderStr);
860  }
861
862  if (const FunctionProtoType *Proto
863        = Function->getType()->getAs<FunctionProtoType>())
864    if (Proto->isVariadic())
865      CCStr->AddPlaceholderChunk(", ...");
866}
867
868/// \brief Add template parameter chunks to the given code completion string.
869static void AddTemplateParameterChunks(ASTContext &Context,
870                                       TemplateDecl *Template,
871                                       CodeCompletionString *Result,
872                                       unsigned MaxParameters = 0) {
873  typedef CodeCompletionString::Chunk Chunk;
874
875  CodeCompletionString *CCStr = Result;
876  bool FirstParameter = true;
877
878  TemplateParameterList *Params = Template->getTemplateParameters();
879  TemplateParameterList::iterator PEnd = Params->end();
880  if (MaxParameters)
881    PEnd = Params->begin() + MaxParameters;
882  for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
883    bool HasDefaultArg = false;
884    std::string PlaceholderStr;
885    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
886      if (TTP->wasDeclaredWithTypename())
887        PlaceholderStr = "typename";
888      else
889        PlaceholderStr = "class";
890
891      if (TTP->getIdentifier()) {
892        PlaceholderStr += ' ';
893        PlaceholderStr += TTP->getIdentifier()->getName();
894      }
895
896      HasDefaultArg = TTP->hasDefaultArgument();
897    } else if (NonTypeTemplateParmDecl *NTTP
898               = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
899      if (NTTP->getIdentifier())
900        PlaceholderStr = NTTP->getIdentifier()->getName();
901      NTTP->getType().getAsStringInternal(PlaceholderStr,
902                                          Context.PrintingPolicy);
903      HasDefaultArg = NTTP->hasDefaultArgument();
904    } else {
905      assert(isa<TemplateTemplateParmDecl>(*P));
906      TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
907
908      // Since putting the template argument list into the placeholder would
909      // be very, very long, we just use an abbreviation.
910      PlaceholderStr = "template<...> class";
911      if (TTP->getIdentifier()) {
912        PlaceholderStr += ' ';
913        PlaceholderStr += TTP->getIdentifier()->getName();
914      }
915
916      HasDefaultArg = TTP->hasDefaultArgument();
917    }
918
919    if (HasDefaultArg) {
920      // When we see an optional default argument, put that argument and
921      // the remaining default arguments into a new, optional string.
922      CodeCompletionString *Opt = new CodeCompletionString;
923      CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
924      CCStr = Opt;
925    }
926
927    if (FirstParameter)
928      FirstParameter = false;
929    else
930      CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
931
932    // Add the placeholder string.
933    CCStr->AddPlaceholderChunk(PlaceholderStr);
934  }
935}
936
937/// \brief Add a qualifier to the given code-completion string, if the
938/// provided nested-name-specifier is non-NULL.
939void AddQualifierToCompletionString(CodeCompletionString *Result,
940                                    NestedNameSpecifier *Qualifier,
941                                    bool QualifierIsInformative,
942                                    ASTContext &Context) {
943  if (!Qualifier)
944    return;
945
946  std::string PrintedNNS;
947  {
948    llvm::raw_string_ostream OS(PrintedNNS);
949    Qualifier->print(OS, Context.PrintingPolicy);
950  }
951  if (QualifierIsInformative)
952    Result->AddInformativeChunk(PrintedNNS);
953  else
954    Result->AddTextChunk(PrintedNNS);
955}
956
957/// \brief If possible, create a new code completion string for the given
958/// result.
959///
960/// \returns Either a new, heap-allocated code completion string describing
961/// how to use this result, or NULL to indicate that the string or name of the
962/// result is all that is needed.
963CodeCompletionString *
964CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
965  typedef CodeCompletionString::Chunk Chunk;
966
967  if (Kind == RK_Pattern)
968    return Pattern->Clone();
969
970  CodeCompletionString *Result = new CodeCompletionString;
971
972  if (Kind == RK_Keyword) {
973    Result->AddTypedTextChunk(Keyword);
974    return Result;
975  }
976
977  if (Kind == RK_Macro) {
978    MacroInfo *MI = S.PP.getMacroInfo(Macro);
979    assert(MI && "Not a macro?");
980
981    Result->AddTypedTextChunk(Macro->getName());
982
983    if (!MI->isFunctionLike())
984      return Result;
985
986    // Format a function-like macro with placeholders for the arguments.
987    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
988    for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
989         A != AEnd; ++A) {
990      if (A != MI->arg_begin())
991        Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
992
993      if (!MI->isVariadic() || A != AEnd - 1) {
994        // Non-variadic argument.
995        Result->AddPlaceholderChunk((*A)->getName());
996        continue;
997      }
998
999      // Variadic argument; cope with the different between GNU and C99
1000      // variadic macros, providing a single placeholder for the rest of the
1001      // arguments.
1002      if ((*A)->isStr("__VA_ARGS__"))
1003        Result->AddPlaceholderChunk("...");
1004      else {
1005        std::string Arg = (*A)->getName();
1006        Arg += "...";
1007        Result->AddPlaceholderChunk(Arg);
1008      }
1009    }
1010    Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1011    return Result;
1012  }
1013
1014  assert(Kind == RK_Declaration && "Missed a macro kind?");
1015  NamedDecl *ND = Declaration;
1016
1017  if (StartsNestedNameSpecifier) {
1018    Result->AddTypedTextChunk(ND->getNameAsString());
1019    Result->AddTextChunk("::");
1020    return Result;
1021  }
1022
1023  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
1024    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1025                                   S.Context);
1026    Result->AddTypedTextChunk(Function->getNameAsString());
1027    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1028    AddFunctionParameterChunks(S.Context, Function, Result);
1029    Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1030    return Result;
1031  }
1032
1033  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
1034    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1035                                   S.Context);
1036    FunctionDecl *Function = FunTmpl->getTemplatedDecl();
1037    Result->AddTypedTextChunk(Function->getNameAsString());
1038
1039    // Figure out which template parameters are deduced (or have default
1040    // arguments).
1041    llvm::SmallVector<bool, 16> Deduced;
1042    S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
1043    unsigned LastDeducibleArgument;
1044    for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
1045         --LastDeducibleArgument) {
1046      if (!Deduced[LastDeducibleArgument - 1]) {
1047        // C++0x: Figure out if the template argument has a default. If so,
1048        // the user doesn't need to type this argument.
1049        // FIXME: We need to abstract template parameters better!
1050        bool HasDefaultArg = false;
1051        NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
1052                                                                      LastDeducibleArgument - 1);
1053        if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1054          HasDefaultArg = TTP->hasDefaultArgument();
1055        else if (NonTypeTemplateParmDecl *NTTP
1056                 = dyn_cast<NonTypeTemplateParmDecl>(Param))
1057          HasDefaultArg = NTTP->hasDefaultArgument();
1058        else {
1059          assert(isa<TemplateTemplateParmDecl>(Param));
1060          HasDefaultArg
1061            = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
1062        }
1063
1064        if (!HasDefaultArg)
1065          break;
1066      }
1067    }
1068
1069    if (LastDeducibleArgument) {
1070      // Some of the function template arguments cannot be deduced from a
1071      // function call, so we introduce an explicit template argument list
1072      // containing all of the arguments up to the first deducible argument.
1073      Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
1074      AddTemplateParameterChunks(S.Context, FunTmpl, Result,
1075                                 LastDeducibleArgument);
1076      Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
1077    }
1078
1079    // Add the function parameters
1080    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1081    AddFunctionParameterChunks(S.Context, Function, Result);
1082    Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1083    return Result;
1084  }
1085
1086  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
1087    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1088                                   S.Context);
1089    Result->AddTypedTextChunk(Template->getNameAsString());
1090    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
1091    AddTemplateParameterChunks(S.Context, Template, Result);
1092    Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
1093    return Result;
1094  }
1095
1096  if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
1097    Selector Sel = Method->getSelector();
1098    if (Sel.isUnarySelector()) {
1099      Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
1100      return Result;
1101    }
1102
1103    std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
1104    SelName += ':';
1105    if (StartParameter == 0)
1106      Result->AddTypedTextChunk(SelName);
1107    else {
1108      Result->AddInformativeChunk(SelName);
1109
1110      // If there is only one parameter, and we're past it, add an empty
1111      // typed-text chunk since there is nothing to type.
1112      if (Method->param_size() == 1)
1113        Result->AddTypedTextChunk("");
1114    }
1115    unsigned Idx = 0;
1116    for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
1117                                     PEnd = Method->param_end();
1118         P != PEnd; (void)++P, ++Idx) {
1119      if (Idx > 0) {
1120        std::string Keyword;
1121        if (Idx > StartParameter)
1122          Keyword = " ";
1123        if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
1124          Keyword += II->getName().str();
1125        Keyword += ":";
1126        if (Idx < StartParameter || AllParametersAreInformative) {
1127          Result->AddInformativeChunk(Keyword);
1128        } else if (Idx == StartParameter)
1129          Result->AddTypedTextChunk(Keyword);
1130        else
1131          Result->AddTextChunk(Keyword);
1132      }
1133
1134      // If we're before the starting parameter, skip the placeholder.
1135      if (Idx < StartParameter)
1136        continue;
1137
1138      std::string Arg;
1139      (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
1140      Arg = "(" + Arg + ")";
1141      if (IdentifierInfo *II = (*P)->getIdentifier())
1142        Arg += II->getName().str();
1143      if (AllParametersAreInformative)
1144        Result->AddInformativeChunk(Arg);
1145      else
1146        Result->AddPlaceholderChunk(Arg);
1147    }
1148
1149    return Result;
1150  }
1151
1152  if (Qualifier)
1153    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1154                                   S.Context);
1155
1156  Result->AddTypedTextChunk(ND->getNameAsString());
1157  return Result;
1158}
1159
1160CodeCompletionString *
1161CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
1162                                                          unsigned CurrentArg,
1163                                                               Sema &S) const {
1164  typedef CodeCompletionString::Chunk Chunk;
1165
1166  CodeCompletionString *Result = new CodeCompletionString;
1167  FunctionDecl *FDecl = getFunction();
1168  const FunctionProtoType *Proto
1169    = dyn_cast<FunctionProtoType>(getFunctionType());
1170  if (!FDecl && !Proto) {
1171    // Function without a prototype. Just give the return type and a
1172    // highlighted ellipsis.
1173    const FunctionType *FT = getFunctionType();
1174    Result->AddTextChunk(
1175            FT->getResultType().getAsString(S.Context.PrintingPolicy));
1176    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1177    Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1178    Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1179    return Result;
1180  }
1181
1182  if (FDecl)
1183    Result->AddTextChunk(FDecl->getNameAsString());
1184  else
1185    Result->AddTextChunk(
1186         Proto->getResultType().getAsString(S.Context.PrintingPolicy));
1187
1188  Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1189  unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
1190  for (unsigned I = 0; I != NumParams; ++I) {
1191    if (I)
1192      Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1193
1194    std::string ArgString;
1195    QualType ArgType;
1196
1197    if (FDecl) {
1198      ArgString = FDecl->getParamDecl(I)->getNameAsString();
1199      ArgType = FDecl->getParamDecl(I)->getOriginalType();
1200    } else {
1201      ArgType = Proto->getArgType(I);
1202    }
1203
1204    ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
1205
1206    if (I == CurrentArg)
1207      Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
1208                             ArgString));
1209    else
1210      Result->AddTextChunk(ArgString);
1211  }
1212
1213  if (Proto && Proto->isVariadic()) {
1214    Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1215    if (CurrentArg < NumParams)
1216      Result->AddTextChunk("...");
1217    else
1218      Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1219  }
1220  Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1221
1222  return Result;
1223}
1224
1225namespace {
1226  struct SortCodeCompleteResult {
1227    typedef CodeCompleteConsumer::Result Result;
1228
1229    bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
1230      Selector XSel = X.getObjCSelector();
1231      Selector YSel = Y.getObjCSelector();
1232      if (!XSel.isNull() && !YSel.isNull()) {
1233        // We are comparing two selectors.
1234        unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
1235        if (N == 0)
1236          ++N;
1237        for (unsigned I = 0; I != N; ++I) {
1238          IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
1239          IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
1240          if (!XId || !YId)
1241            return XId && !YId;
1242
1243          switch (XId->getName().compare_lower(YId->getName())) {
1244          case -1: return true;
1245          case 1: return false;
1246          default: break;
1247          }
1248        }
1249
1250        return XSel.getNumArgs() < YSel.getNumArgs();
1251      }
1252
1253      // For non-selectors, order by kind.
1254      if (X.getNameKind() != Y.getNameKind())
1255        return X.getNameKind() < Y.getNameKind();
1256
1257      // Order identifiers by comparison of their lowercased names.
1258      if (IdentifierInfo *XId = X.getAsIdentifierInfo())
1259        return XId->getName().compare_lower(
1260                                     Y.getAsIdentifierInfo()->getName()) < 0;
1261
1262      // Order overloaded operators by the order in which they appear
1263      // in our list of operators.
1264      if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
1265        return XOp < Y.getCXXOverloadedOperator();
1266
1267      // Order C++0x user-defined literal operators lexically by their
1268      // lowercased suffixes.
1269      if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
1270        return XLit->getName().compare_lower(
1271                                  Y.getCXXLiteralIdentifier()->getName()) < 0;
1272
1273      // The only stable ordering we have is to turn the name into a
1274      // string and then compare the lower-case strings. This is
1275      // inefficient, but thankfully does not happen too often.
1276      return llvm::StringRef(X.getAsString()).compare_lower(
1277                                                 Y.getAsString()) < 0;
1278    }
1279
1280    bool operator()(const Result &X, const Result &Y) const {
1281      // Sort first by rank.
1282      if (X.Rank < Y.Rank)
1283        return true;
1284      else if (X.Rank > Y.Rank)
1285        return false;
1286
1287      // We use a special ordering for keywords and patterns, based on the
1288      // typed text.
1289      if ((X.Kind == Result::RK_Keyword || X.Kind == Result::RK_Pattern) &&
1290          (Y.Kind == Result::RK_Keyword || Y.Kind == Result::RK_Pattern)) {
1291        const char *XStr = (X.Kind == Result::RK_Keyword)? X.Keyword
1292                                                   : X.Pattern->getTypedText();
1293        const char *YStr = (Y.Kind == Result::RK_Keyword)? Y.Keyword
1294                                                   : Y.Pattern->getTypedText();
1295        return llvm::StringRef(XStr).compare_lower(YStr) < 0;
1296      }
1297
1298      // Result kinds are ordered by decreasing importance.
1299      if (X.Kind < Y.Kind)
1300        return true;
1301      else if (X.Kind > Y.Kind)
1302        return false;
1303
1304      // Non-hidden names precede hidden names.
1305      if (X.Hidden != Y.Hidden)
1306        return !X.Hidden;
1307
1308      // Non-nested-name-specifiers precede nested-name-specifiers.
1309      if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1310        return !X.StartsNestedNameSpecifier;
1311
1312      // Ordering depends on the kind of result.
1313      switch (X.Kind) {
1314        case Result::RK_Declaration:
1315          // Order based on the declaration names.
1316          return isEarlierDeclarationName(X.Declaration->getDeclName(),
1317                                          Y.Declaration->getDeclName());
1318
1319        case Result::RK_Macro:
1320          return X.Macro->getName().compare_lower(Y.Macro->getName()) < 0;
1321
1322        case Result::RK_Keyword:
1323        case Result::RK_Pattern:
1324          llvm::llvm_unreachable("Result kinds handled above");
1325          break;
1326      }
1327
1328      // Silence GCC warning.
1329      return false;
1330    }
1331  };
1332}
1333
1334static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1335                            ResultBuilder &Results) {
1336  Results.EnterNewScope();
1337  for (Preprocessor::macro_iterator M = PP.macro_begin(),
1338                                 MEnd = PP.macro_end();
1339       M != MEnd; ++M)
1340    Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1341  Results.ExitScope();
1342}
1343
1344static void HandleCodeCompleteResults(Sema *S,
1345                                      CodeCompleteConsumer *CodeCompleter,
1346                                     CodeCompleteConsumer::Result *Results,
1347                                     unsigned NumResults) {
1348  // Sort the results by rank/kind/etc.
1349  std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1350
1351  if (CodeCompleter)
1352    CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
1353
1354  for (unsigned I = 0; I != NumResults; ++I)
1355    Results[I].Destroy();
1356}
1357
1358void Sema::CodeCompleteOrdinaryName(Scope *S) {
1359  ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
1360  unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1361                                           0, CurContext, Results);
1362  if (CodeCompleter->includeMacros())
1363    AddMacroResults(PP, NextRank, Results);
1364  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1365}
1366
1367static void AddObjCProperties(ObjCContainerDecl *Container,
1368                              bool AllowCategories,
1369                              DeclContext *CurContext,
1370                              ResultBuilder &Results) {
1371  typedef CodeCompleteConsumer::Result Result;
1372
1373  // Add properties in this container.
1374  for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
1375                                     PEnd = Container->prop_end();
1376       P != PEnd;
1377       ++P)
1378    Results.MaybeAddResult(Result(*P, 0), CurContext);
1379
1380  // Add properties in referenced protocols.
1381  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
1382    for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
1383                                          PEnd = Protocol->protocol_end();
1384         P != PEnd; ++P)
1385      AddObjCProperties(*P, AllowCategories, CurContext, Results);
1386  } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
1387    if (AllowCategories) {
1388      // Look through categories.
1389      for (ObjCCategoryDecl *Category = IFace->getCategoryList();
1390           Category; Category = Category->getNextClassCategory())
1391        AddObjCProperties(Category, AllowCategories, CurContext, Results);
1392    }
1393
1394    // Look through protocols.
1395    for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
1396                                              E = IFace->protocol_end();
1397         I != E; ++I)
1398      AddObjCProperties(*I, AllowCategories, CurContext, Results);
1399
1400    // Look in the superclass.
1401    if (IFace->getSuperClass())
1402      AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
1403                        Results);
1404  } else if (const ObjCCategoryDecl *Category
1405                                    = dyn_cast<ObjCCategoryDecl>(Container)) {
1406    // Look through protocols.
1407    for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
1408                                           PEnd = Category->protocol_end();
1409         P != PEnd; ++P)
1410      AddObjCProperties(*P, AllowCategories, CurContext, Results);
1411  }
1412}
1413
1414void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1415                                           SourceLocation OpLoc,
1416                                           bool IsArrow) {
1417  if (!BaseE || !CodeCompleter)
1418    return;
1419
1420  typedef CodeCompleteConsumer::Result Result;
1421
1422  Expr *Base = static_cast<Expr *>(BaseE);
1423  QualType BaseType = Base->getType();
1424
1425  if (IsArrow) {
1426    if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1427      BaseType = Ptr->getPointeeType();
1428    else if (BaseType->isObjCObjectPointerType())
1429    /*Do nothing*/ ;
1430    else
1431      return;
1432  }
1433
1434  ResultBuilder Results(*this, &ResultBuilder::IsMember);
1435  unsigned NextRank = 0;
1436
1437  Results.EnterNewScope();
1438  if (const RecordType *Record = BaseType->getAs<RecordType>()) {
1439    // Access to a C/C++ class, struct, or union.
1440    NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1441                                          Record->getDecl(), Results);
1442
1443    if (getLangOptions().CPlusPlus) {
1444      if (!Results.empty()) {
1445        // The "template" keyword can follow "->" or "." in the grammar.
1446        // However, we only want to suggest the template keyword if something
1447        // is dependent.
1448        bool IsDependent = BaseType->isDependentType();
1449        if (!IsDependent) {
1450          for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1451            if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1452              IsDependent = Ctx->isDependentContext();
1453              break;
1454            }
1455        }
1456
1457        if (IsDependent)
1458          Results.MaybeAddResult(Result("template", NextRank++));
1459      }
1460
1461      // We could have the start of a nested-name-specifier. Add those
1462      // results as well.
1463      Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1464      CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
1465                           CurContext, Results);
1466    }
1467  } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
1468    // Objective-C property reference.
1469
1470    // Add property results based on our interface.
1471    const ObjCObjectPointerType *ObjCPtr
1472      = BaseType->getAsObjCInterfacePointerType();
1473    assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
1474    AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
1475
1476    // Add properties from the protocols in a qualified interface.
1477    for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
1478                                              E = ObjCPtr->qual_end();
1479         I != E; ++I)
1480      AddObjCProperties(*I, true, CurContext, Results);
1481
1482    // FIXME: We could (should?) also look for "implicit" properties, identified
1483    // only by the presence of nullary and unary selectors.
1484  } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
1485             (!IsArrow && BaseType->isObjCInterfaceType())) {
1486    // Objective-C instance variable access.
1487    ObjCInterfaceDecl *Class = 0;
1488    if (const ObjCObjectPointerType *ObjCPtr
1489                                    = BaseType->getAs<ObjCObjectPointerType>())
1490      Class = ObjCPtr->getInterfaceDecl();
1491    else
1492      Class = BaseType->getAs<ObjCInterfaceType>()->getDecl();
1493
1494    // Add all ivars from this class and its superclasses.
1495    for (; Class; Class = Class->getSuperClass()) {
1496      for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
1497                                         IVarEnd = Class->ivar_end();
1498           IVar != IVarEnd; ++IVar)
1499        Results.MaybeAddResult(Result(*IVar, 0), CurContext);
1500    }
1501  }
1502
1503  // FIXME: How do we cope with isa?
1504
1505  Results.ExitScope();
1506
1507  // Add macros
1508  if (CodeCompleter->includeMacros())
1509    AddMacroResults(PP, NextRank, Results);
1510
1511  // Hand off the results found for code completion.
1512  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1513}
1514
1515void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1516  if (!CodeCompleter)
1517    return;
1518
1519  typedef CodeCompleteConsumer::Result Result;
1520  ResultBuilder::LookupFilter Filter = 0;
1521  switch ((DeclSpec::TST)TagSpec) {
1522  case DeclSpec::TST_enum:
1523    Filter = &ResultBuilder::IsEnum;
1524    break;
1525
1526  case DeclSpec::TST_union:
1527    Filter = &ResultBuilder::IsUnion;
1528    break;
1529
1530  case DeclSpec::TST_struct:
1531  case DeclSpec::TST_class:
1532    Filter = &ResultBuilder::IsClassOrStruct;
1533    break;
1534
1535  default:
1536    assert(false && "Unknown type specifier kind in CodeCompleteTag");
1537    return;
1538  }
1539
1540  ResultBuilder Results(*this, Filter);
1541  unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1542                                           0, CurContext, Results);
1543
1544  if (getLangOptions().CPlusPlus) {
1545    // We could have the start of a nested-name-specifier. Add those
1546    // results as well.
1547    Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1548    NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1549                                    NextRank, CurContext, Results);
1550  }
1551
1552  if (CodeCompleter->includeMacros())
1553    AddMacroResults(PP, NextRank, Results);
1554  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1555}
1556
1557void Sema::CodeCompleteCase(Scope *S) {
1558  if (getSwitchStack().empty() || !CodeCompleter)
1559    return;
1560
1561  SwitchStmt *Switch = getSwitchStack().back();
1562  if (!Switch->getCond()->getType()->isEnumeralType())
1563    return;
1564
1565  // Code-complete the cases of a switch statement over an enumeration type
1566  // by providing the list of
1567  EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1568
1569  // Determine which enumerators we have already seen in the switch statement.
1570  // FIXME: Ideally, we would also be able to look *past* the code-completion
1571  // token, in case we are code-completing in the middle of the switch and not
1572  // at the end. However, we aren't able to do so at the moment.
1573  llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
1574  NestedNameSpecifier *Qualifier = 0;
1575  for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1576       SC = SC->getNextSwitchCase()) {
1577    CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1578    if (!Case)
1579      continue;
1580
1581    Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1582    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1583      if (EnumConstantDecl *Enumerator
1584            = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1585        // We look into the AST of the case statement to determine which
1586        // enumerator was named. Alternatively, we could compute the value of
1587        // the integral constant expression, then compare it against the
1588        // values of each enumerator. However, value-based approach would not
1589        // work as well with C++ templates where enumerators declared within a
1590        // template are type- and value-dependent.
1591        EnumeratorsSeen.insert(Enumerator);
1592
1593        // If this is a qualified-id, keep track of the nested-name-specifier
1594        // so that we can reproduce it as part of code completion, e.g.,
1595        //
1596        //   switch (TagD.getKind()) {
1597        //     case TagDecl::TK_enum:
1598        //       break;
1599        //     case XXX
1600        //
1601        // At the XXX, our completions are TagDecl::TK_union,
1602        // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1603        // TK_struct, and TK_class.
1604        Qualifier = DRE->getQualifier();
1605      }
1606  }
1607
1608  if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1609    // If there are no prior enumerators in C++, check whether we have to
1610    // qualify the names of the enumerators that we suggest, because they
1611    // may not be visible in this scope.
1612    Qualifier = getRequiredQualification(Context, CurContext,
1613                                         Enum->getDeclContext());
1614
1615    // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1616  }
1617
1618  // Add any enumerators that have not yet been mentioned.
1619  ResultBuilder Results(*this);
1620  Results.EnterNewScope();
1621  for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1622                                  EEnd = Enum->enumerator_end();
1623       E != EEnd; ++E) {
1624    if (EnumeratorsSeen.count(*E))
1625      continue;
1626
1627    Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
1628  }
1629  Results.ExitScope();
1630
1631  if (CodeCompleter->includeMacros())
1632    AddMacroResults(PP, 1, Results);
1633  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1634}
1635
1636namespace {
1637  struct IsBetterOverloadCandidate {
1638    Sema &S;
1639
1640  public:
1641    explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1642
1643    bool
1644    operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1645      return S.isBetterOverloadCandidate(X, Y);
1646    }
1647  };
1648}
1649
1650void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1651                            ExprTy **ArgsIn, unsigned NumArgs) {
1652  if (!CodeCompleter)
1653    return;
1654
1655  Expr *Fn = (Expr *)FnIn;
1656  Expr **Args = (Expr **)ArgsIn;
1657
1658  // Ignore type-dependent call expressions entirely.
1659  if (Fn->isTypeDependent() ||
1660      Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1661    return;
1662
1663  llvm::SmallVector<NamedDecl*,8> Fns;
1664  DeclarationName UnqualifiedName;
1665  NestedNameSpecifier *Qualifier;
1666  SourceRange QualifierRange;
1667  bool ArgumentDependentLookup;
1668  bool Overloaded;
1669  bool HasExplicitTemplateArgs;
1670  TemplateArgumentListInfo ExplicitTemplateArgs;
1671
1672  DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
1673                          ArgumentDependentLookup, Overloaded,
1674                          HasExplicitTemplateArgs, ExplicitTemplateArgs);
1675
1676
1677  // FIXME: What if we're calling something that isn't a function declaration?
1678  // FIXME: What if we're calling a pseudo-destructor?
1679  // FIXME: What if we're calling a member function?
1680
1681  // Build an overload candidate set based on the functions we find.
1682  OverloadCandidateSet CandidateSet;
1683  AddOverloadedCallCandidates(Fns, UnqualifiedName,
1684                              ArgumentDependentLookup,
1685                       (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
1686                              Args, NumArgs,
1687                              CandidateSet,
1688                              /*PartialOverloading=*/true);
1689
1690  // Sort the overload candidate set by placing the best overloads first.
1691  std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1692                   IsBetterOverloadCandidate(*this));
1693
1694  // Add the remaining viable overload candidates as code-completion reslults.
1695  typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1696  llvm::SmallVector<ResultCandidate, 8> Results;
1697
1698  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1699                                   CandEnd = CandidateSet.end();
1700       Cand != CandEnd; ++Cand) {
1701    if (Cand->Viable)
1702      Results.push_back(ResultCandidate(Cand->Function));
1703  }
1704  CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
1705                                           Results.size());
1706}
1707
1708void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1709                                   bool EnteringContext) {
1710  if (!SS.getScopeRep() || !CodeCompleter)
1711    return;
1712
1713  DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1714  if (!Ctx)
1715    return;
1716
1717  ResultBuilder Results(*this);
1718  unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
1719
1720  // The "template" keyword can follow "::" in the grammar, but only
1721  // put it into the grammar if the nested-name-specifier is dependent.
1722  NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1723  if (!Results.empty() && NNS->isDependent())
1724    Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1725
1726  if (CodeCompleter->includeMacros())
1727    AddMacroResults(PP, NextRank + 1, Results);
1728  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1729}
1730
1731void Sema::CodeCompleteUsing(Scope *S) {
1732  if (!CodeCompleter)
1733    return;
1734
1735  ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
1736  Results.EnterNewScope();
1737
1738  // If we aren't in class scope, we could see the "namespace" keyword.
1739  if (!S->isClassScope())
1740    Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1741
1742  // After "using", we can see anything that would start a
1743  // nested-name-specifier.
1744  unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1745                                           0, CurContext, Results);
1746  Results.ExitScope();
1747
1748  if (CodeCompleter->includeMacros())
1749    AddMacroResults(PP, NextRank, Results);
1750  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1751}
1752
1753void Sema::CodeCompleteUsingDirective(Scope *S) {
1754  if (!CodeCompleter)
1755    return;
1756
1757  // After "using namespace", we expect to see a namespace name or namespace
1758  // alias.
1759  ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
1760  Results.EnterNewScope();
1761  unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1762                                           0, CurContext, Results);
1763  Results.ExitScope();
1764  if (CodeCompleter->includeMacros())
1765    AddMacroResults(PP, NextRank, Results);
1766  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1767}
1768
1769void Sema::CodeCompleteNamespaceDecl(Scope *S)  {
1770  if (!CodeCompleter)
1771    return;
1772
1773  ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1774  DeclContext *Ctx = (DeclContext *)S->getEntity();
1775  if (!S->getParent())
1776    Ctx = Context.getTranslationUnitDecl();
1777
1778  if (Ctx && Ctx->isFileContext()) {
1779    // We only want to see those namespaces that have already been defined
1780    // within this scope, because its likely that the user is creating an
1781    // extended namespace declaration. Keep track of the most recent
1782    // definition of each namespace.
1783    std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1784    for (DeclContext::specific_decl_iterator<NamespaceDecl>
1785         NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1786         NS != NSEnd; ++NS)
1787      OrigToLatest[NS->getOriginalNamespace()] = *NS;
1788
1789    // Add the most recent definition (or extended definition) of each
1790    // namespace to the list of results.
1791    Results.EnterNewScope();
1792    for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1793         NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1794         NS != NSEnd; ++NS)
1795      Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1796                             CurContext);
1797    Results.ExitScope();
1798  }
1799
1800  if (CodeCompleter->includeMacros())
1801    AddMacroResults(PP, 1, Results);
1802  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1803}
1804
1805void Sema::CodeCompleteNamespaceAliasDecl(Scope *S)  {
1806  if (!CodeCompleter)
1807    return;
1808
1809  // After "namespace", we expect to see a namespace or alias.
1810  ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
1811  unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1812                                           0, CurContext, Results);
1813  if (CodeCompleter->includeMacros())
1814    AddMacroResults(PP, NextRank, Results);
1815  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1816}
1817
1818void Sema::CodeCompleteOperatorName(Scope *S) {
1819  if (!CodeCompleter)
1820    return;
1821
1822  typedef CodeCompleteConsumer::Result Result;
1823  ResultBuilder Results(*this, &ResultBuilder::IsType);
1824  Results.EnterNewScope();
1825
1826  // Add the names of overloadable operators.
1827#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly)      \
1828  if (std::strcmp(Spelling, "?"))                                                  \
1829    Results.MaybeAddResult(Result(Spelling, 0));
1830#include "clang/Basic/OperatorKinds.def"
1831
1832  // Add any type names visible from the current scope
1833  unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1834                                           0, CurContext, Results);
1835
1836  // Add any type specifiers
1837  AddTypeSpecifierResults(getLangOptions(), 0, Results);
1838
1839  // Add any nested-name-specifiers
1840  Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1841  NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1842                                  NextRank + 1, CurContext, Results);
1843  Results.ExitScope();
1844
1845  if (CodeCompleter->includeMacros())
1846    AddMacroResults(PP, NextRank, Results);
1847  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1848}
1849
1850/// \brief Determine whether the addition of the given flag to an Objective-C
1851/// property's attributes will cause a conflict.
1852static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
1853  // Check if we've already added this flag.
1854  if (Attributes & NewFlag)
1855    return true;
1856
1857  Attributes |= NewFlag;
1858
1859  // Check for collisions with "readonly".
1860  if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1861      (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
1862                     ObjCDeclSpec::DQ_PR_assign |
1863                     ObjCDeclSpec::DQ_PR_copy |
1864                     ObjCDeclSpec::DQ_PR_retain)))
1865    return true;
1866
1867  // Check for more than one of { assign, copy, retain }.
1868  unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
1869                                             ObjCDeclSpec::DQ_PR_copy |
1870                                             ObjCDeclSpec::DQ_PR_retain);
1871  if (AssignCopyRetMask &&
1872      AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
1873      AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
1874      AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
1875    return true;
1876
1877  return false;
1878}
1879
1880void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
1881  if (!CodeCompleter)
1882    return;
1883
1884  unsigned Attributes = ODS.getPropertyAttributes();
1885
1886  typedef CodeCompleteConsumer::Result Result;
1887  ResultBuilder Results(*this);
1888  Results.EnterNewScope();
1889  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
1890    Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
1891  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
1892    Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
1893  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
1894    Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
1895  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
1896    Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
1897  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
1898    Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
1899  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
1900    Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
1901  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
1902    CodeCompletionString *Setter = new CodeCompletionString;
1903    Setter->AddTypedTextChunk("setter");
1904    Setter->AddTextChunk(" = ");
1905    Setter->AddPlaceholderChunk("method");
1906    Results.MaybeAddResult(CodeCompleteConsumer::Result(Setter, 0));
1907  }
1908  if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
1909    CodeCompletionString *Getter = new CodeCompletionString;
1910    Getter->AddTypedTextChunk("getter");
1911    Getter->AddTextChunk(" = ");
1912    Getter->AddPlaceholderChunk("method");
1913    Results.MaybeAddResult(CodeCompleteConsumer::Result(Getter, 0));
1914  }
1915  Results.ExitScope();
1916  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1917}
1918
1919/// \brief Descripts the kind of Objective-C method that we want to find
1920/// via code completion.
1921enum ObjCMethodKind {
1922  MK_Any, //< Any kind of method, provided it means other specified criteria.
1923  MK_ZeroArgSelector, //< Zero-argument (unary) selector.
1924  MK_OneArgSelector //< One-argument selector.
1925};
1926
1927static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
1928                                   ObjCMethodKind WantKind,
1929                                   IdentifierInfo **SelIdents,
1930                                   unsigned NumSelIdents) {
1931  Selector Sel = Method->getSelector();
1932  if (NumSelIdents > Sel.getNumArgs())
1933    return false;
1934
1935  switch (WantKind) {
1936  case MK_Any:             break;
1937  case MK_ZeroArgSelector: return Sel.isUnarySelector();
1938  case MK_OneArgSelector:  return Sel.getNumArgs() == 1;
1939  }
1940
1941  for (unsigned I = 0; I != NumSelIdents; ++I)
1942    if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
1943      return false;
1944
1945  return true;
1946}
1947
1948/// \brief Add all of the Objective-C methods in the given Objective-C
1949/// container to the set of results.
1950///
1951/// The container will be a class, protocol, category, or implementation of
1952/// any of the above. This mether will recurse to include methods from
1953/// the superclasses of classes along with their categories, protocols, and
1954/// implementations.
1955///
1956/// \param Container the container in which we'll look to find methods.
1957///
1958/// \param WantInstance whether to add instance methods (only); if false, this
1959/// routine will add factory methods (only).
1960///
1961/// \param CurContext the context in which we're performing the lookup that
1962/// finds methods.
1963///
1964/// \param Results the structure into which we'll add results.
1965static void AddObjCMethods(ObjCContainerDecl *Container,
1966                           bool WantInstanceMethods,
1967                           ObjCMethodKind WantKind,
1968                           IdentifierInfo **SelIdents,
1969                           unsigned NumSelIdents,
1970                           DeclContext *CurContext,
1971                           ResultBuilder &Results) {
1972  typedef CodeCompleteConsumer::Result Result;
1973  for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
1974                                       MEnd = Container->meth_end();
1975       M != MEnd; ++M) {
1976    if ((*M)->isInstanceMethod() == WantInstanceMethods) {
1977      // Check whether the selector identifiers we've been given are a
1978      // subset of the identifiers for this particular method.
1979      if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
1980        continue;
1981
1982      Result R = Result(*M, 0);
1983      R.StartParameter = NumSelIdents;
1984      R.AllParametersAreInformative = (WantKind != MK_Any);
1985      Results.MaybeAddResult(R, CurContext);
1986    }
1987  }
1988
1989  ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
1990  if (!IFace)
1991    return;
1992
1993  // Add methods in protocols.
1994  const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
1995  for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1996                                            E = Protocols.end();
1997       I != E; ++I)
1998    AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
1999                   CurContext, Results);
2000
2001  // Add methods in categories.
2002  for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
2003       CatDecl = CatDecl->getNextClassCategory()) {
2004    AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
2005                   NumSelIdents, CurContext, Results);
2006
2007    // Add a categories protocol methods.
2008    const ObjCList<ObjCProtocolDecl> &Protocols
2009      = CatDecl->getReferencedProtocols();
2010    for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
2011                                              E = Protocols.end();
2012         I != E; ++I)
2013      AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
2014                     NumSelIdents, CurContext, Results);
2015
2016    // Add methods in category implementations.
2017    if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
2018      AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
2019                     NumSelIdents, CurContext, Results);
2020  }
2021
2022  // Add methods in superclass.
2023  if (IFace->getSuperClass())
2024    AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
2025                   SelIdents, NumSelIdents, CurContext, Results);
2026
2027  // Add methods in our implementation, if any.
2028  if (ObjCImplementationDecl *Impl = IFace->getImplementation())
2029    AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
2030                   NumSelIdents, CurContext, Results);
2031}
2032
2033
2034void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
2035                                          DeclPtrTy *Methods,
2036                                          unsigned NumMethods) {
2037  typedef CodeCompleteConsumer::Result Result;
2038
2039  // Try to find the interface where getters might live.
2040  ObjCInterfaceDecl *Class
2041    = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
2042  if (!Class) {
2043    if (ObjCCategoryDecl *Category
2044          = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
2045      Class = Category->getClassInterface();
2046
2047    if (!Class)
2048      return;
2049  }
2050
2051  // Find all of the potential getters.
2052  ResultBuilder Results(*this);
2053  Results.EnterNewScope();
2054
2055  // FIXME: We need to do this because Objective-C methods don't get
2056  // pushed into DeclContexts early enough. Argh!
2057  for (unsigned I = 0; I != NumMethods; ++I) {
2058    if (ObjCMethodDecl *Method
2059            = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
2060      if (Method->isInstanceMethod() &&
2061          isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
2062        Result R = Result(Method, 0);
2063        R.AllParametersAreInformative = true;
2064        Results.MaybeAddResult(R, CurContext);
2065      }
2066  }
2067
2068  AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
2069  Results.ExitScope();
2070  HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
2071}
2072
2073void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
2074                                          DeclPtrTy *Methods,
2075                                          unsigned NumMethods) {
2076  typedef CodeCompleteConsumer::Result Result;
2077
2078  // Try to find the interface where setters might live.
2079  ObjCInterfaceDecl *Class
2080    = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
2081  if (!Class) {
2082    if (ObjCCategoryDecl *Category
2083          = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
2084      Class = Category->getClassInterface();
2085
2086    if (!Class)
2087      return;
2088  }
2089
2090  // Find all of the potential getters.
2091  ResultBuilder Results(*this);
2092  Results.EnterNewScope();
2093
2094  // FIXME: We need to do this because Objective-C methods don't get
2095  // pushed into DeclContexts early enough. Argh!
2096  for (unsigned I = 0; I != NumMethods; ++I) {
2097    if (ObjCMethodDecl *Method
2098            = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
2099      if (Method->isInstanceMethod() &&
2100          isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
2101        Result R = Result(Method, 0);
2102        R.AllParametersAreInformative = true;
2103        Results.MaybeAddResult(R, CurContext);
2104      }
2105  }
2106
2107  AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
2108
2109  Results.ExitScope();
2110  HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
2111}
2112
2113void Sema::CodeCompleteObjCClassMessage(Scope *S, IdentifierInfo *FName,
2114                                        SourceLocation FNameLoc,
2115                                        IdentifierInfo **SelIdents,
2116                                        unsigned NumSelIdents) {
2117  typedef CodeCompleteConsumer::Result Result;
2118  ObjCInterfaceDecl *CDecl = 0;
2119
2120  if (FName->isStr("super")) {
2121    // We're sending a message to "super".
2122    if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
2123      // Figure out which interface we're in.
2124      CDecl = CurMethod->getClassInterface();
2125      if (!CDecl)
2126        return;
2127
2128      // Find the superclass of this class.
2129      CDecl = CDecl->getSuperClass();
2130      if (!CDecl)
2131        return;
2132
2133      if (CurMethod->isInstanceMethod()) {
2134        // We are inside an instance method, which means that the message
2135        // send [super ...] is actually calling an instance method on the
2136        // current object. Build the super expression and handle this like
2137        // an instance method.
2138        QualType SuperTy = Context.getObjCInterfaceType(CDecl);
2139        SuperTy = Context.getObjCObjectPointerType(SuperTy);
2140        OwningExprResult Super
2141          = Owned(new (Context) ObjCSuperExpr(FNameLoc, SuperTy));
2142        return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
2143                                               SelIdents, NumSelIdents);
2144      }
2145
2146      // Okay, we're calling a factory method in our superclass.
2147    }
2148  }
2149
2150  // If the given name refers to an interface type, retrieve the
2151  // corresponding declaration.
2152  if (!CDecl)
2153    if (TypeTy *Ty = getTypeName(*FName, FNameLoc, S, 0, false)) {
2154      QualType T = GetTypeFromParser(Ty, 0);
2155      if (!T.isNull())
2156        if (const ObjCInterfaceType *Interface = T->getAs<ObjCInterfaceType>())
2157          CDecl = Interface->getDecl();
2158    }
2159
2160  if (!CDecl && FName->isStr("super")) {
2161    // "super" may be the name of a variable, in which case we are
2162    // probably calling an instance method.
2163    CXXScopeSpec SS;
2164    UnqualifiedId id;
2165    id.setIdentifier(FName, FNameLoc);
2166    OwningExprResult Super = ActOnIdExpression(S, SS, id, false, false);
2167    return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
2168                                           SelIdents, NumSelIdents);
2169  }
2170
2171  // Add all of the factory methods in this Objective-C class, its protocols,
2172  // superclasses, categories, implementation, etc.
2173  ResultBuilder Results(*this);
2174  Results.EnterNewScope();
2175  AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
2176                 Results);
2177  Results.ExitScope();
2178
2179  // This also suppresses remaining diagnostics.
2180  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2181}
2182
2183void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
2184                                           IdentifierInfo **SelIdents,
2185                                           unsigned NumSelIdents) {
2186  typedef CodeCompleteConsumer::Result Result;
2187
2188  Expr *RecExpr = static_cast<Expr *>(Receiver);
2189  QualType RecType = RecExpr->getType();
2190
2191  // If necessary, apply function/array conversion to the receiver.
2192  // C99 6.7.5.3p[7,8].
2193  DefaultFunctionArrayConversion(RecExpr);
2194  QualType ReceiverType = RecExpr->getType();
2195
2196  if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType()) {
2197    // FIXME: We're messaging 'id'. Do we actually want to look up every method
2198    // in the universe?
2199    return;
2200  }
2201
2202  // Build the set of methods we can see.
2203  ResultBuilder Results(*this);
2204  Results.EnterNewScope();
2205
2206  // Handle messages to Class. This really isn't a message to an instance
2207  // method, so we treat it the same way we would treat a message send to a
2208  // class method.
2209  if (ReceiverType->isObjCClassType() ||
2210      ReceiverType->isObjCQualifiedClassType()) {
2211    if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
2212      if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
2213        AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
2214                       CurContext, Results);
2215    }
2216  }
2217  // Handle messages to a qualified ID ("id<foo>").
2218  else if (const ObjCObjectPointerType *QualID
2219             = ReceiverType->getAsObjCQualifiedIdType()) {
2220    // Search protocols for instance methods.
2221    for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
2222                                              E = QualID->qual_end();
2223         I != E; ++I)
2224      AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
2225                     Results);
2226  }
2227  // Handle messages to a pointer to interface type.
2228  else if (const ObjCObjectPointerType *IFacePtr
2229                              = ReceiverType->getAsObjCInterfacePointerType()) {
2230    // Search the class, its superclasses, etc., for instance methods.
2231    AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
2232                   NumSelIdents, CurContext, Results);
2233
2234    // Search protocols for instance methods.
2235    for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
2236         E = IFacePtr->qual_end();
2237         I != E; ++I)
2238      AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
2239                     Results);
2240  }
2241
2242  Results.ExitScope();
2243  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2244}
2245
2246/// \brief Add all of the protocol declarations that we find in the given
2247/// (translation unit) context.
2248static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
2249                               bool OnlyForwardDeclarations,
2250                               ResultBuilder &Results) {
2251  typedef CodeCompleteConsumer::Result Result;
2252
2253  for (DeclContext::decl_iterator D = Ctx->decls_begin(),
2254                               DEnd = Ctx->decls_end();
2255       D != DEnd; ++D) {
2256    // Record any protocols we find.
2257    if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
2258      if (!OnlyForwardDeclarations || Proto->isForwardDecl())
2259        Results.MaybeAddResult(Result(Proto, 0), CurContext);
2260
2261    // Record any forward-declared protocols we find.
2262    if (ObjCForwardProtocolDecl *Forward
2263          = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2264      for (ObjCForwardProtocolDecl::protocol_iterator
2265             P = Forward->protocol_begin(),
2266             PEnd = Forward->protocol_end();
2267           P != PEnd; ++P)
2268        if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
2269          Results.MaybeAddResult(Result(*P, 0), CurContext);
2270    }
2271  }
2272}
2273
2274void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
2275                                              unsigned NumProtocols) {
2276  ResultBuilder Results(*this);
2277  Results.EnterNewScope();
2278
2279  // Tell the result set to ignore all of the protocols we have
2280  // already seen.
2281  for (unsigned I = 0; I != NumProtocols; ++I)
2282    if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first))
2283      Results.Ignore(Protocol);
2284
2285  // Add all protocols.
2286  AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
2287                     Results);
2288
2289  Results.ExitScope();
2290  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2291}
2292
2293void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
2294  ResultBuilder Results(*this);
2295  Results.EnterNewScope();
2296
2297  // Add all protocols.
2298  AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
2299                     Results);
2300
2301  Results.ExitScope();
2302  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2303}
2304
2305/// \brief Add all of the Objective-C interface declarations that we find in
2306/// the given (translation unit) context.
2307static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
2308                                bool OnlyForwardDeclarations,
2309                                bool OnlyUnimplemented,
2310                                ResultBuilder &Results) {
2311  typedef CodeCompleteConsumer::Result Result;
2312
2313  for (DeclContext::decl_iterator D = Ctx->decls_begin(),
2314                               DEnd = Ctx->decls_end();
2315       D != DEnd; ++D) {
2316    // Record any interfaces we find.
2317    if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
2318      if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
2319          (!OnlyUnimplemented || !Class->getImplementation()))
2320        Results.MaybeAddResult(Result(Class, 0), CurContext);
2321
2322    // Record any forward-declared interfaces we find.
2323    if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
2324      for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
2325           C != CEnd; ++C)
2326        if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
2327            (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
2328          Results.MaybeAddResult(Result(C->getInterface(), 0), CurContext);
2329    }
2330  }
2331}
2332
2333void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
2334  ResultBuilder Results(*this);
2335  Results.EnterNewScope();
2336
2337  // Add all classes.
2338  AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
2339                      false, Results);
2340
2341  Results.ExitScope();
2342  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2343}
2344
2345void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName) {
2346  ResultBuilder Results(*this);
2347  Results.EnterNewScope();
2348
2349  // Make sure that we ignore the class we're currently defining.
2350  NamedDecl *CurClass
2351    = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
2352  if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
2353    Results.Ignore(CurClass);
2354
2355  // Add all classes.
2356  AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
2357                      false, Results);
2358
2359  Results.ExitScope();
2360  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2361}
2362
2363void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
2364  ResultBuilder Results(*this);
2365  Results.EnterNewScope();
2366
2367  // Add all unimplemented classes.
2368  AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
2369                      true, Results);
2370
2371  Results.ExitScope();
2372  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2373}
2374
2375void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
2376                                             IdentifierInfo *ClassName) {
2377  typedef CodeCompleteConsumer::Result Result;
2378
2379  ResultBuilder Results(*this);
2380
2381  // Ignore any categories we find that have already been implemented by this
2382  // interface.
2383  llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
2384  NamedDecl *CurClass
2385    = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
2386  if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
2387    for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
2388         Category = Category->getNextClassCategory())
2389      CategoryNames.insert(Category->getIdentifier());
2390
2391  // Add all of the categories we know about.
2392  Results.EnterNewScope();
2393  TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
2394  for (DeclContext::decl_iterator D = TU->decls_begin(),
2395                               DEnd = TU->decls_end();
2396       D != DEnd; ++D)
2397    if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
2398      if (CategoryNames.insert(Category->getIdentifier()))
2399          Results.MaybeAddResult(Result(Category, 0), CurContext);
2400  Results.ExitScope();
2401
2402  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2403}
2404
2405void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
2406                                                  IdentifierInfo *ClassName) {
2407  typedef CodeCompleteConsumer::Result Result;
2408
2409  // Find the corresponding interface. If we couldn't find the interface, the
2410  // program itself is ill-formed. However, we'll try to be helpful still by
2411  // providing the list of all of the categories we know about.
2412  NamedDecl *CurClass
2413    = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
2414  ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
2415  if (!Class)
2416    return CodeCompleteObjCInterfaceCategory(S, ClassName);
2417
2418  ResultBuilder Results(*this);
2419
2420  // Add all of the categories that have have corresponding interface
2421  // declarations in this class and any of its superclasses, except for
2422  // already-implemented categories in the class itself.
2423  llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
2424  Results.EnterNewScope();
2425  bool IgnoreImplemented = true;
2426  while (Class) {
2427    for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
2428         Category = Category->getNextClassCategory())
2429      if ((!IgnoreImplemented || !Category->getImplementation()) &&
2430          CategoryNames.insert(Category->getIdentifier()))
2431        Results.MaybeAddResult(Result(Category, 0), CurContext);
2432
2433    Class = Class->getSuperClass();
2434    IgnoreImplemented = false;
2435  }
2436  Results.ExitScope();
2437
2438  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2439}
2440
2441void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
2442  typedef CodeCompleteConsumer::Result Result;
2443  ResultBuilder Results(*this);
2444
2445  // Figure out where this @synthesize lives.
2446  ObjCContainerDecl *Container
2447    = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
2448  if (!Container ||
2449      (!isa<ObjCImplementationDecl>(Container) &&
2450       !isa<ObjCCategoryImplDecl>(Container)))
2451    return;
2452
2453  // Ignore any properties that have already been implemented.
2454  for (DeclContext::decl_iterator D = Container->decls_begin(),
2455                               DEnd = Container->decls_end();
2456       D != DEnd; ++D)
2457    if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
2458      Results.Ignore(PropertyImpl->getPropertyDecl());
2459
2460  // Add any properties that we find.
2461  Results.EnterNewScope();
2462  if (ObjCImplementationDecl *ClassImpl
2463        = dyn_cast<ObjCImplementationDecl>(Container))
2464    AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
2465                      Results);
2466  else
2467    AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
2468                      false, CurContext, Results);
2469  Results.ExitScope();
2470
2471  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2472}
2473
2474void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
2475                                                  IdentifierInfo *PropertyName,
2476                                                  DeclPtrTy ObjCImpDecl) {
2477  typedef CodeCompleteConsumer::Result Result;
2478  ResultBuilder Results(*this);
2479
2480  // Figure out where this @synthesize lives.
2481  ObjCContainerDecl *Container
2482    = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
2483  if (!Container ||
2484      (!isa<ObjCImplementationDecl>(Container) &&
2485       !isa<ObjCCategoryImplDecl>(Container)))
2486    return;
2487
2488  // Figure out which interface we're looking into.
2489  ObjCInterfaceDecl *Class = 0;
2490  if (ObjCImplementationDecl *ClassImpl
2491                                 = dyn_cast<ObjCImplementationDecl>(Container))
2492    Class = ClassImpl->getClassInterface();
2493  else
2494    Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
2495                                                          ->getClassInterface();
2496
2497  // Add all of the instance variables in this class and its superclasses.
2498  Results.EnterNewScope();
2499  for(; Class; Class = Class->getSuperClass()) {
2500    // FIXME: We could screen the type of each ivar for compatibility with
2501    // the property, but is that being too paternal?
2502    for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
2503                                       IVarEnd = Class->ivar_end();
2504         IVar != IVarEnd; ++IVar)
2505      Results.MaybeAddResult(Result(*IVar, 0), CurContext);
2506  }
2507  Results.ExitScope();
2508
2509  HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2510}
2511