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