CodeCompleteConsumer.cpp revision 78d6ae80f2c1eeb9817a9ca1a87052505450fcad
1//===---- CodeCompleteConsumer.h - Code Completion Interface ----*- 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 implements the CodeCompleteConsumer class.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Sema/CodeCompleteConsumer.h"
14#include "clang/AST/DeclCXX.h"
15#include "clang/Parse/Scope.h"
16#include "clang/Lex/Preprocessor.h"
17#include "Sema.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/Support/Compiler.h"
20#include "llvm/Support/raw_ostream.h"
21#include <algorithm>
22#include <cstring>
23#include <functional>
24using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// Code completion string implementation
28//===----------------------------------------------------------------------===//
29CodeCompletionString::Chunk
30CodeCompletionString::Chunk::CreateText(const char *Text) {
31  Chunk Result;
32  Result.Kind = CK_Text;
33  char *New = new char [std::strlen(Text) + 1];
34  std::strcpy(New, Text);
35  Result.Text = New;
36  return Result;
37}
38
39CodeCompletionString::Chunk
40CodeCompletionString::Chunk::CreateOptional(
41                                 std::auto_ptr<CodeCompletionString> Optional) {
42  Chunk Result;
43  Result.Kind = CK_Optional;
44  Result.Optional = Optional.release();
45  return Result;
46}
47
48CodeCompletionString::Chunk
49CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
50  Chunk Result;
51  Result.Kind = CK_Placeholder;
52  char *New = new char [std::strlen(Placeholder) + 1];
53  std::strcpy(New, Placeholder);
54  Result.Placeholder = New;
55  return Result;
56}
57
58void
59CodeCompletionString::Chunk::Destroy() {
60  switch (Kind) {
61  case CK_Text: delete [] Text; break;
62  case CK_Optional: delete Optional; break;
63  case CK_Placeholder: delete [] Placeholder; break;
64  }
65}
66
67CodeCompletionString::~CodeCompletionString() {
68  std::for_each(Chunks.begin(), Chunks.end(),
69                std::mem_fun_ref(&Chunk::Destroy));
70}
71
72std::string CodeCompletionString::getAsString() const {
73  std::string Result;
74  llvm::raw_string_ostream OS(Result);
75
76  for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
77    switch (C->Kind) {
78    case CK_Text: OS << C->Text; break;
79    case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
80    case CK_Placeholder: OS << "<#" << C->Placeholder << "#>"; break;
81    }
82  }
83
84  return Result;
85}
86
87//===----------------------------------------------------------------------===//
88// Code completion consumer implementation
89//===----------------------------------------------------------------------===//
90
91CodeCompleteConsumer::CodeCompleteConsumer(Sema &S) : SemaRef(S) {
92  SemaRef.setCodeCompleteConsumer(this);
93}
94
95CodeCompleteConsumer::~CodeCompleteConsumer() {
96  SemaRef.setCodeCompleteConsumer(0);
97}
98
99void
100CodeCompleteConsumer::CodeCompleteMemberReferenceExpr(Scope *S,
101                                                      QualType BaseType,
102                                                      bool IsArrow) {
103  if (IsArrow) {
104    if (const PointerType *Ptr = BaseType->getAs<PointerType>())
105      BaseType = Ptr->getPointeeType();
106    else if (BaseType->isObjCObjectPointerType())
107    /*Do nothing*/ ;
108    else
109      return;
110  }
111
112  ResultSet Results(*this);
113  unsigned NextRank = 0;
114
115  if (const RecordType *Record = BaseType->getAs<RecordType>()) {
116    NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank, Results);
117
118    if (getSema().getLangOptions().CPlusPlus) {
119      if (!Results.empty()) {
120        // The "template" keyword can follow "->" or "." in the grammar.
121        // However, we only want to suggest the template keyword if something
122        // is dependent.
123        bool IsDependent = BaseType->isDependentType();
124        if (!IsDependent) {
125          for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
126            if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
127              IsDependent = Ctx->isDependentContext();
128              break;
129            }
130        }
131
132        if (IsDependent)
133          Results.MaybeAddResult(Result("template", NextRank++));
134      }
135
136      // We could have the start of a nested-name-specifier. Add those
137      // results as well.
138      Results.setFilter(&CodeCompleteConsumer::IsNestedNameSpecifier);
139      CollectLookupResults(S, NextRank, Results);
140    }
141
142    // Hand off the results found for code completion.
143    ProcessCodeCompleteResults(Results.data(), Results.size());
144
145    // We're done!
146    return;
147  }
148}
149
150void CodeCompleteConsumer::CodeCompleteTag(Scope *S, ElaboratedType::TagKind TK) {
151  ResultSet::LookupFilter Filter = 0;
152  switch (TK) {
153  case ElaboratedType::TK_enum:
154    Filter = &CodeCompleteConsumer::IsEnum;
155    break;
156
157  case ElaboratedType::TK_class:
158  case ElaboratedType::TK_struct:
159    Filter = &CodeCompleteConsumer::IsClassOrStruct;
160    break;
161
162  case ElaboratedType::TK_union:
163    Filter = &CodeCompleteConsumer::IsUnion;
164    break;
165  }
166
167  ResultSet Results(*this, Filter);
168  unsigned NextRank = CollectLookupResults(S, 0, Results);
169
170  if (getSema().getLangOptions().CPlusPlus) {
171    // We could have the start of a nested-name-specifier. Add those
172    // results as well.
173    Results.setFilter(&CodeCompleteConsumer::IsNestedNameSpecifier);
174    CollectLookupResults(S, NextRank, Results);
175  }
176
177  ProcessCodeCompleteResults(Results.data(), Results.size());
178}
179
180void
181CodeCompleteConsumer::CodeCompleteQualifiedId(Scope *S,
182                                              NestedNameSpecifier *NNS,
183                                              bool EnteringContext) {
184  CXXScopeSpec SS;
185  SS.setScopeRep(NNS);
186  DeclContext *Ctx = getSema().computeDeclContext(SS, EnteringContext);
187  if (!Ctx)
188    return;
189
190  ResultSet Results(*this);
191  unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Results);
192
193  // The "template" keyword can follow "::" in the grammar, but only
194  // put it into the grammar if the nested-name-specifier is dependent.
195  if (!Results.empty() && NNS->isDependent())
196    Results.MaybeAddResult(Result("template", NextRank));
197
198  ProcessCodeCompleteResults(Results.data(), Results.size());
199}
200
201void CodeCompleteConsumer::CodeCompleteUsing(Scope *S) {
202  ResultSet Results(*this, &CodeCompleteConsumer::IsNestedNameSpecifier);
203
204  // If we aren't in class scope, we could see the "namespace" keyword.
205  if (!S->isClassScope())
206    Results.MaybeAddResult(Result("namespace", 0));
207
208  // After "using", we can see anything that would start a
209  // nested-name-specifier.
210  CollectLookupResults(S, 0, Results);
211
212  ProcessCodeCompleteResults(Results.data(), Results.size());
213}
214
215void CodeCompleteConsumer::CodeCompleteUsingDirective(Scope *S) {
216  // After "using namespace", we expect to see a namespace name or namespace
217  // alias.
218  ResultSet Results(*this, &CodeCompleteConsumer::IsNamespaceOrAlias);
219  CollectLookupResults(S, 0, Results);
220  ProcessCodeCompleteResults(Results.data(), Results.size());
221}
222
223void CodeCompleteConsumer::CodeCompleteNamespaceDecl(Scope *S) {
224  ResultSet Results(*this, &CodeCompleteConsumer::IsNamespace);
225  DeclContext *Ctx = (DeclContext *)S->getEntity();
226  if (!S->getParent())
227    Ctx = getSema().Context.getTranslationUnitDecl();
228
229  if (Ctx && Ctx->isFileContext()) {
230    // We only want to see those namespaces that have already been defined
231    // within this scope, because its likely that the user is creating an
232    // extended namespace declaration. Keep track of the most recent
233    // definition of each namespace.
234    std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
235    for (DeclContext::specific_decl_iterator<NamespaceDecl>
236           NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
237         NS != NSEnd; ++NS)
238      OrigToLatest[NS->getOriginalNamespace()] = *NS;
239
240    // Add the most recent definition (or extended definition) of each
241    // namespace to the list of results.
242    for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
243          NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
244         NS != NSEnd; ++NS)
245      Results.MaybeAddResult(Result(NS->second, 0));
246  }
247
248  ProcessCodeCompleteResults(Results.data(), Results.size());
249}
250
251void CodeCompleteConsumer::CodeCompleteNamespaceAliasDecl(Scope *S) {
252  // After "namespace", we expect to see a namespace  or alias.
253  ResultSet Results(*this, &CodeCompleteConsumer::IsNamespaceOrAlias);
254  CollectLookupResults(S, 0, Results);
255  ProcessCodeCompleteResults(Results.data(), Results.size());
256}
257
258void CodeCompleteConsumer::CodeCompleteOperatorName(Scope *S) {
259  ResultSet Results(*this, &CodeCompleteConsumer::IsType);
260
261  // Add the names of overloadable operators.
262#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly)      \
263  if (std::strcmp(Spelling, "?"))                                                  \
264    Results.MaybeAddResult(Result(Spelling, 0));
265#include "clang/Basic/OperatorKinds.def"
266
267  // Add any type names visible from the current scope
268  unsigned NextRank = CollectLookupResults(S, 0, Results);
269
270  // Add any type specifiers
271  AddTypeSpecifierResults(0, Results);
272
273  // Add any nested-name-specifiers
274  Results.setFilter(&CodeCompleteConsumer::IsNestedNameSpecifier);
275  CollectLookupResults(S, NextRank + 1, Results);
276
277  ProcessCodeCompleteResults(Results.data(), Results.size());
278}
279
280void CodeCompleteConsumer::ResultSet::MaybeAddResult(Result R) {
281  if (R.Kind != Result::RK_Declaration) {
282    // For non-declaration results, just add the result.
283    Results.push_back(R);
284    return;
285  }
286
287  // Look through using declarations.
288  if (UsingDecl *Using = dyn_cast<UsingDecl>(R.Declaration))
289    return MaybeAddResult(Result(Using->getTargetDecl(), R.Rank));
290
291  // Handle each declaration in an overload set separately.
292  if (OverloadedFunctionDecl *Ovl
293        = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) {
294    for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
295                                                FEnd = Ovl->function_end();
296         F != FEnd; ++F)
297      MaybeAddResult(Result(*F, R.Rank));
298
299    return;
300  }
301
302  Decl *CanonDecl = R.Declaration->getCanonicalDecl();
303  unsigned IDNS = CanonDecl->getIdentifierNamespace();
304
305  // Friend declarations and declarations introduced due to friends are never
306  // added as results.
307  if (isa<FriendDecl>(CanonDecl) ||
308      (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
309    return;
310
311  if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
312    // __va_list_tag is a freak of nature. Find it and skip it.
313    if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
314      return;
315
316    // FIXME: Should we filter out other names in the implementation's
317    // namespace, e.g., those containing a __ or that start with _[A-Z]?
318  }
319
320  // C++ constructors are never found by name lookup.
321  if (isa<CXXConstructorDecl>(CanonDecl))
322    return;
323
324  // Filter out any unwanted results.
325  if (Filter && !(Completer.*Filter)(R.Declaration))
326    return;
327
328  ShadowMap &SMap = ShadowMaps.back();
329  ShadowMap::iterator I, IEnd;
330  for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
331       I != IEnd; ++I) {
332    NamedDecl *ND = I->second.first;
333    unsigned Index = I->second.second;
334    if (ND->getCanonicalDecl() == CanonDecl) {
335      // This is a redeclaration. Always pick the newer declaration.
336      I->second.first = R.Declaration;
337      Results[Index].Declaration = R.Declaration;
338
339      // Pick the best rank of the two.
340      Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
341
342      // We're done.
343      return;
344    }
345  }
346
347  // This is a new declaration in this scope. However, check whether this
348  // declaration name is hidden by a similarly-named declaration in an outer
349  // scope.
350  std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
351  --SMEnd;
352  for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
353    for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
354         I != IEnd; ++I) {
355      // A tag declaration does not hide a non-tag declaration.
356      if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
357          (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
358                   Decl::IDNS_ObjCProtocol)))
359        continue;
360
361      // Protocols are in distinct namespaces from everything else.
362      if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
363           || (IDNS & Decl::IDNS_ObjCProtocol)) &&
364          I->second.first->getIdentifierNamespace() != IDNS)
365        continue;
366
367      // The newly-added result is hidden by an entry in the shadow map.
368      if (Completer.canHiddenResultBeFound(R.Declaration, I->second.first)) {
369        // Note that this result was hidden.
370        R.Hidden = true;
371      } else {
372        // This result was hidden and cannot be found; don't bother adding
373        // it.
374        return;
375      }
376
377      break;
378    }
379  }
380
381  // Make sure that any given declaration only shows up in the result set once.
382  if (!AllDeclsFound.insert(CanonDecl))
383    return;
384
385  // Insert this result into the set of results and into the current shadow
386  // map.
387  SMap.insert(std::make_pair(R.Declaration->getDeclName(),
388                             std::make_pair(R.Declaration, Results.size())));
389  Results.push_back(R);
390}
391
392/// \brief Enter into a new scope.
393void CodeCompleteConsumer::ResultSet::EnterNewScope() {
394  ShadowMaps.push_back(ShadowMap());
395}
396
397/// \brief Exit from the current scope.
398void CodeCompleteConsumer::ResultSet::ExitScope() {
399  ShadowMaps.pop_back();
400}
401
402// Find the next outer declaration context corresponding to this scope.
403static DeclContext *findOuterContext(Scope *S) {
404  for (S = S->getParent(); S; S = S->getParent())
405    if (S->getEntity())
406      return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
407
408  return 0;
409}
410
411/// \brief Collect the results of searching for declarations within the given
412/// scope and its parent scopes.
413///
414/// \param S the scope in which we will start looking for declarations.
415///
416/// \param InitialRank the initial rank given to results in this scope.
417/// Larger rank values will be used for results found in parent scopes.
418unsigned CodeCompleteConsumer::CollectLookupResults(Scope *S,
419                                                    unsigned InitialRank,
420                                                    ResultSet &Results) {
421  if (!S)
422    return InitialRank;
423
424  // FIXME: Using directives!
425
426  unsigned NextRank = InitialRank;
427  Results.EnterNewScope();
428  if (S->getEntity() &&
429      !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
430    // Look into this scope's declaration context, along with any of its
431    // parent lookup contexts (e.g., enclosing classes), up to the point
432    // where we hit the context stored in the next outer scope.
433    DeclContext *Ctx = (DeclContext *)S->getEntity();
434    DeclContext *OuterCtx = findOuterContext(S);
435
436    for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
437         Ctx = Ctx->getLookupParent()) {
438      if (Ctx->isFunctionOrMethod())
439        continue;
440
441      NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, Results);
442    }
443  } else if (!S->getParent()) {
444    // Look into the translation unit scope. We walk through the translation
445    // unit's declaration context, because the Scope itself won't have all of
446    // the declarations if
447    NextRank = CollectMemberLookupResults(
448                                    getSema().Context.getTranslationUnitDecl(),
449                                          NextRank + 1, Results);
450  } else {
451    // Walk through the declarations in this Scope.
452    for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
453         D != DEnd; ++D) {
454      if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
455        Results.MaybeAddResult(Result(ND, NextRank));
456    }
457
458    NextRank = NextRank + 1;
459  }
460
461  // Lookup names in the parent scope.
462  NextRank = CollectLookupResults(S->getParent(), NextRank, Results);
463  Results.ExitScope();
464
465  return NextRank;
466}
467
468/// \brief Collect the results of searching for members within the given
469/// declaration context.
470///
471/// \param Ctx the declaration context from which we will gather results.
472///
473/// \param InitialRank the initial rank given to results in this declaration
474/// context. Larger rank values will be used for, e.g., members found in
475/// base classes.
476///
477/// \param Results the result set that will be extended with any results
478/// found within this declaration context (and, for a C++ class, its bases).
479///
480/// \returns the next higher rank value, after considering all of the
481/// names within this declaration context.
482unsigned CodeCompleteConsumer::CollectMemberLookupResults(DeclContext *Ctx,
483                                                          unsigned InitialRank,
484                                                          ResultSet &Results) {
485  llvm::SmallPtrSet<DeclContext *, 16> Visited;
486  return CollectMemberLookupResults(Ctx, InitialRank, Visited, Results);
487}
488
489/// \brief Collect the results of searching for members within the given
490/// declaration context.
491///
492/// \param Ctx the declaration context from which we will gather results.
493///
494/// \param InitialRank the initial rank given to results in this declaration
495/// context. Larger rank values will be used for, e.g., members found in
496/// base classes.
497///
498/// \param Visited the set of declaration contexts that have already been
499/// visited. Declaration contexts will only be visited once.
500///
501/// \param Results the result set that will be extended with any results
502/// found within this declaration context (and, for a C++ class, its bases).
503///
504/// \returns the next higher rank value, after considering all of the
505/// names within this declaration context.
506unsigned CodeCompleteConsumer::CollectMemberLookupResults(DeclContext *Ctx,
507                                                          unsigned InitialRank,
508                                 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
509                                                          ResultSet &Results) {
510  // Make sure we don't visit the same context twice.
511  if (!Visited.insert(Ctx->getPrimaryContext()))
512    return InitialRank;
513
514  // Enumerate all of the results in this context.
515  Results.EnterNewScope();
516  for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
517       CurCtx = CurCtx->getNextContext()) {
518    for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
519                                 DEnd = CurCtx->decls_end();
520         D != DEnd; ++D) {
521      if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
522        Results.MaybeAddResult(Result(ND, InitialRank));
523    }
524  }
525
526  // Traverse the contexts of inherited classes.
527  unsigned NextRank = InitialRank;
528  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
529    for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
530                                         BEnd = Record->bases_end();
531         B != BEnd; ++B) {
532      QualType BaseType = B->getType();
533
534      // Don't look into dependent bases, because name lookup can't look
535      // there anyway.
536      if (BaseType->isDependentType())
537        continue;
538
539      const RecordType *Record = BaseType->getAs<RecordType>();
540      if (!Record)
541        continue;
542
543      // FIXME: It would be nice to be able to determine whether referencing
544      // a particular member would be ambiguous. For example, given
545      //
546      //   struct A { int member; };
547      //   struct B { int member; };
548      //   struct C : A, B { };
549      //
550      //   void f(C *c) { c->### }
551      // accessing 'member' would result in an ambiguity. However, code
552      // completion could be smart enough to qualify the member with the
553      // base class, e.g.,
554      //
555      //   c->B::member
556      //
557      // or
558      //
559      //   c->A::member
560
561      // Collect results from this base class (and its bases).
562      NextRank = std::max(NextRank,
563                          CollectMemberLookupResults(Record->getDecl(),
564                                                     InitialRank + 1,
565                                                     Visited,
566                                                     Results));
567    }
568  }
569
570  // FIXME: Look into base classes in Objective-C!
571
572  Results.ExitScope();
573  return NextRank;
574}
575
576/// \brief Determines whether the given declaration is suitable as the
577/// start of a C++ nested-name-specifier, e.g., a class or namespace.
578bool CodeCompleteConsumer::IsNestedNameSpecifier(NamedDecl *ND) const {
579  // Allow us to find class templates, too.
580  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
581    ND = ClassTemplate->getTemplatedDecl();
582
583  return getSema().isAcceptableNestedNameSpecifier(ND);
584}
585
586/// \brief Determines whether the given declaration is an enumeration.
587bool CodeCompleteConsumer::IsEnum(NamedDecl *ND) const {
588  return isa<EnumDecl>(ND);
589}
590
591/// \brief Determines whether the given declaration is a class or struct.
592bool CodeCompleteConsumer::IsClassOrStruct(NamedDecl *ND) const {
593  // Allow us to find class templates, too.
594  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
595    ND = ClassTemplate->getTemplatedDecl();
596
597  if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
598    return RD->getTagKind() == TagDecl::TK_class ||
599           RD->getTagKind() == TagDecl::TK_struct;
600
601  return false;
602}
603
604/// \brief Determines whether the given declaration is a union.
605bool CodeCompleteConsumer::IsUnion(NamedDecl *ND) const {
606  // Allow us to find class templates, too.
607  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
608    ND = ClassTemplate->getTemplatedDecl();
609
610  if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
611    return RD->getTagKind() == TagDecl::TK_union;
612
613  return false;
614}
615
616/// \brief Determines whether the given declaration is a namespace.
617bool CodeCompleteConsumer::IsNamespace(NamedDecl *ND) const {
618  return isa<NamespaceDecl>(ND);
619}
620
621/// \brief Determines whether the given declaration is a namespace or
622/// namespace alias.
623bool CodeCompleteConsumer::IsNamespaceOrAlias(NamedDecl *ND) const {
624  return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
625}
626
627/// \brief Brief determines whether the given declaration is a namespace or
628/// namespace alias.
629bool CodeCompleteConsumer::IsType(NamedDecl *ND) const {
630  return isa<TypeDecl>(ND);
631}
632
633namespace {
634  struct VISIBILITY_HIDDEN SortCodeCompleteResult {
635    typedef CodeCompleteConsumer::Result Result;
636
637    bool operator()(const Result &X, const Result &Y) const {
638      // Sort first by rank.
639      if (X.Rank < Y.Rank)
640        return true;
641      else if (X.Rank > Y.Rank)
642        return false;
643
644      // Result kinds are ordered by decreasing importance.
645      if (X.Kind < Y.Kind)
646        return true;
647      else if (X.Kind > Y.Kind)
648        return false;
649
650      // Non-hidden names precede hidden names.
651      if (X.Hidden != Y.Hidden)
652        return !X.Hidden;
653
654      // Ordering depends on the kind of result.
655      switch (X.Kind) {
656      case Result::RK_Declaration:
657        // Order based on the declaration names.
658        return X.Declaration->getDeclName() < Y.Declaration->getDeclName();
659
660      case Result::RK_Keyword:
661        return strcmp(X.Keyword, Y.Keyword) == -1;
662      }
663
664      // If only our C++ compiler did control-flow warnings properly.
665      return false;
666    }
667  };
668}
669
670/// \brief Determines whether the given hidden result could be found with
671/// some extra work, e.g., by qualifying the name.
672///
673/// \param Hidden the declaration that is hidden by the currenly \p Visible
674/// declaration.
675///
676/// \param Visible the declaration with the same name that is already visible.
677///
678/// \returns true if the hidden result can be found by some mechanism,
679/// false otherwise.
680bool CodeCompleteConsumer::canHiddenResultBeFound(NamedDecl *Hidden,
681                                                  NamedDecl *Visible) {
682  // In C, there is no way to refer to a hidden name.
683  if (!getSema().getLangOptions().CPlusPlus)
684    return false;
685
686  DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
687
688  // There is no way to qualify a name declared in a function or method.
689  if (HiddenCtx->isFunctionOrMethod())
690    return false;
691
692  // If the hidden and visible declarations are in different name-lookup
693  // contexts, then we can qualify the name of the hidden declaration.
694  // FIXME: Optionally compute the string needed to refer to the hidden
695  // name.
696  return HiddenCtx != Visible->getDeclContext()->getLookupContext();
697}
698
699/// \brief Add type specifiers for the current language as keyword results.
700void CodeCompleteConsumer::AddTypeSpecifierResults(unsigned Rank,
701                                                   ResultSet &Results) {
702  Results.MaybeAddResult(Result("short", Rank));
703  Results.MaybeAddResult(Result("long", Rank));
704  Results.MaybeAddResult(Result("signed", Rank));
705  Results.MaybeAddResult(Result("unsigned", Rank));
706  Results.MaybeAddResult(Result("void", Rank));
707  Results.MaybeAddResult(Result("char", Rank));
708  Results.MaybeAddResult(Result("int", Rank));
709  Results.MaybeAddResult(Result("float", Rank));
710  Results.MaybeAddResult(Result("double", Rank));
711  Results.MaybeAddResult(Result("enum", Rank));
712  Results.MaybeAddResult(Result("struct", Rank));
713  Results.MaybeAddResult(Result("union", Rank));
714
715  if (getSema().getLangOptions().C99) {
716    // C99-specific
717    Results.MaybeAddResult(Result("_Complex", Rank));
718    Results.MaybeAddResult(Result("_Imaginary", Rank));
719    Results.MaybeAddResult(Result("_Bool", Rank));
720  }
721
722  if (getSema().getLangOptions().CPlusPlus) {
723    // C++-specific
724    Results.MaybeAddResult(Result("bool", Rank));
725    Results.MaybeAddResult(Result("class", Rank));
726    Results.MaybeAddResult(Result("typename", Rank));
727    Results.MaybeAddResult(Result("wchar_t", Rank));
728
729    if (getSema().getLangOptions().CPlusPlus0x) {
730      Results.MaybeAddResult(Result("char16_t", Rank));
731      Results.MaybeAddResult(Result("char32_t", Rank));
732      Results.MaybeAddResult(Result("decltype", Rank));
733    }
734  }
735
736  // GNU extensions
737  if (getSema().getLangOptions().GNUMode) {
738    // FIXME: Enable when we actually support decimal floating point.
739    //    Results.MaybeAddResult(Result("_Decimal32", Rank));
740    //    Results.MaybeAddResult(Result("_Decimal64", Rank));
741    //    Results.MaybeAddResult(Result("_Decimal128", Rank));
742    Results.MaybeAddResult(Result("typeof", Rank));
743  }
744}
745
746/// \brief Add function parameter chunks to the given code completion string.
747static void AddFunctionParameterChunks(ASTContext &Context,
748                                       FunctionDecl *Function,
749                                       CodeCompletionString *Result) {
750  CodeCompletionString *CCStr = Result;
751
752  for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
753    ParmVarDecl *Param = Function->getParamDecl(P);
754
755    if (Param->hasDefaultArg()) {
756      // When we see an optional default argument, put that argument and
757      // the remaining default arguments into a new, optional string.
758      CodeCompletionString *Opt = new CodeCompletionString;
759      CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
760      CCStr = Opt;
761    }
762
763    if (P != 0)
764      CCStr->AddTextChunk(", ");
765
766    // Format the placeholder string.
767    std::string PlaceholderStr;
768    if (Param->getIdentifier())
769      PlaceholderStr = Param->getIdentifier()->getName();
770
771    Param->getType().getAsStringInternal(PlaceholderStr,
772                                         Context.PrintingPolicy);
773
774    // Add the placeholder string.
775    CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
776  }
777}
778
779/// \brief Add template parameter chunks to the given code completion string.
780static void AddTemplateParameterChunks(ASTContext &Context,
781                                       TemplateDecl *Template,
782                                       CodeCompletionString *Result,
783                                       unsigned MaxParameters = 0) {
784  CodeCompletionString *CCStr = Result;
785  bool FirstParameter = true;
786
787  TemplateParameterList *Params = Template->getTemplateParameters();
788  TemplateParameterList::iterator PEnd = Params->end();
789  if (MaxParameters)
790    PEnd = Params->begin() + MaxParameters;
791  for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
792    bool HasDefaultArg = false;
793    std::string PlaceholderStr;
794    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
795      if (TTP->wasDeclaredWithTypename())
796        PlaceholderStr = "typename";
797      else
798        PlaceholderStr = "class";
799
800      if (TTP->getIdentifier()) {
801        PlaceholderStr += ' ';
802        PlaceholderStr += TTP->getIdentifier()->getName();
803      }
804
805      HasDefaultArg = TTP->hasDefaultArgument();
806    } else if (NonTypeTemplateParmDecl *NTTP
807                 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
808      if (NTTP->getIdentifier())
809        PlaceholderStr = NTTP->getIdentifier()->getName();
810      NTTP->getType().getAsStringInternal(PlaceholderStr,
811                                          Context.PrintingPolicy);
812      HasDefaultArg = NTTP->hasDefaultArgument();
813    } else {
814      assert(isa<TemplateTemplateParmDecl>(*P));
815      TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
816
817      // Since putting the template argument list into the placeholder would
818      // be very, very long, we just use an abbreviation.
819      PlaceholderStr = "template<...> class";
820      if (TTP->getIdentifier()) {
821        PlaceholderStr += ' ';
822        PlaceholderStr += TTP->getIdentifier()->getName();
823      }
824
825      HasDefaultArg = TTP->hasDefaultArgument();
826    }
827
828    if (HasDefaultArg) {
829      // When we see an optional default argument, put that argument and
830      // the remaining default arguments into a new, optional string.
831      CodeCompletionString *Opt = new CodeCompletionString;
832      CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
833      CCStr = Opt;
834    }
835
836    if (FirstParameter)
837      FirstParameter = false;
838    else
839      CCStr->AddTextChunk(", ");
840
841    // Add the placeholder string.
842    CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
843  }
844}
845
846/// \brief If possible, create a new code completion string for the given
847/// result.
848///
849/// \returns Either a new, heap-allocated code completion string describing
850/// how to use this result, or NULL to indicate that the string or name of the
851/// result is all that is needed.
852CodeCompletionString *
853CodeCompleteConsumer::CreateCodeCompletionString(Result R) {
854  if (R.Kind != Result::RK_Declaration)
855    return 0;
856
857  NamedDecl *ND = R.Declaration;
858
859  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
860    CodeCompletionString *Result = new CodeCompletionString;
861    Result->AddTextChunk(Function->getNameAsString().c_str());
862    Result->AddTextChunk("(");
863    AddFunctionParameterChunks(getSema().Context, Function, Result);
864    Result->AddTextChunk(")");
865    return Result;
866  }
867
868  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
869    CodeCompletionString *Result = new CodeCompletionString;
870    FunctionDecl *Function = FunTmpl->getTemplatedDecl();
871    Result->AddTextChunk(Function->getNameAsString().c_str());
872
873    // Figure out which template parameters are deduced (or have default
874    // arguments).
875    llvm::SmallVector<bool, 16> Deduced;
876    getSema().MarkDeducedTemplateParameters(FunTmpl, Deduced);
877    unsigned LastDeducibleArgument;
878    for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
879         --LastDeducibleArgument) {
880      if (!Deduced[LastDeducibleArgument - 1]) {
881        // C++0x: Figure out if the template argument has a default. If so,
882        // the user doesn't need to type this argument.
883        // FIXME: We need to abstract template parameters better!
884        bool HasDefaultArg = false;
885        NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
886                                                    LastDeducibleArgument - 1);
887        if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
888          HasDefaultArg = TTP->hasDefaultArgument();
889        else if (NonTypeTemplateParmDecl *NTTP
890                   = dyn_cast<NonTypeTemplateParmDecl>(Param))
891          HasDefaultArg = NTTP->hasDefaultArgument();
892        else {
893          assert(isa<TemplateTemplateParmDecl>(Param));
894          HasDefaultArg
895            = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
896        }
897
898        if (!HasDefaultArg)
899          break;
900      }
901    }
902
903    if (LastDeducibleArgument) {
904      // Some of the function template arguments cannot be deduced from a
905      // function call, so we introduce an explicit template argument list
906      // containing all of the arguments up to the first deducible argument.
907      Result->AddTextChunk("<");
908      AddTemplateParameterChunks(getSema().Context, FunTmpl, Result,
909                                 LastDeducibleArgument);
910      Result->AddTextChunk(">");
911    }
912
913    // Add the function parameters
914    Result->AddTextChunk("(");
915    AddFunctionParameterChunks(getSema().Context, Function, Result);
916    Result->AddTextChunk(")");
917    return Result;
918  }
919
920  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
921    CodeCompletionString *Result = new CodeCompletionString;
922    Result->AddTextChunk(Template->getNameAsString().c_str());
923    Result->AddTextChunk("<");
924    AddTemplateParameterChunks(getSema().Context, Template, Result);
925    Result->AddTextChunk(">");
926    return Result;
927  }
928
929  return 0;
930}
931
932void
933PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Result *Results,
934                                                         unsigned NumResults) {
935  // Sort the results by rank/kind/etc.
936  std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
937
938  // Print the results.
939  for (unsigned I = 0; I != NumResults; ++I) {
940    switch (Results[I].Kind) {
941    case Result::RK_Declaration:
942      OS << Results[I].Declaration->getNameAsString() << " : "
943         << Results[I].Rank;
944      if (Results[I].Hidden)
945        OS << " (Hidden)";
946      if (CodeCompletionString *CCS = CreateCodeCompletionString(Results[I])) {
947        OS << " : " << CCS->getAsString();
948        delete CCS;
949      }
950
951      OS << '\n';
952      break;
953
954    case Result::RK_Keyword:
955      OS << Results[I].Keyword << " : " << Results[I].Rank << '\n';
956      break;
957    }
958  }
959
960  // Once we've printed the code-completion results, suppress remaining
961  // diagnostics.
962  // FIXME: Move this somewhere else!
963  getSema().PP.getDiagnostics().setSuppressAllDiagnostics();
964}
965