blob: b19fda216d5c272c5d7ccba30fcb94d4501176eb [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 Gregor456c4a12009-09-21 20:12:40 +0000200 return 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 Gregor456c4a12009-09-21 20:12:40 +0000284
285 if (!R.Qualifier)
286 R.Qualifier = getRequiredQualification(SemaRef.Context,
287 CurContext,
288 R.Declaration->getDeclContext());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000289 } else {
290 // This result was hidden and cannot be found; don't bother adding
291 // it.
292 return;
293 }
294
295 break;
296 }
297 }
298
299 // Make sure that any given declaration only shows up in the result set once.
300 if (!AllDeclsFound.insert(CanonDecl))
301 return;
302
303 // Insert this result into the set of results and into the current shadow
304 // map.
305 SMap.insert(std::make_pair(R.Declaration->getDeclName(),
306 std::make_pair(R.Declaration, Results.size())));
307 Results.push_back(R);
308}
309
310/// \brief Enter into a new scope.
311void ResultBuilder::EnterNewScope() {
312 ShadowMaps.push_back(ShadowMap());
313}
314
315/// \brief Exit from the current scope.
316void ResultBuilder::ExitScope() {
317 ShadowMaps.pop_back();
318}
319
Douglas Gregor791215b2009-09-21 20:51:25 +0000320/// \brief Determines whether this given declaration will be found by
321/// ordinary name lookup.
322bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
323 unsigned IDNS = Decl::IDNS_Ordinary;
324 if (SemaRef.getLangOptions().CPlusPlus)
325 IDNS |= Decl::IDNS_Tag;
326
327 return ND->getIdentifierNamespace() & IDNS;
328}
329
Douglas Gregor86d9a522009-09-21 16:56:56 +0000330/// \brief Determines whether the given declaration is suitable as the
331/// start of a C++ nested-name-specifier, e.g., a class or namespace.
332bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
333 // Allow us to find class templates, too.
334 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
335 ND = ClassTemplate->getTemplatedDecl();
336
337 return SemaRef.isAcceptableNestedNameSpecifier(ND);
338}
339
340/// \brief Determines whether the given declaration is an enumeration.
341bool ResultBuilder::IsEnum(NamedDecl *ND) const {
342 return isa<EnumDecl>(ND);
343}
344
345/// \brief Determines whether the given declaration is a class or struct.
346bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
347 // Allow us to find class templates, too.
348 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
349 ND = ClassTemplate->getTemplatedDecl();
350
351 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
352 return RD->getTagKind() == TagDecl::TK_class ||
353 RD->getTagKind() == TagDecl::TK_struct;
354
355 return false;
356}
357
358/// \brief Determines whether the given declaration is a union.
359bool ResultBuilder::IsUnion(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_union;
366
367 return false;
368}
369
370/// \brief Determines whether the given declaration is a namespace.
371bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
372 return isa<NamespaceDecl>(ND);
373}
374
375/// \brief Determines whether the given declaration is a namespace or
376/// namespace alias.
377bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
378 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
379}
380
381/// \brief Brief determines whether the given declaration is a namespace or
382/// namespace alias.
383bool ResultBuilder::IsType(NamedDecl *ND) const {
384 return isa<TypeDecl>(ND);
385}
386
387// Find the next outer declaration context corresponding to this scope.
388static DeclContext *findOuterContext(Scope *S) {
389 for (S = S->getParent(); S; S = S->getParent())
390 if (S->getEntity())
391 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
392
393 return 0;
394}
395
396/// \brief Collect the results of searching for members within the given
397/// declaration context.
398///
399/// \param Ctx the declaration context from which we will gather results.
400///
401/// \param InitialRank the initial rank given to results in this declaration
402/// context. Larger rank values will be used for, e.g., members found in
403/// base classes.
404///
405/// \param Visited the set of declaration contexts that have already been
406/// visited. Declaration contexts will only be visited once.
407///
408/// \param Results the result set that will be extended with any results
409/// found within this declaration context (and, for a C++ class, its bases).
410///
411/// \returns the next higher rank value, after considering all of the
412/// names within this declaration context.
413static unsigned CollectMemberLookupResults(DeclContext *Ctx,
414 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000415 DeclContext *CurContext,
416 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000417 ResultBuilder &Results) {
418 // Make sure we don't visit the same context twice.
419 if (!Visited.insert(Ctx->getPrimaryContext()))
420 return InitialRank;
421
422 // Enumerate all of the results in this context.
423 Results.EnterNewScope();
424 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
425 CurCtx = CurCtx->getNextContext()) {
426 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
427 DEnd = CurCtx->decls_end();
428 D != DEnd; ++D) {
429 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor456c4a12009-09-21 20:12:40 +0000430 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, InitialRank),
431 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000432 }
433 }
434
435 // Traverse the contexts of inherited classes.
436 unsigned NextRank = InitialRank;
437 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
438 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
439 BEnd = Record->bases_end();
440 B != BEnd; ++B) {
441 QualType BaseType = B->getType();
442
443 // Don't look into dependent bases, because name lookup can't look
444 // there anyway.
445 if (BaseType->isDependentType())
446 continue;
447
448 const RecordType *Record = BaseType->getAs<RecordType>();
449 if (!Record)
450 continue;
451
452 // FIXME: It would be nice to be able to determine whether referencing
453 // a particular member would be ambiguous. For example, given
454 //
455 // struct A { int member; };
456 // struct B { int member; };
457 // struct C : A, B { };
458 //
459 // void f(C *c) { c->### }
460 // accessing 'member' would result in an ambiguity. However, code
461 // completion could be smart enough to qualify the member with the
462 // base class, e.g.,
463 //
464 // c->B::member
465 //
466 // or
467 //
468 // c->A::member
469
470 // Collect results from this base class (and its bases).
471 NextRank = std::max(NextRank,
472 CollectMemberLookupResults(Record->getDecl(),
473 InitialRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000474 CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000475 Visited,
476 Results));
477 }
478 }
479
480 // FIXME: Look into base classes in Objective-C!
481
482 Results.ExitScope();
483 return NextRank;
484}
485
486/// \brief Collect the results of searching for members within the given
487/// declaration context.
488///
489/// \param Ctx the declaration context from which we will gather results.
490///
491/// \param InitialRank the initial rank given to results in this declaration
492/// context. Larger rank values will be used for, e.g., members found in
493/// base classes.
494///
495/// \param Results the result set that will be extended with any results
496/// found within this declaration context (and, for a C++ class, its bases).
497///
498/// \returns the next higher rank value, after considering all of the
499/// names within this declaration context.
500static unsigned CollectMemberLookupResults(DeclContext *Ctx,
501 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000502 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000503 ResultBuilder &Results) {
504 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000505 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
506 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000507}
508
509/// \brief Collect the results of searching for declarations within the given
510/// scope and its parent scopes.
511///
512/// \param S the scope in which we will start looking for declarations.
513///
514/// \param InitialRank the initial rank given to results in this scope.
515/// Larger rank values will be used for results found in parent scopes.
516///
Douglas Gregor456c4a12009-09-21 20:12:40 +0000517/// \param CurContext the context from which lookup results will be found.
518///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000519/// \param Results the builder object that will receive each result.
520static unsigned CollectLookupResults(Scope *S,
521 TranslationUnitDecl *TranslationUnit,
522 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000523 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000524 ResultBuilder &Results) {
525 if (!S)
526 return InitialRank;
527
528 // FIXME: Using directives!
529
530 unsigned NextRank = InitialRank;
531 Results.EnterNewScope();
532 if (S->getEntity() &&
533 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
534 // Look into this scope's declaration context, along with any of its
535 // parent lookup contexts (e.g., enclosing classes), up to the point
536 // where we hit the context stored in the next outer scope.
537 DeclContext *Ctx = (DeclContext *)S->getEntity();
538 DeclContext *OuterCtx = findOuterContext(S);
539
540 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
541 Ctx = Ctx->getLookupParent()) {
542 if (Ctx->isFunctionOrMethod())
543 continue;
544
Douglas Gregor456c4a12009-09-21 20:12:40 +0000545 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
546 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000547 }
548 } else if (!S->getParent()) {
549 // Look into the translation unit scope. We walk through the translation
550 // unit's declaration context, because the Scope itself won't have all of
551 // the declarations if we loaded a precompiled header.
552 // FIXME: We would like the translation unit's Scope object to point to the
553 // translation unit, so we don't need this special "if" branch. However,
554 // doing so would force the normal C++ name-lookup code to look into the
555 // translation unit decl when the IdentifierInfo chains would suffice.
556 // Once we fix that problem (which is part of a more general "don't look
557 // in DeclContexts unless we have to" optimization), we can eliminate the
558 // TranslationUnit parameter entirely.
559 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000560 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000561 } else {
562 // Walk through the declarations in this Scope.
563 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
564 D != DEnd; ++D) {
565 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
Douglas Gregor456c4a12009-09-21 20:12:40 +0000566 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
567 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000568 }
569
570 NextRank = NextRank + 1;
571 }
572
573 // Lookup names in the parent scope.
574 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000575 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000576 Results.ExitScope();
577
578 return NextRank;
579}
580
581/// \brief Add type specifiers for the current language as keyword results.
582static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
583 ResultBuilder &Results) {
584 typedef CodeCompleteConsumer::Result Result;
585 Results.MaybeAddResult(Result("short", Rank));
586 Results.MaybeAddResult(Result("long", Rank));
587 Results.MaybeAddResult(Result("signed", Rank));
588 Results.MaybeAddResult(Result("unsigned", Rank));
589 Results.MaybeAddResult(Result("void", Rank));
590 Results.MaybeAddResult(Result("char", Rank));
591 Results.MaybeAddResult(Result("int", Rank));
592 Results.MaybeAddResult(Result("float", Rank));
593 Results.MaybeAddResult(Result("double", Rank));
594 Results.MaybeAddResult(Result("enum", Rank));
595 Results.MaybeAddResult(Result("struct", Rank));
596 Results.MaybeAddResult(Result("union", Rank));
597
598 if (LangOpts.C99) {
599 // C99-specific
600 Results.MaybeAddResult(Result("_Complex", Rank));
601 Results.MaybeAddResult(Result("_Imaginary", Rank));
602 Results.MaybeAddResult(Result("_Bool", Rank));
603 }
604
605 if (LangOpts.CPlusPlus) {
606 // C++-specific
607 Results.MaybeAddResult(Result("bool", Rank));
608 Results.MaybeAddResult(Result("class", Rank));
609 Results.MaybeAddResult(Result("typename", Rank));
610 Results.MaybeAddResult(Result("wchar_t", Rank));
611
612 if (LangOpts.CPlusPlus0x) {
613 Results.MaybeAddResult(Result("char16_t", Rank));
614 Results.MaybeAddResult(Result("char32_t", Rank));
615 Results.MaybeAddResult(Result("decltype", Rank));
616 }
617 }
618
619 // GNU extensions
620 if (LangOpts.GNUMode) {
621 // FIXME: Enable when we actually support decimal floating point.
622 // Results.MaybeAddResult(Result("_Decimal32", Rank));
623 // Results.MaybeAddResult(Result("_Decimal64", Rank));
624 // Results.MaybeAddResult(Result("_Decimal128", Rank));
625 Results.MaybeAddResult(Result("typeof", Rank));
626 }
627}
628
629/// \brief Add function parameter chunks to the given code completion string.
630static void AddFunctionParameterChunks(ASTContext &Context,
631 FunctionDecl *Function,
632 CodeCompletionString *Result) {
633 CodeCompletionString *CCStr = Result;
634
635 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
636 ParmVarDecl *Param = Function->getParamDecl(P);
637
638 if (Param->hasDefaultArg()) {
639 // When we see an optional default argument, put that argument and
640 // the remaining default arguments into a new, optional string.
641 CodeCompletionString *Opt = new CodeCompletionString;
642 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
643 CCStr = Opt;
644 }
645
646 if (P != 0)
647 CCStr->AddTextChunk(", ");
648
649 // Format the placeholder string.
650 std::string PlaceholderStr;
651 if (Param->getIdentifier())
652 PlaceholderStr = Param->getIdentifier()->getName();
653
654 Param->getType().getAsStringInternal(PlaceholderStr,
655 Context.PrintingPolicy);
656
657 // Add the placeholder string.
658 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
659 }
Douglas Gregorb3d45252009-09-22 21:42:17 +0000660
661 if (const FunctionProtoType *Proto
662 = Function->getType()->getAs<FunctionProtoType>())
663 if (Proto->isVariadic())
664 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000665}
666
667/// \brief Add template parameter chunks to the given code completion string.
668static void AddTemplateParameterChunks(ASTContext &Context,
669 TemplateDecl *Template,
670 CodeCompletionString *Result,
671 unsigned MaxParameters = 0) {
672 CodeCompletionString *CCStr = Result;
673 bool FirstParameter = true;
674
675 TemplateParameterList *Params = Template->getTemplateParameters();
676 TemplateParameterList::iterator PEnd = Params->end();
677 if (MaxParameters)
678 PEnd = Params->begin() + MaxParameters;
679 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
680 bool HasDefaultArg = false;
681 std::string PlaceholderStr;
682 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
683 if (TTP->wasDeclaredWithTypename())
684 PlaceholderStr = "typename";
685 else
686 PlaceholderStr = "class";
687
688 if (TTP->getIdentifier()) {
689 PlaceholderStr += ' ';
690 PlaceholderStr += TTP->getIdentifier()->getName();
691 }
692
693 HasDefaultArg = TTP->hasDefaultArgument();
694 } else if (NonTypeTemplateParmDecl *NTTP
695 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
696 if (NTTP->getIdentifier())
697 PlaceholderStr = NTTP->getIdentifier()->getName();
698 NTTP->getType().getAsStringInternal(PlaceholderStr,
699 Context.PrintingPolicy);
700 HasDefaultArg = NTTP->hasDefaultArgument();
701 } else {
702 assert(isa<TemplateTemplateParmDecl>(*P));
703 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
704
705 // Since putting the template argument list into the placeholder would
706 // be very, very long, we just use an abbreviation.
707 PlaceholderStr = "template<...> class";
708 if (TTP->getIdentifier()) {
709 PlaceholderStr += ' ';
710 PlaceholderStr += TTP->getIdentifier()->getName();
711 }
712
713 HasDefaultArg = TTP->hasDefaultArgument();
714 }
715
716 if (HasDefaultArg) {
717 // When we see an optional default argument, put that argument and
718 // the remaining default arguments into a new, optional string.
719 CodeCompletionString *Opt = new CodeCompletionString;
720 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
721 CCStr = Opt;
722 }
723
724 if (FirstParameter)
725 FirstParameter = false;
726 else
727 CCStr->AddTextChunk(", ");
728
729 // Add the placeholder string.
730 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
731 }
732}
733
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000734/// \brief Add a qualifier to the given code-completion string, if the
735/// provided nested-name-specifier is non-NULL.
736void AddQualifierToCompletionString(CodeCompletionString *Result,
737 NestedNameSpecifier *Qualifier,
738 ASTContext &Context) {
739 if (!Qualifier)
740 return;
741
742 std::string PrintedNNS;
743 {
744 llvm::raw_string_ostream OS(PrintedNNS);
745 Qualifier->print(OS, Context.PrintingPolicy);
746 }
747 Result->AddTextChunk(PrintedNNS.c_str());
748}
749
Douglas Gregor86d9a522009-09-21 16:56:56 +0000750/// \brief If possible, create a new code completion string for the given
751/// result.
752///
753/// \returns Either a new, heap-allocated code completion string describing
754/// how to use this result, or NULL to indicate that the string or name of the
755/// result is all that is needed.
756CodeCompletionString *
757CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
758 if (Kind != RK_Declaration)
759 return 0;
760
761 NamedDecl *ND = Declaration;
762
763 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
764 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000765 AddQualifierToCompletionString(Result, Qualifier, S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000766 Result->AddTextChunk(Function->getNameAsString().c_str());
767 Result->AddTextChunk("(");
768 AddFunctionParameterChunks(S.Context, Function, Result);
769 Result->AddTextChunk(")");
770 return Result;
771 }
772
773 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
774 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000775 AddQualifierToCompletionString(Result, Qualifier, S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000776 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
777 Result->AddTextChunk(Function->getNameAsString().c_str());
778
779 // Figure out which template parameters are deduced (or have default
780 // arguments).
781 llvm::SmallVector<bool, 16> Deduced;
782 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
783 unsigned LastDeducibleArgument;
784 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
785 --LastDeducibleArgument) {
786 if (!Deduced[LastDeducibleArgument - 1]) {
787 // C++0x: Figure out if the template argument has a default. If so,
788 // the user doesn't need to type this argument.
789 // FIXME: We need to abstract template parameters better!
790 bool HasDefaultArg = false;
791 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
792 LastDeducibleArgument - 1);
793 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
794 HasDefaultArg = TTP->hasDefaultArgument();
795 else if (NonTypeTemplateParmDecl *NTTP
796 = dyn_cast<NonTypeTemplateParmDecl>(Param))
797 HasDefaultArg = NTTP->hasDefaultArgument();
798 else {
799 assert(isa<TemplateTemplateParmDecl>(Param));
800 HasDefaultArg
801 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
802 }
803
804 if (!HasDefaultArg)
805 break;
806 }
807 }
808
809 if (LastDeducibleArgument) {
810 // Some of the function template arguments cannot be deduced from a
811 // function call, so we introduce an explicit template argument list
812 // containing all of the arguments up to the first deducible argument.
813 Result->AddTextChunk("<");
814 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
815 LastDeducibleArgument);
816 Result->AddTextChunk(">");
817 }
818
819 // Add the function parameters
820 Result->AddTextChunk("(");
821 AddFunctionParameterChunks(S.Context, Function, Result);
822 Result->AddTextChunk(")");
823 return Result;
824 }
825
826 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
827 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000828 AddQualifierToCompletionString(Result, Qualifier, S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000829 Result->AddTextChunk(Template->getNameAsString().c_str());
830 Result->AddTextChunk("<");
831 AddTemplateParameterChunks(S.Context, Template, Result);
832 Result->AddTextChunk(">");
833 return Result;
834 }
835
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000836 if (Qualifier) {
837 CodeCompletionString *Result = new CodeCompletionString;
838 AddQualifierToCompletionString(Result, Qualifier, S.Context);
839 Result->AddTextChunk(ND->getNameAsString().c_str());
840 return Result;
841 }
842
Douglas Gregor86d9a522009-09-21 16:56:56 +0000843 return 0;
844}
845
846namespace {
847 struct SortCodeCompleteResult {
848 typedef CodeCompleteConsumer::Result Result;
849
850 bool operator()(const Result &X, const Result &Y) const {
851 // Sort first by rank.
852 if (X.Rank < Y.Rank)
853 return true;
854 else if (X.Rank > Y.Rank)
855 return false;
856
857 // Result kinds are ordered by decreasing importance.
858 if (X.Kind < Y.Kind)
859 return true;
860 else if (X.Kind > Y.Kind)
861 return false;
862
863 // Non-hidden names precede hidden names.
864 if (X.Hidden != Y.Hidden)
865 return !X.Hidden;
866
867 // Ordering depends on the kind of result.
868 switch (X.Kind) {
869 case Result::RK_Declaration:
870 // Order based on the declaration names.
871 return X.Declaration->getDeclName() < Y.Declaration->getDeclName();
872
873 case Result::RK_Keyword:
874 return strcmp(X.Keyword, Y.Keyword) == -1;
875 }
876
877 // Silence GCC warning.
878 return false;
879 }
880 };
881}
882
883static void HandleCodeCompleteResults(CodeCompleteConsumer *CodeCompleter,
884 CodeCompleteConsumer::Result *Results,
885 unsigned NumResults) {
886 // Sort the results by rank/kind/etc.
887 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
888
889 if (CodeCompleter)
890 CodeCompleter->ProcessCodeCompleteResults(Results, NumResults);
891}
892
Douglas Gregor791215b2009-09-21 20:51:25 +0000893void Sema::CodeCompleteOrdinaryName(Scope *S) {
894 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
895 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
896 Results);
897 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
898}
899
Douglas Gregor81b747b2009-09-17 21:32:03 +0000900void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
901 SourceLocation OpLoc,
902 bool IsArrow) {
903 if (!BaseE || !CodeCompleter)
904 return;
905
Douglas Gregor86d9a522009-09-21 16:56:56 +0000906 typedef CodeCompleteConsumer::Result Result;
907
Douglas Gregor81b747b2009-09-17 21:32:03 +0000908 Expr *Base = static_cast<Expr *>(BaseE);
909 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000910
911 if (IsArrow) {
912 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
913 BaseType = Ptr->getPointeeType();
914 else if (BaseType->isObjCObjectPointerType())
915 /*Do nothing*/ ;
916 else
917 return;
918 }
919
920 ResultBuilder Results(*this);
921 unsigned NextRank = 0;
922
923 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor456c4a12009-09-21 20:12:40 +0000924 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
925 Record->getDecl(), Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000926
927 if (getLangOptions().CPlusPlus) {
928 if (!Results.empty()) {
929 // The "template" keyword can follow "->" or "." in the grammar.
930 // However, we only want to suggest the template keyword if something
931 // is dependent.
932 bool IsDependent = BaseType->isDependentType();
933 if (!IsDependent) {
934 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
935 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
936 IsDependent = Ctx->isDependentContext();
937 break;
938 }
939 }
940
941 if (IsDependent)
942 Results.MaybeAddResult(Result("template", NextRank++));
943 }
944
945 // We could have the start of a nested-name-specifier. Add those
946 // results as well.
947 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
948 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000949 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000950 }
951
952 // Hand off the results found for code completion.
953 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
954
955 // We're done!
956 return;
957 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000958}
959
Douglas Gregor374929f2009-09-18 15:37:17 +0000960void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
961 if (!CodeCompleter)
962 return;
963
Douglas Gregor86d9a522009-09-21 16:56:56 +0000964 typedef CodeCompleteConsumer::Result Result;
965 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +0000966 switch ((DeclSpec::TST)TagSpec) {
967 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +0000968 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +0000969 break;
970
971 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +0000972 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +0000973 break;
974
975 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +0000976 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +0000977 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +0000978 break;
979
980 default:
981 assert(false && "Unknown type specifier kind in CodeCompleteTag");
982 return;
983 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000984
985 ResultBuilder Results(*this, Filter);
986 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +0000987 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000988
989 if (getLangOptions().CPlusPlus) {
990 // We could have the start of a nested-name-specifier. Add those
991 // results as well.
992 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
993 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000994 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000995 }
996
997 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +0000998}
999
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001000void Sema::CodeCompleteCase(Scope *S) {
1001 if (getSwitchStack().empty() || !CodeCompleter)
1002 return;
1003
1004 SwitchStmt *Switch = getSwitchStack().back();
1005 if (!Switch->getCond()->getType()->isEnumeralType())
1006 return;
1007
1008 // Code-complete the cases of a switch statement over an enumeration type
1009 // by providing the list of
1010 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1011
1012 // Determine which enumerators we have already seen in the switch statement.
1013 // FIXME: Ideally, we would also be able to look *past* the code-completion
1014 // token, in case we are code-completing in the middle of the switch and not
1015 // at the end. However, we aren't able to do so at the moment.
1016 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001017 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001018 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1019 SC = SC->getNextSwitchCase()) {
1020 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1021 if (!Case)
1022 continue;
1023
1024 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1025 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1026 if (EnumConstantDecl *Enumerator
1027 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1028 // We look into the AST of the case statement to determine which
1029 // enumerator was named. Alternatively, we could compute the value of
1030 // the integral constant expression, then compare it against the
1031 // values of each enumerator. However, value-based approach would not
1032 // work as well with C++ templates where enumerators declared within a
1033 // template are type- and value-dependent.
1034 EnumeratorsSeen.insert(Enumerator);
1035
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001036 // If this is a qualified-id, keep track of the nested-name-specifier
1037 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001038 //
1039 // switch (TagD.getKind()) {
1040 // case TagDecl::TK_enum:
1041 // break;
1042 // case XXX
1043 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001044 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001045 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1046 // TK_struct, and TK_class.
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001047 if (QualifiedDeclRefExpr *QDRE = dyn_cast<QualifiedDeclRefExpr>(DRE))
1048 Qualifier = QDRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001049 }
1050 }
1051
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001052 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1053 // If there are no prior enumerators in C++, check whether we have to
1054 // qualify the names of the enumerators that we suggest, because they
1055 // may not be visible in this scope.
1056 Qualifier = getRequiredQualification(Context, CurContext,
1057 Enum->getDeclContext());
1058
1059 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1060 }
1061
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001062 // Add any enumerators that have not yet been mentioned.
1063 ResultBuilder Results(*this);
1064 Results.EnterNewScope();
1065 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1066 EEnd = Enum->enumerator_end();
1067 E != EEnd; ++E) {
1068 if (EnumeratorsSeen.count(*E))
1069 continue;
1070
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001071 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001072 }
1073 Results.ExitScope();
1074
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001075 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1076}
1077
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001078namespace {
1079 struct IsBetterOverloadCandidate {
1080 Sema &S;
1081
1082 public:
1083 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1084
1085 bool
1086 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1087 return S.isBetterOverloadCandidate(X, Y);
1088 }
1089 };
1090}
1091
1092void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1093 ExprTy **ArgsIn, unsigned NumArgs) {
1094 if (!CodeCompleter)
1095 return;
1096
1097 Expr *Fn = (Expr *)FnIn;
1098 Expr **Args = (Expr **)ArgsIn;
1099
1100 // Ignore type-dependent call expressions entirely.
1101 if (Fn->isTypeDependent() ||
1102 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1103 return;
1104
1105 NamedDecl *Function;
1106 DeclarationName UnqualifiedName;
1107 NestedNameSpecifier *Qualifier;
1108 SourceRange QualifierRange;
1109 bool ArgumentDependentLookup;
1110 bool HasExplicitTemplateArgs;
1111 const TemplateArgument *ExplicitTemplateArgs;
1112 unsigned NumExplicitTemplateArgs;
1113
1114 DeconstructCallFunction(Fn,
1115 Function, UnqualifiedName, Qualifier, QualifierRange,
1116 ArgumentDependentLookup, HasExplicitTemplateArgs,
1117 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1118
1119
1120 // FIXME: What if we're calling something that isn't a function declaration?
1121 // FIXME: What if we're calling a pseudo-destructor?
1122 // FIXME: What if we're calling a member function?
1123
1124 // Build an overload candidate set based on the functions we find.
1125 OverloadCandidateSet CandidateSet;
1126 AddOverloadedCallCandidates(Function, UnqualifiedName,
1127 ArgumentDependentLookup, HasExplicitTemplateArgs,
1128 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1129 Args, NumArgs,
1130 CandidateSet,
1131 /*PartialOverloading=*/true);
1132
1133 // Sort the overload candidate set by placing the best overloads first.
1134 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1135 IsBetterOverloadCandidate(*this));
1136
1137 // Add the remaining viable overload candidates as code-completion reslults.
1138 typedef CodeCompleteConsumer::Result Result;
1139 ResultBuilder Results(*this);
Anders Carlsson90756302009-09-22 17:29:51 +00001140 Results.EnterNewScope();
1141
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001142 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1143 CandEnd = CandidateSet.end();
1144 Cand != CandEnd; ++Cand) {
1145 if (Cand->Viable)
1146 Results.MaybeAddResult(Result(Cand->Function, 0), 0);
1147 }
1148
Anders Carlsson90756302009-09-22 17:29:51 +00001149 Results.ExitScope();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001150 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1151}
1152
Douglas Gregor81b747b2009-09-17 21:32:03 +00001153void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1154 bool EnteringContext) {
1155 if (!SS.getScopeRep() || !CodeCompleter)
1156 return;
1157
Douglas Gregor86d9a522009-09-21 16:56:56 +00001158 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1159 if (!Ctx)
1160 return;
1161
1162 ResultBuilder Results(*this);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001163 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001164
1165 // The "template" keyword can follow "::" in the grammar, but only
1166 // put it into the grammar if the nested-name-specifier is dependent.
1167 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1168 if (!Results.empty() && NNS->isDependent())
1169 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1170
1171 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001172}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001173
1174void Sema::CodeCompleteUsing(Scope *S) {
1175 if (!CodeCompleter)
1176 return;
1177
Douglas Gregor86d9a522009-09-21 16:56:56 +00001178 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
1179
1180 // If we aren't in class scope, we could see the "namespace" keyword.
1181 if (!S->isClassScope())
1182 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1183
1184 // After "using", we can see anything that would start a
1185 // nested-name-specifier.
Douglas Gregor456c4a12009-09-21 20:12:40 +00001186 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0,
1187 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001188
1189 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001190}
1191
1192void Sema::CodeCompleteUsingDirective(Scope *S) {
1193 if (!CodeCompleter)
1194 return;
1195
Douglas Gregor86d9a522009-09-21 16:56:56 +00001196 // After "using namespace", we expect to see a namespace name or namespace
1197 // alias.
1198 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001199 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1200 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001201 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001202}
1203
1204void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1205 if (!CodeCompleter)
1206 return;
1207
Douglas Gregor86d9a522009-09-21 16:56:56 +00001208 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1209 DeclContext *Ctx = (DeclContext *)S->getEntity();
1210 if (!S->getParent())
1211 Ctx = Context.getTranslationUnitDecl();
1212
1213 if (Ctx && Ctx->isFileContext()) {
1214 // We only want to see those namespaces that have already been defined
1215 // within this scope, because its likely that the user is creating an
1216 // extended namespace declaration. Keep track of the most recent
1217 // definition of each namespace.
1218 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1219 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1220 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1221 NS != NSEnd; ++NS)
1222 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1223
1224 // Add the most recent definition (or extended definition) of each
1225 // namespace to the list of results.
1226 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1227 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1228 NS != NSEnd; ++NS)
Douglas Gregor456c4a12009-09-21 20:12:40 +00001229 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1230 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001231 }
1232
1233 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001234}
1235
1236void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1237 if (!CodeCompleter)
1238 return;
1239
Douglas Gregor86d9a522009-09-21 16:56:56 +00001240 // After "namespace", we expect to see a namespace or alias.
1241 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001242 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1243 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001244 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001245}
1246
Douglas Gregored8d3222009-09-18 20:05:18 +00001247void Sema::CodeCompleteOperatorName(Scope *S) {
1248 if (!CodeCompleter)
1249 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001250
1251 typedef CodeCompleteConsumer::Result Result;
1252 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregored8d3222009-09-18 20:05:18 +00001253
Douglas Gregor86d9a522009-09-21 16:56:56 +00001254 // Add the names of overloadable operators.
1255#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1256 if (std::strcmp(Spelling, "?")) \
1257 Results.MaybeAddResult(Result(Spelling, 0));
1258#include "clang/Basic/OperatorKinds.def"
1259
1260 // Add any type names visible from the current scope
1261 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001262 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001263
1264 // Add any type specifiers
1265 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1266
1267 // Add any nested-name-specifiers
1268 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1269 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +00001270 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001271
1272 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00001273}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001274