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