blob: d7697a7333a1dce574cc713af147f46cba6d26d5 [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 }
201
202 // Look through using declarations.
203 if (UsingDecl *Using = dyn_cast<UsingDecl>(R.Declaration))
Douglas Gregor0563c262009-09-22 23:15:58 +0000204 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
205 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000206
207 // Handle each declaration in an overload set separately.
208 if (OverloadedFunctionDecl *Ovl
209 = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) {
210 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
211 FEnd = Ovl->function_end();
212 F != FEnd; ++F)
Douglas Gregor456c4a12009-09-21 20:12:40 +0000213 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000214
215 return;
216 }
217
218 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
219 unsigned IDNS = CanonDecl->getIdentifierNamespace();
220
221 // Friend declarations and declarations introduced due to friends are never
222 // added as results.
223 if (isa<FriendDecl>(CanonDecl) ||
224 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
225 return;
226
227 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
228 // __va_list_tag is a freak of nature. Find it and skip it.
229 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
230 return;
231
232 // FIXME: Should we filter out other names in the implementation's
233 // namespace, e.g., those containing a __ or that start with _[A-Z]?
234 }
235
236 // C++ constructors are never found by name lookup.
237 if (isa<CXXConstructorDecl>(CanonDecl))
238 return;
239
240 // Filter out any unwanted results.
241 if (Filter && !(this->*Filter)(R.Declaration))
242 return;
243
244 ShadowMap &SMap = ShadowMaps.back();
245 ShadowMap::iterator I, IEnd;
246 for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
247 I != IEnd; ++I) {
248 NamedDecl *ND = I->second.first;
249 unsigned Index = I->second.second;
250 if (ND->getCanonicalDecl() == CanonDecl) {
251 // This is a redeclaration. Always pick the newer declaration.
252 I->second.first = R.Declaration;
253 Results[Index].Declaration = R.Declaration;
254
255 // Pick the best rank of the two.
256 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
257
258 // We're done.
259 return;
260 }
261 }
262
263 // This is a new declaration in this scope. However, check whether this
264 // declaration name is hidden by a similarly-named declaration in an outer
265 // scope.
266 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
267 --SMEnd;
268 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
269 for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
270 I != IEnd; ++I) {
271 // A tag declaration does not hide a non-tag declaration.
272 if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
273 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
274 Decl::IDNS_ObjCProtocol)))
275 continue;
276
277 // Protocols are in distinct namespaces from everything else.
278 if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
279 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
280 I->second.first->getIdentifierNamespace() != IDNS)
281 continue;
282
283 // The newly-added result is hidden by an entry in the shadow map.
284 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
285 I->second.first)) {
286 // Note that this result was hidden.
287 R.Hidden = true;
Douglas Gregor0563c262009-09-22 23:15:58 +0000288 R.QualifierIsInformative = false;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000289
290 if (!R.Qualifier)
291 R.Qualifier = getRequiredQualification(SemaRef.Context,
292 CurContext,
293 R.Declaration->getDeclContext());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000294 } else {
295 // This result was hidden and cannot be found; don't bother adding
296 // it.
297 return;
298 }
299
300 break;
301 }
302 }
303
304 // Make sure that any given declaration only shows up in the result set once.
305 if (!AllDeclsFound.insert(CanonDecl))
306 return;
307
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000308 // If the filter is for nested-name-specifiers, then this result starts a
309 // nested-name-specifier.
310 if ((Filter == &ResultBuilder::IsNestedNameSpecifier) ||
311 (Filter == &ResultBuilder::IsMember &&
312 isa<CXXRecordDecl>(R.Declaration) &&
313 cast<CXXRecordDecl>(R.Declaration)->isInjectedClassName()))
314 R.StartsNestedNameSpecifier = true;
315
Douglas Gregor0563c262009-09-22 23:15:58 +0000316 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000317 if (R.QualifierIsInformative && !R.Qualifier &&
318 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000319 DeclContext *Ctx = R.Declaration->getDeclContext();
320 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
321 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
322 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
323 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
324 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
325 else
326 R.QualifierIsInformative = false;
327 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000328
Douglas Gregor86d9a522009-09-21 16:56:56 +0000329 // Insert this result into the set of results and into the current shadow
330 // map.
331 SMap.insert(std::make_pair(R.Declaration->getDeclName(),
332 std::make_pair(R.Declaration, Results.size())));
333 Results.push_back(R);
334}
335
336/// \brief Enter into a new scope.
337void ResultBuilder::EnterNewScope() {
338 ShadowMaps.push_back(ShadowMap());
339}
340
341/// \brief Exit from the current scope.
342void ResultBuilder::ExitScope() {
343 ShadowMaps.pop_back();
344}
345
Douglas Gregor791215b2009-09-21 20:51:25 +0000346/// \brief Determines whether this given declaration will be found by
347/// ordinary name lookup.
348bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
349 unsigned IDNS = Decl::IDNS_Ordinary;
350 if (SemaRef.getLangOptions().CPlusPlus)
351 IDNS |= Decl::IDNS_Tag;
352
353 return ND->getIdentifierNamespace() & IDNS;
354}
355
Douglas Gregor86d9a522009-09-21 16:56:56 +0000356/// \brief Determines whether the given declaration is suitable as the
357/// start of a C++ nested-name-specifier, e.g., a class or namespace.
358bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
359 // Allow us to find class templates, too.
360 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
361 ND = ClassTemplate->getTemplatedDecl();
362
363 return SemaRef.isAcceptableNestedNameSpecifier(ND);
364}
365
366/// \brief Determines whether the given declaration is an enumeration.
367bool ResultBuilder::IsEnum(NamedDecl *ND) const {
368 return isa<EnumDecl>(ND);
369}
370
371/// \brief Determines whether the given declaration is a class or struct.
372bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
373 // Allow us to find class templates, too.
374 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
375 ND = ClassTemplate->getTemplatedDecl();
376
377 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
378 return RD->getTagKind() == TagDecl::TK_class ||
379 RD->getTagKind() == TagDecl::TK_struct;
380
381 return false;
382}
383
384/// \brief Determines whether the given declaration is a union.
385bool ResultBuilder::IsUnion(NamedDecl *ND) const {
386 // Allow us to find class templates, too.
387 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
388 ND = ClassTemplate->getTemplatedDecl();
389
390 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
391 return RD->getTagKind() == TagDecl::TK_union;
392
393 return false;
394}
395
396/// \brief Determines whether the given declaration is a namespace.
397bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
398 return isa<NamespaceDecl>(ND);
399}
400
401/// \brief Determines whether the given declaration is a namespace or
402/// namespace alias.
403bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
404 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
405}
406
407/// \brief Brief determines whether the given declaration is a namespace or
408/// namespace alias.
409bool ResultBuilder::IsType(NamedDecl *ND) const {
410 return isa<TypeDecl>(ND);
411}
412
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000413/// \brief Since every declaration found within a class is a member that we
414/// care about, always returns true. This predicate exists mostly to
415/// communicate to the result builder that we are performing a lookup for
416/// member access.
417bool ResultBuilder::IsMember(NamedDecl *ND) const {
418 return true;
419}
420
Douglas Gregor86d9a522009-09-21 16:56:56 +0000421// Find the next outer declaration context corresponding to this scope.
422static DeclContext *findOuterContext(Scope *S) {
423 for (S = S->getParent(); S; S = S->getParent())
424 if (S->getEntity())
425 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
426
427 return 0;
428}
429
430/// \brief Collect the results of searching for members within the given
431/// declaration context.
432///
433/// \param Ctx the declaration context from which we will gather results.
434///
Douglas Gregor0563c262009-09-22 23:15:58 +0000435/// \param Rank the rank given to results in this declaration context.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000436///
437/// \param Visited the set of declaration contexts that have already been
438/// visited. Declaration contexts will only be visited once.
439///
440/// \param Results the result set that will be extended with any results
441/// found within this declaration context (and, for a C++ class, its bases).
442///
Douglas Gregor0563c262009-09-22 23:15:58 +0000443/// \param InBaseClass whether we are in a base class.
444///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000445/// \returns the next higher rank value, after considering all of the
446/// names within this declaration context.
447static unsigned CollectMemberLookupResults(DeclContext *Ctx,
Douglas Gregor0563c262009-09-22 23:15:58 +0000448 unsigned Rank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000449 DeclContext *CurContext,
450 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor0563c262009-09-22 23:15:58 +0000451 ResultBuilder &Results,
452 bool InBaseClass = false) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000453 // Make sure we don't visit the same context twice.
454 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor0563c262009-09-22 23:15:58 +0000455 return Rank;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000456
457 // Enumerate all of the results in this context.
Douglas Gregor0563c262009-09-22 23:15:58 +0000458 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000459 Results.EnterNewScope();
460 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
461 CurCtx = CurCtx->getNextContext()) {
462 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
463 DEnd = CurCtx->decls_end();
464 D != DEnd; ++D) {
465 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor0563c262009-09-22 23:15:58 +0000466 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000467 }
468 }
469
470 // Traverse the contexts of inherited classes.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000471 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
472 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
473 BEnd = Record->bases_end();
474 B != BEnd; ++B) {
475 QualType BaseType = B->getType();
476
477 // Don't look into dependent bases, because name lookup can't look
478 // there anyway.
479 if (BaseType->isDependentType())
480 continue;
481
482 const RecordType *Record = BaseType->getAs<RecordType>();
483 if (!Record)
484 continue;
485
486 // FIXME: It would be nice to be able to determine whether referencing
487 // a particular member would be ambiguous. For example, given
488 //
489 // struct A { int member; };
490 // struct B { int member; };
491 // struct C : A, B { };
492 //
493 // void f(C *c) { c->### }
494 // accessing 'member' would result in an ambiguity. However, code
495 // completion could be smart enough to qualify the member with the
496 // base class, e.g.,
497 //
498 // c->B::member
499 //
500 // or
501 //
502 // c->A::member
503
504 // Collect results from this base class (and its bases).
Douglas Gregor0563c262009-09-22 23:15:58 +0000505 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
506 Results, /*InBaseClass=*/true);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000507 }
508 }
509
510 // FIXME: Look into base classes in Objective-C!
511
512 Results.ExitScope();
Douglas Gregor0563c262009-09-22 23:15:58 +0000513 return Rank + 1;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000514}
515
516/// \brief Collect the results of searching for members within the given
517/// declaration context.
518///
519/// \param Ctx the declaration context from which we will gather results.
520///
521/// \param InitialRank the initial rank given to results in this declaration
522/// context. Larger rank values will be used for, e.g., members found in
523/// base classes.
524///
525/// \param Results the result set that will be extended with any results
526/// found within this declaration context (and, for a C++ class, its bases).
527///
528/// \returns the next higher rank value, after considering all of the
529/// names within this declaration context.
530static unsigned CollectMemberLookupResults(DeclContext *Ctx,
531 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000532 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000533 ResultBuilder &Results) {
534 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000535 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
536 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000537}
538
539/// \brief Collect the results of searching for declarations within the given
540/// scope and its parent scopes.
541///
542/// \param S the scope in which we will start looking for declarations.
543///
544/// \param InitialRank the initial rank given to results in this scope.
545/// Larger rank values will be used for results found in parent scopes.
546///
Douglas Gregor456c4a12009-09-21 20:12:40 +0000547/// \param CurContext the context from which lookup results will be found.
548///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000549/// \param Results the builder object that will receive each result.
550static unsigned CollectLookupResults(Scope *S,
551 TranslationUnitDecl *TranslationUnit,
552 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000553 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000554 ResultBuilder &Results) {
555 if (!S)
556 return InitialRank;
557
558 // FIXME: Using directives!
559
560 unsigned NextRank = InitialRank;
561 Results.EnterNewScope();
562 if (S->getEntity() &&
563 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
564 // Look into this scope's declaration context, along with any of its
565 // parent lookup contexts (e.g., enclosing classes), up to the point
566 // where we hit the context stored in the next outer scope.
567 DeclContext *Ctx = (DeclContext *)S->getEntity();
568 DeclContext *OuterCtx = findOuterContext(S);
569
570 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
571 Ctx = Ctx->getLookupParent()) {
572 if (Ctx->isFunctionOrMethod())
573 continue;
574
Douglas Gregor456c4a12009-09-21 20:12:40 +0000575 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
576 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000577 }
578 } else if (!S->getParent()) {
579 // Look into the translation unit scope. We walk through the translation
580 // unit's declaration context, because the Scope itself won't have all of
581 // the declarations if we loaded a precompiled header.
582 // FIXME: We would like the translation unit's Scope object to point to the
583 // translation unit, so we don't need this special "if" branch. However,
584 // doing so would force the normal C++ name-lookup code to look into the
585 // translation unit decl when the IdentifierInfo chains would suffice.
586 // Once we fix that problem (which is part of a more general "don't look
587 // in DeclContexts unless we have to" optimization), we can eliminate the
588 // TranslationUnit parameter entirely.
589 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000590 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000591 } else {
592 // Walk through the declarations in this Scope.
593 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
594 D != DEnd; ++D) {
595 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
Douglas Gregor456c4a12009-09-21 20:12:40 +0000596 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
597 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000598 }
599
600 NextRank = NextRank + 1;
601 }
602
603 // Lookup names in the parent scope.
604 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000605 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000606 Results.ExitScope();
607
608 return NextRank;
609}
610
611/// \brief Add type specifiers for the current language as keyword results.
612static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
613 ResultBuilder &Results) {
614 typedef CodeCompleteConsumer::Result Result;
615 Results.MaybeAddResult(Result("short", Rank));
616 Results.MaybeAddResult(Result("long", Rank));
617 Results.MaybeAddResult(Result("signed", Rank));
618 Results.MaybeAddResult(Result("unsigned", Rank));
619 Results.MaybeAddResult(Result("void", Rank));
620 Results.MaybeAddResult(Result("char", Rank));
621 Results.MaybeAddResult(Result("int", Rank));
622 Results.MaybeAddResult(Result("float", Rank));
623 Results.MaybeAddResult(Result("double", Rank));
624 Results.MaybeAddResult(Result("enum", Rank));
625 Results.MaybeAddResult(Result("struct", Rank));
626 Results.MaybeAddResult(Result("union", Rank));
627
628 if (LangOpts.C99) {
629 // C99-specific
630 Results.MaybeAddResult(Result("_Complex", Rank));
631 Results.MaybeAddResult(Result("_Imaginary", Rank));
632 Results.MaybeAddResult(Result("_Bool", Rank));
633 }
634
635 if (LangOpts.CPlusPlus) {
636 // C++-specific
637 Results.MaybeAddResult(Result("bool", Rank));
638 Results.MaybeAddResult(Result("class", Rank));
639 Results.MaybeAddResult(Result("typename", Rank));
640 Results.MaybeAddResult(Result("wchar_t", Rank));
641
642 if (LangOpts.CPlusPlus0x) {
643 Results.MaybeAddResult(Result("char16_t", Rank));
644 Results.MaybeAddResult(Result("char32_t", Rank));
645 Results.MaybeAddResult(Result("decltype", Rank));
646 }
647 }
648
649 // GNU extensions
650 if (LangOpts.GNUMode) {
651 // FIXME: Enable when we actually support decimal floating point.
652 // Results.MaybeAddResult(Result("_Decimal32", Rank));
653 // Results.MaybeAddResult(Result("_Decimal64", Rank));
654 // Results.MaybeAddResult(Result("_Decimal128", Rank));
655 Results.MaybeAddResult(Result("typeof", Rank));
656 }
657}
658
659/// \brief Add function parameter chunks to the given code completion string.
660static void AddFunctionParameterChunks(ASTContext &Context,
661 FunctionDecl *Function,
662 CodeCompletionString *Result) {
663 CodeCompletionString *CCStr = Result;
664
665 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
666 ParmVarDecl *Param = Function->getParamDecl(P);
667
668 if (Param->hasDefaultArg()) {
669 // When we see an optional default argument, put that argument and
670 // the remaining default arguments into a new, optional string.
671 CodeCompletionString *Opt = new CodeCompletionString;
672 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
673 CCStr = Opt;
674 }
675
676 if (P != 0)
677 CCStr->AddTextChunk(", ");
678
679 // Format the placeholder string.
680 std::string PlaceholderStr;
681 if (Param->getIdentifier())
682 PlaceholderStr = Param->getIdentifier()->getName();
683
684 Param->getType().getAsStringInternal(PlaceholderStr,
685 Context.PrintingPolicy);
686
687 // Add the placeholder string.
688 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
689 }
Douglas Gregorb3d45252009-09-22 21:42:17 +0000690
691 if (const FunctionProtoType *Proto
692 = Function->getType()->getAs<FunctionProtoType>())
693 if (Proto->isVariadic())
694 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000695}
696
697/// \brief Add template parameter chunks to the given code completion string.
698static void AddTemplateParameterChunks(ASTContext &Context,
699 TemplateDecl *Template,
700 CodeCompletionString *Result,
701 unsigned MaxParameters = 0) {
702 CodeCompletionString *CCStr = Result;
703 bool FirstParameter = true;
704
705 TemplateParameterList *Params = Template->getTemplateParameters();
706 TemplateParameterList::iterator PEnd = Params->end();
707 if (MaxParameters)
708 PEnd = Params->begin() + MaxParameters;
709 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
710 bool HasDefaultArg = false;
711 std::string PlaceholderStr;
712 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
713 if (TTP->wasDeclaredWithTypename())
714 PlaceholderStr = "typename";
715 else
716 PlaceholderStr = "class";
717
718 if (TTP->getIdentifier()) {
719 PlaceholderStr += ' ';
720 PlaceholderStr += TTP->getIdentifier()->getName();
721 }
722
723 HasDefaultArg = TTP->hasDefaultArgument();
724 } else if (NonTypeTemplateParmDecl *NTTP
725 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
726 if (NTTP->getIdentifier())
727 PlaceholderStr = NTTP->getIdentifier()->getName();
728 NTTP->getType().getAsStringInternal(PlaceholderStr,
729 Context.PrintingPolicy);
730 HasDefaultArg = NTTP->hasDefaultArgument();
731 } else {
732 assert(isa<TemplateTemplateParmDecl>(*P));
733 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
734
735 // Since putting the template argument list into the placeholder would
736 // be very, very long, we just use an abbreviation.
737 PlaceholderStr = "template<...> class";
738 if (TTP->getIdentifier()) {
739 PlaceholderStr += ' ';
740 PlaceholderStr += TTP->getIdentifier()->getName();
741 }
742
743 HasDefaultArg = TTP->hasDefaultArgument();
744 }
745
746 if (HasDefaultArg) {
747 // When we see an optional default argument, put that argument and
748 // the remaining default arguments into a new, optional string.
749 CodeCompletionString *Opt = new CodeCompletionString;
750 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
751 CCStr = Opt;
752 }
753
754 if (FirstParameter)
755 FirstParameter = false;
756 else
757 CCStr->AddTextChunk(", ");
758
759 // Add the placeholder string.
760 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
761 }
762}
763
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000764/// \brief Add a qualifier to the given code-completion string, if the
765/// provided nested-name-specifier is non-NULL.
766void AddQualifierToCompletionString(CodeCompletionString *Result,
767 NestedNameSpecifier *Qualifier,
Douglas Gregor0563c262009-09-22 23:15:58 +0000768 bool QualifierIsInformative,
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000769 ASTContext &Context) {
770 if (!Qualifier)
771 return;
772
773 std::string PrintedNNS;
774 {
775 llvm::raw_string_ostream OS(PrintedNNS);
776 Qualifier->print(OS, Context.PrintingPolicy);
777 }
Douglas Gregor0563c262009-09-22 23:15:58 +0000778 if (QualifierIsInformative)
779 Result->AddInformativeChunk(PrintedNNS.c_str());
780 else
781 Result->AddTextChunk(PrintedNNS.c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000782}
783
Douglas Gregor86d9a522009-09-21 16:56:56 +0000784/// \brief If possible, create a new code completion string for the given
785/// result.
786///
787/// \returns Either a new, heap-allocated code completion string describing
788/// how to use this result, or NULL to indicate that the string or name of the
789/// result is all that is needed.
790CodeCompletionString *
791CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
792 if (Kind != RK_Declaration)
793 return 0;
794
795 NamedDecl *ND = Declaration;
796
797 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
798 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000799 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
800 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000801 Result->AddTextChunk(Function->getNameAsString().c_str());
802 Result->AddTextChunk("(");
803 AddFunctionParameterChunks(S.Context, Function, Result);
804 Result->AddTextChunk(")");
805 return Result;
806 }
807
808 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
809 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000810 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
811 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000812 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
813 Result->AddTextChunk(Function->getNameAsString().c_str());
814
815 // Figure out which template parameters are deduced (or have default
816 // arguments).
817 llvm::SmallVector<bool, 16> Deduced;
818 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
819 unsigned LastDeducibleArgument;
820 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
821 --LastDeducibleArgument) {
822 if (!Deduced[LastDeducibleArgument - 1]) {
823 // C++0x: Figure out if the template argument has a default. If so,
824 // the user doesn't need to type this argument.
825 // FIXME: We need to abstract template parameters better!
826 bool HasDefaultArg = false;
827 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
828 LastDeducibleArgument - 1);
829 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
830 HasDefaultArg = TTP->hasDefaultArgument();
831 else if (NonTypeTemplateParmDecl *NTTP
832 = dyn_cast<NonTypeTemplateParmDecl>(Param))
833 HasDefaultArg = NTTP->hasDefaultArgument();
834 else {
835 assert(isa<TemplateTemplateParmDecl>(Param));
836 HasDefaultArg
837 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
838 }
839
840 if (!HasDefaultArg)
841 break;
842 }
843 }
844
845 if (LastDeducibleArgument) {
846 // Some of the function template arguments cannot be deduced from a
847 // function call, so we introduce an explicit template argument list
848 // containing all of the arguments up to the first deducible argument.
849 Result->AddTextChunk("<");
850 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
851 LastDeducibleArgument);
852 Result->AddTextChunk(">");
853 }
854
855 // Add the function parameters
856 Result->AddTextChunk("(");
857 AddFunctionParameterChunks(S.Context, Function, Result);
858 Result->AddTextChunk(")");
859 return Result;
860 }
861
862 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
863 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000864 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
865 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000866 Result->AddTextChunk(Template->getNameAsString().c_str());
867 Result->AddTextChunk("<");
868 AddTemplateParameterChunks(S.Context, Template, Result);
869 Result->AddTextChunk(">");
870 return Result;
871 }
872
Douglas Gregor3e7253f2009-09-22 23:22:24 +0000873 if (Qualifier || StartsNestedNameSpecifier) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000874 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000875 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
876 S.Context);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000877 Result->AddTextChunk(ND->getNameAsString().c_str());
Douglas Gregor3e7253f2009-09-22 23:22:24 +0000878 if (StartsNestedNameSpecifier)
879 Result->AddTextChunk("::");
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000880 return Result;
881 }
882
Douglas Gregor86d9a522009-09-21 16:56:56 +0000883 return 0;
884}
885
Douglas Gregor86d802e2009-09-23 00:34:09 +0000886CodeCompletionString *
887CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
888 unsigned CurrentArg,
889 Sema &S) const {
890 CodeCompletionString *Result = new CodeCompletionString;
891 FunctionDecl *FDecl = getFunction();
892 const FunctionProtoType *Proto
893 = dyn_cast<FunctionProtoType>(getFunctionType());
894 if (!FDecl && !Proto) {
895 // Function without a prototype. Just give the return type and a
896 // highlighted ellipsis.
897 const FunctionType *FT = getFunctionType();
898 Result->AddTextChunk(
899 FT->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
900 Result->AddTextChunk("(");
901 Result->AddPlaceholderChunk("...");
902 Result->AddTextChunk("(");
903 return Result;
904 }
905
906 if (FDecl)
907 Result->AddTextChunk(FDecl->getNameAsString().c_str());
908 else
909 Result->AddTextChunk(
910 Proto->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
911
912 Result->AddTextChunk("(");
913 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
914 for (unsigned I = 0; I != NumParams; ++I) {
915 if (I)
916 Result->AddTextChunk(", ");
917
918 std::string ArgString;
919 QualType ArgType;
920
921 if (FDecl) {
922 ArgString = FDecl->getParamDecl(I)->getNameAsString();
923 ArgType = FDecl->getParamDecl(I)->getOriginalType();
924 } else {
925 ArgType = Proto->getArgType(I);
926 }
927
928 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
929
930 if (I == CurrentArg)
931 Result->AddPlaceholderChunk(ArgString.c_str());
932 else
933 Result->AddTextChunk(ArgString.c_str());
934 }
935
936 if (Proto && Proto->isVariadic()) {
937 Result->AddTextChunk(", ");
938 if (CurrentArg < NumParams)
939 Result->AddTextChunk("...");
940 else
941 Result->AddPlaceholderChunk("...");
942 }
943 Result->AddTextChunk(")");
944
945 return Result;
946}
947
Douglas Gregor86d9a522009-09-21 16:56:56 +0000948namespace {
949 struct SortCodeCompleteResult {
950 typedef CodeCompleteConsumer::Result Result;
951
Douglas Gregor6a684032009-09-28 03:51:44 +0000952 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
953 if (X.getNameKind() != Y.getNameKind())
954 return X.getNameKind() < Y.getNameKind();
955
956 return llvm::LowercaseString(X.getAsString())
957 < llvm::LowercaseString(Y.getAsString());
958 }
959
Douglas Gregor86d9a522009-09-21 16:56:56 +0000960 bool operator()(const Result &X, const Result &Y) const {
961 // Sort first by rank.
962 if (X.Rank < Y.Rank)
963 return true;
964 else if (X.Rank > Y.Rank)
965 return false;
966
967 // Result kinds are ordered by decreasing importance.
968 if (X.Kind < Y.Kind)
969 return true;
970 else if (X.Kind > Y.Kind)
971 return false;
972
973 // Non-hidden names precede hidden names.
974 if (X.Hidden != Y.Hidden)
975 return !X.Hidden;
976
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000977 // Non-nested-name-specifiers precede nested-name-specifiers.
978 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
979 return !X.StartsNestedNameSpecifier;
980
Douglas Gregor86d9a522009-09-21 16:56:56 +0000981 // Ordering depends on the kind of result.
982 switch (X.Kind) {
983 case Result::RK_Declaration:
984 // Order based on the declaration names.
Douglas Gregor6a684032009-09-28 03:51:44 +0000985 return isEarlierDeclarationName(X.Declaration->getDeclName(),
986 Y.Declaration->getDeclName());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000987
988 case Result::RK_Keyword:
Steve Naroff7f511122009-10-08 23:45:10 +0000989 return strcmp(X.Keyword, Y.Keyword) < 0;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000990 }
991
992 // Silence GCC warning.
993 return false;
994 }
995 };
996}
997
998static void HandleCodeCompleteResults(CodeCompleteConsumer *CodeCompleter,
999 CodeCompleteConsumer::Result *Results,
1000 unsigned NumResults) {
1001 // Sort the results by rank/kind/etc.
1002 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1003
1004 if (CodeCompleter)
1005 CodeCompleter->ProcessCodeCompleteResults(Results, NumResults);
1006}
1007
Douglas Gregor791215b2009-09-21 20:51:25 +00001008void Sema::CodeCompleteOrdinaryName(Scope *S) {
1009 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
1010 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1011 Results);
1012 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1013}
1014
Douglas Gregor81b747b2009-09-17 21:32:03 +00001015void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1016 SourceLocation OpLoc,
1017 bool IsArrow) {
1018 if (!BaseE || !CodeCompleter)
1019 return;
1020
Douglas Gregor86d9a522009-09-21 16:56:56 +00001021 typedef CodeCompleteConsumer::Result Result;
1022
Douglas Gregor81b747b2009-09-17 21:32:03 +00001023 Expr *Base = static_cast<Expr *>(BaseE);
1024 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001025
1026 if (IsArrow) {
1027 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1028 BaseType = Ptr->getPointeeType();
1029 else if (BaseType->isObjCObjectPointerType())
1030 /*Do nothing*/ ;
1031 else
1032 return;
1033 }
1034
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001035 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001036 unsigned NextRank = 0;
1037
1038 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor456c4a12009-09-21 20:12:40 +00001039 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1040 Record->getDecl(), Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001041
1042 if (getLangOptions().CPlusPlus) {
1043 if (!Results.empty()) {
1044 // The "template" keyword can follow "->" or "." in the grammar.
1045 // However, we only want to suggest the template keyword if something
1046 // is dependent.
1047 bool IsDependent = BaseType->isDependentType();
1048 if (!IsDependent) {
1049 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1050 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1051 IsDependent = Ctx->isDependentContext();
1052 break;
1053 }
1054 }
1055
1056 if (IsDependent)
1057 Results.MaybeAddResult(Result("template", NextRank++));
1058 }
1059
1060 // We could have the start of a nested-name-specifier. Add those
1061 // results as well.
1062 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1063 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +00001064 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001065 }
1066
1067 // Hand off the results found for code completion.
1068 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1069
1070 // We're done!
1071 return;
1072 }
Douglas Gregor81b747b2009-09-17 21:32:03 +00001073}
1074
Douglas Gregor374929f2009-09-18 15:37:17 +00001075void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1076 if (!CodeCompleter)
1077 return;
1078
Douglas Gregor86d9a522009-09-21 16:56:56 +00001079 typedef CodeCompleteConsumer::Result Result;
1080 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +00001081 switch ((DeclSpec::TST)TagSpec) {
1082 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001083 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +00001084 break;
1085
1086 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001087 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +00001088 break;
1089
1090 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00001091 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001092 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00001093 break;
1094
1095 default:
1096 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1097 return;
1098 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001099
1100 ResultBuilder Results(*this, Filter);
1101 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001102 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001103
1104 if (getLangOptions().CPlusPlus) {
1105 // We could have the start of a nested-name-specifier. Add those
1106 // results as well.
1107 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1108 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +00001109 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001110 }
1111
1112 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00001113}
1114
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001115void Sema::CodeCompleteCase(Scope *S) {
1116 if (getSwitchStack().empty() || !CodeCompleter)
1117 return;
1118
1119 SwitchStmt *Switch = getSwitchStack().back();
1120 if (!Switch->getCond()->getType()->isEnumeralType())
1121 return;
1122
1123 // Code-complete the cases of a switch statement over an enumeration type
1124 // by providing the list of
1125 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1126
1127 // Determine which enumerators we have already seen in the switch statement.
1128 // FIXME: Ideally, we would also be able to look *past* the code-completion
1129 // token, in case we are code-completing in the middle of the switch and not
1130 // at the end. However, we aren't able to do so at the moment.
1131 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001132 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001133 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1134 SC = SC->getNextSwitchCase()) {
1135 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1136 if (!Case)
1137 continue;
1138
1139 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1140 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1141 if (EnumConstantDecl *Enumerator
1142 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1143 // We look into the AST of the case statement to determine which
1144 // enumerator was named. Alternatively, we could compute the value of
1145 // the integral constant expression, then compare it against the
1146 // values of each enumerator. However, value-based approach would not
1147 // work as well with C++ templates where enumerators declared within a
1148 // template are type- and value-dependent.
1149 EnumeratorsSeen.insert(Enumerator);
1150
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001151 // If this is a qualified-id, keep track of the nested-name-specifier
1152 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001153 //
1154 // switch (TagD.getKind()) {
1155 // case TagDecl::TK_enum:
1156 // break;
1157 // case XXX
1158 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001159 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001160 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1161 // TK_struct, and TK_class.
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001162 if (QualifiedDeclRefExpr *QDRE = dyn_cast<QualifiedDeclRefExpr>(DRE))
1163 Qualifier = QDRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001164 }
1165 }
1166
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001167 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1168 // If there are no prior enumerators in C++, check whether we have to
1169 // qualify the names of the enumerators that we suggest, because they
1170 // may not be visible in this scope.
1171 Qualifier = getRequiredQualification(Context, CurContext,
1172 Enum->getDeclContext());
1173
1174 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1175 }
1176
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001177 // Add any enumerators that have not yet been mentioned.
1178 ResultBuilder Results(*this);
1179 Results.EnterNewScope();
1180 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1181 EEnd = Enum->enumerator_end();
1182 E != EEnd; ++E) {
1183 if (EnumeratorsSeen.count(*E))
1184 continue;
1185
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001186 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001187 }
1188 Results.ExitScope();
1189
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001190 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1191}
1192
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001193namespace {
1194 struct IsBetterOverloadCandidate {
1195 Sema &S;
1196
1197 public:
1198 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1199
1200 bool
1201 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1202 return S.isBetterOverloadCandidate(X, Y);
1203 }
1204 };
1205}
1206
1207void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1208 ExprTy **ArgsIn, unsigned NumArgs) {
1209 if (!CodeCompleter)
1210 return;
1211
1212 Expr *Fn = (Expr *)FnIn;
1213 Expr **Args = (Expr **)ArgsIn;
1214
1215 // Ignore type-dependent call expressions entirely.
1216 if (Fn->isTypeDependent() ||
1217 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1218 return;
1219
1220 NamedDecl *Function;
1221 DeclarationName UnqualifiedName;
1222 NestedNameSpecifier *Qualifier;
1223 SourceRange QualifierRange;
1224 bool ArgumentDependentLookup;
1225 bool HasExplicitTemplateArgs;
1226 const TemplateArgument *ExplicitTemplateArgs;
1227 unsigned NumExplicitTemplateArgs;
1228
1229 DeconstructCallFunction(Fn,
1230 Function, UnqualifiedName, Qualifier, QualifierRange,
1231 ArgumentDependentLookup, HasExplicitTemplateArgs,
1232 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1233
1234
1235 // FIXME: What if we're calling something that isn't a function declaration?
1236 // FIXME: What if we're calling a pseudo-destructor?
1237 // FIXME: What if we're calling a member function?
1238
1239 // Build an overload candidate set based on the functions we find.
1240 OverloadCandidateSet CandidateSet;
1241 AddOverloadedCallCandidates(Function, UnqualifiedName,
1242 ArgumentDependentLookup, HasExplicitTemplateArgs,
1243 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1244 Args, NumArgs,
1245 CandidateSet,
1246 /*PartialOverloading=*/true);
1247
1248 // Sort the overload candidate set by placing the best overloads first.
1249 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1250 IsBetterOverloadCandidate(*this));
1251
1252 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05944382009-09-23 00:16:58 +00001253 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1254 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlsson90756302009-09-22 17:29:51 +00001255
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001256 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1257 CandEnd = CandidateSet.end();
1258 Cand != CandEnd; ++Cand) {
1259 if (Cand->Viable)
Douglas Gregor05944382009-09-23 00:16:58 +00001260 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001261 }
Douglas Gregor05944382009-09-23 00:16:58 +00001262 CodeCompleter->ProcessOverloadCandidates(NumArgs, Results.data(),
1263 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001264}
1265
Douglas Gregor81b747b2009-09-17 21:32:03 +00001266void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1267 bool EnteringContext) {
1268 if (!SS.getScopeRep() || !CodeCompleter)
1269 return;
1270
Douglas Gregor86d9a522009-09-21 16:56:56 +00001271 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1272 if (!Ctx)
1273 return;
1274
1275 ResultBuilder Results(*this);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001276 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001277
1278 // The "template" keyword can follow "::" in the grammar, but only
1279 // put it into the grammar if the nested-name-specifier is dependent.
1280 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1281 if (!Results.empty() && NNS->isDependent())
1282 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1283
1284 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001285}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001286
1287void Sema::CodeCompleteUsing(Scope *S) {
1288 if (!CodeCompleter)
1289 return;
1290
Douglas Gregor86d9a522009-09-21 16:56:56 +00001291 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001292 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001293
1294 // If we aren't in class scope, we could see the "namespace" keyword.
1295 if (!S->isClassScope())
1296 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1297
1298 // After "using", we can see anything that would start a
1299 // nested-name-specifier.
Douglas Gregor456c4a12009-09-21 20:12:40 +00001300 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0,
1301 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 Gregor49f40bd2009-09-18 19:03:04 +00001305}
1306
1307void Sema::CodeCompleteUsingDirective(Scope *S) {
1308 if (!CodeCompleter)
1309 return;
1310
Douglas Gregor86d9a522009-09-21 16:56:56 +00001311 // After "using namespace", we expect to see a namespace name or namespace
1312 // alias.
1313 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001314 Results.EnterNewScope();
Douglas Gregor456c4a12009-09-21 20:12:40 +00001315 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1316 Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001317 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001318 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001319}
1320
1321void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1322 if (!CodeCompleter)
1323 return;
1324
Douglas Gregor86d9a522009-09-21 16:56:56 +00001325 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1326 DeclContext *Ctx = (DeclContext *)S->getEntity();
1327 if (!S->getParent())
1328 Ctx = Context.getTranslationUnitDecl();
1329
1330 if (Ctx && Ctx->isFileContext()) {
1331 // We only want to see those namespaces that have already been defined
1332 // within this scope, because its likely that the user is creating an
1333 // extended namespace declaration. Keep track of the most recent
1334 // definition of each namespace.
1335 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1336 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1337 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1338 NS != NSEnd; ++NS)
1339 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1340
1341 // Add the most recent definition (or extended definition) of each
1342 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001343 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001344 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1345 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1346 NS != NSEnd; ++NS)
Douglas Gregor456c4a12009-09-21 20:12:40 +00001347 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1348 CurContext);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001349 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001350 }
1351
1352 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001353}
1354
1355void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1356 if (!CodeCompleter)
1357 return;
1358
Douglas Gregor86d9a522009-09-21 16:56:56 +00001359 // After "namespace", we expect to see a namespace or alias.
1360 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001361 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1362 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001363 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001364}
1365
Douglas Gregored8d3222009-09-18 20:05:18 +00001366void Sema::CodeCompleteOperatorName(Scope *S) {
1367 if (!CodeCompleter)
1368 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001369
1370 typedef CodeCompleteConsumer::Result Result;
1371 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001372 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00001373
Douglas Gregor86d9a522009-09-21 16:56:56 +00001374 // Add the names of overloadable operators.
1375#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1376 if (std::strcmp(Spelling, "?")) \
1377 Results.MaybeAddResult(Result(Spelling, 0));
1378#include "clang/Basic/OperatorKinds.def"
1379
1380 // Add any type names visible from the current scope
1381 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001382 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001383
1384 // Add any type specifiers
1385 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1386
1387 // Add any nested-name-specifiers
1388 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1389 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +00001390 CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001391 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001392
1393 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00001394}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001395
Steve Naroffece8e712009-10-08 21:55:05 +00001396void Sema::CodeCompleteObjCProperty(Scope *S, ObjCDeclSpec &ODS) {
1397 if (!CodeCompleter)
1398 return;
1399 unsigned Attributes = ODS.getPropertyAttributes();
1400
1401 typedef CodeCompleteConsumer::Result Result;
1402 ResultBuilder Results(*this);
1403 Results.EnterNewScope();
1404 if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly))
1405 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
1406 if (!(Attributes & ObjCDeclSpec::DQ_PR_assign))
1407 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
1408 if (!(Attributes & ObjCDeclSpec::DQ_PR_readwrite))
1409 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
1410 if (!(Attributes & ObjCDeclSpec::DQ_PR_retain))
1411 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
1412 if (!(Attributes & ObjCDeclSpec::DQ_PR_copy))
1413 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
1414 if (!(Attributes & ObjCDeclSpec::DQ_PR_nonatomic))
1415 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
1416 if (!(Attributes & ObjCDeclSpec::DQ_PR_setter))
1417 Results.MaybeAddResult(CodeCompleteConsumer::Result("setter", 0));
1418 if (!(Attributes & ObjCDeclSpec::DQ_PR_getter))
1419 Results.MaybeAddResult(CodeCompleteConsumer::Result("getter", 0));
1420 Results.ExitScope();
1421 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1422}