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