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