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