blob: f57480e13e8106d7b229ae5edab63852428f3c1d [file] [log] [blame]
Douglas Gregor81b747b2009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
13#include "Sema.h"
14#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000015#include "clang/AST/ExprCXX.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000016#include "llvm/ADT/SmallPtrSet.h"
17#include <list>
18#include <map>
19#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000020
21using namespace clang;
22
23/// \brief Set the code-completion consumer for semantic analysis.
24void Sema::setCodeCompleteConsumer(CodeCompleteConsumer *CCC) {
25 assert(((CodeCompleter != 0) != (CCC != 0)) &&
26 "Already set or cleared a code-completion consumer?");
27 CodeCompleter = CCC;
28}
29
Douglas Gregor86d9a522009-09-21 16:56:56 +000030namespace {
31 /// \brief A container of code-completion results.
32 class ResultBuilder {
33 public:
34 /// \brief The type of a name-lookup filter, which can be provided to the
35 /// name-lookup routines to specify which declarations should be included in
36 /// the result set (when it returns true) and which declarations should be
37 /// filtered out (returns false).
38 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
39
40 typedef CodeCompleteConsumer::Result Result;
41
42 private:
43 /// \brief The actual results we have found.
44 std::vector<Result> Results;
45
46 /// \brief A record of all of the declarations we have found and placed
47 /// into the result set, used to ensure that no declaration ever gets into
48 /// the result set twice.
49 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
50
51 /// \brief A mapping from declaration names to the declarations that have
52 /// this name within a particular scope and their index within the list of
53 /// results.
54 typedef std::multimap<DeclarationName,
55 std::pair<NamedDecl *, unsigned> > ShadowMap;
56
57 /// \brief The semantic analysis object for which results are being
58 /// produced.
59 Sema &SemaRef;
60
61 /// \brief If non-NULL, a filter function used to remove any code-completion
62 /// results that are not desirable.
63 LookupFilter Filter;
64
65 /// \brief A list of shadow maps, which is used to model name hiding at
66 /// different levels of, e.g., the inheritance hierarchy.
67 std::list<ShadowMap> ShadowMaps;
68
69 public:
70 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
71 : SemaRef(SemaRef), Filter(Filter) { }
72
73 /// \brief Set the filter used for code-completion results.
74 void setFilter(LookupFilter Filter) {
75 this->Filter = Filter;
76 }
77
78 typedef std::vector<Result>::iterator iterator;
79 iterator begin() { return Results.begin(); }
80 iterator end() { return Results.end(); }
81
82 Result *data() { return Results.empty()? 0 : &Results.front(); }
83 unsigned size() const { return Results.size(); }
84 bool empty() const { return Results.empty(); }
85
86 /// \brief Add a new result to this result set (if it isn't already in one
87 /// of the shadow maps), or replace an existing result (for, e.g., a
88 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +000089 ///
90 /// \param R the result to add (if it is unique).
91 ///
92 /// \param R the context in which this result will be named.
93 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +000094
95 /// \brief Enter into a new scope.
96 void EnterNewScope();
97
98 /// \brief Exit from the current scope.
99 void ExitScope();
100
101 /// \name Name lookup predicates
102 ///
103 /// These predicates can be passed to the name lookup functions to filter the
104 /// results of name lookup. All of the predicates have the same type, so that
105 ///
106 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000107 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000108 bool IsNestedNameSpecifier(NamedDecl *ND) const;
109 bool IsEnum(NamedDecl *ND) const;
110 bool IsClassOrStruct(NamedDecl *ND) const;
111 bool IsUnion(NamedDecl *ND) const;
112 bool IsNamespace(NamedDecl *ND) const;
113 bool IsNamespaceOrAlias(NamedDecl *ND) const;
114 bool IsType(NamedDecl *ND) const;
115 //@}
116 };
117}
118
119/// \brief Determines whether the given hidden result could be found with
120/// some extra work, e.g., by qualifying the name.
121///
122/// \param Hidden the declaration that is hidden by the currenly \p Visible
123/// declaration.
124///
125/// \param Visible the declaration with the same name that is already visible.
126///
127/// \returns true if the hidden result can be found by some mechanism,
128/// false otherwise.
129static bool canHiddenResultBeFound(const LangOptions &LangOpts,
130 NamedDecl *Hidden, NamedDecl *Visible) {
131 // In C, there is no way to refer to a hidden name.
132 if (!LangOpts.CPlusPlus)
133 return false;
134
135 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
136
137 // There is no way to qualify a name declared in a function or method.
138 if (HiddenCtx->isFunctionOrMethod())
139 return false;
140
Douglas Gregor86d9a522009-09-21 16:56:56 +0000141 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
142}
143
Douglas Gregor456c4a12009-09-21 20:12:40 +0000144/// \brief Compute the qualification required to get from the current context
145/// (\p CurContext) to the target context (\p TargetContext).
146///
147/// \param Context the AST context in which the qualification will be used.
148///
149/// \param CurContext the context where an entity is being named, which is
150/// typically based on the current scope.
151///
152/// \param TargetContext the context in which the named entity actually
153/// resides.
154///
155/// \returns a nested name specifier that refers into the target context, or
156/// NULL if no qualification is needed.
157static NestedNameSpecifier *
158getRequiredQualification(ASTContext &Context,
159 DeclContext *CurContext,
160 DeclContext *TargetContext) {
161 llvm::SmallVector<DeclContext *, 4> TargetParents;
162
163 for (DeclContext *CommonAncestor = TargetContext;
164 CommonAncestor && !CommonAncestor->Encloses(CurContext);
165 CommonAncestor = CommonAncestor->getLookupParent()) {
166 if (CommonAncestor->isTransparentContext() ||
167 CommonAncestor->isFunctionOrMethod())
168 continue;
169
170 TargetParents.push_back(CommonAncestor);
171 }
172
173 NestedNameSpecifier *Result = 0;
174 while (!TargetParents.empty()) {
175 DeclContext *Parent = TargetParents.back();
176 TargetParents.pop_back();
177
178 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
179 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
180 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
181 Result = NestedNameSpecifier::Create(Context, Result,
182 false,
183 Context.getTypeDeclType(TD).getTypePtr());
184 else
185 assert(Parent->isTranslationUnit());
186 }
187
188 return Result;
189}
190
191void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000192 if (R.Kind != Result::RK_Declaration) {
193 // For non-declaration results, just add the result.
194 Results.push_back(R);
195 return;
196 }
197
198 // Look through using declarations.
199 if (UsingDecl *Using = dyn_cast<UsingDecl>(R.Declaration))
Douglas Gregor0563c262009-09-22 23:15:58 +0000200 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
201 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000202
203 // Handle each declaration in an overload set separately.
204 if (OverloadedFunctionDecl *Ovl
205 = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) {
206 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
207 FEnd = Ovl->function_end();
208 F != FEnd; ++F)
Douglas Gregor456c4a12009-09-21 20:12:40 +0000209 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000210
211 return;
212 }
213
214 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
215 unsigned IDNS = CanonDecl->getIdentifierNamespace();
216
217 // Friend declarations and declarations introduced due to friends are never
218 // added as results.
219 if (isa<FriendDecl>(CanonDecl) ||
220 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
221 return;
222
223 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
224 // __va_list_tag is a freak of nature. Find it and skip it.
225 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
226 return;
227
228 // FIXME: Should we filter out other names in the implementation's
229 // namespace, e.g., those containing a __ or that start with _[A-Z]?
230 }
231
232 // C++ constructors are never found by name lookup.
233 if (isa<CXXConstructorDecl>(CanonDecl))
234 return;
235
236 // Filter out any unwanted results.
237 if (Filter && !(this->*Filter)(R.Declaration))
238 return;
239
240 ShadowMap &SMap = ShadowMaps.back();
241 ShadowMap::iterator I, IEnd;
242 for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
243 I != IEnd; ++I) {
244 NamedDecl *ND = I->second.first;
245 unsigned Index = I->second.second;
246 if (ND->getCanonicalDecl() == CanonDecl) {
247 // This is a redeclaration. Always pick the newer declaration.
248 I->second.first = R.Declaration;
249 Results[Index].Declaration = R.Declaration;
250
251 // Pick the best rank of the two.
252 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
253
254 // We're done.
255 return;
256 }
257 }
258
259 // This is a new declaration in this scope. However, check whether this
260 // declaration name is hidden by a similarly-named declaration in an outer
261 // scope.
262 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
263 --SMEnd;
264 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
265 for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
266 I != IEnd; ++I) {
267 // A tag declaration does not hide a non-tag declaration.
268 if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
269 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
270 Decl::IDNS_ObjCProtocol)))
271 continue;
272
273 // Protocols are in distinct namespaces from everything else.
274 if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
275 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
276 I->second.first->getIdentifierNamespace() != IDNS)
277 continue;
278
279 // The newly-added result is hidden by an entry in the shadow map.
280 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
281 I->second.first)) {
282 // Note that this result was hidden.
283 R.Hidden = true;
Douglas Gregor0563c262009-09-22 23:15:58 +0000284 R.QualifierIsInformative = false;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000285
286 if (!R.Qualifier)
287 R.Qualifier = getRequiredQualification(SemaRef.Context,
288 CurContext,
289 R.Declaration->getDeclContext());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000290 } else {
291 // This result was hidden and cannot be found; don't bother adding
292 // it.
293 return;
294 }
295
296 break;
297 }
298 }
299
300 // Make sure that any given declaration only shows up in the result set once.
301 if (!AllDeclsFound.insert(CanonDecl))
302 return;
303
Douglas Gregor0563c262009-09-22 23:15:58 +0000304 // If this result is supposed to have an informative qualifier, add one.
305 if (R.QualifierIsInformative && !R.Qualifier) {
306 DeclContext *Ctx = R.Declaration->getDeclContext();
307 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
308 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
309 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
310 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
311 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
312 else
313 R.QualifierIsInformative = false;
314 }
315
Douglas Gregor86d9a522009-09-21 16:56:56 +0000316 // Insert this result into the set of results and into the current shadow
317 // map.
318 SMap.insert(std::make_pair(R.Declaration->getDeclName(),
319 std::make_pair(R.Declaration, Results.size())));
320 Results.push_back(R);
321}
322
323/// \brief Enter into a new scope.
324void ResultBuilder::EnterNewScope() {
325 ShadowMaps.push_back(ShadowMap());
326}
327
328/// \brief Exit from the current scope.
329void ResultBuilder::ExitScope() {
330 ShadowMaps.pop_back();
331}
332
Douglas Gregor791215b2009-09-21 20:51:25 +0000333/// \brief Determines whether this given declaration will be found by
334/// ordinary name lookup.
335bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
336 unsigned IDNS = Decl::IDNS_Ordinary;
337 if (SemaRef.getLangOptions().CPlusPlus)
338 IDNS |= Decl::IDNS_Tag;
339
340 return ND->getIdentifierNamespace() & IDNS;
341}
342
Douglas Gregor86d9a522009-09-21 16:56:56 +0000343/// \brief Determines whether the given declaration is suitable as the
344/// start of a C++ nested-name-specifier, e.g., a class or namespace.
345bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
346 // Allow us to find class templates, too.
347 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
348 ND = ClassTemplate->getTemplatedDecl();
349
350 return SemaRef.isAcceptableNestedNameSpecifier(ND);
351}
352
353/// \brief Determines whether the given declaration is an enumeration.
354bool ResultBuilder::IsEnum(NamedDecl *ND) const {
355 return isa<EnumDecl>(ND);
356}
357
358/// \brief Determines whether the given declaration is a class or struct.
359bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
360 // Allow us to find class templates, too.
361 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
362 ND = ClassTemplate->getTemplatedDecl();
363
364 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
365 return RD->getTagKind() == TagDecl::TK_class ||
366 RD->getTagKind() == TagDecl::TK_struct;
367
368 return false;
369}
370
371/// \brief Determines whether the given declaration is a union.
372bool ResultBuilder::IsUnion(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_union;
379
380 return false;
381}
382
383/// \brief Determines whether the given declaration is a namespace.
384bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
385 return isa<NamespaceDecl>(ND);
386}
387
388/// \brief Determines whether the given declaration is a namespace or
389/// namespace alias.
390bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
391 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
392}
393
394/// \brief Brief determines whether the given declaration is a namespace or
395/// namespace alias.
396bool ResultBuilder::IsType(NamedDecl *ND) const {
397 return isa<TypeDecl>(ND);
398}
399
400// Find the next outer declaration context corresponding to this scope.
401static DeclContext *findOuterContext(Scope *S) {
402 for (S = S->getParent(); S; S = S->getParent())
403 if (S->getEntity())
404 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
405
406 return 0;
407}
408
409/// \brief Collect the results of searching for members within the given
410/// declaration context.
411///
412/// \param Ctx the declaration context from which we will gather results.
413///
Douglas Gregor0563c262009-09-22 23:15:58 +0000414/// \param Rank the rank given to results in this declaration context.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000415///
416/// \param Visited the set of declaration contexts that have already been
417/// visited. Declaration contexts will only be visited once.
418///
419/// \param Results the result set that will be extended with any results
420/// found within this declaration context (and, for a C++ class, its bases).
421///
Douglas Gregor0563c262009-09-22 23:15:58 +0000422/// \param InBaseClass whether we are in a base class.
423///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000424/// \returns the next higher rank value, after considering all of the
425/// names within this declaration context.
426static unsigned CollectMemberLookupResults(DeclContext *Ctx,
Douglas Gregor0563c262009-09-22 23:15:58 +0000427 unsigned Rank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000428 DeclContext *CurContext,
429 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor0563c262009-09-22 23:15:58 +0000430 ResultBuilder &Results,
431 bool InBaseClass = false) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000432 // Make sure we don't visit the same context twice.
433 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor0563c262009-09-22 23:15:58 +0000434 return Rank;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000435
436 // Enumerate all of the results in this context.
Douglas Gregor0563c262009-09-22 23:15:58 +0000437 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000438 Results.EnterNewScope();
439 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
440 CurCtx = CurCtx->getNextContext()) {
441 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
442 DEnd = CurCtx->decls_end();
443 D != DEnd; ++D) {
444 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor0563c262009-09-22 23:15:58 +0000445 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000446 }
447 }
448
449 // Traverse the contexts of inherited classes.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000450 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
451 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
452 BEnd = Record->bases_end();
453 B != BEnd; ++B) {
454 QualType BaseType = B->getType();
455
456 // Don't look into dependent bases, because name lookup can't look
457 // there anyway.
458 if (BaseType->isDependentType())
459 continue;
460
461 const RecordType *Record = BaseType->getAs<RecordType>();
462 if (!Record)
463 continue;
464
465 // FIXME: It would be nice to be able to determine whether referencing
466 // a particular member would be ambiguous. For example, given
467 //
468 // struct A { int member; };
469 // struct B { int member; };
470 // struct C : A, B { };
471 //
472 // void f(C *c) { c->### }
473 // accessing 'member' would result in an ambiguity. However, code
474 // completion could be smart enough to qualify the member with the
475 // base class, e.g.,
476 //
477 // c->B::member
478 //
479 // or
480 //
481 // c->A::member
482
483 // Collect results from this base class (and its bases).
Douglas Gregor0563c262009-09-22 23:15:58 +0000484 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
485 Results, /*InBaseClass=*/true);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000486 }
487 }
488
489 // FIXME: Look into base classes in Objective-C!
490
491 Results.ExitScope();
Douglas Gregor0563c262009-09-22 23:15:58 +0000492 return Rank + 1;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000493}
494
495/// \brief Collect the results of searching for members within the given
496/// declaration context.
497///
498/// \param Ctx the declaration context from which we will gather results.
499///
500/// \param InitialRank the initial rank given to results in this declaration
501/// context. Larger rank values will be used for, e.g., members found in
502/// base classes.
503///
504/// \param Results the result set that will be extended with any results
505/// found within this declaration context (and, for a C++ class, its bases).
506///
507/// \returns the next higher rank value, after considering all of the
508/// names within this declaration context.
509static unsigned CollectMemberLookupResults(DeclContext *Ctx,
510 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000511 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000512 ResultBuilder &Results) {
513 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000514 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
515 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000516}
517
518/// \brief Collect the results of searching for declarations within the given
519/// scope and its parent scopes.
520///
521/// \param S the scope in which we will start looking for declarations.
522///
523/// \param InitialRank the initial rank given to results in this scope.
524/// Larger rank values will be used for results found in parent scopes.
525///
Douglas Gregor456c4a12009-09-21 20:12:40 +0000526/// \param CurContext the context from which lookup results will be found.
527///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000528/// \param Results the builder object that will receive each result.
529static unsigned CollectLookupResults(Scope *S,
530 TranslationUnitDecl *TranslationUnit,
531 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000532 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000533 ResultBuilder &Results) {
534 if (!S)
535 return InitialRank;
536
537 // FIXME: Using directives!
538
539 unsigned NextRank = InitialRank;
540 Results.EnterNewScope();
541 if (S->getEntity() &&
542 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
543 // Look into this scope's declaration context, along with any of its
544 // parent lookup contexts (e.g., enclosing classes), up to the point
545 // where we hit the context stored in the next outer scope.
546 DeclContext *Ctx = (DeclContext *)S->getEntity();
547 DeclContext *OuterCtx = findOuterContext(S);
548
549 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
550 Ctx = Ctx->getLookupParent()) {
551 if (Ctx->isFunctionOrMethod())
552 continue;
553
Douglas Gregor456c4a12009-09-21 20:12:40 +0000554 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
555 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000556 }
557 } else if (!S->getParent()) {
558 // Look into the translation unit scope. We walk through the translation
559 // unit's declaration context, because the Scope itself won't have all of
560 // the declarations if we loaded a precompiled header.
561 // FIXME: We would like the translation unit's Scope object to point to the
562 // translation unit, so we don't need this special "if" branch. However,
563 // doing so would force the normal C++ name-lookup code to look into the
564 // translation unit decl when the IdentifierInfo chains would suffice.
565 // Once we fix that problem (which is part of a more general "don't look
566 // in DeclContexts unless we have to" optimization), we can eliminate the
567 // TranslationUnit parameter entirely.
568 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000569 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000570 } else {
571 // Walk through the declarations in this Scope.
572 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
573 D != DEnd; ++D) {
574 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
Douglas Gregor456c4a12009-09-21 20:12:40 +0000575 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
576 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000577 }
578
579 NextRank = NextRank + 1;
580 }
581
582 // Lookup names in the parent scope.
583 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000584 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000585 Results.ExitScope();
586
587 return NextRank;
588}
589
590/// \brief Add type specifiers for the current language as keyword results.
591static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
592 ResultBuilder &Results) {
593 typedef CodeCompleteConsumer::Result Result;
594 Results.MaybeAddResult(Result("short", Rank));
595 Results.MaybeAddResult(Result("long", Rank));
596 Results.MaybeAddResult(Result("signed", Rank));
597 Results.MaybeAddResult(Result("unsigned", Rank));
598 Results.MaybeAddResult(Result("void", Rank));
599 Results.MaybeAddResult(Result("char", Rank));
600 Results.MaybeAddResult(Result("int", Rank));
601 Results.MaybeAddResult(Result("float", Rank));
602 Results.MaybeAddResult(Result("double", Rank));
603 Results.MaybeAddResult(Result("enum", Rank));
604 Results.MaybeAddResult(Result("struct", Rank));
605 Results.MaybeAddResult(Result("union", Rank));
606
607 if (LangOpts.C99) {
608 // C99-specific
609 Results.MaybeAddResult(Result("_Complex", Rank));
610 Results.MaybeAddResult(Result("_Imaginary", Rank));
611 Results.MaybeAddResult(Result("_Bool", Rank));
612 }
613
614 if (LangOpts.CPlusPlus) {
615 // C++-specific
616 Results.MaybeAddResult(Result("bool", Rank));
617 Results.MaybeAddResult(Result("class", Rank));
618 Results.MaybeAddResult(Result("typename", Rank));
619 Results.MaybeAddResult(Result("wchar_t", Rank));
620
621 if (LangOpts.CPlusPlus0x) {
622 Results.MaybeAddResult(Result("char16_t", Rank));
623 Results.MaybeAddResult(Result("char32_t", Rank));
624 Results.MaybeAddResult(Result("decltype", Rank));
625 }
626 }
627
628 // GNU extensions
629 if (LangOpts.GNUMode) {
630 // FIXME: Enable when we actually support decimal floating point.
631 // Results.MaybeAddResult(Result("_Decimal32", Rank));
632 // Results.MaybeAddResult(Result("_Decimal64", Rank));
633 // Results.MaybeAddResult(Result("_Decimal128", Rank));
634 Results.MaybeAddResult(Result("typeof", Rank));
635 }
636}
637
638/// \brief Add function parameter chunks to the given code completion string.
639static void AddFunctionParameterChunks(ASTContext &Context,
640 FunctionDecl *Function,
641 CodeCompletionString *Result) {
642 CodeCompletionString *CCStr = Result;
643
644 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
645 ParmVarDecl *Param = Function->getParamDecl(P);
646
647 if (Param->hasDefaultArg()) {
648 // When we see an optional default argument, put that argument and
649 // the remaining default arguments into a new, optional string.
650 CodeCompletionString *Opt = new CodeCompletionString;
651 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
652 CCStr = Opt;
653 }
654
655 if (P != 0)
656 CCStr->AddTextChunk(", ");
657
658 // Format the placeholder string.
659 std::string PlaceholderStr;
660 if (Param->getIdentifier())
661 PlaceholderStr = Param->getIdentifier()->getName();
662
663 Param->getType().getAsStringInternal(PlaceholderStr,
664 Context.PrintingPolicy);
665
666 // Add the placeholder string.
667 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
668 }
Douglas Gregorb3d45252009-09-22 21:42:17 +0000669
670 if (const FunctionProtoType *Proto
671 = Function->getType()->getAs<FunctionProtoType>())
672 if (Proto->isVariadic())
673 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000674}
675
676/// \brief Add template parameter chunks to the given code completion string.
677static void AddTemplateParameterChunks(ASTContext &Context,
678 TemplateDecl *Template,
679 CodeCompletionString *Result,
680 unsigned MaxParameters = 0) {
681 CodeCompletionString *CCStr = Result;
682 bool FirstParameter = true;
683
684 TemplateParameterList *Params = Template->getTemplateParameters();
685 TemplateParameterList::iterator PEnd = Params->end();
686 if (MaxParameters)
687 PEnd = Params->begin() + MaxParameters;
688 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
689 bool HasDefaultArg = false;
690 std::string PlaceholderStr;
691 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
692 if (TTP->wasDeclaredWithTypename())
693 PlaceholderStr = "typename";
694 else
695 PlaceholderStr = "class";
696
697 if (TTP->getIdentifier()) {
698 PlaceholderStr += ' ';
699 PlaceholderStr += TTP->getIdentifier()->getName();
700 }
701
702 HasDefaultArg = TTP->hasDefaultArgument();
703 } else if (NonTypeTemplateParmDecl *NTTP
704 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
705 if (NTTP->getIdentifier())
706 PlaceholderStr = NTTP->getIdentifier()->getName();
707 NTTP->getType().getAsStringInternal(PlaceholderStr,
708 Context.PrintingPolicy);
709 HasDefaultArg = NTTP->hasDefaultArgument();
710 } else {
711 assert(isa<TemplateTemplateParmDecl>(*P));
712 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
713
714 // Since putting the template argument list into the placeholder would
715 // be very, very long, we just use an abbreviation.
716 PlaceholderStr = "template<...> class";
717 if (TTP->getIdentifier()) {
718 PlaceholderStr += ' ';
719 PlaceholderStr += TTP->getIdentifier()->getName();
720 }
721
722 HasDefaultArg = TTP->hasDefaultArgument();
723 }
724
725 if (HasDefaultArg) {
726 // When we see an optional default argument, put that argument and
727 // the remaining default arguments into a new, optional string.
728 CodeCompletionString *Opt = new CodeCompletionString;
729 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
730 CCStr = Opt;
731 }
732
733 if (FirstParameter)
734 FirstParameter = false;
735 else
736 CCStr->AddTextChunk(", ");
737
738 // Add the placeholder string.
739 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
740 }
741}
742
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000743/// \brief Add a qualifier to the given code-completion string, if the
744/// provided nested-name-specifier is non-NULL.
745void AddQualifierToCompletionString(CodeCompletionString *Result,
746 NestedNameSpecifier *Qualifier,
Douglas Gregor0563c262009-09-22 23:15:58 +0000747 bool QualifierIsInformative,
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000748 ASTContext &Context) {
749 if (!Qualifier)
750 return;
751
752 std::string PrintedNNS;
753 {
754 llvm::raw_string_ostream OS(PrintedNNS);
755 Qualifier->print(OS, Context.PrintingPolicy);
756 }
Douglas Gregor0563c262009-09-22 23:15:58 +0000757 if (QualifierIsInformative)
758 Result->AddInformativeChunk(PrintedNNS.c_str());
759 else
760 Result->AddTextChunk(PrintedNNS.c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000761}
762
Douglas Gregor86d9a522009-09-21 16:56:56 +0000763/// \brief If possible, create a new code completion string for the given
764/// result.
765///
766/// \returns Either a new, heap-allocated code completion string describing
767/// how to use this result, or NULL to indicate that the string or name of the
768/// result is all that is needed.
769CodeCompletionString *
770CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
771 if (Kind != RK_Declaration)
772 return 0;
773
774 NamedDecl *ND = Declaration;
775
776 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
777 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000778 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
779 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000780 Result->AddTextChunk(Function->getNameAsString().c_str());
781 Result->AddTextChunk("(");
782 AddFunctionParameterChunks(S.Context, Function, Result);
783 Result->AddTextChunk(")");
784 return Result;
785 }
786
787 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
788 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000789 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
790 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000791 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
792 Result->AddTextChunk(Function->getNameAsString().c_str());
793
794 // Figure out which template parameters are deduced (or have default
795 // arguments).
796 llvm::SmallVector<bool, 16> Deduced;
797 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
798 unsigned LastDeducibleArgument;
799 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
800 --LastDeducibleArgument) {
801 if (!Deduced[LastDeducibleArgument - 1]) {
802 // C++0x: Figure out if the template argument has a default. If so,
803 // the user doesn't need to type this argument.
804 // FIXME: We need to abstract template parameters better!
805 bool HasDefaultArg = false;
806 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
807 LastDeducibleArgument - 1);
808 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
809 HasDefaultArg = TTP->hasDefaultArgument();
810 else if (NonTypeTemplateParmDecl *NTTP
811 = dyn_cast<NonTypeTemplateParmDecl>(Param))
812 HasDefaultArg = NTTP->hasDefaultArgument();
813 else {
814 assert(isa<TemplateTemplateParmDecl>(Param));
815 HasDefaultArg
816 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
817 }
818
819 if (!HasDefaultArg)
820 break;
821 }
822 }
823
824 if (LastDeducibleArgument) {
825 // Some of the function template arguments cannot be deduced from a
826 // function call, so we introduce an explicit template argument list
827 // containing all of the arguments up to the first deducible argument.
828 Result->AddTextChunk("<");
829 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
830 LastDeducibleArgument);
831 Result->AddTextChunk(">");
832 }
833
834 // Add the function parameters
835 Result->AddTextChunk("(");
836 AddFunctionParameterChunks(S.Context, Function, Result);
837 Result->AddTextChunk(")");
838 return Result;
839 }
840
841 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
842 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000843 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
844 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000845 Result->AddTextChunk(Template->getNameAsString().c_str());
846 Result->AddTextChunk("<");
847 AddTemplateParameterChunks(S.Context, Template, Result);
848 Result->AddTextChunk(">");
849 return Result;
850 }
851
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000852 if (Qualifier) {
853 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000854 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
855 S.Context);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000856 Result->AddTextChunk(ND->getNameAsString().c_str());
857 return Result;
858 }
859
Douglas Gregor86d9a522009-09-21 16:56:56 +0000860 return 0;
861}
862
863namespace {
864 struct SortCodeCompleteResult {
865 typedef CodeCompleteConsumer::Result Result;
866
867 bool operator()(const Result &X, const Result &Y) const {
868 // Sort first by rank.
869 if (X.Rank < Y.Rank)
870 return true;
871 else if (X.Rank > Y.Rank)
872 return false;
873
874 // Result kinds are ordered by decreasing importance.
875 if (X.Kind < Y.Kind)
876 return true;
877 else if (X.Kind > Y.Kind)
878 return false;
879
880 // Non-hidden names precede hidden names.
881 if (X.Hidden != Y.Hidden)
882 return !X.Hidden;
883
884 // Ordering depends on the kind of result.
885 switch (X.Kind) {
886 case Result::RK_Declaration:
887 // Order based on the declaration names.
888 return X.Declaration->getDeclName() < Y.Declaration->getDeclName();
889
890 case Result::RK_Keyword:
891 return strcmp(X.Keyword, Y.Keyword) == -1;
892 }
893
894 // Silence GCC warning.
895 return false;
896 }
897 };
898}
899
900static void HandleCodeCompleteResults(CodeCompleteConsumer *CodeCompleter,
901 CodeCompleteConsumer::Result *Results,
902 unsigned NumResults) {
903 // Sort the results by rank/kind/etc.
904 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
905
906 if (CodeCompleter)
907 CodeCompleter->ProcessCodeCompleteResults(Results, NumResults);
908}
909
Douglas Gregor791215b2009-09-21 20:51:25 +0000910void Sema::CodeCompleteOrdinaryName(Scope *S) {
911 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
912 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
913 Results);
914 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
915}
916
Douglas Gregor81b747b2009-09-17 21:32:03 +0000917void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
918 SourceLocation OpLoc,
919 bool IsArrow) {
920 if (!BaseE || !CodeCompleter)
921 return;
922
Douglas Gregor86d9a522009-09-21 16:56:56 +0000923 typedef CodeCompleteConsumer::Result Result;
924
Douglas Gregor81b747b2009-09-17 21:32:03 +0000925 Expr *Base = static_cast<Expr *>(BaseE);
926 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000927
928 if (IsArrow) {
929 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
930 BaseType = Ptr->getPointeeType();
931 else if (BaseType->isObjCObjectPointerType())
932 /*Do nothing*/ ;
933 else
934 return;
935 }
936
937 ResultBuilder Results(*this);
938 unsigned NextRank = 0;
939
940 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor456c4a12009-09-21 20:12:40 +0000941 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
942 Record->getDecl(), Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000943
944 if (getLangOptions().CPlusPlus) {
945 if (!Results.empty()) {
946 // The "template" keyword can follow "->" or "." in the grammar.
947 // However, we only want to suggest the template keyword if something
948 // is dependent.
949 bool IsDependent = BaseType->isDependentType();
950 if (!IsDependent) {
951 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
952 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
953 IsDependent = Ctx->isDependentContext();
954 break;
955 }
956 }
957
958 if (IsDependent)
959 Results.MaybeAddResult(Result("template", NextRank++));
960 }
961
962 // We could have the start of a nested-name-specifier. Add those
963 // results as well.
964 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
965 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000966 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000967 }
968
969 // Hand off the results found for code completion.
970 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
971
972 // We're done!
973 return;
974 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000975}
976
Douglas Gregor374929f2009-09-18 15:37:17 +0000977void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
978 if (!CodeCompleter)
979 return;
980
Douglas Gregor86d9a522009-09-21 16:56:56 +0000981 typedef CodeCompleteConsumer::Result Result;
982 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +0000983 switch ((DeclSpec::TST)TagSpec) {
984 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +0000985 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +0000986 break;
987
988 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +0000989 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +0000990 break;
991
992 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +0000993 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +0000994 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +0000995 break;
996
997 default:
998 assert(false && "Unknown type specifier kind in CodeCompleteTag");
999 return;
1000 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001001
1002 ResultBuilder Results(*this, Filter);
1003 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001004 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001005
1006 if (getLangOptions().CPlusPlus) {
1007 // We could have the start of a nested-name-specifier. Add those
1008 // results as well.
1009 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1010 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +00001011 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001012 }
1013
1014 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00001015}
1016
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001017void Sema::CodeCompleteCase(Scope *S) {
1018 if (getSwitchStack().empty() || !CodeCompleter)
1019 return;
1020
1021 SwitchStmt *Switch = getSwitchStack().back();
1022 if (!Switch->getCond()->getType()->isEnumeralType())
1023 return;
1024
1025 // Code-complete the cases of a switch statement over an enumeration type
1026 // by providing the list of
1027 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1028
1029 // Determine which enumerators we have already seen in the switch statement.
1030 // FIXME: Ideally, we would also be able to look *past* the code-completion
1031 // token, in case we are code-completing in the middle of the switch and not
1032 // at the end. However, we aren't able to do so at the moment.
1033 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001034 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001035 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1036 SC = SC->getNextSwitchCase()) {
1037 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1038 if (!Case)
1039 continue;
1040
1041 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1042 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1043 if (EnumConstantDecl *Enumerator
1044 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1045 // We look into the AST of the case statement to determine which
1046 // enumerator was named. Alternatively, we could compute the value of
1047 // the integral constant expression, then compare it against the
1048 // values of each enumerator. However, value-based approach would not
1049 // work as well with C++ templates where enumerators declared within a
1050 // template are type- and value-dependent.
1051 EnumeratorsSeen.insert(Enumerator);
1052
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001053 // If this is a qualified-id, keep track of the nested-name-specifier
1054 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001055 //
1056 // switch (TagD.getKind()) {
1057 // case TagDecl::TK_enum:
1058 // break;
1059 // case XXX
1060 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001061 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001062 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1063 // TK_struct, and TK_class.
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001064 if (QualifiedDeclRefExpr *QDRE = dyn_cast<QualifiedDeclRefExpr>(DRE))
1065 Qualifier = QDRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001066 }
1067 }
1068
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001069 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1070 // If there are no prior enumerators in C++, check whether we have to
1071 // qualify the names of the enumerators that we suggest, because they
1072 // may not be visible in this scope.
1073 Qualifier = getRequiredQualification(Context, CurContext,
1074 Enum->getDeclContext());
1075
1076 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1077 }
1078
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001079 // Add any enumerators that have not yet been mentioned.
1080 ResultBuilder Results(*this);
1081 Results.EnterNewScope();
1082 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1083 EEnd = Enum->enumerator_end();
1084 E != EEnd; ++E) {
1085 if (EnumeratorsSeen.count(*E))
1086 continue;
1087
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001088 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001089 }
1090 Results.ExitScope();
1091
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001092 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1093}
1094
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001095namespace {
1096 struct IsBetterOverloadCandidate {
1097 Sema &S;
1098
1099 public:
1100 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1101
1102 bool
1103 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1104 return S.isBetterOverloadCandidate(X, Y);
1105 }
1106 };
1107}
1108
1109void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1110 ExprTy **ArgsIn, unsigned NumArgs) {
1111 if (!CodeCompleter)
1112 return;
1113
1114 Expr *Fn = (Expr *)FnIn;
1115 Expr **Args = (Expr **)ArgsIn;
1116
1117 // Ignore type-dependent call expressions entirely.
1118 if (Fn->isTypeDependent() ||
1119 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1120 return;
1121
1122 NamedDecl *Function;
1123 DeclarationName UnqualifiedName;
1124 NestedNameSpecifier *Qualifier;
1125 SourceRange QualifierRange;
1126 bool ArgumentDependentLookup;
1127 bool HasExplicitTemplateArgs;
1128 const TemplateArgument *ExplicitTemplateArgs;
1129 unsigned NumExplicitTemplateArgs;
1130
1131 DeconstructCallFunction(Fn,
1132 Function, UnqualifiedName, Qualifier, QualifierRange,
1133 ArgumentDependentLookup, HasExplicitTemplateArgs,
1134 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1135
1136
1137 // FIXME: What if we're calling something that isn't a function declaration?
1138 // FIXME: What if we're calling a pseudo-destructor?
1139 // FIXME: What if we're calling a member function?
1140
1141 // Build an overload candidate set based on the functions we find.
1142 OverloadCandidateSet CandidateSet;
1143 AddOverloadedCallCandidates(Function, UnqualifiedName,
1144 ArgumentDependentLookup, HasExplicitTemplateArgs,
1145 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1146 Args, NumArgs,
1147 CandidateSet,
1148 /*PartialOverloading=*/true);
1149
1150 // Sort the overload candidate set by placing the best overloads first.
1151 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1152 IsBetterOverloadCandidate(*this));
1153
1154 // Add the remaining viable overload candidates as code-completion reslults.
1155 typedef CodeCompleteConsumer::Result Result;
1156 ResultBuilder Results(*this);
Anders Carlsson90756302009-09-22 17:29:51 +00001157 Results.EnterNewScope();
1158
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001159 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1160 CandEnd = CandidateSet.end();
1161 Cand != CandEnd; ++Cand) {
1162 if (Cand->Viable)
1163 Results.MaybeAddResult(Result(Cand->Function, 0), 0);
1164 }
1165
Anders Carlsson90756302009-09-22 17:29:51 +00001166 Results.ExitScope();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001167 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1168}
1169
Douglas Gregor81b747b2009-09-17 21:32:03 +00001170void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1171 bool EnteringContext) {
1172 if (!SS.getScopeRep() || !CodeCompleter)
1173 return;
1174
Douglas Gregor86d9a522009-09-21 16:56:56 +00001175 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1176 if (!Ctx)
1177 return;
1178
1179 ResultBuilder Results(*this);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001180 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001181
1182 // The "template" keyword can follow "::" in the grammar, but only
1183 // put it into the grammar if the nested-name-specifier is dependent.
1184 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1185 if (!Results.empty() && NNS->isDependent())
1186 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1187
1188 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001189}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001190
1191void Sema::CodeCompleteUsing(Scope *S) {
1192 if (!CodeCompleter)
1193 return;
1194
Douglas Gregor86d9a522009-09-21 16:56:56 +00001195 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
1196
1197 // If we aren't in class scope, we could see the "namespace" keyword.
1198 if (!S->isClassScope())
1199 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1200
1201 // After "using", we can see anything that would start a
1202 // nested-name-specifier.
Douglas Gregor456c4a12009-09-21 20:12:40 +00001203 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0,
1204 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001205
1206 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001207}
1208
1209void Sema::CodeCompleteUsingDirective(Scope *S) {
1210 if (!CodeCompleter)
1211 return;
1212
Douglas Gregor86d9a522009-09-21 16:56:56 +00001213 // After "using namespace", we expect to see a namespace name or namespace
1214 // alias.
1215 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001216 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1217 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001218 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001219}
1220
1221void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1222 if (!CodeCompleter)
1223 return;
1224
Douglas Gregor86d9a522009-09-21 16:56:56 +00001225 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1226 DeclContext *Ctx = (DeclContext *)S->getEntity();
1227 if (!S->getParent())
1228 Ctx = Context.getTranslationUnitDecl();
1229
1230 if (Ctx && Ctx->isFileContext()) {
1231 // We only want to see those namespaces that have already been defined
1232 // within this scope, because its likely that the user is creating an
1233 // extended namespace declaration. Keep track of the most recent
1234 // definition of each namespace.
1235 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1236 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1237 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1238 NS != NSEnd; ++NS)
1239 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1240
1241 // Add the most recent definition (or extended definition) of each
1242 // namespace to the list of results.
1243 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1244 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1245 NS != NSEnd; ++NS)
Douglas Gregor456c4a12009-09-21 20:12:40 +00001246 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1247 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001248 }
1249
1250 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001251}
1252
1253void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1254 if (!CodeCompleter)
1255 return;
1256
Douglas Gregor86d9a522009-09-21 16:56:56 +00001257 // After "namespace", we expect to see a namespace or alias.
1258 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001259 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1260 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001261 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001262}
1263
Douglas Gregored8d3222009-09-18 20:05:18 +00001264void Sema::CodeCompleteOperatorName(Scope *S) {
1265 if (!CodeCompleter)
1266 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001267
1268 typedef CodeCompleteConsumer::Result Result;
1269 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregored8d3222009-09-18 20:05:18 +00001270
Douglas Gregor86d9a522009-09-21 16:56:56 +00001271 // Add the names of overloadable operators.
1272#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1273 if (std::strcmp(Spelling, "?")) \
1274 Results.MaybeAddResult(Result(Spelling, 0));
1275#include "clang/Basic/OperatorKinds.def"
1276
1277 // Add any type names visible from the current scope
1278 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001279 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001280
1281 // Add any type specifiers
1282 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1283
1284 // Add any nested-name-specifiers
1285 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1286 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +00001287 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001288
1289 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00001290}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001291