blob: 4c46696d1df001884112b37635506a1e5683230b [file] [log] [blame]
Douglas Gregor2436e712009-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 Gregorf2510672009-09-21 19:57:38 +000015#include "clang/AST/ExprCXX.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000016#include "llvm/ADT/SmallPtrSet.h"
17#include <list>
18#include <map>
19#include <vector>
Douglas Gregor2436e712009-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 Gregor3545ff42009-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 Gregor2af2f672009-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 Gregor3545ff42009-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 Gregor9d64c5e2009-09-21 20:51:25 +0000107 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor3545ff42009-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;
Douglas Gregore412a5a2009-09-23 22:26:46 +0000115 bool IsMember(NamedDecl *ND) const;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000116 //@}
117 };
118}
119
120/// \brief Determines whether the given hidden result could be found with
121/// some extra work, e.g., by qualifying the name.
122///
123/// \param Hidden the declaration that is hidden by the currenly \p Visible
124/// declaration.
125///
126/// \param Visible the declaration with the same name that is already visible.
127///
128/// \returns true if the hidden result can be found by some mechanism,
129/// false otherwise.
130static bool canHiddenResultBeFound(const LangOptions &LangOpts,
131 NamedDecl *Hidden, NamedDecl *Visible) {
132 // In C, there is no way to refer to a hidden name.
133 if (!LangOpts.CPlusPlus)
134 return false;
135
136 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
137
138 // There is no way to qualify a name declared in a function or method.
139 if (HiddenCtx->isFunctionOrMethod())
140 return false;
141
Douglas Gregor3545ff42009-09-21 16:56:56 +0000142 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
143}
144
Douglas Gregor2af2f672009-09-21 20:12:40 +0000145/// \brief Compute the qualification required to get from the current context
146/// (\p CurContext) to the target context (\p TargetContext).
147///
148/// \param Context the AST context in which the qualification will be used.
149///
150/// \param CurContext the context where an entity is being named, which is
151/// typically based on the current scope.
152///
153/// \param TargetContext the context in which the named entity actually
154/// resides.
155///
156/// \returns a nested name specifier that refers into the target context, or
157/// NULL if no qualification is needed.
158static NestedNameSpecifier *
159getRequiredQualification(ASTContext &Context,
160 DeclContext *CurContext,
161 DeclContext *TargetContext) {
162 llvm::SmallVector<DeclContext *, 4> TargetParents;
163
164 for (DeclContext *CommonAncestor = TargetContext;
165 CommonAncestor && !CommonAncestor->Encloses(CurContext);
166 CommonAncestor = CommonAncestor->getLookupParent()) {
167 if (CommonAncestor->isTransparentContext() ||
168 CommonAncestor->isFunctionOrMethod())
169 continue;
170
171 TargetParents.push_back(CommonAncestor);
172 }
173
174 NestedNameSpecifier *Result = 0;
175 while (!TargetParents.empty()) {
176 DeclContext *Parent = TargetParents.back();
177 TargetParents.pop_back();
178
179 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
180 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
181 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
182 Result = NestedNameSpecifier::Create(Context, Result,
183 false,
184 Context.getTypeDeclType(TD).getTypePtr());
185 else
186 assert(Parent->isTranslationUnit());
187 }
188
189 return Result;
190}
191
192void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
Douglas Gregor64b12b52009-09-22 23:31:26 +0000193 assert(!ShadowMaps.empty() && "Must enter into a results scope");
194
Douglas Gregor3545ff42009-09-21 16:56:56 +0000195 if (R.Kind != Result::RK_Declaration) {
196 // For non-declaration results, just add the result.
197 Results.push_back(R);
198 return;
199 }
200
201 // Look through using declarations.
202 if (UsingDecl *Using = dyn_cast<UsingDecl>(R.Declaration))
Douglas Gregor5bf52692009-09-22 23:15:58 +0000203 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
204 CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000205
206 // Handle each declaration in an overload set separately.
207 if (OverloadedFunctionDecl *Ovl
208 = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) {
209 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
210 FEnd = Ovl->function_end();
211 F != FEnd; ++F)
Douglas Gregor2af2f672009-09-21 20:12:40 +0000212 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000213
214 return;
215 }
216
217 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
218 unsigned IDNS = CanonDecl->getIdentifierNamespace();
219
220 // Friend declarations and declarations introduced due to friends are never
221 // added as results.
222 if (isa<FriendDecl>(CanonDecl) ||
223 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
224 return;
225
226 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
227 // __va_list_tag is a freak of nature. Find it and skip it.
228 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
229 return;
230
231 // FIXME: Should we filter out other names in the implementation's
232 // namespace, e.g., those containing a __ or that start with _[A-Z]?
233 }
234
235 // C++ constructors are never found by name lookup.
236 if (isa<CXXConstructorDecl>(CanonDecl))
237 return;
238
239 // Filter out any unwanted results.
240 if (Filter && !(this->*Filter)(R.Declaration))
241 return;
242
243 ShadowMap &SMap = ShadowMaps.back();
244 ShadowMap::iterator I, IEnd;
245 for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
246 I != IEnd; ++I) {
247 NamedDecl *ND = I->second.first;
248 unsigned Index = I->second.second;
249 if (ND->getCanonicalDecl() == CanonDecl) {
250 // This is a redeclaration. Always pick the newer declaration.
251 I->second.first = R.Declaration;
252 Results[Index].Declaration = R.Declaration;
253
254 // Pick the best rank of the two.
255 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
256
257 // We're done.
258 return;
259 }
260 }
261
262 // This is a new declaration in this scope. However, check whether this
263 // declaration name is hidden by a similarly-named declaration in an outer
264 // scope.
265 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
266 --SMEnd;
267 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
268 for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
269 I != IEnd; ++I) {
270 // A tag declaration does not hide a non-tag declaration.
271 if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
272 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
273 Decl::IDNS_ObjCProtocol)))
274 continue;
275
276 // Protocols are in distinct namespaces from everything else.
277 if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
278 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
279 I->second.first->getIdentifierNamespace() != IDNS)
280 continue;
281
282 // The newly-added result is hidden by an entry in the shadow map.
283 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
284 I->second.first)) {
285 // Note that this result was hidden.
286 R.Hidden = true;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000287 R.QualifierIsInformative = false;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000288
289 if (!R.Qualifier)
290 R.Qualifier = getRequiredQualification(SemaRef.Context,
291 CurContext,
292 R.Declaration->getDeclContext());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000293 } else {
294 // This result was hidden and cannot be found; don't bother adding
295 // it.
296 return;
297 }
298
299 break;
300 }
301 }
302
303 // Make sure that any given declaration only shows up in the result set once.
304 if (!AllDeclsFound.insert(CanonDecl))
305 return;
306
Douglas Gregore412a5a2009-09-23 22:26:46 +0000307 // If the filter is for nested-name-specifiers, then this result starts a
308 // nested-name-specifier.
309 if ((Filter == &ResultBuilder::IsNestedNameSpecifier) ||
310 (Filter == &ResultBuilder::IsMember &&
311 isa<CXXRecordDecl>(R.Declaration) &&
312 cast<CXXRecordDecl>(R.Declaration)->isInjectedClassName()))
313 R.StartsNestedNameSpecifier = true;
314
Douglas Gregor5bf52692009-09-22 23:15:58 +0000315 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000316 if (R.QualifierIsInformative && !R.Qualifier &&
317 !R.StartsNestedNameSpecifier) {
Douglas Gregor5bf52692009-09-22 23:15:58 +0000318 DeclContext *Ctx = R.Declaration->getDeclContext();
319 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
320 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
321 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
322 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
323 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
324 else
325 R.QualifierIsInformative = false;
326 }
Douglas Gregore412a5a2009-09-23 22:26:46 +0000327
Douglas Gregor3545ff42009-09-21 16:56:56 +0000328 // Insert this result into the set of results and into the current shadow
329 // map.
330 SMap.insert(std::make_pair(R.Declaration->getDeclName(),
331 std::make_pair(R.Declaration, Results.size())));
332 Results.push_back(R);
333}
334
335/// \brief Enter into a new scope.
336void ResultBuilder::EnterNewScope() {
337 ShadowMaps.push_back(ShadowMap());
338}
339
340/// \brief Exit from the current scope.
341void ResultBuilder::ExitScope() {
342 ShadowMaps.pop_back();
343}
344
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000345/// \brief Determines whether this given declaration will be found by
346/// ordinary name lookup.
347bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
348 unsigned IDNS = Decl::IDNS_Ordinary;
349 if (SemaRef.getLangOptions().CPlusPlus)
350 IDNS |= Decl::IDNS_Tag;
351
352 return ND->getIdentifierNamespace() & IDNS;
353}
354
Douglas Gregor3545ff42009-09-21 16:56:56 +0000355/// \brief Determines whether the given declaration is suitable as the
356/// start of a C++ nested-name-specifier, e.g., a class or namespace.
357bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
358 // Allow us to find class templates, too.
359 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
360 ND = ClassTemplate->getTemplatedDecl();
361
362 return SemaRef.isAcceptableNestedNameSpecifier(ND);
363}
364
365/// \brief Determines whether the given declaration is an enumeration.
366bool ResultBuilder::IsEnum(NamedDecl *ND) const {
367 return isa<EnumDecl>(ND);
368}
369
370/// \brief Determines whether the given declaration is a class or struct.
371bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
372 // Allow us to find class templates, too.
373 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
374 ND = ClassTemplate->getTemplatedDecl();
375
376 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
377 return RD->getTagKind() == TagDecl::TK_class ||
378 RD->getTagKind() == TagDecl::TK_struct;
379
380 return false;
381}
382
383/// \brief Determines whether the given declaration is a union.
384bool ResultBuilder::IsUnion(NamedDecl *ND) const {
385 // Allow us to find class templates, too.
386 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
387 ND = ClassTemplate->getTemplatedDecl();
388
389 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
390 return RD->getTagKind() == TagDecl::TK_union;
391
392 return false;
393}
394
395/// \brief Determines whether the given declaration is a namespace.
396bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
397 return isa<NamespaceDecl>(ND);
398}
399
400/// \brief Determines whether the given declaration is a namespace or
401/// namespace alias.
402bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
403 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
404}
405
406/// \brief Brief determines whether the given declaration is a namespace or
407/// namespace alias.
408bool ResultBuilder::IsType(NamedDecl *ND) const {
409 return isa<TypeDecl>(ND);
410}
411
Douglas Gregore412a5a2009-09-23 22:26:46 +0000412/// \brief Since every declaration found within a class is a member that we
413/// care about, always returns true. This predicate exists mostly to
414/// communicate to the result builder that we are performing a lookup for
415/// member access.
416bool ResultBuilder::IsMember(NamedDecl *ND) const {
417 return true;
418}
419
Douglas Gregor3545ff42009-09-21 16:56:56 +0000420// Find the next outer declaration context corresponding to this scope.
421static DeclContext *findOuterContext(Scope *S) {
422 for (S = S->getParent(); S; S = S->getParent())
423 if (S->getEntity())
424 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
425
426 return 0;
427}
428
429/// \brief Collect the results of searching for members within the given
430/// declaration context.
431///
432/// \param Ctx the declaration context from which we will gather results.
433///
Douglas Gregor5bf52692009-09-22 23:15:58 +0000434/// \param Rank the rank given to results in this declaration context.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000435///
436/// \param Visited the set of declaration contexts that have already been
437/// visited. Declaration contexts will only be visited once.
438///
439/// \param Results the result set that will be extended with any results
440/// found within this declaration context (and, for a C++ class, its bases).
441///
Douglas Gregor5bf52692009-09-22 23:15:58 +0000442/// \param InBaseClass whether we are in a base class.
443///
Douglas Gregor3545ff42009-09-21 16:56:56 +0000444/// \returns the next higher rank value, after considering all of the
445/// names within this declaration context.
446static unsigned CollectMemberLookupResults(DeclContext *Ctx,
Douglas Gregor5bf52692009-09-22 23:15:58 +0000447 unsigned Rank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000448 DeclContext *CurContext,
449 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor5bf52692009-09-22 23:15:58 +0000450 ResultBuilder &Results,
451 bool InBaseClass = false) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000452 // Make sure we don't visit the same context twice.
453 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor5bf52692009-09-22 23:15:58 +0000454 return Rank;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000455
456 // Enumerate all of the results in this context.
Douglas Gregor5bf52692009-09-22 23:15:58 +0000457 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000458 Results.EnterNewScope();
459 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
460 CurCtx = CurCtx->getNextContext()) {
461 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
462 DEnd = CurCtx->decls_end();
463 D != DEnd; ++D) {
464 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor5bf52692009-09-22 23:15:58 +0000465 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000466 }
467 }
468
469 // Traverse the contexts of inherited classes.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000470 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
471 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
472 BEnd = Record->bases_end();
473 B != BEnd; ++B) {
474 QualType BaseType = B->getType();
475
476 // Don't look into dependent bases, because name lookup can't look
477 // there anyway.
478 if (BaseType->isDependentType())
479 continue;
480
481 const RecordType *Record = BaseType->getAs<RecordType>();
482 if (!Record)
483 continue;
484
485 // FIXME: It would be nice to be able to determine whether referencing
486 // a particular member would be ambiguous. For example, given
487 //
488 // struct A { int member; };
489 // struct B { int member; };
490 // struct C : A, B { };
491 //
492 // void f(C *c) { c->### }
493 // accessing 'member' would result in an ambiguity. However, code
494 // completion could be smart enough to qualify the member with the
495 // base class, e.g.,
496 //
497 // c->B::member
498 //
499 // or
500 //
501 // c->A::member
502
503 // Collect results from this base class (and its bases).
Douglas Gregor5bf52692009-09-22 23:15:58 +0000504 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
505 Results, /*InBaseClass=*/true);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000506 }
507 }
508
509 // FIXME: Look into base classes in Objective-C!
510
511 Results.ExitScope();
Douglas Gregor5bf52692009-09-22 23:15:58 +0000512 return Rank + 1;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000513}
514
515/// \brief Collect the results of searching for members within the given
516/// declaration context.
517///
518/// \param Ctx the declaration context from which we will gather results.
519///
520/// \param InitialRank the initial rank given to results in this declaration
521/// context. Larger rank values will be used for, e.g., members found in
522/// base classes.
523///
524/// \param Results the result set that will be extended with any results
525/// found within this declaration context (and, for a C++ class, its bases).
526///
527/// \returns the next higher rank value, after considering all of the
528/// names within this declaration context.
529static unsigned CollectMemberLookupResults(DeclContext *Ctx,
530 unsigned InitialRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000531 DeclContext *CurContext,
Douglas Gregor3545ff42009-09-21 16:56:56 +0000532 ResultBuilder &Results) {
533 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000534 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
535 Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000536}
537
538/// \brief Collect the results of searching for declarations within the given
539/// scope and its parent scopes.
540///
541/// \param S the scope in which we will start looking for declarations.
542///
543/// \param InitialRank the initial rank given to results in this scope.
544/// Larger rank values will be used for results found in parent scopes.
545///
Douglas Gregor2af2f672009-09-21 20:12:40 +0000546/// \param CurContext the context from which lookup results will be found.
547///
Douglas Gregor3545ff42009-09-21 16:56:56 +0000548/// \param Results the builder object that will receive each result.
549static unsigned CollectLookupResults(Scope *S,
550 TranslationUnitDecl *TranslationUnit,
551 unsigned InitialRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000552 DeclContext *CurContext,
Douglas Gregor3545ff42009-09-21 16:56:56 +0000553 ResultBuilder &Results) {
554 if (!S)
555 return InitialRank;
556
557 // FIXME: Using directives!
558
559 unsigned NextRank = InitialRank;
560 Results.EnterNewScope();
561 if (S->getEntity() &&
562 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
563 // Look into this scope's declaration context, along with any of its
564 // parent lookup contexts (e.g., enclosing classes), up to the point
565 // where we hit the context stored in the next outer scope.
566 DeclContext *Ctx = (DeclContext *)S->getEntity();
567 DeclContext *OuterCtx = findOuterContext(S);
568
569 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
570 Ctx = Ctx->getLookupParent()) {
571 if (Ctx->isFunctionOrMethod())
572 continue;
573
Douglas Gregor2af2f672009-09-21 20:12:40 +0000574 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
575 Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000576 }
577 } else if (!S->getParent()) {
578 // Look into the translation unit scope. We walk through the translation
579 // unit's declaration context, because the Scope itself won't have all of
580 // the declarations if we loaded a precompiled header.
581 // FIXME: We would like the translation unit's Scope object to point to the
582 // translation unit, so we don't need this special "if" branch. However,
583 // doing so would force the normal C++ name-lookup code to look into the
584 // translation unit decl when the IdentifierInfo chains would suffice.
585 // Once we fix that problem (which is part of a more general "don't look
586 // in DeclContexts unless we have to" optimization), we can eliminate the
587 // TranslationUnit parameter entirely.
588 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000589 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000590 } else {
591 // Walk through the declarations in this Scope.
592 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
593 D != DEnd; ++D) {
594 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
Douglas Gregor2af2f672009-09-21 20:12:40 +0000595 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
596 CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000597 }
598
599 NextRank = NextRank + 1;
600 }
601
602 // Lookup names in the parent scope.
603 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000604 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000605 Results.ExitScope();
606
607 return NextRank;
608}
609
610/// \brief Add type specifiers for the current language as keyword results.
611static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
612 ResultBuilder &Results) {
613 typedef CodeCompleteConsumer::Result Result;
614 Results.MaybeAddResult(Result("short", Rank));
615 Results.MaybeAddResult(Result("long", Rank));
616 Results.MaybeAddResult(Result("signed", Rank));
617 Results.MaybeAddResult(Result("unsigned", Rank));
618 Results.MaybeAddResult(Result("void", Rank));
619 Results.MaybeAddResult(Result("char", Rank));
620 Results.MaybeAddResult(Result("int", Rank));
621 Results.MaybeAddResult(Result("float", Rank));
622 Results.MaybeAddResult(Result("double", Rank));
623 Results.MaybeAddResult(Result("enum", Rank));
624 Results.MaybeAddResult(Result("struct", Rank));
625 Results.MaybeAddResult(Result("union", Rank));
626
627 if (LangOpts.C99) {
628 // C99-specific
629 Results.MaybeAddResult(Result("_Complex", Rank));
630 Results.MaybeAddResult(Result("_Imaginary", Rank));
631 Results.MaybeAddResult(Result("_Bool", Rank));
632 }
633
634 if (LangOpts.CPlusPlus) {
635 // C++-specific
636 Results.MaybeAddResult(Result("bool", Rank));
637 Results.MaybeAddResult(Result("class", Rank));
638 Results.MaybeAddResult(Result("typename", Rank));
639 Results.MaybeAddResult(Result("wchar_t", Rank));
640
641 if (LangOpts.CPlusPlus0x) {
642 Results.MaybeAddResult(Result("char16_t", Rank));
643 Results.MaybeAddResult(Result("char32_t", Rank));
644 Results.MaybeAddResult(Result("decltype", Rank));
645 }
646 }
647
648 // GNU extensions
649 if (LangOpts.GNUMode) {
650 // FIXME: Enable when we actually support decimal floating point.
651 // Results.MaybeAddResult(Result("_Decimal32", Rank));
652 // Results.MaybeAddResult(Result("_Decimal64", Rank));
653 // Results.MaybeAddResult(Result("_Decimal128", Rank));
654 Results.MaybeAddResult(Result("typeof", Rank));
655 }
656}
657
658/// \brief Add function parameter chunks to the given code completion string.
659static void AddFunctionParameterChunks(ASTContext &Context,
660 FunctionDecl *Function,
661 CodeCompletionString *Result) {
662 CodeCompletionString *CCStr = Result;
663
664 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
665 ParmVarDecl *Param = Function->getParamDecl(P);
666
667 if (Param->hasDefaultArg()) {
668 // When we see an optional default argument, put that argument and
669 // the remaining default arguments into a new, optional string.
670 CodeCompletionString *Opt = new CodeCompletionString;
671 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
672 CCStr = Opt;
673 }
674
675 if (P != 0)
676 CCStr->AddTextChunk(", ");
677
678 // Format the placeholder string.
679 std::string PlaceholderStr;
680 if (Param->getIdentifier())
681 PlaceholderStr = Param->getIdentifier()->getName();
682
683 Param->getType().getAsStringInternal(PlaceholderStr,
684 Context.PrintingPolicy);
685
686 // Add the placeholder string.
687 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
688 }
Douglas Gregorba449032009-09-22 21:42:17 +0000689
690 if (const FunctionProtoType *Proto
691 = Function->getType()->getAs<FunctionProtoType>())
692 if (Proto->isVariadic())
693 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor3545ff42009-09-21 16:56:56 +0000694}
695
696/// \brief Add template parameter chunks to the given code completion string.
697static void AddTemplateParameterChunks(ASTContext &Context,
698 TemplateDecl *Template,
699 CodeCompletionString *Result,
700 unsigned MaxParameters = 0) {
701 CodeCompletionString *CCStr = Result;
702 bool FirstParameter = true;
703
704 TemplateParameterList *Params = Template->getTemplateParameters();
705 TemplateParameterList::iterator PEnd = Params->end();
706 if (MaxParameters)
707 PEnd = Params->begin() + MaxParameters;
708 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
709 bool HasDefaultArg = false;
710 std::string PlaceholderStr;
711 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
712 if (TTP->wasDeclaredWithTypename())
713 PlaceholderStr = "typename";
714 else
715 PlaceholderStr = "class";
716
717 if (TTP->getIdentifier()) {
718 PlaceholderStr += ' ';
719 PlaceholderStr += TTP->getIdentifier()->getName();
720 }
721
722 HasDefaultArg = TTP->hasDefaultArgument();
723 } else if (NonTypeTemplateParmDecl *NTTP
724 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
725 if (NTTP->getIdentifier())
726 PlaceholderStr = NTTP->getIdentifier()->getName();
727 NTTP->getType().getAsStringInternal(PlaceholderStr,
728 Context.PrintingPolicy);
729 HasDefaultArg = NTTP->hasDefaultArgument();
730 } else {
731 assert(isa<TemplateTemplateParmDecl>(*P));
732 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
733
734 // Since putting the template argument list into the placeholder would
735 // be very, very long, we just use an abbreviation.
736 PlaceholderStr = "template<...> class";
737 if (TTP->getIdentifier()) {
738 PlaceholderStr += ' ';
739 PlaceholderStr += TTP->getIdentifier()->getName();
740 }
741
742 HasDefaultArg = TTP->hasDefaultArgument();
743 }
744
745 if (HasDefaultArg) {
746 // When we see an optional default argument, put that argument and
747 // the remaining default arguments into a new, optional string.
748 CodeCompletionString *Opt = new CodeCompletionString;
749 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
750 CCStr = Opt;
751 }
752
753 if (FirstParameter)
754 FirstParameter = false;
755 else
756 CCStr->AddTextChunk(", ");
757
758 // Add the placeholder string.
759 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
760 }
761}
762
Douglas Gregorf2510672009-09-21 19:57:38 +0000763/// \brief Add a qualifier to the given code-completion string, if the
764/// provided nested-name-specifier is non-NULL.
765void AddQualifierToCompletionString(CodeCompletionString *Result,
766 NestedNameSpecifier *Qualifier,
Douglas Gregor5bf52692009-09-22 23:15:58 +0000767 bool QualifierIsInformative,
Douglas Gregorf2510672009-09-21 19:57:38 +0000768 ASTContext &Context) {
769 if (!Qualifier)
770 return;
771
772 std::string PrintedNNS;
773 {
774 llvm::raw_string_ostream OS(PrintedNNS);
775 Qualifier->print(OS, Context.PrintingPolicy);
776 }
Douglas Gregor5bf52692009-09-22 23:15:58 +0000777 if (QualifierIsInformative)
778 Result->AddInformativeChunk(PrintedNNS.c_str());
779 else
780 Result->AddTextChunk(PrintedNNS.c_str());
Douglas Gregorf2510672009-09-21 19:57:38 +0000781}
782
Douglas Gregor3545ff42009-09-21 16:56:56 +0000783/// \brief If possible, create a new code completion string for the given
784/// result.
785///
786/// \returns Either a new, heap-allocated code completion string describing
787/// how to use this result, or NULL to indicate that the string or name of the
788/// result is all that is needed.
789CodeCompletionString *
790CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
791 if (Kind != RK_Declaration)
792 return 0;
793
794 NamedDecl *ND = Declaration;
795
796 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
797 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000798 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
799 S.Context);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000800 Result->AddTextChunk(Function->getNameAsString().c_str());
801 Result->AddTextChunk("(");
802 AddFunctionParameterChunks(S.Context, Function, Result);
803 Result->AddTextChunk(")");
804 return Result;
805 }
806
807 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
808 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000809 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
810 S.Context);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000811 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
812 Result->AddTextChunk(Function->getNameAsString().c_str());
813
814 // Figure out which template parameters are deduced (or have default
815 // arguments).
816 llvm::SmallVector<bool, 16> Deduced;
817 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
818 unsigned LastDeducibleArgument;
819 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
820 --LastDeducibleArgument) {
821 if (!Deduced[LastDeducibleArgument - 1]) {
822 // C++0x: Figure out if the template argument has a default. If so,
823 // the user doesn't need to type this argument.
824 // FIXME: We need to abstract template parameters better!
825 bool HasDefaultArg = false;
826 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
827 LastDeducibleArgument - 1);
828 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
829 HasDefaultArg = TTP->hasDefaultArgument();
830 else if (NonTypeTemplateParmDecl *NTTP
831 = dyn_cast<NonTypeTemplateParmDecl>(Param))
832 HasDefaultArg = NTTP->hasDefaultArgument();
833 else {
834 assert(isa<TemplateTemplateParmDecl>(Param));
835 HasDefaultArg
836 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
837 }
838
839 if (!HasDefaultArg)
840 break;
841 }
842 }
843
844 if (LastDeducibleArgument) {
845 // Some of the function template arguments cannot be deduced from a
846 // function call, so we introduce an explicit template argument list
847 // containing all of the arguments up to the first deducible argument.
848 Result->AddTextChunk("<");
849 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
850 LastDeducibleArgument);
851 Result->AddTextChunk(">");
852 }
853
854 // Add the function parameters
855 Result->AddTextChunk("(");
856 AddFunctionParameterChunks(S.Context, Function, Result);
857 Result->AddTextChunk(")");
858 return Result;
859 }
860
861 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
862 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000863 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
864 S.Context);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000865 Result->AddTextChunk(Template->getNameAsString().c_str());
866 Result->AddTextChunk("<");
867 AddTemplateParameterChunks(S.Context, Template, Result);
868 Result->AddTextChunk(">");
869 return Result;
870 }
871
Douglas Gregor2b3ee152009-09-22 23:22:24 +0000872 if (Qualifier || StartsNestedNameSpecifier) {
Douglas Gregorf2510672009-09-21 19:57:38 +0000873 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000874 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
875 S.Context);
Douglas Gregorf2510672009-09-21 19:57:38 +0000876 Result->AddTextChunk(ND->getNameAsString().c_str());
Douglas Gregor2b3ee152009-09-22 23:22:24 +0000877 if (StartsNestedNameSpecifier)
878 Result->AddTextChunk("::");
Douglas Gregorf2510672009-09-21 19:57:38 +0000879 return Result;
880 }
881
Douglas Gregor3545ff42009-09-21 16:56:56 +0000882 return 0;
883}
884
Douglas Gregorf0f51982009-09-23 00:34:09 +0000885CodeCompletionString *
886CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
887 unsigned CurrentArg,
888 Sema &S) const {
889 CodeCompletionString *Result = new CodeCompletionString;
890 FunctionDecl *FDecl = getFunction();
891 const FunctionProtoType *Proto
892 = dyn_cast<FunctionProtoType>(getFunctionType());
893 if (!FDecl && !Proto) {
894 // Function without a prototype. Just give the return type and a
895 // highlighted ellipsis.
896 const FunctionType *FT = getFunctionType();
897 Result->AddTextChunk(
898 FT->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
899 Result->AddTextChunk("(");
900 Result->AddPlaceholderChunk("...");
901 Result->AddTextChunk("(");
902 return Result;
903 }
904
905 if (FDecl)
906 Result->AddTextChunk(FDecl->getNameAsString().c_str());
907 else
908 Result->AddTextChunk(
909 Proto->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
910
911 Result->AddTextChunk("(");
912 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
913 for (unsigned I = 0; I != NumParams; ++I) {
914 if (I)
915 Result->AddTextChunk(", ");
916
917 std::string ArgString;
918 QualType ArgType;
919
920 if (FDecl) {
921 ArgString = FDecl->getParamDecl(I)->getNameAsString();
922 ArgType = FDecl->getParamDecl(I)->getOriginalType();
923 } else {
924 ArgType = Proto->getArgType(I);
925 }
926
927 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
928
929 if (I == CurrentArg)
930 Result->AddPlaceholderChunk(ArgString.c_str());
931 else
932 Result->AddTextChunk(ArgString.c_str());
933 }
934
935 if (Proto && Proto->isVariadic()) {
936 Result->AddTextChunk(", ");
937 if (CurrentArg < NumParams)
938 Result->AddTextChunk("...");
939 else
940 Result->AddPlaceholderChunk("...");
941 }
942 Result->AddTextChunk(")");
943
944 return Result;
945}
946
Douglas Gregor3545ff42009-09-21 16:56:56 +0000947namespace {
948 struct SortCodeCompleteResult {
949 typedef CodeCompleteConsumer::Result Result;
950
951 bool operator()(const Result &X, const Result &Y) const {
952 // Sort first by rank.
953 if (X.Rank < Y.Rank)
954 return true;
955 else if (X.Rank > Y.Rank)
956 return false;
957
958 // Result kinds are ordered by decreasing importance.
959 if (X.Kind < Y.Kind)
960 return true;
961 else if (X.Kind > Y.Kind)
962 return false;
963
964 // Non-hidden names precede hidden names.
965 if (X.Hidden != Y.Hidden)
966 return !X.Hidden;
967
Douglas Gregore412a5a2009-09-23 22:26:46 +0000968 // Non-nested-name-specifiers precede nested-name-specifiers.
969 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
970 return !X.StartsNestedNameSpecifier;
971
Douglas Gregor3545ff42009-09-21 16:56:56 +0000972 // Ordering depends on the kind of result.
973 switch (X.Kind) {
974 case Result::RK_Declaration:
975 // Order based on the declaration names.
976 return X.Declaration->getDeclName() < Y.Declaration->getDeclName();
977
978 case Result::RK_Keyword:
979 return strcmp(X.Keyword, Y.Keyword) == -1;
980 }
981
982 // Silence GCC warning.
983 return false;
984 }
985 };
986}
987
988static void HandleCodeCompleteResults(CodeCompleteConsumer *CodeCompleter,
989 CodeCompleteConsumer::Result *Results,
990 unsigned NumResults) {
991 // Sort the results by rank/kind/etc.
992 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
993
994 if (CodeCompleter)
995 CodeCompleter->ProcessCodeCompleteResults(Results, NumResults);
996}
997
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000998void Sema::CodeCompleteOrdinaryName(Scope *S) {
999 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
1000 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1001 Results);
1002 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1003}
1004
Douglas Gregor2436e712009-09-17 21:32:03 +00001005void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1006 SourceLocation OpLoc,
1007 bool IsArrow) {
1008 if (!BaseE || !CodeCompleter)
1009 return;
1010
Douglas Gregor3545ff42009-09-21 16:56:56 +00001011 typedef CodeCompleteConsumer::Result Result;
1012
Douglas Gregor2436e712009-09-17 21:32:03 +00001013 Expr *Base = static_cast<Expr *>(BaseE);
1014 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001015
1016 if (IsArrow) {
1017 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1018 BaseType = Ptr->getPointeeType();
1019 else if (BaseType->isObjCObjectPointerType())
1020 /*Do nothing*/ ;
1021 else
1022 return;
1023 }
1024
Douglas Gregore412a5a2009-09-23 22:26:46 +00001025 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001026 unsigned NextRank = 0;
1027
1028 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor2af2f672009-09-21 20:12:40 +00001029 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1030 Record->getDecl(), Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001031
1032 if (getLangOptions().CPlusPlus) {
1033 if (!Results.empty()) {
1034 // The "template" keyword can follow "->" or "." in the grammar.
1035 // However, we only want to suggest the template keyword if something
1036 // is dependent.
1037 bool IsDependent = BaseType->isDependentType();
1038 if (!IsDependent) {
1039 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1040 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1041 IsDependent = Ctx->isDependentContext();
1042 break;
1043 }
1044 }
1045
1046 if (IsDependent)
1047 Results.MaybeAddResult(Result("template", NextRank++));
1048 }
1049
1050 // We could have the start of a nested-name-specifier. Add those
1051 // results as well.
1052 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1053 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +00001054 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001055 }
1056
1057 // Hand off the results found for code completion.
1058 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1059
1060 // We're done!
1061 return;
1062 }
Douglas Gregor2436e712009-09-17 21:32:03 +00001063}
1064
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001065void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1066 if (!CodeCompleter)
1067 return;
1068
Douglas Gregor3545ff42009-09-21 16:56:56 +00001069 typedef CodeCompleteConsumer::Result Result;
1070 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001071 switch ((DeclSpec::TST)TagSpec) {
1072 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00001073 Filter = &ResultBuilder::IsEnum;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001074 break;
1075
1076 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00001077 Filter = &ResultBuilder::IsUnion;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001078 break;
1079
1080 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001081 case DeclSpec::TST_class:
Douglas Gregor3545ff42009-09-21 16:56:56 +00001082 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001083 break;
1084
1085 default:
1086 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1087 return;
1088 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001089
1090 ResultBuilder Results(*this, Filter);
1091 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor2af2f672009-09-21 20:12:40 +00001092 0, CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001093
1094 if (getLangOptions().CPlusPlus) {
1095 // We could have the start of a nested-name-specifier. Add those
1096 // results as well.
1097 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1098 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +00001099 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001100 }
1101
1102 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001103}
1104
Douglas Gregord328d572009-09-21 18:10:23 +00001105void Sema::CodeCompleteCase(Scope *S) {
1106 if (getSwitchStack().empty() || !CodeCompleter)
1107 return;
1108
1109 SwitchStmt *Switch = getSwitchStack().back();
1110 if (!Switch->getCond()->getType()->isEnumeralType())
1111 return;
1112
1113 // Code-complete the cases of a switch statement over an enumeration type
1114 // by providing the list of
1115 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1116
1117 // Determine which enumerators we have already seen in the switch statement.
1118 // FIXME: Ideally, we would also be able to look *past* the code-completion
1119 // token, in case we are code-completing in the middle of the switch and not
1120 // at the end. However, we aren't able to do so at the moment.
1121 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorf2510672009-09-21 19:57:38 +00001122 NestedNameSpecifier *Qualifier = 0;
Douglas Gregord328d572009-09-21 18:10:23 +00001123 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1124 SC = SC->getNextSwitchCase()) {
1125 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1126 if (!Case)
1127 continue;
1128
1129 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1130 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1131 if (EnumConstantDecl *Enumerator
1132 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1133 // We look into the AST of the case statement to determine which
1134 // enumerator was named. Alternatively, we could compute the value of
1135 // the integral constant expression, then compare it against the
1136 // values of each enumerator. However, value-based approach would not
1137 // work as well with C++ templates where enumerators declared within a
1138 // template are type- and value-dependent.
1139 EnumeratorsSeen.insert(Enumerator);
1140
Douglas Gregorf2510672009-09-21 19:57:38 +00001141 // If this is a qualified-id, keep track of the nested-name-specifier
1142 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00001143 //
1144 // switch (TagD.getKind()) {
1145 // case TagDecl::TK_enum:
1146 // break;
1147 // case XXX
1148 //
Douglas Gregorf2510672009-09-21 19:57:38 +00001149 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00001150 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1151 // TK_struct, and TK_class.
Douglas Gregorf2510672009-09-21 19:57:38 +00001152 if (QualifiedDeclRefExpr *QDRE = dyn_cast<QualifiedDeclRefExpr>(DRE))
1153 Qualifier = QDRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00001154 }
1155 }
1156
Douglas Gregorf2510672009-09-21 19:57:38 +00001157 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1158 // If there are no prior enumerators in C++, check whether we have to
1159 // qualify the names of the enumerators that we suggest, because they
1160 // may not be visible in this scope.
1161 Qualifier = getRequiredQualification(Context, CurContext,
1162 Enum->getDeclContext());
1163
1164 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1165 }
1166
Douglas Gregord328d572009-09-21 18:10:23 +00001167 // Add any enumerators that have not yet been mentioned.
1168 ResultBuilder Results(*this);
1169 Results.EnterNewScope();
1170 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1171 EEnd = Enum->enumerator_end();
1172 E != EEnd; ++E) {
1173 if (EnumeratorsSeen.count(*E))
1174 continue;
1175
Douglas Gregorf2510672009-09-21 19:57:38 +00001176 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregord328d572009-09-21 18:10:23 +00001177 }
1178 Results.ExitScope();
1179
Douglas Gregord328d572009-09-21 18:10:23 +00001180 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1181}
1182
Douglas Gregorcabea402009-09-22 15:41:20 +00001183namespace {
1184 struct IsBetterOverloadCandidate {
1185 Sema &S;
1186
1187 public:
1188 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1189
1190 bool
1191 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1192 return S.isBetterOverloadCandidate(X, Y);
1193 }
1194 };
1195}
1196
1197void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1198 ExprTy **ArgsIn, unsigned NumArgs) {
1199 if (!CodeCompleter)
1200 return;
1201
1202 Expr *Fn = (Expr *)FnIn;
1203 Expr **Args = (Expr **)ArgsIn;
1204
1205 // Ignore type-dependent call expressions entirely.
1206 if (Fn->isTypeDependent() ||
1207 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1208 return;
1209
1210 NamedDecl *Function;
1211 DeclarationName UnqualifiedName;
1212 NestedNameSpecifier *Qualifier;
1213 SourceRange QualifierRange;
1214 bool ArgumentDependentLookup;
1215 bool HasExplicitTemplateArgs;
1216 const TemplateArgument *ExplicitTemplateArgs;
1217 unsigned NumExplicitTemplateArgs;
1218
1219 DeconstructCallFunction(Fn,
1220 Function, UnqualifiedName, Qualifier, QualifierRange,
1221 ArgumentDependentLookup, HasExplicitTemplateArgs,
1222 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1223
1224
1225 // FIXME: What if we're calling something that isn't a function declaration?
1226 // FIXME: What if we're calling a pseudo-destructor?
1227 // FIXME: What if we're calling a member function?
1228
1229 // Build an overload candidate set based on the functions we find.
1230 OverloadCandidateSet CandidateSet;
1231 AddOverloadedCallCandidates(Function, UnqualifiedName,
1232 ArgumentDependentLookup, HasExplicitTemplateArgs,
1233 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1234 Args, NumArgs,
1235 CandidateSet,
1236 /*PartialOverloading=*/true);
1237
1238 // Sort the overload candidate set by placing the best overloads first.
1239 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1240 IsBetterOverloadCandidate(*this));
1241
1242 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05f477c2009-09-23 00:16:58 +00001243 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1244 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlssone7ceb852009-09-22 17:29:51 +00001245
Douglas Gregorcabea402009-09-22 15:41:20 +00001246 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1247 CandEnd = CandidateSet.end();
1248 Cand != CandEnd; ++Cand) {
1249 if (Cand->Viable)
Douglas Gregor05f477c2009-09-23 00:16:58 +00001250 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregorcabea402009-09-22 15:41:20 +00001251 }
Douglas Gregor05f477c2009-09-23 00:16:58 +00001252 CodeCompleter->ProcessOverloadCandidates(NumArgs, Results.data(),
1253 Results.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00001254}
1255
Douglas Gregor2436e712009-09-17 21:32:03 +00001256void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1257 bool EnteringContext) {
1258 if (!SS.getScopeRep() || !CodeCompleter)
1259 return;
1260
Douglas Gregor3545ff42009-09-21 16:56:56 +00001261 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1262 if (!Ctx)
1263 return;
1264
1265 ResultBuilder Results(*this);
Douglas Gregor2af2f672009-09-21 20:12:40 +00001266 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001267
1268 // The "template" keyword can follow "::" in the grammar, but only
1269 // put it into the grammar if the nested-name-specifier is dependent.
1270 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1271 if (!Results.empty() && NNS->isDependent())
1272 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1273
1274 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00001275}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001276
1277void Sema::CodeCompleteUsing(Scope *S) {
1278 if (!CodeCompleter)
1279 return;
1280
Douglas Gregor3545ff42009-09-21 16:56:56 +00001281 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001282 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001283
1284 // If we aren't in class scope, we could see the "namespace" keyword.
1285 if (!S->isClassScope())
1286 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1287
1288 // After "using", we can see anything that would start a
1289 // nested-name-specifier.
Douglas Gregor2af2f672009-09-21 20:12:40 +00001290 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0,
1291 CurContext, Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001292 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001293
1294 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001295}
1296
1297void Sema::CodeCompleteUsingDirective(Scope *S) {
1298 if (!CodeCompleter)
1299 return;
1300
Douglas Gregor3545ff42009-09-21 16:56:56 +00001301 // After "using namespace", we expect to see a namespace name or namespace
1302 // alias.
1303 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001304 Results.EnterNewScope();
Douglas Gregor2af2f672009-09-21 20:12:40 +00001305 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1306 Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001307 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001308 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001309}
1310
1311void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1312 if (!CodeCompleter)
1313 return;
1314
Douglas Gregor3545ff42009-09-21 16:56:56 +00001315 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1316 DeclContext *Ctx = (DeclContext *)S->getEntity();
1317 if (!S->getParent())
1318 Ctx = Context.getTranslationUnitDecl();
1319
1320 if (Ctx && Ctx->isFileContext()) {
1321 // We only want to see those namespaces that have already been defined
1322 // within this scope, because its likely that the user is creating an
1323 // extended namespace declaration. Keep track of the most recent
1324 // definition of each namespace.
1325 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1326 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1327 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1328 NS != NSEnd; ++NS)
1329 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1330
1331 // Add the most recent definition (or extended definition) of each
1332 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00001333 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001334 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1335 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1336 NS != NSEnd; ++NS)
Douglas Gregor2af2f672009-09-21 20:12:40 +00001337 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1338 CurContext);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001339 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001340 }
1341
1342 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001343}
1344
1345void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1346 if (!CodeCompleter)
1347 return;
1348
Douglas Gregor3545ff42009-09-21 16:56:56 +00001349 // After "namespace", we expect to see a namespace or alias.
1350 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor2af2f672009-09-21 20:12:40 +00001351 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1352 Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001353 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001354}
1355
Douglas Gregorc811ede2009-09-18 20:05:18 +00001356void Sema::CodeCompleteOperatorName(Scope *S) {
1357 if (!CodeCompleter)
1358 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001359
1360 typedef CodeCompleteConsumer::Result Result;
1361 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001362 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00001363
Douglas Gregor3545ff42009-09-21 16:56:56 +00001364 // Add the names of overloadable operators.
1365#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1366 if (std::strcmp(Spelling, "?")) \
1367 Results.MaybeAddResult(Result(Spelling, 0));
1368#include "clang/Basic/OperatorKinds.def"
1369
1370 // Add any type names visible from the current scope
1371 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor2af2f672009-09-21 20:12:40 +00001372 0, CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001373
1374 // Add any type specifiers
1375 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1376
1377 // Add any nested-name-specifiers
1378 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1379 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank + 1,
Douglas Gregor2af2f672009-09-21 20:12:40 +00001380 CurContext, Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001381 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001382
1383 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00001384}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001385