SemaCodeComplete.cpp revision 60e7ac5778bfae023c6526c5ffd7e4f947f7cb4d
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/Lex/MacroInfo.h"
17#include "clang/Lex/Preprocessor.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/StringExtras.h"
20#include <list>
21#include <map>
22#include <vector>
23
24using namespace clang;
25
26/// \brief Set the code-completion consumer for semantic analysis.
27void Sema::setCodeCompleteConsumer(CodeCompleteConsumer *CCC) {
28  assert(((CodeCompleter != 0) != (CCC != 0)) &&
29         "Already set or cleared a code-completion consumer?");
30  CodeCompleter = CCC;
31}
32
33namespace {
34  /// \brief A container of code-completion results.
35  class ResultBuilder {
36  public:
37    /// \brief The type of a name-lookup filter, which can be provided to the
38    /// name-lookup routines to specify which declarations should be included in
39    /// the result set (when it returns true) and which declarations should be
40    /// filtered out (returns false).
41    typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
42
43    typedef CodeCompleteConsumer::Result Result;
44
45  private:
46    /// \brief The actual results we have found.
47    std::vector<Result> Results;
48
49    /// \brief A record of all of the declarations we have found and placed
50    /// into the result set, used to ensure that no declaration ever gets into
51    /// the result set twice.
52    llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
53
54    /// \brief A mapping from declaration names to the declarations that have
55    /// this name within a particular scope and their index within the list of
56    /// results.
57    typedef std::multimap<DeclarationName,
58                          std::pair<NamedDecl *, unsigned> > ShadowMap;
59
60    /// \brief The semantic analysis object for which results are being
61    /// produced.
62    Sema &SemaRef;
63
64    /// \brief If non-NULL, a filter function used to remove any code-completion
65    /// results that are not desirable.
66    LookupFilter Filter;
67
68    /// \brief A list of shadow maps, which is used to model name hiding at
69    /// different levels of, e.g., the inheritance hierarchy.
70    std::list<ShadowMap> ShadowMaps;
71
72  public:
73    explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
74      : SemaRef(SemaRef), Filter(Filter) { }
75
76    /// \brief Set the filter used for code-completion results.
77    void setFilter(LookupFilter Filter) {
78      this->Filter = Filter;
79    }
80
81    typedef std::vector<Result>::iterator iterator;
82    iterator begin() { return Results.begin(); }
83    iterator end() { return Results.end(); }
84
85    Result *data() { return Results.empty()? 0 : &Results.front(); }
86    unsigned size() const { return Results.size(); }
87    bool empty() const { return Results.empty(); }
88
89    /// \brief Add a new result to this result set (if it isn't already in one
90    /// of the shadow maps), or replace an existing result (for, e.g., a
91    /// redeclaration).
92    ///
93    /// \param R the result to add (if it is unique).
94    ///
95    /// \param R the context in which this result will be named.
96    void MaybeAddResult(Result R, DeclContext *CurContext = 0);
97
98    /// \brief Enter into a new scope.
99    void EnterNewScope();
100
101    /// \brief Exit from the current scope.
102    void ExitScope();
103
104    /// \name Name lookup predicates
105    ///
106    /// These predicates can be passed to the name lookup functions to filter the
107    /// results of name lookup. All of the predicates have the same type, so that
108    ///
109    //@{
110    bool IsOrdinaryName(NamedDecl *ND) const;
111    bool IsNestedNameSpecifier(NamedDecl *ND) const;
112    bool IsEnum(NamedDecl *ND) const;
113    bool IsClassOrStruct(NamedDecl *ND) const;
114    bool IsUnion(NamedDecl *ND) const;
115    bool IsNamespace(NamedDecl *ND) const;
116    bool IsNamespaceOrAlias(NamedDecl *ND) const;
117    bool IsType(NamedDecl *ND) const;
118    bool IsMember(NamedDecl *ND) const;
119    //@}
120  };
121}
122
123/// \brief Determines whether the given hidden result could be found with
124/// some extra work, e.g., by qualifying the name.
125///
126/// \param Hidden the declaration that is hidden by the currenly \p Visible
127/// declaration.
128///
129/// \param Visible the declaration with the same name that is already visible.
130///
131/// \returns true if the hidden result can be found by some mechanism,
132/// false otherwise.
133static bool canHiddenResultBeFound(const LangOptions &LangOpts,
134                                   NamedDecl *Hidden, NamedDecl *Visible) {
135  // In C, there is no way to refer to a hidden name.
136  if (!LangOpts.CPlusPlus)
137    return false;
138
139  DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
140
141  // There is no way to qualify a name declared in a function or method.
142  if (HiddenCtx->isFunctionOrMethod())
143    return false;
144
145  return HiddenCtx != Visible->getDeclContext()->getLookupContext();
146}
147
148/// \brief Compute the qualification required to get from the current context
149/// (\p CurContext) to the target context (\p TargetContext).
150///
151/// \param Context the AST context in which the qualification will be used.
152///
153/// \param CurContext the context where an entity is being named, which is
154/// typically based on the current scope.
155///
156/// \param TargetContext the context in which the named entity actually
157/// resides.
158///
159/// \returns a nested name specifier that refers into the target context, or
160/// NULL if no qualification is needed.
161static NestedNameSpecifier *
162getRequiredQualification(ASTContext &Context,
163                         DeclContext *CurContext,
164                         DeclContext *TargetContext) {
165  llvm::SmallVector<DeclContext *, 4> TargetParents;
166
167  for (DeclContext *CommonAncestor = TargetContext;
168       CommonAncestor && !CommonAncestor->Encloses(CurContext);
169       CommonAncestor = CommonAncestor->getLookupParent()) {
170    if (CommonAncestor->isTransparentContext() ||
171        CommonAncestor->isFunctionOrMethod())
172      continue;
173
174    TargetParents.push_back(CommonAncestor);
175  }
176
177  NestedNameSpecifier *Result = 0;
178  while (!TargetParents.empty()) {
179    DeclContext *Parent = TargetParents.back();
180    TargetParents.pop_back();
181
182    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
183      Result = NestedNameSpecifier::Create(Context, Result, Namespace);
184    else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
185      Result = NestedNameSpecifier::Create(Context, Result,
186                                           false,
187                                     Context.getTypeDeclType(TD).getTypePtr());
188    else
189      assert(Parent->isTranslationUnit());
190  }
191  return Result;
192}
193
194void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
195  assert(!ShadowMaps.empty() && "Must enter into a results scope");
196
197  if (R.Kind != Result::RK_Declaration) {
198    // For non-declaration results, just add the result.
199    Results.push_back(R);
200    return;
201  }
202
203  // Skip unnamed entities.
204  if (!R.Declaration->getDeclName())
205    return;
206
207  // Look through using declarations.
208  if (UsingDecl *Using = dyn_cast<UsingDecl>(R.Declaration))
209    MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
210                   CurContext);
211
212  // Handle each declaration in an overload set separately.
213  if (OverloadedFunctionDecl *Ovl
214        = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) {
215    for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
216         FEnd = Ovl->function_end();
217         F != FEnd; ++F)
218      MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
219
220    return;
221  }
222
223  Decl *CanonDecl = R.Declaration->getCanonicalDecl();
224  unsigned IDNS = CanonDecl->getIdentifierNamespace();
225
226  // Friend declarations and declarations introduced due to friends are never
227  // added as results.
228  if (isa<FriendDecl>(CanonDecl) ||
229      (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
230    return;
231
232  if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
233    // __va_list_tag is a freak of nature. Find it and skip it.
234    if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
235      return;
236
237    // Filter out names reserved for the implementation (C99 7.1.3,
238    // C++ [lib.global.names]). Users don't need to see those.
239    //
240    // FIXME: Add predicate for this.
241    if (Id->getLength() >= 2) {
242      const char *Name = Id->getNameStart();
243      if (Name[0] == '_' &&
244          (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
245        return;
246    }
247  }
248
249  // C++ constructors are never found by name lookup.
250  if (isa<CXXConstructorDecl>(CanonDecl))
251    return;
252
253  // Filter out any unwanted results.
254  if (Filter && !(this->*Filter)(R.Declaration))
255    return;
256
257  ShadowMap &SMap = ShadowMaps.back();
258  ShadowMap::iterator I, IEnd;
259  for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
260       I != IEnd; ++I) {
261    NamedDecl *ND = I->second.first;
262    unsigned Index = I->second.second;
263    if (ND->getCanonicalDecl() == CanonDecl) {
264      // This is a redeclaration. Always pick the newer declaration.
265      I->second.first = R.Declaration;
266      Results[Index].Declaration = R.Declaration;
267
268      // Pick the best rank of the two.
269      Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
270
271      // We're done.
272      return;
273    }
274  }
275
276  // This is a new declaration in this scope. However, check whether this
277  // declaration name is hidden by a similarly-named declaration in an outer
278  // scope.
279  std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
280  --SMEnd;
281  for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
282    for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
283         I != IEnd; ++I) {
284      // A tag declaration does not hide a non-tag declaration.
285      if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
286          (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
287                   Decl::IDNS_ObjCProtocol)))
288        continue;
289
290      // Protocols are in distinct namespaces from everything else.
291      if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
292           || (IDNS & Decl::IDNS_ObjCProtocol)) &&
293          I->second.first->getIdentifierNamespace() != IDNS)
294        continue;
295
296      // The newly-added result is hidden by an entry in the shadow map.
297      if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
298                                 I->second.first)) {
299        // Note that this result was hidden.
300        R.Hidden = true;
301        R.QualifierIsInformative = false;
302
303        if (!R.Qualifier)
304          R.Qualifier = getRequiredQualification(SemaRef.Context,
305                                                 CurContext,
306                                              R.Declaration->getDeclContext());
307      } else {
308        // This result was hidden and cannot be found; don't bother adding
309        // it.
310        return;
311      }
312
313      break;
314    }
315  }
316
317  // Make sure that any given declaration only shows up in the result set once.
318  if (!AllDeclsFound.insert(CanonDecl))
319    return;
320
321  // If the filter is for nested-name-specifiers, then this result starts a
322  // nested-name-specifier.
323  if ((Filter == &ResultBuilder::IsNestedNameSpecifier) ||
324      (Filter == &ResultBuilder::IsMember &&
325       isa<CXXRecordDecl>(R.Declaration) &&
326       cast<CXXRecordDecl>(R.Declaration)->isInjectedClassName()))
327    R.StartsNestedNameSpecifier = true;
328
329  // If this result is supposed to have an informative qualifier, add one.
330  if (R.QualifierIsInformative && !R.Qualifier &&
331      !R.StartsNestedNameSpecifier) {
332    DeclContext *Ctx = R.Declaration->getDeclContext();
333    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
334      R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
335    else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
336      R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
337                             SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
338    else
339      R.QualifierIsInformative = false;
340  }
341
342  // Insert this result into the set of results and into the current shadow
343  // map.
344  SMap.insert(std::make_pair(R.Declaration->getDeclName(),
345                             std::make_pair(R.Declaration, Results.size())));
346  Results.push_back(R);
347}
348
349/// \brief Enter into a new scope.
350void ResultBuilder::EnterNewScope() {
351  ShadowMaps.push_back(ShadowMap());
352}
353
354/// \brief Exit from the current scope.
355void ResultBuilder::ExitScope() {
356  ShadowMaps.pop_back();
357}
358
359/// \brief Determines whether this given declaration will be found by
360/// ordinary name lookup.
361bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
362  unsigned IDNS = Decl::IDNS_Ordinary;
363  if (SemaRef.getLangOptions().CPlusPlus)
364    IDNS |= Decl::IDNS_Tag;
365
366  return ND->getIdentifierNamespace() & IDNS;
367}
368
369/// \brief Determines whether the given declaration is suitable as the
370/// start of a C++ nested-name-specifier, e.g., a class or namespace.
371bool ResultBuilder::IsNestedNameSpecifier(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  return SemaRef.isAcceptableNestedNameSpecifier(ND);
377}
378
379/// \brief Determines whether the given declaration is an enumeration.
380bool ResultBuilder::IsEnum(NamedDecl *ND) const {
381  return isa<EnumDecl>(ND);
382}
383
384/// \brief Determines whether the given declaration is a class or struct.
385bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
386  // Allow us to find class templates, too.
387  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
388    ND = ClassTemplate->getTemplatedDecl();
389
390  if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
391    return RD->getTagKind() == TagDecl::TK_class ||
392    RD->getTagKind() == TagDecl::TK_struct;
393
394  return false;
395}
396
397/// \brief Determines whether the given declaration is a union.
398bool ResultBuilder::IsUnion(NamedDecl *ND) const {
399  // Allow us to find class templates, too.
400  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
401    ND = ClassTemplate->getTemplatedDecl();
402
403  if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
404    return RD->getTagKind() == TagDecl::TK_union;
405
406  return false;
407}
408
409/// \brief Determines whether the given declaration is a namespace.
410bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
411  return isa<NamespaceDecl>(ND);
412}
413
414/// \brief Determines whether the given declaration is a namespace or
415/// namespace alias.
416bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
417  return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
418}
419
420/// \brief Brief determines whether the given declaration is a namespace or
421/// namespace alias.
422bool ResultBuilder::IsType(NamedDecl *ND) const {
423  return isa<TypeDecl>(ND);
424}
425
426/// \brief Since every declaration found within a class is a member that we
427/// care about, always returns true. This predicate exists mostly to
428/// communicate to the result builder that we are performing a lookup for
429/// member access.
430bool ResultBuilder::IsMember(NamedDecl *ND) const {
431  return true;
432}
433
434// Find the next outer declaration context corresponding to this scope.
435static DeclContext *findOuterContext(Scope *S) {
436  for (S = S->getParent(); S; S = S->getParent())
437    if (S->getEntity())
438      return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
439
440  return 0;
441}
442
443/// \brief Collect the results of searching for members within the given
444/// declaration context.
445///
446/// \param Ctx the declaration context from which we will gather results.
447///
448/// \param Rank the rank given to results in this declaration context.
449///
450/// \param Visited the set of declaration contexts that have already been
451/// visited. Declaration contexts will only be visited once.
452///
453/// \param Results the result set that will be extended with any results
454/// found within this declaration context (and, for a C++ class, its bases).
455///
456/// \param InBaseClass whether we are in a base class.
457///
458/// \returns the next higher rank value, after considering all of the
459/// names within this declaration context.
460static unsigned CollectMemberLookupResults(DeclContext *Ctx,
461                                           unsigned Rank,
462                                           DeclContext *CurContext,
463                                 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
464                                           ResultBuilder &Results,
465                                           bool InBaseClass = false) {
466  // Make sure we don't visit the same context twice.
467  if (!Visited.insert(Ctx->getPrimaryContext()))
468    return Rank;
469
470  // Enumerate all of the results in this context.
471  typedef CodeCompleteConsumer::Result Result;
472  Results.EnterNewScope();
473  for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
474       CurCtx = CurCtx->getNextContext()) {
475    for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
476                                 DEnd = CurCtx->decls_end();
477         D != DEnd; ++D) {
478      if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
479        Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
480
481      // Visit transparent contexts inside this context.
482      if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
483        if (InnerCtx->isTransparentContext())
484          CollectMemberLookupResults(InnerCtx, Rank, CurContext, Visited,
485                                     Results, InBaseClass);
486      }
487    }
488  }
489
490  // Traverse the contexts of inherited classes.
491  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
492    for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
493                                         BEnd = Record->bases_end();
494         B != BEnd; ++B) {
495      QualType BaseType = B->getType();
496
497      // Don't look into dependent bases, because name lookup can't look
498      // there anyway.
499      if (BaseType->isDependentType())
500        continue;
501
502      const RecordType *Record = BaseType->getAs<RecordType>();
503      if (!Record)
504        continue;
505
506      // FIXME: It would be nice to be able to determine whether referencing
507      // a particular member would be ambiguous. For example, given
508      //
509      //   struct A { int member; };
510      //   struct B { int member; };
511      //   struct C : A, B { };
512      //
513      //   void f(C *c) { c->### }
514      // accessing 'member' would result in an ambiguity. However, code
515      // completion could be smart enough to qualify the member with the
516      // base class, e.g.,
517      //
518      //   c->B::member
519      //
520      // or
521      //
522      //   c->A::member
523
524      // Collect results from this base class (and its bases).
525      CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
526                                 Results, /*InBaseClass=*/true);
527    }
528  }
529
530  // FIXME: Look into base classes in Objective-C!
531
532  Results.ExitScope();
533  return Rank + 1;
534}
535
536/// \brief Collect the results of searching for members within the given
537/// declaration context.
538///
539/// \param Ctx the declaration context from which we will gather results.
540///
541/// \param InitialRank the initial rank given to results in this declaration
542/// context. Larger rank values will be used for, e.g., members found in
543/// base classes.
544///
545/// \param Results the result set that will be extended with any results
546/// found within this declaration context (and, for a C++ class, its bases).
547///
548/// \returns the next higher rank value, after considering all of the
549/// names within this declaration context.
550static unsigned CollectMemberLookupResults(DeclContext *Ctx,
551                                           unsigned InitialRank,
552                                           DeclContext *CurContext,
553                                           ResultBuilder &Results) {
554  llvm::SmallPtrSet<DeclContext *, 16> Visited;
555  return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
556                                    Results);
557}
558
559/// \brief Collect the results of searching for declarations within the given
560/// scope and its parent scopes.
561///
562/// \param S the scope in which we will start looking for declarations.
563///
564/// \param InitialRank the initial rank given to results in this scope.
565/// Larger rank values will be used for results found in parent scopes.
566///
567/// \param CurContext the context from which lookup results will be found.
568///
569/// \param Results the builder object that will receive each result.
570static unsigned CollectLookupResults(Scope *S,
571                                     TranslationUnitDecl *TranslationUnit,
572                                     unsigned InitialRank,
573                                     DeclContext *CurContext,
574                                     ResultBuilder &Results) {
575  if (!S)
576    return InitialRank;
577
578  // FIXME: Using directives!
579
580  unsigned NextRank = InitialRank;
581  Results.EnterNewScope();
582  if (S->getEntity() &&
583      !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
584    // Look into this scope's declaration context, along with any of its
585    // parent lookup contexts (e.g., enclosing classes), up to the point
586    // where we hit the context stored in the next outer scope.
587    DeclContext *Ctx = (DeclContext *)S->getEntity();
588    DeclContext *OuterCtx = findOuterContext(S);
589
590    for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
591         Ctx = Ctx->getLookupParent()) {
592      if (Ctx->isFunctionOrMethod())
593        continue;
594
595      NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
596                                            Results);
597    }
598  } else if (!S->getParent()) {
599    // Look into the translation unit scope. We walk through the translation
600    // unit's declaration context, because the Scope itself won't have all of
601    // the declarations if we loaded a precompiled header.
602    // FIXME: We would like the translation unit's Scope object to point to the
603    // translation unit, so we don't need this special "if" branch. However,
604    // doing so would force the normal C++ name-lookup code to look into the
605    // translation unit decl when the IdentifierInfo chains would suffice.
606    // Once we fix that problem (which is part of a more general "don't look
607    // in DeclContexts unless we have to" optimization), we can eliminate the
608    // TranslationUnit parameter entirely.
609    NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
610                                          CurContext, Results);
611  } else {
612    // Walk through the declarations in this Scope.
613    for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
614         D != DEnd; ++D) {
615      if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
616        Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
617                               CurContext);
618    }
619
620    NextRank = NextRank + 1;
621  }
622
623  // Lookup names in the parent scope.
624  NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
625                                  CurContext, Results);
626  Results.ExitScope();
627
628  return NextRank;
629}
630
631/// \brief Add type specifiers for the current language as keyword results.
632static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
633                                    ResultBuilder &Results) {
634  typedef CodeCompleteConsumer::Result Result;
635  Results.MaybeAddResult(Result("short", Rank));
636  Results.MaybeAddResult(Result("long", Rank));
637  Results.MaybeAddResult(Result("signed", Rank));
638  Results.MaybeAddResult(Result("unsigned", Rank));
639  Results.MaybeAddResult(Result("void", Rank));
640  Results.MaybeAddResult(Result("char", Rank));
641  Results.MaybeAddResult(Result("int", Rank));
642  Results.MaybeAddResult(Result("float", Rank));
643  Results.MaybeAddResult(Result("double", Rank));
644  Results.MaybeAddResult(Result("enum", Rank));
645  Results.MaybeAddResult(Result("struct", Rank));
646  Results.MaybeAddResult(Result("union", Rank));
647
648  if (LangOpts.C99) {
649    // C99-specific
650    Results.MaybeAddResult(Result("_Complex", Rank));
651    Results.MaybeAddResult(Result("_Imaginary", Rank));
652    Results.MaybeAddResult(Result("_Bool", Rank));
653  }
654
655  if (LangOpts.CPlusPlus) {
656    // C++-specific
657    Results.MaybeAddResult(Result("bool", Rank));
658    Results.MaybeAddResult(Result("class", Rank));
659    Results.MaybeAddResult(Result("typename", Rank));
660    Results.MaybeAddResult(Result("wchar_t", Rank));
661
662    if (LangOpts.CPlusPlus0x) {
663      Results.MaybeAddResult(Result("char16_t", Rank));
664      Results.MaybeAddResult(Result("char32_t", Rank));
665      Results.MaybeAddResult(Result("decltype", Rank));
666    }
667  }
668
669  // GNU extensions
670  if (LangOpts.GNUMode) {
671    // FIXME: Enable when we actually support decimal floating point.
672    //    Results.MaybeAddResult(Result("_Decimal32", Rank));
673    //    Results.MaybeAddResult(Result("_Decimal64", Rank));
674    //    Results.MaybeAddResult(Result("_Decimal128", Rank));
675    Results.MaybeAddResult(Result("typeof", Rank));
676  }
677}
678
679/// \brief Add function parameter chunks to the given code completion string.
680static void AddFunctionParameterChunks(ASTContext &Context,
681                                       FunctionDecl *Function,
682                                       CodeCompletionString *Result) {
683  typedef CodeCompletionString::Chunk Chunk;
684
685  CodeCompletionString *CCStr = Result;
686
687  for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
688    ParmVarDecl *Param = Function->getParamDecl(P);
689
690    if (Param->hasDefaultArg()) {
691      // When we see an optional default argument, put that argument and
692      // the remaining default arguments into a new, optional string.
693      CodeCompletionString *Opt = new CodeCompletionString;
694      CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
695      CCStr = Opt;
696    }
697
698    if (P != 0)
699      CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
700
701    // Format the placeholder string.
702    std::string PlaceholderStr;
703    if (Param->getIdentifier())
704      PlaceholderStr = Param->getIdentifier()->getName();
705
706    Param->getType().getAsStringInternal(PlaceholderStr,
707                                         Context.PrintingPolicy);
708
709    // Add the placeholder string.
710    CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
711  }
712
713  if (const FunctionProtoType *Proto
714        = Function->getType()->getAs<FunctionProtoType>())
715    if (Proto->isVariadic())
716      CCStr->AddPlaceholderChunk(", ...");
717}
718
719/// \brief Add template parameter chunks to the given code completion string.
720static void AddTemplateParameterChunks(ASTContext &Context,
721                                       TemplateDecl *Template,
722                                       CodeCompletionString *Result,
723                                       unsigned MaxParameters = 0) {
724  typedef CodeCompletionString::Chunk Chunk;
725
726  CodeCompletionString *CCStr = Result;
727  bool FirstParameter = true;
728
729  TemplateParameterList *Params = Template->getTemplateParameters();
730  TemplateParameterList::iterator PEnd = Params->end();
731  if (MaxParameters)
732    PEnd = Params->begin() + MaxParameters;
733  for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
734    bool HasDefaultArg = false;
735    std::string PlaceholderStr;
736    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
737      if (TTP->wasDeclaredWithTypename())
738        PlaceholderStr = "typename";
739      else
740        PlaceholderStr = "class";
741
742      if (TTP->getIdentifier()) {
743        PlaceholderStr += ' ';
744        PlaceholderStr += TTP->getIdentifier()->getName();
745      }
746
747      HasDefaultArg = TTP->hasDefaultArgument();
748    } else if (NonTypeTemplateParmDecl *NTTP
749               = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
750      if (NTTP->getIdentifier())
751        PlaceholderStr = NTTP->getIdentifier()->getName();
752      NTTP->getType().getAsStringInternal(PlaceholderStr,
753                                          Context.PrintingPolicy);
754      HasDefaultArg = NTTP->hasDefaultArgument();
755    } else {
756      assert(isa<TemplateTemplateParmDecl>(*P));
757      TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
758
759      // Since putting the template argument list into the placeholder would
760      // be very, very long, we just use an abbreviation.
761      PlaceholderStr = "template<...> class";
762      if (TTP->getIdentifier()) {
763        PlaceholderStr += ' ';
764        PlaceholderStr += TTP->getIdentifier()->getName();
765      }
766
767      HasDefaultArg = TTP->hasDefaultArgument();
768    }
769
770    if (HasDefaultArg) {
771      // When we see an optional default argument, put that argument and
772      // the remaining default arguments into a new, optional string.
773      CodeCompletionString *Opt = new CodeCompletionString;
774      CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
775      CCStr = Opt;
776    }
777
778    if (FirstParameter)
779      FirstParameter = false;
780    else
781      CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
782
783    // Add the placeholder string.
784    CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
785  }
786}
787
788/// \brief Add a qualifier to the given code-completion string, if the
789/// provided nested-name-specifier is non-NULL.
790void AddQualifierToCompletionString(CodeCompletionString *Result,
791                                    NestedNameSpecifier *Qualifier,
792                                    bool QualifierIsInformative,
793                                    ASTContext &Context) {
794  if (!Qualifier)
795    return;
796
797  std::string PrintedNNS;
798  {
799    llvm::raw_string_ostream OS(PrintedNNS);
800    Qualifier->print(OS, Context.PrintingPolicy);
801  }
802  if (QualifierIsInformative)
803    Result->AddInformativeChunk(PrintedNNS.c_str());
804  else
805    Result->AddTextChunk(PrintedNNS.c_str());
806}
807
808/// \brief If possible, create a new code completion string for the given
809/// result.
810///
811/// \returns Either a new, heap-allocated code completion string describing
812/// how to use this result, or NULL to indicate that the string or name of the
813/// result is all that is needed.
814CodeCompletionString *
815CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
816  typedef CodeCompletionString::Chunk Chunk;
817
818  if (Kind == RK_Keyword)
819    return 0;
820
821  if (Kind == RK_Macro) {
822    MacroInfo *MI = S.PP.getMacroInfo(Macro);
823    if (!MI || !MI->isFunctionLike())
824      return 0;
825
826    // Format a function-like macro with placeholders for the arguments.
827    CodeCompletionString *Result = new CodeCompletionString;
828    Result->AddTypedTextChunk(Macro->getName().str().c_str());
829    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
830    for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
831         A != AEnd; ++A) {
832      if (A != MI->arg_begin())
833        Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
834
835      if (!MI->isVariadic() || A != AEnd - 1) {
836        // Non-variadic argument.
837        Result->AddPlaceholderChunk((*A)->getName().str().c_str());
838        continue;
839      }
840
841      // Variadic argument; cope with the different between GNU and C99
842      // variadic macros, providing a single placeholder for the rest of the
843      // arguments.
844      if ((*A)->isStr("__VA_ARGS__"))
845        Result->AddPlaceholderChunk("...");
846      else {
847        std::string Arg = (*A)->getName();
848        Arg += "...";
849        Result->AddPlaceholderChunk(Arg.c_str());
850      }
851    }
852    Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
853    return Result;
854  }
855
856  assert(Kind == RK_Declaration && "Missed a macro kind?");
857  NamedDecl *ND = Declaration;
858
859  if (StartsNestedNameSpecifier) {
860    CodeCompletionString *Result = new CodeCompletionString;
861    Result->AddTypedTextChunk(ND->getNameAsString().c_str());
862    Result->AddTextChunk("::");
863    return Result;
864  }
865
866  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
867    CodeCompletionString *Result = new CodeCompletionString;
868    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
869                                   S.Context);
870    Result->AddTypedTextChunk(Function->getNameAsString().c_str());
871    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
872    AddFunctionParameterChunks(S.Context, Function, Result);
873    Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
874    return Result;
875  }
876
877  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
878    CodeCompletionString *Result = new CodeCompletionString;
879    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
880                                   S.Context);
881    FunctionDecl *Function = FunTmpl->getTemplatedDecl();
882    Result->AddTypedTextChunk(Function->getNameAsString().c_str());
883
884    // Figure out which template parameters are deduced (or have default
885    // arguments).
886    llvm::SmallVector<bool, 16> Deduced;
887    S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
888    unsigned LastDeducibleArgument;
889    for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
890         --LastDeducibleArgument) {
891      if (!Deduced[LastDeducibleArgument - 1]) {
892        // C++0x: Figure out if the template argument has a default. If so,
893        // the user doesn't need to type this argument.
894        // FIXME: We need to abstract template parameters better!
895        bool HasDefaultArg = false;
896        NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
897                                                                      LastDeducibleArgument - 1);
898        if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
899          HasDefaultArg = TTP->hasDefaultArgument();
900        else if (NonTypeTemplateParmDecl *NTTP
901                 = dyn_cast<NonTypeTemplateParmDecl>(Param))
902          HasDefaultArg = NTTP->hasDefaultArgument();
903        else {
904          assert(isa<TemplateTemplateParmDecl>(Param));
905          HasDefaultArg
906            = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
907        }
908
909        if (!HasDefaultArg)
910          break;
911      }
912    }
913
914    if (LastDeducibleArgument) {
915      // Some of the function template arguments cannot be deduced from a
916      // function call, so we introduce an explicit template argument list
917      // containing all of the arguments up to the first deducible argument.
918      Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
919      AddTemplateParameterChunks(S.Context, FunTmpl, Result,
920                                 LastDeducibleArgument);
921      Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
922    }
923
924    // Add the function parameters
925    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
926    AddFunctionParameterChunks(S.Context, Function, Result);
927    Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
928    return Result;
929  }
930
931  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
932    CodeCompletionString *Result = new CodeCompletionString;
933    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
934                                   S.Context);
935    Result->AddTypedTextChunk(Template->getNameAsString().c_str());
936    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
937    AddTemplateParameterChunks(S.Context, Template, Result);
938    Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
939    return Result;
940  }
941
942  if (Qualifier) {
943    CodeCompletionString *Result = new CodeCompletionString;
944    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
945                                   S.Context);
946    Result->AddTypedTextChunk(ND->getNameAsString().c_str());
947    return Result;
948  }
949
950  return 0;
951}
952
953CodeCompletionString *
954CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
955                                                          unsigned CurrentArg,
956                                                               Sema &S) const {
957  typedef CodeCompletionString::Chunk Chunk;
958
959  CodeCompletionString *Result = new CodeCompletionString;
960  FunctionDecl *FDecl = getFunction();
961  const FunctionProtoType *Proto
962    = dyn_cast<FunctionProtoType>(getFunctionType());
963  if (!FDecl && !Proto) {
964    // Function without a prototype. Just give the return type and a
965    // highlighted ellipsis.
966    const FunctionType *FT = getFunctionType();
967    Result->AddTextChunk(
968            FT->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
969    Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
970    Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
971    Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
972    return Result;
973  }
974
975  if (FDecl)
976    Result->AddTextChunk(FDecl->getNameAsString().c_str());
977  else
978    Result->AddTextChunk(
979         Proto->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
980
981  Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
982  unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
983  for (unsigned I = 0; I != NumParams; ++I) {
984    if (I)
985      Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
986
987    std::string ArgString;
988    QualType ArgType;
989
990    if (FDecl) {
991      ArgString = FDecl->getParamDecl(I)->getNameAsString();
992      ArgType = FDecl->getParamDecl(I)->getOriginalType();
993    } else {
994      ArgType = Proto->getArgType(I);
995    }
996
997    ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
998
999    if (I == CurrentArg)
1000      Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
1001                             ArgString.c_str()));
1002    else
1003      Result->AddTextChunk(ArgString.c_str());
1004  }
1005
1006  if (Proto && Proto->isVariadic()) {
1007    Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1008    if (CurrentArg < NumParams)
1009      Result->AddTextChunk("...");
1010    else
1011      Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1012  }
1013  Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1014
1015  return Result;
1016}
1017
1018namespace {
1019  struct SortCodeCompleteResult {
1020    typedef CodeCompleteConsumer::Result Result;
1021
1022    bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
1023      if (X.getNameKind() != Y.getNameKind())
1024        return X.getNameKind() < Y.getNameKind();
1025
1026      return llvm::LowercaseString(X.getAsString())
1027        < llvm::LowercaseString(Y.getAsString());
1028    }
1029
1030    bool operator()(const Result &X, const Result &Y) const {
1031      // Sort first by rank.
1032      if (X.Rank < Y.Rank)
1033        return true;
1034      else if (X.Rank > Y.Rank)
1035        return false;
1036
1037      // Result kinds are ordered by decreasing importance.
1038      if (X.Kind < Y.Kind)
1039        return true;
1040      else if (X.Kind > Y.Kind)
1041        return false;
1042
1043      // Non-hidden names precede hidden names.
1044      if (X.Hidden != Y.Hidden)
1045        return !X.Hidden;
1046
1047      // Non-nested-name-specifiers precede nested-name-specifiers.
1048      if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1049        return !X.StartsNestedNameSpecifier;
1050
1051      // Ordering depends on the kind of result.
1052      switch (X.Kind) {
1053        case Result::RK_Declaration:
1054          // Order based on the declaration names.
1055          return isEarlierDeclarationName(X.Declaration->getDeclName(),
1056                                          Y.Declaration->getDeclName());
1057
1058        case Result::RK_Keyword:
1059          return strcmp(X.Keyword, Y.Keyword) < 0;
1060
1061        case Result::RK_Macro:
1062          return llvm::LowercaseString(X.Macro->getName()) <
1063                   llvm::LowercaseString(Y.Macro->getName());
1064      }
1065
1066      // Silence GCC warning.
1067      return false;
1068    }
1069  };
1070}
1071
1072static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1073                            ResultBuilder &Results) {
1074  Results.EnterNewScope();
1075  for (Preprocessor::macro_iterator M = PP.macro_begin(),
1076                                 MEnd = PP.macro_end();
1077       M != MEnd; ++M)
1078    Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1079  Results.ExitScope();
1080}
1081
1082static void HandleCodeCompleteResults(CodeCompleteConsumer *CodeCompleter,
1083                                      CodeCompleteConsumer::Result *Results,
1084                                      unsigned NumResults) {
1085  // Sort the results by rank/kind/etc.
1086  std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1087
1088  if (CodeCompleter)
1089    CodeCompleter->ProcessCodeCompleteResults(Results, NumResults);
1090}
1091
1092void Sema::CodeCompleteOrdinaryName(Scope *S) {
1093  ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
1094  unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1095                                           0, CurContext, Results);
1096  if (CodeCompleter->includeMacros())
1097    AddMacroResults(PP, NextRank, Results);
1098  HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1099}
1100
1101void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1102                                           SourceLocation OpLoc,
1103                                           bool IsArrow) {
1104  if (!BaseE || !CodeCompleter)
1105    return;
1106
1107  typedef CodeCompleteConsumer::Result Result;
1108
1109  Expr *Base = static_cast<Expr *>(BaseE);
1110  QualType BaseType = Base->getType();
1111
1112  if (IsArrow) {
1113    if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1114      BaseType = Ptr->getPointeeType();
1115    else if (BaseType->isObjCObjectPointerType())
1116    /*Do nothing*/ ;
1117    else
1118      return;
1119  }
1120
1121  ResultBuilder Results(*this, &ResultBuilder::IsMember);
1122  unsigned NextRank = 0;
1123
1124  if (const RecordType *Record = BaseType->getAs<RecordType>()) {
1125    NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1126                                          Record->getDecl(), Results);
1127
1128    if (getLangOptions().CPlusPlus) {
1129      if (!Results.empty()) {
1130        // The "template" keyword can follow "->" or "." in the grammar.
1131        // However, we only want to suggest the template keyword if something
1132        // is dependent.
1133        bool IsDependent = BaseType->isDependentType();
1134        if (!IsDependent) {
1135          for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1136            if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1137              IsDependent = Ctx->isDependentContext();
1138              break;
1139            }
1140        }
1141
1142        if (IsDependent)
1143          Results.MaybeAddResult(Result("template", NextRank++));
1144      }
1145
1146      // We could have the start of a nested-name-specifier. Add those
1147      // results as well.
1148      Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1149      CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
1150                           CurContext, Results);
1151    }
1152
1153    // Add macros
1154    if (CodeCompleter->includeMacros())
1155      AddMacroResults(PP, NextRank, Results);
1156
1157    // Hand off the results found for code completion.
1158    HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1159
1160    // We're done!
1161    return;
1162  }
1163}
1164
1165void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1166  if (!CodeCompleter)
1167    return;
1168
1169  typedef CodeCompleteConsumer::Result Result;
1170  ResultBuilder::LookupFilter Filter = 0;
1171  switch ((DeclSpec::TST)TagSpec) {
1172  case DeclSpec::TST_enum:
1173    Filter = &ResultBuilder::IsEnum;
1174    break;
1175
1176  case DeclSpec::TST_union:
1177    Filter = &ResultBuilder::IsUnion;
1178    break;
1179
1180  case DeclSpec::TST_struct:
1181  case DeclSpec::TST_class:
1182    Filter = &ResultBuilder::IsClassOrStruct;
1183    break;
1184
1185  default:
1186    assert(false && "Unknown type specifier kind in CodeCompleteTag");
1187    return;
1188  }
1189
1190  ResultBuilder Results(*this, Filter);
1191  unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1192                                           0, CurContext, Results);
1193
1194  if (getLangOptions().CPlusPlus) {
1195    // We could have the start of a nested-name-specifier. Add those
1196    // results as well.
1197    Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1198    NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1199                                    NextRank, CurContext, Results);
1200  }
1201
1202  if (CodeCompleter->includeMacros())
1203    AddMacroResults(PP, NextRank, Results);
1204  HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1205}
1206
1207void Sema::CodeCompleteCase(Scope *S) {
1208  if (getSwitchStack().empty() || !CodeCompleter)
1209    return;
1210
1211  SwitchStmt *Switch = getSwitchStack().back();
1212  if (!Switch->getCond()->getType()->isEnumeralType())
1213    return;
1214
1215  // Code-complete the cases of a switch statement over an enumeration type
1216  // by providing the list of
1217  EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1218
1219  // Determine which enumerators we have already seen in the switch statement.
1220  // FIXME: Ideally, we would also be able to look *past* the code-completion
1221  // token, in case we are code-completing in the middle of the switch and not
1222  // at the end. However, we aren't able to do so at the moment.
1223  llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
1224  NestedNameSpecifier *Qualifier = 0;
1225  for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1226       SC = SC->getNextSwitchCase()) {
1227    CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1228    if (!Case)
1229      continue;
1230
1231    Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1232    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1233      if (EnumConstantDecl *Enumerator
1234            = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1235        // We look into the AST of the case statement to determine which
1236        // enumerator was named. Alternatively, we could compute the value of
1237        // the integral constant expression, then compare it against the
1238        // values of each enumerator. However, value-based approach would not
1239        // work as well with C++ templates where enumerators declared within a
1240        // template are type- and value-dependent.
1241        EnumeratorsSeen.insert(Enumerator);
1242
1243        // If this is a qualified-id, keep track of the nested-name-specifier
1244        // so that we can reproduce it as part of code completion, e.g.,
1245        //
1246        //   switch (TagD.getKind()) {
1247        //     case TagDecl::TK_enum:
1248        //       break;
1249        //     case XXX
1250        //
1251        // At the XXX, our completions are TagDecl::TK_union,
1252        // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1253        // TK_struct, and TK_class.
1254        Qualifier = DRE->getQualifier();
1255      }
1256  }
1257
1258  if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1259    // If there are no prior enumerators in C++, check whether we have to
1260    // qualify the names of the enumerators that we suggest, because they
1261    // may not be visible in this scope.
1262    Qualifier = getRequiredQualification(Context, CurContext,
1263                                         Enum->getDeclContext());
1264
1265    // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1266  }
1267
1268  // Add any enumerators that have not yet been mentioned.
1269  ResultBuilder Results(*this);
1270  Results.EnterNewScope();
1271  for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1272                                  EEnd = Enum->enumerator_end();
1273       E != EEnd; ++E) {
1274    if (EnumeratorsSeen.count(*E))
1275      continue;
1276
1277    Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
1278  }
1279  Results.ExitScope();
1280
1281  if (CodeCompleter->includeMacros())
1282    AddMacroResults(PP, 1, Results);
1283  HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1284}
1285
1286namespace {
1287  struct IsBetterOverloadCandidate {
1288    Sema &S;
1289
1290  public:
1291    explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1292
1293    bool
1294    operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1295      return S.isBetterOverloadCandidate(X, Y);
1296    }
1297  };
1298}
1299
1300void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1301                            ExprTy **ArgsIn, unsigned NumArgs) {
1302  if (!CodeCompleter)
1303    return;
1304
1305  Expr *Fn = (Expr *)FnIn;
1306  Expr **Args = (Expr **)ArgsIn;
1307
1308  // Ignore type-dependent call expressions entirely.
1309  if (Fn->isTypeDependent() ||
1310      Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1311    return;
1312
1313  NamedDecl *Function;
1314  DeclarationName UnqualifiedName;
1315  NestedNameSpecifier *Qualifier;
1316  SourceRange QualifierRange;
1317  bool ArgumentDependentLookup;
1318  bool HasExplicitTemplateArgs;
1319  const TemplateArgumentLoc *ExplicitTemplateArgs;
1320  unsigned NumExplicitTemplateArgs;
1321
1322  DeconstructCallFunction(Fn,
1323                          Function, UnqualifiedName, Qualifier, QualifierRange,
1324                          ArgumentDependentLookup, HasExplicitTemplateArgs,
1325                          ExplicitTemplateArgs, NumExplicitTemplateArgs);
1326
1327
1328  // FIXME: What if we're calling something that isn't a function declaration?
1329  // FIXME: What if we're calling a pseudo-destructor?
1330  // FIXME: What if we're calling a member function?
1331
1332  // Build an overload candidate set based on the functions we find.
1333  OverloadCandidateSet CandidateSet;
1334  AddOverloadedCallCandidates(Function, UnqualifiedName,
1335                              ArgumentDependentLookup, HasExplicitTemplateArgs,
1336                              ExplicitTemplateArgs, NumExplicitTemplateArgs,
1337                              Args, NumArgs,
1338                              CandidateSet,
1339                              /*PartialOverloading=*/true);
1340
1341  // Sort the overload candidate set by placing the best overloads first.
1342  std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1343                   IsBetterOverloadCandidate(*this));
1344
1345  // Add the remaining viable overload candidates as code-completion reslults.
1346  typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1347  llvm::SmallVector<ResultCandidate, 8> Results;
1348
1349  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1350                                   CandEnd = CandidateSet.end();
1351       Cand != CandEnd; ++Cand) {
1352    if (Cand->Viable)
1353      Results.push_back(ResultCandidate(Cand->Function));
1354  }
1355  CodeCompleter->ProcessOverloadCandidates(NumArgs, Results.data(),
1356                                           Results.size());
1357}
1358
1359void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1360                                   bool EnteringContext) {
1361  if (!SS.getScopeRep() || !CodeCompleter)
1362    return;
1363
1364  DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1365  if (!Ctx)
1366    return;
1367
1368  ResultBuilder Results(*this);
1369  unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
1370
1371  // The "template" keyword can follow "::" in the grammar, but only
1372  // put it into the grammar if the nested-name-specifier is dependent.
1373  NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1374  if (!Results.empty() && NNS->isDependent())
1375    Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1376
1377  if (CodeCompleter->includeMacros())
1378    AddMacroResults(PP, NextRank + 1, Results);
1379  HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1380}
1381
1382void Sema::CodeCompleteUsing(Scope *S) {
1383  if (!CodeCompleter)
1384    return;
1385
1386  ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
1387  Results.EnterNewScope();
1388
1389  // If we aren't in class scope, we could see the "namespace" keyword.
1390  if (!S->isClassScope())
1391    Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1392
1393  // After "using", we can see anything that would start a
1394  // nested-name-specifier.
1395  unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1396                                           0, CurContext, Results);
1397  Results.ExitScope();
1398
1399  if (CodeCompleter->includeMacros())
1400    AddMacroResults(PP, NextRank, Results);
1401  HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1402}
1403
1404void Sema::CodeCompleteUsingDirective(Scope *S) {
1405  if (!CodeCompleter)
1406    return;
1407
1408  // After "using namespace", we expect to see a namespace name or namespace
1409  // alias.
1410  ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
1411  Results.EnterNewScope();
1412  unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1413                                           0, CurContext, Results);
1414  Results.ExitScope();
1415  if (CodeCompleter->includeMacros())
1416    AddMacroResults(PP, NextRank, Results);
1417  HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1418}
1419
1420void Sema::CodeCompleteNamespaceDecl(Scope *S)  {
1421  if (!CodeCompleter)
1422    return;
1423
1424  ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1425  DeclContext *Ctx = (DeclContext *)S->getEntity();
1426  if (!S->getParent())
1427    Ctx = Context.getTranslationUnitDecl();
1428
1429  if (Ctx && Ctx->isFileContext()) {
1430    // We only want to see those namespaces that have already been defined
1431    // within this scope, because its likely that the user is creating an
1432    // extended namespace declaration. Keep track of the most recent
1433    // definition of each namespace.
1434    std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1435    for (DeclContext::specific_decl_iterator<NamespaceDecl>
1436         NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1437         NS != NSEnd; ++NS)
1438      OrigToLatest[NS->getOriginalNamespace()] = *NS;
1439
1440    // Add the most recent definition (or extended definition) of each
1441    // namespace to the list of results.
1442    Results.EnterNewScope();
1443    for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1444         NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1445         NS != NSEnd; ++NS)
1446      Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1447                             CurContext);
1448    Results.ExitScope();
1449  }
1450
1451  if (CodeCompleter->includeMacros())
1452    AddMacroResults(PP, 1, Results);
1453  HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1454}
1455
1456void Sema::CodeCompleteNamespaceAliasDecl(Scope *S)  {
1457  if (!CodeCompleter)
1458    return;
1459
1460  // After "namespace", we expect to see a namespace or alias.
1461  ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
1462  unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1463                                           0, CurContext, Results);
1464  if (CodeCompleter->includeMacros())
1465    AddMacroResults(PP, NextRank, Results);
1466  HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1467}
1468
1469void Sema::CodeCompleteOperatorName(Scope *S) {
1470  if (!CodeCompleter)
1471    return;
1472
1473  typedef CodeCompleteConsumer::Result Result;
1474  ResultBuilder Results(*this, &ResultBuilder::IsType);
1475  Results.EnterNewScope();
1476
1477  // Add the names of overloadable operators.
1478#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly)      \
1479  if (std::strcmp(Spelling, "?"))                                                  \
1480    Results.MaybeAddResult(Result(Spelling, 0));
1481#include "clang/Basic/OperatorKinds.def"
1482
1483  // Add any type names visible from the current scope
1484  unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1485                                           0, CurContext, Results);
1486
1487  // Add any type specifiers
1488  AddTypeSpecifierResults(getLangOptions(), 0, Results);
1489
1490  // Add any nested-name-specifiers
1491  Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1492  NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1493                                  NextRank + 1, CurContext, Results);
1494  Results.ExitScope();
1495
1496  if (CodeCompleter->includeMacros())
1497    AddMacroResults(PP, NextRank, Results);
1498  HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1499}
1500
1501void Sema::CodeCompleteObjCProperty(Scope *S, ObjCDeclSpec &ODS) {
1502  if (!CodeCompleter)
1503    return;
1504  unsigned Attributes = ODS.getPropertyAttributes();
1505
1506  typedef CodeCompleteConsumer::Result Result;
1507  ResultBuilder Results(*this);
1508  Results.EnterNewScope();
1509  if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly))
1510    Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
1511  if (!(Attributes & ObjCDeclSpec::DQ_PR_assign))
1512    Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
1513  if (!(Attributes & ObjCDeclSpec::DQ_PR_readwrite))
1514    Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
1515  if (!(Attributes & ObjCDeclSpec::DQ_PR_retain))
1516    Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
1517  if (!(Attributes & ObjCDeclSpec::DQ_PR_copy))
1518    Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
1519  if (!(Attributes & ObjCDeclSpec::DQ_PR_nonatomic))
1520    Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
1521  if (!(Attributes & ObjCDeclSpec::DQ_PR_setter))
1522    Results.MaybeAddResult(CodeCompleteConsumer::Result("setter", 0));
1523  if (!(Attributes & ObjCDeclSpec::DQ_PR_getter))
1524    Results.MaybeAddResult(CodeCompleteConsumer::Result("getter", 0));
1525  Results.ExitScope();
1526  HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1527}
1528
1529void Sema::CodeCompleteObjCFactoryMethod(Scope *S, IdentifierInfo *FName) {
1530  typedef CodeCompleteConsumer::Result Result;
1531  ResultBuilder Results(*this);
1532  Results.EnterNewScope();
1533
1534  ObjCInterfaceDecl *CDecl = getObjCInterfaceDecl(FName);
1535
1536  while (CDecl != NULL) {
1537    for (ObjCInterfaceDecl::classmeth_iterator I = CDecl->classmeth_begin(),
1538                                               E = CDecl->classmeth_end();
1539         I != E; ++I) {
1540      Results.MaybeAddResult(Result(*I, 0), CurContext);
1541    }
1542    // Add class methods in protocols.
1543    const ObjCList<ObjCProtocolDecl> &Protocols=CDecl->getReferencedProtocols();
1544    for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1545         E = Protocols.end(); I != E; ++I) {
1546      for (ObjCProtocolDecl::classmeth_iterator I2 = (*I)->classmeth_begin(),
1547                                                E2 = (*I)->classmeth_end();
1548           I2 != E2; ++I2) {
1549        Results.MaybeAddResult(Result(*I2, 0), CurContext);
1550      }
1551    }
1552    // Add class methods in categories.
1553    ObjCCategoryDecl *CatDecl = CDecl->getCategoryList();
1554    while (CatDecl) {
1555      for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
1556                                                E = CatDecl->classmeth_end();
1557           I != E; ++I) {
1558        Results.MaybeAddResult(Result(*I, 0), CurContext);
1559      }
1560      // Add a categories protocol methods.
1561      const ObjCList<ObjCProtocolDecl> &Protocols =
1562        CatDecl->getReferencedProtocols();
1563      for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1564           E = Protocols.end(); I != E; ++I) {
1565        for (ObjCProtocolDecl::classmeth_iterator I2 = (*I)->classmeth_begin(),
1566                                                  E2 = (*I)->classmeth_end();
1567             I2 != E2; ++I2) {
1568          Results.MaybeAddResult(Result(*I2, 0), CurContext);
1569        }
1570      }
1571      CatDecl = CatDecl->getNextClassCategory();
1572    }
1573    CDecl = CDecl->getSuperClass();
1574  }
1575  Results.ExitScope();
1576  // This also suppresses remaining diagnostics.
1577  HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1578}
1579
1580void Sema::CodeCompleteObjCInstanceMethod(Scope *S, ExprTy *Receiver) {
1581  typedef CodeCompleteConsumer::Result Result;
1582  ResultBuilder Results(*this);
1583  Results.EnterNewScope();
1584
1585  Expr *RecExpr = static_cast<Expr *>(Receiver);
1586  QualType RecType = RecExpr->getType();
1587
1588  const ObjCObjectPointerType* OCOPT = RecType->getAs<ObjCObjectPointerType>();
1589
1590  if (!OCOPT)
1591    return;
1592
1593  // FIXME: handle 'id', 'Class', and qualified types.
1594  ObjCInterfaceDecl *CDecl = OCOPT->getInterfaceDecl();
1595
1596  while (CDecl != NULL) {
1597    for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1598                                               E = CDecl->instmeth_end();
1599         I != E; ++I) {
1600      Results.MaybeAddResult(Result(*I, 0), CurContext);
1601    }
1602    // Add class methods in protocols.
1603    const ObjCList<ObjCProtocolDecl> &Protocols=CDecl->getReferencedProtocols();
1604    for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1605         E = Protocols.end(); I != E; ++I) {
1606      for (ObjCProtocolDecl::instmeth_iterator I2 = (*I)->instmeth_begin(),
1607                                                E2 = (*I)->instmeth_end();
1608           I2 != E2; ++I2) {
1609        Results.MaybeAddResult(Result(*I2, 0), CurContext);
1610      }
1611    }
1612    // Add class methods in categories.
1613    ObjCCategoryDecl *CatDecl = CDecl->getCategoryList();
1614    while (CatDecl) {
1615      for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
1616                                                E = CatDecl->instmeth_end();
1617           I != E; ++I) {
1618        Results.MaybeAddResult(Result(*I, 0), CurContext);
1619      }
1620      // Add a categories protocol methods.
1621      const ObjCList<ObjCProtocolDecl> &Protocols =
1622        CatDecl->getReferencedProtocols();
1623      for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1624           E = Protocols.end(); I != E; ++I) {
1625        for (ObjCProtocolDecl::instmeth_iterator I2 = (*I)->instmeth_begin(),
1626                                                  E2 = (*I)->instmeth_end();
1627             I2 != E2; ++I2) {
1628          Results.MaybeAddResult(Result(*I2, 0), CurContext);
1629        }
1630      }
1631      CatDecl = CatDecl->getNextClassCategory();
1632    }
1633    CDecl = CDecl->getSuperClass();
1634  }
1635  Results.ExitScope();
1636  // This also suppresses remaining diagnostics.
1637  HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1638}
1639