blob: 754d505bc0212cf24a044bc71ebfc7273490d4b3 [file] [log] [blame]
Douglas Gregor81b747b2009-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 Gregorb9d0ef72009-09-21 19:57:38 +000015#include "clang/AST/ExprCXX.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000016#include "llvm/ADT/SmallPtrSet.h"
17#include <list>
18#include <map>
19#include <vector>
Douglas Gregor81b747b2009-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 Gregor86d9a522009-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 Gregor456c4a12009-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 Gregor86d9a522009-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 Gregor791215b2009-09-21 20:51:25 +0000107 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-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 Gregor86d9a522009-09-21 16:56:56 +0000141 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
142}
143
Douglas Gregor456c4a12009-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 Gregor8e0a0e42009-09-22 23:31:26 +0000192 assert(!ShadowMaps.empty() && "Must enter into a results scope");
193
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000202 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
203 CurContext);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000211 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000286 R.QualifierIsInformative = false;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000287
288 if (!R.Qualifier)
289 R.Qualifier = getRequiredQualification(SemaRef.Context,
290 CurContext,
291 R.Declaration->getDeclContext());
Douglas Gregor86d9a522009-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 Gregor0563c262009-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 Gregor3e7253f2009-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 Gregor86d9a522009-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 Gregor791215b2009-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 Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000421/// \param Rank the rank given to results in this declaration context.
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000429/// \param InBaseClass whether we are in a base class.
430///
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000434 unsigned Rank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000435 DeclContext *CurContext,
436 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor0563c262009-09-22 23:15:58 +0000437 ResultBuilder &Results,
438 bool InBaseClass = false) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000439 // Make sure we don't visit the same context twice.
440 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor0563c262009-09-22 23:15:58 +0000441 return Rank;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000442
443 // Enumerate all of the results in this context.
Douglas Gregor0563c262009-09-22 23:15:58 +0000444 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000452 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000453 }
454 }
455
456 // Traverse the contexts of inherited classes.
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000491 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
492 Results, /*InBaseClass=*/true);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000493 }
494 }
495
496 // FIXME: Look into base classes in Objective-C!
497
498 Results.ExitScope();
Douglas Gregor0563c262009-09-22 23:15:58 +0000499 return Rank + 1;
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000518 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000519 ResultBuilder &Results) {
520 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000521 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
522 Results);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000533/// \param CurContext the context from which lookup results will be found.
534///
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000539 DeclContext *CurContext,
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000561 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
562 Results);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000576 CurContext, Results);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000582 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
583 CurContext);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000591 CurContext, Results);
Douglas Gregor86d9a522009-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 Gregorb3d45252009-09-22 21:42:17 +0000676
677 if (const FunctionProtoType *Proto
678 = Function->getType()->getAs<FunctionProtoType>())
679 if (Proto->isVariadic())
680 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-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 Gregorb9d0ef72009-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 Gregor0563c262009-09-22 23:15:58 +0000754 bool QualifierIsInformative,
Douglas Gregorb9d0ef72009-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 Gregor0563c262009-09-22 23:15:58 +0000764 if (QualifierIsInformative)
765 Result->AddInformativeChunk(PrintedNNS.c_str());
766 else
767 Result->AddTextChunk(PrintedNNS.c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000768}
769
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000785 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
786 S.Context);
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000796 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
797 S.Context);
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000850 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
851 S.Context);
Douglas Gregor86d9a522009-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 Gregor3e7253f2009-09-22 23:22:24 +0000859 if (Qualifier || StartsNestedNameSpecifier) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000860 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000861 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
862 S.Context);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000863 Result->AddTextChunk(ND->getNameAsString().c_str());
Douglas Gregor3e7253f2009-09-22 23:22:24 +0000864 if (StartsNestedNameSpecifier)
865 Result->AddTextChunk("::");
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000866 return Result;
867 }
868
Douglas Gregor86d9a522009-09-21 16:56:56 +0000869 return 0;
870}
871
872namespace {
873 struct SortCodeCompleteResult {
874 typedef CodeCompleteConsumer::Result Result;
875
876 bool operator()(const Result &X, const Result &Y) const {
877 // Sort first by rank.
878 if (X.Rank < Y.Rank)
879 return true;
880 else if (X.Rank > Y.Rank)
881 return false;
882
883 // Result kinds are ordered by decreasing importance.
884 if (X.Kind < Y.Kind)
885 return true;
886 else if (X.Kind > Y.Kind)
887 return false;
888
889 // Non-hidden names precede hidden names.
890 if (X.Hidden != Y.Hidden)
891 return !X.Hidden;
892
893 // Ordering depends on the kind of result.
894 switch (X.Kind) {
895 case Result::RK_Declaration:
896 // Order based on the declaration names.
897 return X.Declaration->getDeclName() < Y.Declaration->getDeclName();
898
899 case Result::RK_Keyword:
900 return strcmp(X.Keyword, Y.Keyword) == -1;
901 }
902
903 // Silence GCC warning.
904 return false;
905 }
906 };
907}
908
909static void HandleCodeCompleteResults(CodeCompleteConsumer *CodeCompleter,
910 CodeCompleteConsumer::Result *Results,
911 unsigned NumResults) {
912 // Sort the results by rank/kind/etc.
913 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
914
915 if (CodeCompleter)
916 CodeCompleter->ProcessCodeCompleteResults(Results, NumResults);
917}
918
Douglas Gregor791215b2009-09-21 20:51:25 +0000919void Sema::CodeCompleteOrdinaryName(Scope *S) {
920 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
921 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
922 Results);
923 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
924}
925
Douglas Gregor81b747b2009-09-17 21:32:03 +0000926void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
927 SourceLocation OpLoc,
928 bool IsArrow) {
929 if (!BaseE || !CodeCompleter)
930 return;
931
Douglas Gregor86d9a522009-09-21 16:56:56 +0000932 typedef CodeCompleteConsumer::Result Result;
933
Douglas Gregor81b747b2009-09-17 21:32:03 +0000934 Expr *Base = static_cast<Expr *>(BaseE);
935 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000936
937 if (IsArrow) {
938 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
939 BaseType = Ptr->getPointeeType();
940 else if (BaseType->isObjCObjectPointerType())
941 /*Do nothing*/ ;
942 else
943 return;
944 }
945
946 ResultBuilder Results(*this);
947 unsigned NextRank = 0;
948
949 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor456c4a12009-09-21 20:12:40 +0000950 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
951 Record->getDecl(), Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000952
953 if (getLangOptions().CPlusPlus) {
954 if (!Results.empty()) {
955 // The "template" keyword can follow "->" or "." in the grammar.
956 // However, we only want to suggest the template keyword if something
957 // is dependent.
958 bool IsDependent = BaseType->isDependentType();
959 if (!IsDependent) {
960 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
961 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
962 IsDependent = Ctx->isDependentContext();
963 break;
964 }
965 }
966
967 if (IsDependent)
968 Results.MaybeAddResult(Result("template", NextRank++));
969 }
970
971 // We could have the start of a nested-name-specifier. Add those
972 // results as well.
973 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
974 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000975 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000976 }
977
978 // Hand off the results found for code completion.
979 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
980
981 // We're done!
982 return;
983 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000984}
985
Douglas Gregor374929f2009-09-18 15:37:17 +0000986void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
987 if (!CodeCompleter)
988 return;
989
Douglas Gregor86d9a522009-09-21 16:56:56 +0000990 typedef CodeCompleteConsumer::Result Result;
991 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +0000992 switch ((DeclSpec::TST)TagSpec) {
993 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +0000994 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +0000995 break;
996
997 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +0000998 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +0000999 break;
1000
1001 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00001002 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001003 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00001004 break;
1005
1006 default:
1007 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1008 return;
1009 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001010
1011 ResultBuilder Results(*this, Filter);
1012 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001013 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001014
1015 if (getLangOptions().CPlusPlus) {
1016 // We could have the start of a nested-name-specifier. Add those
1017 // results as well.
1018 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1019 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +00001020 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001021 }
1022
1023 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00001024}
1025
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001026void Sema::CodeCompleteCase(Scope *S) {
1027 if (getSwitchStack().empty() || !CodeCompleter)
1028 return;
1029
1030 SwitchStmt *Switch = getSwitchStack().back();
1031 if (!Switch->getCond()->getType()->isEnumeralType())
1032 return;
1033
1034 // Code-complete the cases of a switch statement over an enumeration type
1035 // by providing the list of
1036 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1037
1038 // Determine which enumerators we have already seen in the switch statement.
1039 // FIXME: Ideally, we would also be able to look *past* the code-completion
1040 // token, in case we are code-completing in the middle of the switch and not
1041 // at the end. However, we aren't able to do so at the moment.
1042 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001043 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001044 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1045 SC = SC->getNextSwitchCase()) {
1046 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1047 if (!Case)
1048 continue;
1049
1050 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1051 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1052 if (EnumConstantDecl *Enumerator
1053 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1054 // We look into the AST of the case statement to determine which
1055 // enumerator was named. Alternatively, we could compute the value of
1056 // the integral constant expression, then compare it against the
1057 // values of each enumerator. However, value-based approach would not
1058 // work as well with C++ templates where enumerators declared within a
1059 // template are type- and value-dependent.
1060 EnumeratorsSeen.insert(Enumerator);
1061
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001062 // If this is a qualified-id, keep track of the nested-name-specifier
1063 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001064 //
1065 // switch (TagD.getKind()) {
1066 // case TagDecl::TK_enum:
1067 // break;
1068 // case XXX
1069 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001070 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001071 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1072 // TK_struct, and TK_class.
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001073 if (QualifiedDeclRefExpr *QDRE = dyn_cast<QualifiedDeclRefExpr>(DRE))
1074 Qualifier = QDRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001075 }
1076 }
1077
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001078 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1079 // If there are no prior enumerators in C++, check whether we have to
1080 // qualify the names of the enumerators that we suggest, because they
1081 // may not be visible in this scope.
1082 Qualifier = getRequiredQualification(Context, CurContext,
1083 Enum->getDeclContext());
1084
1085 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1086 }
1087
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001088 // Add any enumerators that have not yet been mentioned.
1089 ResultBuilder Results(*this);
1090 Results.EnterNewScope();
1091 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1092 EEnd = Enum->enumerator_end();
1093 E != EEnd; ++E) {
1094 if (EnumeratorsSeen.count(*E))
1095 continue;
1096
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001097 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001098 }
1099 Results.ExitScope();
1100
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001101 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1102}
1103
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001104namespace {
1105 struct IsBetterOverloadCandidate {
1106 Sema &S;
1107
1108 public:
1109 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1110
1111 bool
1112 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1113 return S.isBetterOverloadCandidate(X, Y);
1114 }
1115 };
1116}
1117
1118void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1119 ExprTy **ArgsIn, unsigned NumArgs) {
1120 if (!CodeCompleter)
1121 return;
1122
1123 Expr *Fn = (Expr *)FnIn;
1124 Expr **Args = (Expr **)ArgsIn;
1125
1126 // Ignore type-dependent call expressions entirely.
1127 if (Fn->isTypeDependent() ||
1128 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1129 return;
1130
1131 NamedDecl *Function;
1132 DeclarationName UnqualifiedName;
1133 NestedNameSpecifier *Qualifier;
1134 SourceRange QualifierRange;
1135 bool ArgumentDependentLookup;
1136 bool HasExplicitTemplateArgs;
1137 const TemplateArgument *ExplicitTemplateArgs;
1138 unsigned NumExplicitTemplateArgs;
1139
1140 DeconstructCallFunction(Fn,
1141 Function, UnqualifiedName, Qualifier, QualifierRange,
1142 ArgumentDependentLookup, HasExplicitTemplateArgs,
1143 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1144
1145
1146 // FIXME: What if we're calling something that isn't a function declaration?
1147 // FIXME: What if we're calling a pseudo-destructor?
1148 // FIXME: What if we're calling a member function?
1149
1150 // Build an overload candidate set based on the functions we find.
1151 OverloadCandidateSet CandidateSet;
1152 AddOverloadedCallCandidates(Function, UnqualifiedName,
1153 ArgumentDependentLookup, HasExplicitTemplateArgs,
1154 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1155 Args, NumArgs,
1156 CandidateSet,
1157 /*PartialOverloading=*/true);
1158
1159 // Sort the overload candidate set by placing the best overloads first.
1160 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1161 IsBetterOverloadCandidate(*this));
1162
1163 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05944382009-09-23 00:16:58 +00001164 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1165 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlsson90756302009-09-22 17:29:51 +00001166
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001167 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1168 CandEnd = CandidateSet.end();
1169 Cand != CandEnd; ++Cand) {
1170 if (Cand->Viable)
Douglas Gregor05944382009-09-23 00:16:58 +00001171 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001172 }
Douglas Gregor05944382009-09-23 00:16:58 +00001173 CodeCompleter->ProcessOverloadCandidates(NumArgs, Results.data(),
1174 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001175}
1176
Douglas Gregor81b747b2009-09-17 21:32:03 +00001177void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1178 bool EnteringContext) {
1179 if (!SS.getScopeRep() || !CodeCompleter)
1180 return;
1181
Douglas Gregor86d9a522009-09-21 16:56:56 +00001182 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1183 if (!Ctx)
1184 return;
1185
1186 ResultBuilder Results(*this);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001187 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001188
1189 // The "template" keyword can follow "::" in the grammar, but only
1190 // put it into the grammar if the nested-name-specifier is dependent.
1191 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1192 if (!Results.empty() && NNS->isDependent())
1193 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1194
1195 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001196}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001197
1198void Sema::CodeCompleteUsing(Scope *S) {
1199 if (!CodeCompleter)
1200 return;
1201
Douglas Gregor86d9a522009-09-21 16:56:56 +00001202 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001203 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001204
1205 // If we aren't in class scope, we could see the "namespace" keyword.
1206 if (!S->isClassScope())
1207 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1208
1209 // After "using", we can see anything that would start a
1210 // nested-name-specifier.
Douglas Gregor456c4a12009-09-21 20:12:40 +00001211 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0,
1212 CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001213 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001214
1215 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001216}
1217
1218void Sema::CodeCompleteUsingDirective(Scope *S) {
1219 if (!CodeCompleter)
1220 return;
1221
Douglas Gregor86d9a522009-09-21 16:56:56 +00001222 // After "using namespace", we expect to see a namespace name or namespace
1223 // alias.
1224 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001225 Results.EnterNewScope();
Douglas Gregor456c4a12009-09-21 20:12:40 +00001226 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1227 Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001228 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001229 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001230}
1231
1232void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1233 if (!CodeCompleter)
1234 return;
1235
Douglas Gregor86d9a522009-09-21 16:56:56 +00001236 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1237 DeclContext *Ctx = (DeclContext *)S->getEntity();
1238 if (!S->getParent())
1239 Ctx = Context.getTranslationUnitDecl();
1240
1241 if (Ctx && Ctx->isFileContext()) {
1242 // We only want to see those namespaces that have already been defined
1243 // within this scope, because its likely that the user is creating an
1244 // extended namespace declaration. Keep track of the most recent
1245 // definition of each namespace.
1246 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1247 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1248 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1249 NS != NSEnd; ++NS)
1250 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1251
1252 // Add the most recent definition (or extended definition) of each
1253 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001254 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001255 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1256 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1257 NS != NSEnd; ++NS)
Douglas Gregor456c4a12009-09-21 20:12:40 +00001258 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1259 CurContext);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001260 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001261 }
1262
1263 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001264}
1265
1266void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1267 if (!CodeCompleter)
1268 return;
1269
Douglas Gregor86d9a522009-09-21 16:56:56 +00001270 // After "namespace", we expect to see a namespace or alias.
1271 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001272 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1273 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001274 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001275}
1276
Douglas Gregored8d3222009-09-18 20:05:18 +00001277void Sema::CodeCompleteOperatorName(Scope *S) {
1278 if (!CodeCompleter)
1279 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001280
1281 typedef CodeCompleteConsumer::Result Result;
1282 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001283 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00001284
Douglas Gregor86d9a522009-09-21 16:56:56 +00001285 // Add the names of overloadable operators.
1286#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1287 if (std::strcmp(Spelling, "?")) \
1288 Results.MaybeAddResult(Result(Spelling, 0));
1289#include "clang/Basic/OperatorKinds.def"
1290
1291 // Add any type names visible from the current scope
1292 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001293 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001294
1295 // Add any type specifiers
1296 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1297
1298 // Add any nested-name-specifiers
1299 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1300 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +00001301 CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001302 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001303
1304 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00001305}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001306