blob: c3efcdd05b272d490c7de617733529dfc523cb6e [file] [log] [blame]
Douglas Gregor2436e712009-09-17 21:32:03 +00001//===---------------- 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"
Douglas Gregor3545ff42009-09-21 16:56:56 +000015#include "llvm/ADT/SmallPtrSet.h"
16#include <list>
17#include <map>
18#include <vector>
Douglas Gregor2436e712009-09-17 21:32:03 +000019
20using namespace clang;
21
22/// \brief Set the code-completion consumer for semantic analysis.
23void Sema::setCodeCompleteConsumer(CodeCompleteConsumer *CCC) {
24 assert(((CodeCompleter != 0) != (CCC != 0)) &&
25 "Already set or cleared a code-completion consumer?");
26 CodeCompleter = CCC;
27}
28
Douglas Gregor3545ff42009-09-21 16:56:56 +000029namespace {
30 /// \brief A container of code-completion results.
31 class ResultBuilder {
32 public:
33 /// \brief The type of a name-lookup filter, which can be provided to the
34 /// name-lookup routines to specify which declarations should be included in
35 /// the result set (when it returns true) and which declarations should be
36 /// filtered out (returns false).
37 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
38
39 typedef CodeCompleteConsumer::Result Result;
40
41 private:
42 /// \brief The actual results we have found.
43 std::vector<Result> Results;
44
45 /// \brief A record of all of the declarations we have found and placed
46 /// into the result set, used to ensure that no declaration ever gets into
47 /// the result set twice.
48 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
49
50 /// \brief A mapping from declaration names to the declarations that have
51 /// this name within a particular scope and their index within the list of
52 /// results.
53 typedef std::multimap<DeclarationName,
54 std::pair<NamedDecl *, unsigned> > ShadowMap;
55
56 /// \brief The semantic analysis object for which results are being
57 /// produced.
58 Sema &SemaRef;
59
60 /// \brief If non-NULL, a filter function used to remove any code-completion
61 /// results that are not desirable.
62 LookupFilter Filter;
63
64 /// \brief A list of shadow maps, which is used to model name hiding at
65 /// different levels of, e.g., the inheritance hierarchy.
66 std::list<ShadowMap> ShadowMaps;
67
68 public:
69 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
70 : SemaRef(SemaRef), Filter(Filter) { }
71
72 /// \brief Set the filter used for code-completion results.
73 void setFilter(LookupFilter Filter) {
74 this->Filter = Filter;
75 }
76
77 typedef std::vector<Result>::iterator iterator;
78 iterator begin() { return Results.begin(); }
79 iterator end() { return Results.end(); }
80
81 Result *data() { return Results.empty()? 0 : &Results.front(); }
82 unsigned size() const { return Results.size(); }
83 bool empty() const { return Results.empty(); }
84
85 /// \brief Add a new result to this result set (if it isn't already in one
86 /// of the shadow maps), or replace an existing result (for, e.g., a
87 /// redeclaration).
88 void MaybeAddResult(Result R);
89
90 /// \brief Enter into a new scope.
91 void EnterNewScope();
92
93 /// \brief Exit from the current scope.
94 void ExitScope();
95
96 /// \name Name lookup predicates
97 ///
98 /// These predicates can be passed to the name lookup functions to filter the
99 /// results of name lookup. All of the predicates have the same type, so that
100 ///
101 //@{
102 bool IsNestedNameSpecifier(NamedDecl *ND) const;
103 bool IsEnum(NamedDecl *ND) const;
104 bool IsClassOrStruct(NamedDecl *ND) const;
105 bool IsUnion(NamedDecl *ND) const;
106 bool IsNamespace(NamedDecl *ND) const;
107 bool IsNamespaceOrAlias(NamedDecl *ND) const;
108 bool IsType(NamedDecl *ND) const;
109 //@}
110 };
111}
112
113/// \brief Determines whether the given hidden result could be found with
114/// some extra work, e.g., by qualifying the name.
115///
116/// \param Hidden the declaration that is hidden by the currenly \p Visible
117/// declaration.
118///
119/// \param Visible the declaration with the same name that is already visible.
120///
121/// \returns true if the hidden result can be found by some mechanism,
122/// false otherwise.
123static bool canHiddenResultBeFound(const LangOptions &LangOpts,
124 NamedDecl *Hidden, NamedDecl *Visible) {
125 // In C, there is no way to refer to a hidden name.
126 if (!LangOpts.CPlusPlus)
127 return false;
128
129 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
130
131 // There is no way to qualify a name declared in a function or method.
132 if (HiddenCtx->isFunctionOrMethod())
133 return false;
134
135 // If the hidden and visible declarations are in different name-lookup
136 // contexts, then we can qualify the name of the hidden declaration.
137 // FIXME: Optionally compute the string needed to refer to the hidden
138 // name.
139 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
140}
141
142void ResultBuilder::MaybeAddResult(Result R) {
143 if (R.Kind != Result::RK_Declaration) {
144 // For non-declaration results, just add the result.
145 Results.push_back(R);
146 return;
147 }
148
149 // Look through using declarations.
150 if (UsingDecl *Using = dyn_cast<UsingDecl>(R.Declaration))
151 return MaybeAddResult(Result(Using->getTargetDecl(), R.Rank));
152
153 // Handle each declaration in an overload set separately.
154 if (OverloadedFunctionDecl *Ovl
155 = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) {
156 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
157 FEnd = Ovl->function_end();
158 F != FEnd; ++F)
159 MaybeAddResult(Result(*F, R.Rank));
160
161 return;
162 }
163
164 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
165 unsigned IDNS = CanonDecl->getIdentifierNamespace();
166
167 // Friend declarations and declarations introduced due to friends are never
168 // added as results.
169 if (isa<FriendDecl>(CanonDecl) ||
170 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
171 return;
172
173 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
174 // __va_list_tag is a freak of nature. Find it and skip it.
175 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
176 return;
177
178 // FIXME: Should we filter out other names in the implementation's
179 // namespace, e.g., those containing a __ or that start with _[A-Z]?
180 }
181
182 // C++ constructors are never found by name lookup.
183 if (isa<CXXConstructorDecl>(CanonDecl))
184 return;
185
186 // Filter out any unwanted results.
187 if (Filter && !(this->*Filter)(R.Declaration))
188 return;
189
190 ShadowMap &SMap = ShadowMaps.back();
191 ShadowMap::iterator I, IEnd;
192 for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
193 I != IEnd; ++I) {
194 NamedDecl *ND = I->second.first;
195 unsigned Index = I->second.second;
196 if (ND->getCanonicalDecl() == CanonDecl) {
197 // This is a redeclaration. Always pick the newer declaration.
198 I->second.first = R.Declaration;
199 Results[Index].Declaration = R.Declaration;
200
201 // Pick the best rank of the two.
202 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
203
204 // We're done.
205 return;
206 }
207 }
208
209 // This is a new declaration in this scope. However, check whether this
210 // declaration name is hidden by a similarly-named declaration in an outer
211 // scope.
212 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
213 --SMEnd;
214 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
215 for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
216 I != IEnd; ++I) {
217 // A tag declaration does not hide a non-tag declaration.
218 if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
219 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
220 Decl::IDNS_ObjCProtocol)))
221 continue;
222
223 // Protocols are in distinct namespaces from everything else.
224 if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
225 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
226 I->second.first->getIdentifierNamespace() != IDNS)
227 continue;
228
229 // The newly-added result is hidden by an entry in the shadow map.
230 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
231 I->second.first)) {
232 // Note that this result was hidden.
233 R.Hidden = true;
234 } else {
235 // This result was hidden and cannot be found; don't bother adding
236 // it.
237 return;
238 }
239
240 break;
241 }
242 }
243
244 // Make sure that any given declaration only shows up in the result set once.
245 if (!AllDeclsFound.insert(CanonDecl))
246 return;
247
248 // Insert this result into the set of results and into the current shadow
249 // map.
250 SMap.insert(std::make_pair(R.Declaration->getDeclName(),
251 std::make_pair(R.Declaration, Results.size())));
252 Results.push_back(R);
253}
254
255/// \brief Enter into a new scope.
256void ResultBuilder::EnterNewScope() {
257 ShadowMaps.push_back(ShadowMap());
258}
259
260/// \brief Exit from the current scope.
261void ResultBuilder::ExitScope() {
262 ShadowMaps.pop_back();
263}
264
265/// \brief Determines whether the given declaration is suitable as the
266/// start of a C++ nested-name-specifier, e.g., a class or namespace.
267bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
268 // Allow us to find class templates, too.
269 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
270 ND = ClassTemplate->getTemplatedDecl();
271
272 return SemaRef.isAcceptableNestedNameSpecifier(ND);
273}
274
275/// \brief Determines whether the given declaration is an enumeration.
276bool ResultBuilder::IsEnum(NamedDecl *ND) const {
277 return isa<EnumDecl>(ND);
278}
279
280/// \brief Determines whether the given declaration is a class or struct.
281bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
282 // Allow us to find class templates, too.
283 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
284 ND = ClassTemplate->getTemplatedDecl();
285
286 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
287 return RD->getTagKind() == TagDecl::TK_class ||
288 RD->getTagKind() == TagDecl::TK_struct;
289
290 return false;
291}
292
293/// \brief Determines whether the given declaration is a union.
294bool ResultBuilder::IsUnion(NamedDecl *ND) const {
295 // Allow us to find class templates, too.
296 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
297 ND = ClassTemplate->getTemplatedDecl();
298
299 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
300 return RD->getTagKind() == TagDecl::TK_union;
301
302 return false;
303}
304
305/// \brief Determines whether the given declaration is a namespace.
306bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
307 return isa<NamespaceDecl>(ND);
308}
309
310/// \brief Determines whether the given declaration is a namespace or
311/// namespace alias.
312bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
313 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
314}
315
316/// \brief Brief determines whether the given declaration is a namespace or
317/// namespace alias.
318bool ResultBuilder::IsType(NamedDecl *ND) const {
319 return isa<TypeDecl>(ND);
320}
321
322// Find the next outer declaration context corresponding to this scope.
323static DeclContext *findOuterContext(Scope *S) {
324 for (S = S->getParent(); S; S = S->getParent())
325 if (S->getEntity())
326 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
327
328 return 0;
329}
330
331/// \brief Collect the results of searching for members within the given
332/// declaration context.
333///
334/// \param Ctx the declaration context from which we will gather results.
335///
336/// \param InitialRank the initial rank given to results in this declaration
337/// context. Larger rank values will be used for, e.g., members found in
338/// base classes.
339///
340/// \param Visited the set of declaration contexts that have already been
341/// visited. Declaration contexts will only be visited once.
342///
343/// \param Results the result set that will be extended with any results
344/// found within this declaration context (and, for a C++ class, its bases).
345///
346/// \returns the next higher rank value, after considering all of the
347/// names within this declaration context.
348static unsigned CollectMemberLookupResults(DeclContext *Ctx,
349 unsigned InitialRank,
350 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
351 ResultBuilder &Results) {
352 // Make sure we don't visit the same context twice.
353 if (!Visited.insert(Ctx->getPrimaryContext()))
354 return InitialRank;
355
356 // Enumerate all of the results in this context.
357 Results.EnterNewScope();
358 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
359 CurCtx = CurCtx->getNextContext()) {
360 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
361 DEnd = CurCtx->decls_end();
362 D != DEnd; ++D) {
363 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
364 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, InitialRank));
365 }
366 }
367
368 // Traverse the contexts of inherited classes.
369 unsigned NextRank = InitialRank;
370 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
371 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
372 BEnd = Record->bases_end();
373 B != BEnd; ++B) {
374 QualType BaseType = B->getType();
375
376 // Don't look into dependent bases, because name lookup can't look
377 // there anyway.
378 if (BaseType->isDependentType())
379 continue;
380
381 const RecordType *Record = BaseType->getAs<RecordType>();
382 if (!Record)
383 continue;
384
385 // FIXME: It would be nice to be able to determine whether referencing
386 // a particular member would be ambiguous. For example, given
387 //
388 // struct A { int member; };
389 // struct B { int member; };
390 // struct C : A, B { };
391 //
392 // void f(C *c) { c->### }
393 // accessing 'member' would result in an ambiguity. However, code
394 // completion could be smart enough to qualify the member with the
395 // base class, e.g.,
396 //
397 // c->B::member
398 //
399 // or
400 //
401 // c->A::member
402
403 // Collect results from this base class (and its bases).
404 NextRank = std::max(NextRank,
405 CollectMemberLookupResults(Record->getDecl(),
406 InitialRank + 1,
407 Visited,
408 Results));
409 }
410 }
411
412 // FIXME: Look into base classes in Objective-C!
413
414 Results.ExitScope();
415 return NextRank;
416}
417
418/// \brief Collect the results of searching for members within the given
419/// declaration context.
420///
421/// \param Ctx the declaration context from which we will gather results.
422///
423/// \param InitialRank the initial rank given to results in this declaration
424/// context. Larger rank values will be used for, e.g., members found in
425/// base classes.
426///
427/// \param Results the result set that will be extended with any results
428/// found within this declaration context (and, for a C++ class, its bases).
429///
430/// \returns the next higher rank value, after considering all of the
431/// names within this declaration context.
432static unsigned CollectMemberLookupResults(DeclContext *Ctx,
433 unsigned InitialRank,
434 ResultBuilder &Results) {
435 llvm::SmallPtrSet<DeclContext *, 16> Visited;
436 return CollectMemberLookupResults(Ctx, InitialRank, Visited, Results);
437}
438
439/// \brief Collect the results of searching for declarations within the given
440/// scope and its parent scopes.
441///
442/// \param S the scope in which we will start looking for declarations.
443///
444/// \param InitialRank the initial rank given to results in this scope.
445/// Larger rank values will be used for results found in parent scopes.
446///
447/// \param Results the builder object that will receive each result.
448static unsigned CollectLookupResults(Scope *S,
449 TranslationUnitDecl *TranslationUnit,
450 unsigned InitialRank,
451 ResultBuilder &Results) {
452 if (!S)
453 return InitialRank;
454
455 // FIXME: Using directives!
456
457 unsigned NextRank = InitialRank;
458 Results.EnterNewScope();
459 if (S->getEntity() &&
460 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
461 // Look into this scope's declaration context, along with any of its
462 // parent lookup contexts (e.g., enclosing classes), up to the point
463 // where we hit the context stored in the next outer scope.
464 DeclContext *Ctx = (DeclContext *)S->getEntity();
465 DeclContext *OuterCtx = findOuterContext(S);
466
467 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
468 Ctx = Ctx->getLookupParent()) {
469 if (Ctx->isFunctionOrMethod())
470 continue;
471
472 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, Results);
473 }
474 } else if (!S->getParent()) {
475 // Look into the translation unit scope. We walk through the translation
476 // unit's declaration context, because the Scope itself won't have all of
477 // the declarations if we loaded a precompiled header.
478 // FIXME: We would like the translation unit's Scope object to point to the
479 // translation unit, so we don't need this special "if" branch. However,
480 // doing so would force the normal C++ name-lookup code to look into the
481 // translation unit decl when the IdentifierInfo chains would suffice.
482 // Once we fix that problem (which is part of a more general "don't look
483 // in DeclContexts unless we have to" optimization), we can eliminate the
484 // TranslationUnit parameter entirely.
485 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
486 Results);
487 } else {
488 // Walk through the declarations in this Scope.
489 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
490 D != DEnd; ++D) {
491 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
492 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank));
493 }
494
495 NextRank = NextRank + 1;
496 }
497
498 // Lookup names in the parent scope.
499 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
500 Results);
501 Results.ExitScope();
502
503 return NextRank;
504}
505
506/// \brief Add type specifiers for the current language as keyword results.
507static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
508 ResultBuilder &Results) {
509 typedef CodeCompleteConsumer::Result Result;
510 Results.MaybeAddResult(Result("short", Rank));
511 Results.MaybeAddResult(Result("long", Rank));
512 Results.MaybeAddResult(Result("signed", Rank));
513 Results.MaybeAddResult(Result("unsigned", Rank));
514 Results.MaybeAddResult(Result("void", Rank));
515 Results.MaybeAddResult(Result("char", Rank));
516 Results.MaybeAddResult(Result("int", Rank));
517 Results.MaybeAddResult(Result("float", Rank));
518 Results.MaybeAddResult(Result("double", Rank));
519 Results.MaybeAddResult(Result("enum", Rank));
520 Results.MaybeAddResult(Result("struct", Rank));
521 Results.MaybeAddResult(Result("union", Rank));
522
523 if (LangOpts.C99) {
524 // C99-specific
525 Results.MaybeAddResult(Result("_Complex", Rank));
526 Results.MaybeAddResult(Result("_Imaginary", Rank));
527 Results.MaybeAddResult(Result("_Bool", Rank));
528 }
529
530 if (LangOpts.CPlusPlus) {
531 // C++-specific
532 Results.MaybeAddResult(Result("bool", Rank));
533 Results.MaybeAddResult(Result("class", Rank));
534 Results.MaybeAddResult(Result("typename", Rank));
535 Results.MaybeAddResult(Result("wchar_t", Rank));
536
537 if (LangOpts.CPlusPlus0x) {
538 Results.MaybeAddResult(Result("char16_t", Rank));
539 Results.MaybeAddResult(Result("char32_t", Rank));
540 Results.MaybeAddResult(Result("decltype", Rank));
541 }
542 }
543
544 // GNU extensions
545 if (LangOpts.GNUMode) {
546 // FIXME: Enable when we actually support decimal floating point.
547 // Results.MaybeAddResult(Result("_Decimal32", Rank));
548 // Results.MaybeAddResult(Result("_Decimal64", Rank));
549 // Results.MaybeAddResult(Result("_Decimal128", Rank));
550 Results.MaybeAddResult(Result("typeof", Rank));
551 }
552}
553
554/// \brief Add function parameter chunks to the given code completion string.
555static void AddFunctionParameterChunks(ASTContext &Context,
556 FunctionDecl *Function,
557 CodeCompletionString *Result) {
558 CodeCompletionString *CCStr = Result;
559
560 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
561 ParmVarDecl *Param = Function->getParamDecl(P);
562
563 if (Param->hasDefaultArg()) {
564 // When we see an optional default argument, put that argument and
565 // the remaining default arguments into a new, optional string.
566 CodeCompletionString *Opt = new CodeCompletionString;
567 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
568 CCStr = Opt;
569 }
570
571 if (P != 0)
572 CCStr->AddTextChunk(", ");
573
574 // Format the placeholder string.
575 std::string PlaceholderStr;
576 if (Param->getIdentifier())
577 PlaceholderStr = Param->getIdentifier()->getName();
578
579 Param->getType().getAsStringInternal(PlaceholderStr,
580 Context.PrintingPolicy);
581
582 // Add the placeholder string.
583 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
584 }
585}
586
587/// \brief Add template parameter chunks to the given code completion string.
588static void AddTemplateParameterChunks(ASTContext &Context,
589 TemplateDecl *Template,
590 CodeCompletionString *Result,
591 unsigned MaxParameters = 0) {
592 CodeCompletionString *CCStr = Result;
593 bool FirstParameter = true;
594
595 TemplateParameterList *Params = Template->getTemplateParameters();
596 TemplateParameterList::iterator PEnd = Params->end();
597 if (MaxParameters)
598 PEnd = Params->begin() + MaxParameters;
599 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
600 bool HasDefaultArg = false;
601 std::string PlaceholderStr;
602 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
603 if (TTP->wasDeclaredWithTypename())
604 PlaceholderStr = "typename";
605 else
606 PlaceholderStr = "class";
607
608 if (TTP->getIdentifier()) {
609 PlaceholderStr += ' ';
610 PlaceholderStr += TTP->getIdentifier()->getName();
611 }
612
613 HasDefaultArg = TTP->hasDefaultArgument();
614 } else if (NonTypeTemplateParmDecl *NTTP
615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616 if (NTTP->getIdentifier())
617 PlaceholderStr = NTTP->getIdentifier()->getName();
618 NTTP->getType().getAsStringInternal(PlaceholderStr,
619 Context.PrintingPolicy);
620 HasDefaultArg = NTTP->hasDefaultArgument();
621 } else {
622 assert(isa<TemplateTemplateParmDecl>(*P));
623 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
624
625 // Since putting the template argument list into the placeholder would
626 // be very, very long, we just use an abbreviation.
627 PlaceholderStr = "template<...> class";
628 if (TTP->getIdentifier()) {
629 PlaceholderStr += ' ';
630 PlaceholderStr += TTP->getIdentifier()->getName();
631 }
632
633 HasDefaultArg = TTP->hasDefaultArgument();
634 }
635
636 if (HasDefaultArg) {
637 // When we see an optional default argument, put that argument and
638 // the remaining default arguments into a new, optional string.
639 CodeCompletionString *Opt = new CodeCompletionString;
640 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
641 CCStr = Opt;
642 }
643
644 if (FirstParameter)
645 FirstParameter = false;
646 else
647 CCStr->AddTextChunk(", ");
648
649 // Add the placeholder string.
650 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
651 }
652}
653
654/// \brief If possible, create a new code completion string for the given
655/// result.
656///
657/// \returns Either a new, heap-allocated code completion string describing
658/// how to use this result, or NULL to indicate that the string or name of the
659/// result is all that is needed.
660CodeCompletionString *
661CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
662 if (Kind != RK_Declaration)
663 return 0;
664
665 NamedDecl *ND = Declaration;
666
667 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
668 CodeCompletionString *Result = new CodeCompletionString;
669 Result->AddTextChunk(Function->getNameAsString().c_str());
670 Result->AddTextChunk("(");
671 AddFunctionParameterChunks(S.Context, Function, Result);
672 Result->AddTextChunk(")");
673 return Result;
674 }
675
676 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
677 CodeCompletionString *Result = new CodeCompletionString;
678 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
679 Result->AddTextChunk(Function->getNameAsString().c_str());
680
681 // Figure out which template parameters are deduced (or have default
682 // arguments).
683 llvm::SmallVector<bool, 16> Deduced;
684 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
685 unsigned LastDeducibleArgument;
686 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
687 --LastDeducibleArgument) {
688 if (!Deduced[LastDeducibleArgument - 1]) {
689 // C++0x: Figure out if the template argument has a default. If so,
690 // the user doesn't need to type this argument.
691 // FIXME: We need to abstract template parameters better!
692 bool HasDefaultArg = false;
693 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
694 LastDeducibleArgument - 1);
695 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
696 HasDefaultArg = TTP->hasDefaultArgument();
697 else if (NonTypeTemplateParmDecl *NTTP
698 = dyn_cast<NonTypeTemplateParmDecl>(Param))
699 HasDefaultArg = NTTP->hasDefaultArgument();
700 else {
701 assert(isa<TemplateTemplateParmDecl>(Param));
702 HasDefaultArg
703 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
704 }
705
706 if (!HasDefaultArg)
707 break;
708 }
709 }
710
711 if (LastDeducibleArgument) {
712 // Some of the function template arguments cannot be deduced from a
713 // function call, so we introduce an explicit template argument list
714 // containing all of the arguments up to the first deducible argument.
715 Result->AddTextChunk("<");
716 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
717 LastDeducibleArgument);
718 Result->AddTextChunk(">");
719 }
720
721 // Add the function parameters
722 Result->AddTextChunk("(");
723 AddFunctionParameterChunks(S.Context, Function, Result);
724 Result->AddTextChunk(")");
725 return Result;
726 }
727
728 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
729 CodeCompletionString *Result = new CodeCompletionString;
730 Result->AddTextChunk(Template->getNameAsString().c_str());
731 Result->AddTextChunk("<");
732 AddTemplateParameterChunks(S.Context, Template, Result);
733 Result->AddTextChunk(">");
734 return Result;
735 }
736
737 return 0;
738}
739
740namespace {
741 struct SortCodeCompleteResult {
742 typedef CodeCompleteConsumer::Result Result;
743
744 bool operator()(const Result &X, const Result &Y) const {
745 // Sort first by rank.
746 if (X.Rank < Y.Rank)
747 return true;
748 else if (X.Rank > Y.Rank)
749 return false;
750
751 // Result kinds are ordered by decreasing importance.
752 if (X.Kind < Y.Kind)
753 return true;
754 else if (X.Kind > Y.Kind)
755 return false;
756
757 // Non-hidden names precede hidden names.
758 if (X.Hidden != Y.Hidden)
759 return !X.Hidden;
760
761 // Ordering depends on the kind of result.
762 switch (X.Kind) {
763 case Result::RK_Declaration:
764 // Order based on the declaration names.
765 return X.Declaration->getDeclName() < Y.Declaration->getDeclName();
766
767 case Result::RK_Keyword:
768 return strcmp(X.Keyword, Y.Keyword) == -1;
769 }
770
771 // Silence GCC warning.
772 return false;
773 }
774 };
775}
776
777static void HandleCodeCompleteResults(CodeCompleteConsumer *CodeCompleter,
778 CodeCompleteConsumer::Result *Results,
779 unsigned NumResults) {
780 // Sort the results by rank/kind/etc.
781 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
782
783 if (CodeCompleter)
784 CodeCompleter->ProcessCodeCompleteResults(Results, NumResults);
785}
786
Douglas Gregor2436e712009-09-17 21:32:03 +0000787void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
788 SourceLocation OpLoc,
789 bool IsArrow) {
790 if (!BaseE || !CodeCompleter)
791 return;
792
Douglas Gregor3545ff42009-09-21 16:56:56 +0000793 typedef CodeCompleteConsumer::Result Result;
794
Douglas Gregor2436e712009-09-17 21:32:03 +0000795 Expr *Base = static_cast<Expr *>(BaseE);
796 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +0000797
798 if (IsArrow) {
799 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
800 BaseType = Ptr->getPointeeType();
801 else if (BaseType->isObjCObjectPointerType())
802 /*Do nothing*/ ;
803 else
804 return;
805 }
806
807 ResultBuilder Results(*this);
808 unsigned NextRank = 0;
809
810 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
811 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank, Results);
812
813 if (getLangOptions().CPlusPlus) {
814 if (!Results.empty()) {
815 // The "template" keyword can follow "->" or "." in the grammar.
816 // However, we only want to suggest the template keyword if something
817 // is dependent.
818 bool IsDependent = BaseType->isDependentType();
819 if (!IsDependent) {
820 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
821 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
822 IsDependent = Ctx->isDependentContext();
823 break;
824 }
825 }
826
827 if (IsDependent)
828 Results.MaybeAddResult(Result("template", NextRank++));
829 }
830
831 // We could have the start of a nested-name-specifier. Add those
832 // results as well.
833 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
834 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
835 Results);
836 }
837
838 // Hand off the results found for code completion.
839 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
840
841 // We're done!
842 return;
843 }
Douglas Gregor2436e712009-09-17 21:32:03 +0000844}
845
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000846void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
847 if (!CodeCompleter)
848 return;
849
Douglas Gregor3545ff42009-09-21 16:56:56 +0000850 typedef CodeCompleteConsumer::Result Result;
851 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000852 switch ((DeclSpec::TST)TagSpec) {
853 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +0000854 Filter = &ResultBuilder::IsEnum;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000855 break;
856
857 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +0000858 Filter = &ResultBuilder::IsUnion;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000859 break;
860
861 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000862 case DeclSpec::TST_class:
Douglas Gregor3545ff42009-09-21 16:56:56 +0000863 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000864 break;
865
866 default:
867 assert(false && "Unknown type specifier kind in CodeCompleteTag");
868 return;
869 }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000870
871 ResultBuilder Results(*this, Filter);
872 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
873 0, Results);
874
875 if (getLangOptions().CPlusPlus) {
876 // We could have the start of a nested-name-specifier. Add those
877 // results as well.
878 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
879 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
880 Results);
881 }
882
883 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000884}
885
Douglas Gregord328d572009-09-21 18:10:23 +0000886void Sema::CodeCompleteCase(Scope *S) {
887 if (getSwitchStack().empty() || !CodeCompleter)
888 return;
889
890 SwitchStmt *Switch = getSwitchStack().back();
891 if (!Switch->getCond()->getType()->isEnumeralType())
892 return;
893
894 // Code-complete the cases of a switch statement over an enumeration type
895 // by providing the list of
896 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
897
898 // Determine which enumerators we have already seen in the switch statement.
899 // FIXME: Ideally, we would also be able to look *past* the code-completion
900 // token, in case we are code-completing in the middle of the switch and not
901 // at the end. However, we aren't able to do so at the moment.
902 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
903 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
904 SC = SC->getNextSwitchCase()) {
905 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
906 if (!Case)
907 continue;
908
909 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
910 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
911 if (EnumConstantDecl *Enumerator
912 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
913 // We look into the AST of the case statement to determine which
914 // enumerator was named. Alternatively, we could compute the value of
915 // the integral constant expression, then compare it against the
916 // values of each enumerator. However, value-based approach would not
917 // work as well with C++ templates where enumerators declared within a
918 // template are type- and value-dependent.
919 EnumeratorsSeen.insert(Enumerator);
920
921 // FIXME: If this is a qualified-id, should we keep track of the
922 // nested-name-specifier so we can reproduce it as part of code
923 // completion? e.g.,
924 //
925 // switch (TagD.getKind()) {
926 // case TagDecl::TK_enum:
927 // break;
928 // case XXX
929 //
930 // At the XXX, we would like our completions to be TagDecl::TK_union,
931 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
932 // TK_struct, and TK_class.
933 }
934 }
935
936 // Add any enumerators that have not yet been mentioned.
937 ResultBuilder Results(*this);
938 Results.EnterNewScope();
939 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
940 EEnd = Enum->enumerator_end();
941 E != EEnd; ++E) {
942 if (EnumeratorsSeen.count(*E))
943 continue;
944
945 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0));
946 }
947 Results.ExitScope();
948
949 // In C++, add nested-name-specifiers.
950 if (getLangOptions().CPlusPlus) {
951 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
952 CollectLookupResults(S, Context.getTranslationUnitDecl(), 1,
953 Results);
954 }
955
956 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
957}
958
Douglas Gregor2436e712009-09-17 21:32:03 +0000959void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
960 bool EnteringContext) {
961 if (!SS.getScopeRep() || !CodeCompleter)
962 return;
963
Douglas Gregor3545ff42009-09-21 16:56:56 +0000964 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
965 if (!Ctx)
966 return;
967
968 ResultBuilder Results(*this);
969 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Results);
970
971 // The "template" keyword can follow "::" in the grammar, but only
972 // put it into the grammar if the nested-name-specifier is dependent.
973 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
974 if (!Results.empty() && NNS->isDependent())
975 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
976
977 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +0000978}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000979
980void Sema::CodeCompleteUsing(Scope *S) {
981 if (!CodeCompleter)
982 return;
983
Douglas Gregor3545ff42009-09-21 16:56:56 +0000984 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
985
986 // If we aren't in class scope, we could see the "namespace" keyword.
987 if (!S->isClassScope())
988 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
989
990 // After "using", we can see anything that would start a
991 // nested-name-specifier.
992 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, Results);
993
994 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000995}
996
997void Sema::CodeCompleteUsingDirective(Scope *S) {
998 if (!CodeCompleter)
999 return;
1000
Douglas Gregor3545ff42009-09-21 16:56:56 +00001001 // After "using namespace", we expect to see a namespace name or namespace
1002 // alias.
1003 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
1004 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, Results);
1005 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001006}
1007
1008void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1009 if (!CodeCompleter)
1010 return;
1011
Douglas Gregor3545ff42009-09-21 16:56:56 +00001012 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1013 DeclContext *Ctx = (DeclContext *)S->getEntity();
1014 if (!S->getParent())
1015 Ctx = Context.getTranslationUnitDecl();
1016
1017 if (Ctx && Ctx->isFileContext()) {
1018 // We only want to see those namespaces that have already been defined
1019 // within this scope, because its likely that the user is creating an
1020 // extended namespace declaration. Keep track of the most recent
1021 // definition of each namespace.
1022 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1023 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1024 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1025 NS != NSEnd; ++NS)
1026 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1027
1028 // Add the most recent definition (or extended definition) of each
1029 // namespace to the list of results.
1030 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1031 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1032 NS != NSEnd; ++NS)
1033 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0));
1034 }
1035
1036 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001037}
1038
1039void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1040 if (!CodeCompleter)
1041 return;
1042
Douglas Gregor3545ff42009-09-21 16:56:56 +00001043 // After "namespace", we expect to see a namespace or alias.
1044 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
1045 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, Results);
1046 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001047}
1048
Douglas Gregorc811ede2009-09-18 20:05:18 +00001049void Sema::CodeCompleteOperatorName(Scope *S) {
1050 if (!CodeCompleter)
1051 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001052
1053 typedef CodeCompleteConsumer::Result Result;
1054 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregorc811ede2009-09-18 20:05:18 +00001055
Douglas Gregor3545ff42009-09-21 16:56:56 +00001056 // Add the names of overloadable operators.
1057#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1058 if (std::strcmp(Spelling, "?")) \
1059 Results.MaybeAddResult(Result(Spelling, 0));
1060#include "clang/Basic/OperatorKinds.def"
1061
1062 // Add any type names visible from the current scope
1063 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1064 0, Results);
1065
1066 // Add any type specifiers
1067 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1068
1069 // Add any nested-name-specifiers
1070 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1071 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank + 1,
1072 Results);
1073
1074 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00001075}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001076