blob: de30441c5312820de9fb83ea40f78570e9f6174f [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 Gregor3f7c7f42009-10-30 16:50:04 +000016#include "clang/Lex/MacroInfo.h"
17#include "clang/Lex/Preprocessor.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000018#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000019#include "llvm/ADT/StringExtras.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000020#include <list>
21#include <map>
22#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000023
24using namespace clang;
25
Douglas Gregor86d9a522009-09-21 16:56:56 +000026namespace {
27 /// \brief A container of code-completion results.
28 class ResultBuilder {
29 public:
30 /// \brief The type of a name-lookup filter, which can be provided to the
31 /// name-lookup routines to specify which declarations should be included in
32 /// the result set (when it returns true) and which declarations should be
33 /// filtered out (returns false).
34 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
35
36 typedef CodeCompleteConsumer::Result Result;
37
38 private:
39 /// \brief The actual results we have found.
40 std::vector<Result> Results;
41
42 /// \brief A record of all of the declarations we have found and placed
43 /// into the result set, used to ensure that no declaration ever gets into
44 /// the result set twice.
45 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
46
47 /// \brief A mapping from declaration names to the declarations that have
48 /// this name within a particular scope and their index within the list of
49 /// results.
50 typedef std::multimap<DeclarationName,
51 std::pair<NamedDecl *, unsigned> > ShadowMap;
52
53 /// \brief The semantic analysis object for which results are being
54 /// produced.
55 Sema &SemaRef;
56
57 /// \brief If non-NULL, a filter function used to remove any code-completion
58 /// results that are not desirable.
59 LookupFilter Filter;
60
61 /// \brief A list of shadow maps, which is used to model name hiding at
62 /// different levels of, e.g., the inheritance hierarchy.
63 std::list<ShadowMap> ShadowMaps;
64
65 public:
66 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
67 : SemaRef(SemaRef), Filter(Filter) { }
68
69 /// \brief Set the filter used for code-completion results.
70 void setFilter(LookupFilter Filter) {
71 this->Filter = Filter;
72 }
73
74 typedef std::vector<Result>::iterator iterator;
75 iterator begin() { return Results.begin(); }
76 iterator end() { return Results.end(); }
77
78 Result *data() { return Results.empty()? 0 : &Results.front(); }
79 unsigned size() const { return Results.size(); }
80 bool empty() const { return Results.empty(); }
81
82 /// \brief Add a new result to this result set (if it isn't already in one
83 /// of the shadow maps), or replace an existing result (for, e.g., a
84 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +000085 ///
86 /// \param R the result to add (if it is unique).
87 ///
88 /// \param R the context in which this result will be named.
89 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +000090
91 /// \brief Enter into a new scope.
92 void EnterNewScope();
93
94 /// \brief Exit from the current scope.
95 void ExitScope();
96
97 /// \name Name lookup predicates
98 ///
99 /// These predicates can be passed to the name lookup functions to filter the
100 /// results of name lookup. All of the predicates have the same type, so that
101 ///
102 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000103 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000104 bool IsNestedNameSpecifier(NamedDecl *ND) const;
105 bool IsEnum(NamedDecl *ND) const;
106 bool IsClassOrStruct(NamedDecl *ND) const;
107 bool IsUnion(NamedDecl *ND) const;
108 bool IsNamespace(NamedDecl *ND) const;
109 bool IsNamespaceOrAlias(NamedDecl *ND) const;
110 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000111 bool IsMember(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000112 //@}
113 };
114}
115
116/// \brief Determines whether the given hidden result could be found with
117/// some extra work, e.g., by qualifying the name.
118///
119/// \param Hidden the declaration that is hidden by the currenly \p Visible
120/// declaration.
121///
122/// \param Visible the declaration with the same name that is already visible.
123///
124/// \returns true if the hidden result can be found by some mechanism,
125/// false otherwise.
126static bool canHiddenResultBeFound(const LangOptions &LangOpts,
127 NamedDecl *Hidden, NamedDecl *Visible) {
128 // In C, there is no way to refer to a hidden name.
129 if (!LangOpts.CPlusPlus)
130 return false;
131
132 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
133
134 // There is no way to qualify a name declared in a function or method.
135 if (HiddenCtx->isFunctionOrMethod())
136 return false;
137
Douglas Gregor86d9a522009-09-21 16:56:56 +0000138 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
139}
140
Douglas Gregor456c4a12009-09-21 20:12:40 +0000141/// \brief Compute the qualification required to get from the current context
142/// (\p CurContext) to the target context (\p TargetContext).
143///
144/// \param Context the AST context in which the qualification will be used.
145///
146/// \param CurContext the context where an entity is being named, which is
147/// typically based on the current scope.
148///
149/// \param TargetContext the context in which the named entity actually
150/// resides.
151///
152/// \returns a nested name specifier that refers into the target context, or
153/// NULL if no qualification is needed.
154static NestedNameSpecifier *
155getRequiredQualification(ASTContext &Context,
156 DeclContext *CurContext,
157 DeclContext *TargetContext) {
158 llvm::SmallVector<DeclContext *, 4> TargetParents;
159
160 for (DeclContext *CommonAncestor = TargetContext;
161 CommonAncestor && !CommonAncestor->Encloses(CurContext);
162 CommonAncestor = CommonAncestor->getLookupParent()) {
163 if (CommonAncestor->isTransparentContext() ||
164 CommonAncestor->isFunctionOrMethod())
165 continue;
166
167 TargetParents.push_back(CommonAncestor);
168 }
169
170 NestedNameSpecifier *Result = 0;
171 while (!TargetParents.empty()) {
172 DeclContext *Parent = TargetParents.back();
173 TargetParents.pop_back();
174
175 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
176 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
177 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
178 Result = NestedNameSpecifier::Create(Context, Result,
179 false,
180 Context.getTypeDeclType(TD).getTypePtr());
181 else
182 assert(Parent->isTranslationUnit());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000183 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000184 return Result;
185}
186
187void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
Douglas Gregor8e0a0e42009-09-22 23:31:26 +0000188 assert(!ShadowMaps.empty() && "Must enter into a results scope");
189
Douglas Gregor86d9a522009-09-21 16:56:56 +0000190 if (R.Kind != Result::RK_Declaration) {
191 // For non-declaration results, just add the result.
192 Results.push_back(R);
193 return;
194 }
Douglas Gregorf52cede2009-10-09 22:16:47 +0000195
196 // Skip unnamed entities.
197 if (!R.Declaration->getDeclName())
198 return;
199
Douglas Gregor86d9a522009-09-21 16:56:56 +0000200 // Look through using declarations.
John McCall9488ea12009-11-17 05:59:44 +0000201 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration))
Douglas Gregor0563c262009-09-22 23:15:58 +0000202 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
203 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000204
205 // Handle each declaration in an overload set separately.
206 if (OverloadedFunctionDecl *Ovl
207 = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) {
208 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
209 FEnd = Ovl->function_end();
210 F != FEnd; ++F)
Douglas Gregor456c4a12009-09-21 20:12:40 +0000211 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000212
213 return;
214 }
215
216 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
217 unsigned IDNS = CanonDecl->getIdentifierNamespace();
218
219 // Friend declarations and declarations introduced due to friends are never
220 // added as results.
221 if (isa<FriendDecl>(CanonDecl) ||
222 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
223 return;
224
225 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
226 // __va_list_tag is a freak of nature. Find it and skip it.
227 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
228 return;
229
Douglas Gregorf52cede2009-10-09 22:16:47 +0000230 // Filter out names reserved for the implementation (C99 7.1.3,
231 // C++ [lib.global.names]). Users don't need to see those.
Daniel Dunbare013d682009-10-18 20:26:12 +0000232 //
233 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000234 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000235 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000236 if (Name[0] == '_' &&
237 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
238 return;
239 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000240 }
241
242 // C++ constructors are never found by name lookup.
243 if (isa<CXXConstructorDecl>(CanonDecl))
244 return;
245
246 // Filter out any unwanted results.
247 if (Filter && !(this->*Filter)(R.Declaration))
248 return;
249
250 ShadowMap &SMap = ShadowMaps.back();
251 ShadowMap::iterator I, IEnd;
252 for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
253 I != IEnd; ++I) {
254 NamedDecl *ND = I->second.first;
255 unsigned Index = I->second.second;
256 if (ND->getCanonicalDecl() == CanonDecl) {
257 // This is a redeclaration. Always pick the newer declaration.
258 I->second.first = R.Declaration;
259 Results[Index].Declaration = R.Declaration;
260
261 // Pick the best rank of the two.
262 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
263
264 // We're done.
265 return;
266 }
267 }
268
269 // This is a new declaration in this scope. However, check whether this
270 // declaration name is hidden by a similarly-named declaration in an outer
271 // scope.
272 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
273 --SMEnd;
274 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
275 for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
276 I != IEnd; ++I) {
277 // A tag declaration does not hide a non-tag declaration.
278 if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
279 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
280 Decl::IDNS_ObjCProtocol)))
281 continue;
282
283 // Protocols are in distinct namespaces from everything else.
284 if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
285 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
286 I->second.first->getIdentifierNamespace() != IDNS)
287 continue;
288
289 // The newly-added result is hidden by an entry in the shadow map.
290 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
291 I->second.first)) {
292 // Note that this result was hidden.
293 R.Hidden = true;
Douglas Gregor0563c262009-09-22 23:15:58 +0000294 R.QualifierIsInformative = false;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000295
296 if (!R.Qualifier)
297 R.Qualifier = getRequiredQualification(SemaRef.Context,
298 CurContext,
299 R.Declaration->getDeclContext());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000300 } else {
301 // This result was hidden and cannot be found; don't bother adding
302 // it.
303 return;
304 }
305
306 break;
307 }
308 }
309
310 // Make sure that any given declaration only shows up in the result set once.
311 if (!AllDeclsFound.insert(CanonDecl))
312 return;
313
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000314 // If the filter is for nested-name-specifiers, then this result starts a
315 // nested-name-specifier.
316 if ((Filter == &ResultBuilder::IsNestedNameSpecifier) ||
317 (Filter == &ResultBuilder::IsMember &&
318 isa<CXXRecordDecl>(R.Declaration) &&
319 cast<CXXRecordDecl>(R.Declaration)->isInjectedClassName()))
320 R.StartsNestedNameSpecifier = true;
321
Douglas Gregor0563c262009-09-22 23:15:58 +0000322 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000323 if (R.QualifierIsInformative && !R.Qualifier &&
324 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000325 DeclContext *Ctx = R.Declaration->getDeclContext();
326 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
327 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
328 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
329 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
330 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
331 else
332 R.QualifierIsInformative = false;
333 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000334
Douglas Gregor86d9a522009-09-21 16:56:56 +0000335 // Insert this result into the set of results and into the current shadow
336 // map.
337 SMap.insert(std::make_pair(R.Declaration->getDeclName(),
338 std::make_pair(R.Declaration, Results.size())));
339 Results.push_back(R);
340}
341
342/// \brief Enter into a new scope.
343void ResultBuilder::EnterNewScope() {
344 ShadowMaps.push_back(ShadowMap());
345}
346
347/// \brief Exit from the current scope.
348void ResultBuilder::ExitScope() {
349 ShadowMaps.pop_back();
350}
351
Douglas Gregor791215b2009-09-21 20:51:25 +0000352/// \brief Determines whether this given declaration will be found by
353/// ordinary name lookup.
354bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
355 unsigned IDNS = Decl::IDNS_Ordinary;
356 if (SemaRef.getLangOptions().CPlusPlus)
357 IDNS |= Decl::IDNS_Tag;
358
359 return ND->getIdentifierNamespace() & IDNS;
360}
361
Douglas Gregor86d9a522009-09-21 16:56:56 +0000362/// \brief Determines whether the given declaration is suitable as the
363/// start of a C++ nested-name-specifier, e.g., a class or namespace.
364bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
365 // Allow us to find class templates, too.
366 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
367 ND = ClassTemplate->getTemplatedDecl();
368
369 return SemaRef.isAcceptableNestedNameSpecifier(ND);
370}
371
372/// \brief Determines whether the given declaration is an enumeration.
373bool ResultBuilder::IsEnum(NamedDecl *ND) const {
374 return isa<EnumDecl>(ND);
375}
376
377/// \brief Determines whether the given declaration is a class or struct.
378bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
379 // Allow us to find class templates, too.
380 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
381 ND = ClassTemplate->getTemplatedDecl();
382
383 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
384 return RD->getTagKind() == TagDecl::TK_class ||
385 RD->getTagKind() == TagDecl::TK_struct;
386
387 return false;
388}
389
390/// \brief Determines whether the given declaration is a union.
391bool ResultBuilder::IsUnion(NamedDecl *ND) const {
392 // Allow us to find class templates, too.
393 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
394 ND = ClassTemplate->getTemplatedDecl();
395
396 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
397 return RD->getTagKind() == TagDecl::TK_union;
398
399 return false;
400}
401
402/// \brief Determines whether the given declaration is a namespace.
403bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
404 return isa<NamespaceDecl>(ND);
405}
406
407/// \brief Determines whether the given declaration is a namespace or
408/// namespace alias.
409bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
410 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
411}
412
413/// \brief Brief determines whether the given declaration is a namespace or
414/// namespace alias.
415bool ResultBuilder::IsType(NamedDecl *ND) const {
416 return isa<TypeDecl>(ND);
417}
418
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000419/// \brief Since every declaration found within a class is a member that we
420/// care about, always returns true. This predicate exists mostly to
421/// communicate to the result builder that we are performing a lookup for
422/// member access.
423bool ResultBuilder::IsMember(NamedDecl *ND) const {
424 return true;
425}
426
Douglas Gregor86d9a522009-09-21 16:56:56 +0000427// Find the next outer declaration context corresponding to this scope.
428static DeclContext *findOuterContext(Scope *S) {
429 for (S = S->getParent(); S; S = S->getParent())
430 if (S->getEntity())
431 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
432
433 return 0;
434}
435
436/// \brief Collect the results of searching for members within the given
437/// declaration context.
438///
439/// \param Ctx the declaration context from which we will gather results.
440///
Douglas Gregor0563c262009-09-22 23:15:58 +0000441/// \param Rank the rank given to results in this declaration context.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000442///
443/// \param Visited the set of declaration contexts that have already been
444/// visited. Declaration contexts will only be visited once.
445///
446/// \param Results the result set that will be extended with any results
447/// found within this declaration context (and, for a C++ class, its bases).
448///
Douglas Gregor0563c262009-09-22 23:15:58 +0000449/// \param InBaseClass whether we are in a base class.
450///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000451/// \returns the next higher rank value, after considering all of the
452/// names within this declaration context.
453static unsigned CollectMemberLookupResults(DeclContext *Ctx,
Douglas Gregor0563c262009-09-22 23:15:58 +0000454 unsigned Rank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000455 DeclContext *CurContext,
456 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor0563c262009-09-22 23:15:58 +0000457 ResultBuilder &Results,
458 bool InBaseClass = false) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000459 // Make sure we don't visit the same context twice.
460 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor0563c262009-09-22 23:15:58 +0000461 return Rank;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000462
463 // Enumerate all of the results in this context.
Douglas Gregor0563c262009-09-22 23:15:58 +0000464 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000465 Results.EnterNewScope();
466 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
467 CurCtx = CurCtx->getNextContext()) {
468 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregorff4393c2009-11-09 21:35:27 +0000469 DEnd = CurCtx->decls_end();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000470 D != DEnd; ++D) {
471 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor0563c262009-09-22 23:15:58 +0000472 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregorff4393c2009-11-09 21:35:27 +0000473
474 // Visit transparent contexts inside this context.
475 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
476 if (InnerCtx->isTransparentContext())
477 CollectMemberLookupResults(InnerCtx, Rank, CurContext, Visited,
478 Results, InBaseClass);
479 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000480 }
481 }
482
483 // Traverse the contexts of inherited classes.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000484 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
485 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
Douglas Gregorff4393c2009-11-09 21:35:27 +0000486 BEnd = Record->bases_end();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000487 B != BEnd; ++B) {
488 QualType BaseType = B->getType();
489
490 // Don't look into dependent bases, because name lookup can't look
491 // there anyway.
492 if (BaseType->isDependentType())
493 continue;
494
495 const RecordType *Record = BaseType->getAs<RecordType>();
496 if (!Record)
497 continue;
498
499 // FIXME: It would be nice to be able to determine whether referencing
500 // a particular member would be ambiguous. For example, given
501 //
502 // struct A { int member; };
503 // struct B { int member; };
504 // struct C : A, B { };
505 //
506 // void f(C *c) { c->### }
507 // accessing 'member' would result in an ambiguity. However, code
508 // completion could be smart enough to qualify the member with the
509 // base class, e.g.,
510 //
511 // c->B::member
512 //
513 // or
514 //
515 // c->A::member
516
517 // Collect results from this base class (and its bases).
Douglas Gregor0563c262009-09-22 23:15:58 +0000518 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
519 Results, /*InBaseClass=*/true);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000520 }
521 }
522
523 // FIXME: Look into base classes in Objective-C!
524
525 Results.ExitScope();
Douglas Gregor0563c262009-09-22 23:15:58 +0000526 return Rank + 1;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000527}
528
529/// \brief Collect the results of searching for members within the given
530/// declaration context.
531///
532/// \param Ctx the declaration context from which we will gather results.
533///
534/// \param InitialRank the initial rank given to results in this declaration
535/// context. Larger rank values will be used for, e.g., members found in
536/// base classes.
537///
538/// \param Results the result set that will be extended with any results
539/// found within this declaration context (and, for a C++ class, its bases).
540///
541/// \returns the next higher rank value, after considering all of the
542/// names within this declaration context.
543static unsigned CollectMemberLookupResults(DeclContext *Ctx,
544 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000545 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000546 ResultBuilder &Results) {
547 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000548 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
549 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000550}
551
552/// \brief Collect the results of searching for declarations within the given
553/// scope and its parent scopes.
554///
555/// \param S the scope in which we will start looking for declarations.
556///
557/// \param InitialRank the initial rank given to results in this scope.
558/// Larger rank values will be used for results found in parent scopes.
559///
Douglas Gregor456c4a12009-09-21 20:12:40 +0000560/// \param CurContext the context from which lookup results will be found.
561///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000562/// \param Results the builder object that will receive each result.
563static unsigned CollectLookupResults(Scope *S,
564 TranslationUnitDecl *TranslationUnit,
565 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000566 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000567 ResultBuilder &Results) {
568 if (!S)
569 return InitialRank;
570
571 // FIXME: Using directives!
572
573 unsigned NextRank = InitialRank;
574 Results.EnterNewScope();
575 if (S->getEntity() &&
576 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
577 // Look into this scope's declaration context, along with any of its
578 // parent lookup contexts (e.g., enclosing classes), up to the point
579 // where we hit the context stored in the next outer scope.
580 DeclContext *Ctx = (DeclContext *)S->getEntity();
581 DeclContext *OuterCtx = findOuterContext(S);
582
583 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
584 Ctx = Ctx->getLookupParent()) {
585 if (Ctx->isFunctionOrMethod())
586 continue;
587
Douglas Gregor456c4a12009-09-21 20:12:40 +0000588 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
589 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000590 }
591 } else if (!S->getParent()) {
592 // Look into the translation unit scope. We walk through the translation
593 // unit's declaration context, because the Scope itself won't have all of
594 // the declarations if we loaded a precompiled header.
595 // FIXME: We would like the translation unit's Scope object to point to the
596 // translation unit, so we don't need this special "if" branch. However,
597 // doing so would force the normal C++ name-lookup code to look into the
598 // translation unit decl when the IdentifierInfo chains would suffice.
599 // Once we fix that problem (which is part of a more general "don't look
600 // in DeclContexts unless we have to" optimization), we can eliminate the
601 // TranslationUnit parameter entirely.
602 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000603 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000604 } else {
605 // Walk through the declarations in this Scope.
606 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
607 D != DEnd; ++D) {
608 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
Douglas Gregor456c4a12009-09-21 20:12:40 +0000609 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
610 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000611 }
612
613 NextRank = NextRank + 1;
614 }
615
616 // Lookup names in the parent scope.
617 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000618 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000619 Results.ExitScope();
620
621 return NextRank;
622}
623
624/// \brief Add type specifiers for the current language as keyword results.
625static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
626 ResultBuilder &Results) {
627 typedef CodeCompleteConsumer::Result Result;
628 Results.MaybeAddResult(Result("short", Rank));
629 Results.MaybeAddResult(Result("long", Rank));
630 Results.MaybeAddResult(Result("signed", Rank));
631 Results.MaybeAddResult(Result("unsigned", Rank));
632 Results.MaybeAddResult(Result("void", Rank));
633 Results.MaybeAddResult(Result("char", Rank));
634 Results.MaybeAddResult(Result("int", Rank));
635 Results.MaybeAddResult(Result("float", Rank));
636 Results.MaybeAddResult(Result("double", Rank));
637 Results.MaybeAddResult(Result("enum", Rank));
638 Results.MaybeAddResult(Result("struct", Rank));
639 Results.MaybeAddResult(Result("union", Rank));
640
641 if (LangOpts.C99) {
642 // C99-specific
643 Results.MaybeAddResult(Result("_Complex", Rank));
644 Results.MaybeAddResult(Result("_Imaginary", Rank));
645 Results.MaybeAddResult(Result("_Bool", Rank));
646 }
647
648 if (LangOpts.CPlusPlus) {
649 // C++-specific
650 Results.MaybeAddResult(Result("bool", Rank));
651 Results.MaybeAddResult(Result("class", Rank));
652 Results.MaybeAddResult(Result("typename", Rank));
653 Results.MaybeAddResult(Result("wchar_t", Rank));
654
655 if (LangOpts.CPlusPlus0x) {
656 Results.MaybeAddResult(Result("char16_t", Rank));
657 Results.MaybeAddResult(Result("char32_t", Rank));
658 Results.MaybeAddResult(Result("decltype", Rank));
659 }
660 }
661
662 // GNU extensions
663 if (LangOpts.GNUMode) {
664 // FIXME: Enable when we actually support decimal floating point.
665 // Results.MaybeAddResult(Result("_Decimal32", Rank));
666 // Results.MaybeAddResult(Result("_Decimal64", Rank));
667 // Results.MaybeAddResult(Result("_Decimal128", Rank));
668 Results.MaybeAddResult(Result("typeof", Rank));
669 }
670}
671
672/// \brief Add function parameter chunks to the given code completion string.
673static void AddFunctionParameterChunks(ASTContext &Context,
674 FunctionDecl *Function,
675 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000676 typedef CodeCompletionString::Chunk Chunk;
677
Douglas Gregor86d9a522009-09-21 16:56:56 +0000678 CodeCompletionString *CCStr = Result;
679
680 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
681 ParmVarDecl *Param = Function->getParamDecl(P);
682
683 if (Param->hasDefaultArg()) {
684 // When we see an optional default argument, put that argument and
685 // the remaining default arguments into a new, optional string.
686 CodeCompletionString *Opt = new CodeCompletionString;
687 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
688 CCStr = Opt;
689 }
690
691 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000692 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000693
694 // Format the placeholder string.
695 std::string PlaceholderStr;
696 if (Param->getIdentifier())
697 PlaceholderStr = Param->getIdentifier()->getName();
698
699 Param->getType().getAsStringInternal(PlaceholderStr,
700 Context.PrintingPolicy);
701
702 // Add the placeholder string.
703 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
704 }
Douglas Gregorb3d45252009-09-22 21:42:17 +0000705
706 if (const FunctionProtoType *Proto
707 = Function->getType()->getAs<FunctionProtoType>())
708 if (Proto->isVariadic())
709 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000710}
711
712/// \brief Add template parameter chunks to the given code completion string.
713static void AddTemplateParameterChunks(ASTContext &Context,
714 TemplateDecl *Template,
715 CodeCompletionString *Result,
716 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000717 typedef CodeCompletionString::Chunk Chunk;
718
Douglas Gregor86d9a522009-09-21 16:56:56 +0000719 CodeCompletionString *CCStr = Result;
720 bool FirstParameter = true;
721
722 TemplateParameterList *Params = Template->getTemplateParameters();
723 TemplateParameterList::iterator PEnd = Params->end();
724 if (MaxParameters)
725 PEnd = Params->begin() + MaxParameters;
726 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
727 bool HasDefaultArg = false;
728 std::string PlaceholderStr;
729 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
730 if (TTP->wasDeclaredWithTypename())
731 PlaceholderStr = "typename";
732 else
733 PlaceholderStr = "class";
734
735 if (TTP->getIdentifier()) {
736 PlaceholderStr += ' ';
737 PlaceholderStr += TTP->getIdentifier()->getName();
738 }
739
740 HasDefaultArg = TTP->hasDefaultArgument();
741 } else if (NonTypeTemplateParmDecl *NTTP
742 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
743 if (NTTP->getIdentifier())
744 PlaceholderStr = NTTP->getIdentifier()->getName();
745 NTTP->getType().getAsStringInternal(PlaceholderStr,
746 Context.PrintingPolicy);
747 HasDefaultArg = NTTP->hasDefaultArgument();
748 } else {
749 assert(isa<TemplateTemplateParmDecl>(*P));
750 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
751
752 // Since putting the template argument list into the placeholder would
753 // be very, very long, we just use an abbreviation.
754 PlaceholderStr = "template<...> class";
755 if (TTP->getIdentifier()) {
756 PlaceholderStr += ' ';
757 PlaceholderStr += TTP->getIdentifier()->getName();
758 }
759
760 HasDefaultArg = TTP->hasDefaultArgument();
761 }
762
763 if (HasDefaultArg) {
764 // When we see an optional default argument, put that argument and
765 // the remaining default arguments into a new, optional string.
766 CodeCompletionString *Opt = new CodeCompletionString;
767 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
768 CCStr = Opt;
769 }
770
771 if (FirstParameter)
772 FirstParameter = false;
773 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000774 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000775
776 // Add the placeholder string.
777 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
778 }
779}
780
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000781/// \brief Add a qualifier to the given code-completion string, if the
782/// provided nested-name-specifier is non-NULL.
783void AddQualifierToCompletionString(CodeCompletionString *Result,
784 NestedNameSpecifier *Qualifier,
Douglas Gregor0563c262009-09-22 23:15:58 +0000785 bool QualifierIsInformative,
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000786 ASTContext &Context) {
787 if (!Qualifier)
788 return;
789
790 std::string PrintedNNS;
791 {
792 llvm::raw_string_ostream OS(PrintedNNS);
793 Qualifier->print(OS, Context.PrintingPolicy);
794 }
Douglas Gregor0563c262009-09-22 23:15:58 +0000795 if (QualifierIsInformative)
796 Result->AddInformativeChunk(PrintedNNS.c_str());
797 else
798 Result->AddTextChunk(PrintedNNS.c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000799}
800
Douglas Gregor86d9a522009-09-21 16:56:56 +0000801/// \brief If possible, create a new code completion string for the given
802/// result.
803///
804/// \returns Either a new, heap-allocated code completion string describing
805/// how to use this result, or NULL to indicate that the string or name of the
806/// result is all that is needed.
807CodeCompletionString *
808CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000809 typedef CodeCompletionString::Chunk Chunk;
810
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000811 if (Kind == RK_Keyword)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000812 return 0;
813
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000814 if (Kind == RK_Macro) {
815 MacroInfo *MI = S.PP.getMacroInfo(Macro);
816 if (!MI || !MI->isFunctionLike())
817 return 0;
818
819 // Format a function-like macro with placeholders for the arguments.
820 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000821 Result->AddTypedTextChunk(Macro->getName().str().c_str());
822 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000823 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
824 A != AEnd; ++A) {
825 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000826 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000827
828 if (!MI->isVariadic() || A != AEnd - 1) {
829 // Non-variadic argument.
830 Result->AddPlaceholderChunk((*A)->getName().str().c_str());
831 continue;
832 }
833
834 // Variadic argument; cope with the different between GNU and C99
835 // variadic macros, providing a single placeholder for the rest of the
836 // arguments.
837 if ((*A)->isStr("__VA_ARGS__"))
838 Result->AddPlaceholderChunk("...");
839 else {
840 std::string Arg = (*A)->getName();
841 Arg += "...";
842 Result->AddPlaceholderChunk(Arg.c_str());
843 }
844 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000845 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000846 return Result;
847 }
848
849 assert(Kind == RK_Declaration && "Missed a macro kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000850 NamedDecl *ND = Declaration;
851
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000852 if (StartsNestedNameSpecifier) {
853 CodeCompletionString *Result = new CodeCompletionString;
854 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
855 Result->AddTextChunk("::");
856 return Result;
857 }
858
Douglas Gregor86d9a522009-09-21 16:56:56 +0000859 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
860 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000861 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
862 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000863 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
864 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000865 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000866 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000867 return Result;
868 }
869
870 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
871 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000872 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
873 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000874 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000875 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000876
877 // Figure out which template parameters are deduced (or have default
878 // arguments).
879 llvm::SmallVector<bool, 16> Deduced;
880 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
881 unsigned LastDeducibleArgument;
882 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
883 --LastDeducibleArgument) {
884 if (!Deduced[LastDeducibleArgument - 1]) {
885 // C++0x: Figure out if the template argument has a default. If so,
886 // the user doesn't need to type this argument.
887 // FIXME: We need to abstract template parameters better!
888 bool HasDefaultArg = false;
889 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
890 LastDeducibleArgument - 1);
891 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
892 HasDefaultArg = TTP->hasDefaultArgument();
893 else if (NonTypeTemplateParmDecl *NTTP
894 = dyn_cast<NonTypeTemplateParmDecl>(Param))
895 HasDefaultArg = NTTP->hasDefaultArgument();
896 else {
897 assert(isa<TemplateTemplateParmDecl>(Param));
898 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000899 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000900 }
901
902 if (!HasDefaultArg)
903 break;
904 }
905 }
906
907 if (LastDeducibleArgument) {
908 // Some of the function template arguments cannot be deduced from a
909 // function call, so we introduce an explicit template argument list
910 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000911 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000912 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
913 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000914 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000915 }
916
917 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000918 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000919 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000920 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000921 return Result;
922 }
923
924 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
925 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000926 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
927 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000928 Result->AddTypedTextChunk(Template->getNameAsString().c_str());
929 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000930 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000931 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000932 return Result;
933 }
934
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000935 if (Qualifier) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000936 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000937 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
938 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000939 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000940 return Result;
941 }
942
Douglas Gregor86d9a522009-09-21 16:56:56 +0000943 return 0;
944}
945
Douglas Gregor86d802e2009-09-23 00:34:09 +0000946CodeCompletionString *
947CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
948 unsigned CurrentArg,
949 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000950 typedef CodeCompletionString::Chunk Chunk;
951
Douglas Gregor86d802e2009-09-23 00:34:09 +0000952 CodeCompletionString *Result = new CodeCompletionString;
953 FunctionDecl *FDecl = getFunction();
954 const FunctionProtoType *Proto
955 = dyn_cast<FunctionProtoType>(getFunctionType());
956 if (!FDecl && !Proto) {
957 // Function without a prototype. Just give the return type and a
958 // highlighted ellipsis.
959 const FunctionType *FT = getFunctionType();
960 Result->AddTextChunk(
961 FT->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000962 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
963 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
964 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +0000965 return Result;
966 }
967
968 if (FDecl)
969 Result->AddTextChunk(FDecl->getNameAsString().c_str());
970 else
971 Result->AddTextChunk(
972 Proto->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
973
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000974 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +0000975 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
976 for (unsigned I = 0; I != NumParams; ++I) {
977 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000978 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +0000979
980 std::string ArgString;
981 QualType ArgType;
982
983 if (FDecl) {
984 ArgString = FDecl->getParamDecl(I)->getNameAsString();
985 ArgType = FDecl->getParamDecl(I)->getOriginalType();
986 } else {
987 ArgType = Proto->getArgType(I);
988 }
989
990 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
991
992 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000993 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
994 ArgString.c_str()));
Douglas Gregor86d802e2009-09-23 00:34:09 +0000995 else
996 Result->AddTextChunk(ArgString.c_str());
997 }
998
999 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001000 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001001 if (CurrentArg < NumParams)
1002 Result->AddTextChunk("...");
1003 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001004 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001005 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001006 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001007
1008 return Result;
1009}
1010
Douglas Gregor86d9a522009-09-21 16:56:56 +00001011namespace {
1012 struct SortCodeCompleteResult {
1013 typedef CodeCompleteConsumer::Result Result;
1014
Douglas Gregor6a684032009-09-28 03:51:44 +00001015 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
1016 if (X.getNameKind() != Y.getNameKind())
1017 return X.getNameKind() < Y.getNameKind();
1018
1019 return llvm::LowercaseString(X.getAsString())
1020 < llvm::LowercaseString(Y.getAsString());
1021 }
1022
Douglas Gregor86d9a522009-09-21 16:56:56 +00001023 bool operator()(const Result &X, const Result &Y) const {
1024 // Sort first by rank.
1025 if (X.Rank < Y.Rank)
1026 return true;
1027 else if (X.Rank > Y.Rank)
1028 return false;
1029
1030 // Result kinds are ordered by decreasing importance.
1031 if (X.Kind < Y.Kind)
1032 return true;
1033 else if (X.Kind > Y.Kind)
1034 return false;
1035
1036 // Non-hidden names precede hidden names.
1037 if (X.Hidden != Y.Hidden)
1038 return !X.Hidden;
1039
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001040 // Non-nested-name-specifiers precede nested-name-specifiers.
1041 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1042 return !X.StartsNestedNameSpecifier;
1043
Douglas Gregor86d9a522009-09-21 16:56:56 +00001044 // Ordering depends on the kind of result.
1045 switch (X.Kind) {
1046 case Result::RK_Declaration:
1047 // Order based on the declaration names.
Douglas Gregor6a684032009-09-28 03:51:44 +00001048 return isEarlierDeclarationName(X.Declaration->getDeclName(),
1049 Y.Declaration->getDeclName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001050
1051 case Result::RK_Keyword:
Steve Naroff7f511122009-10-08 23:45:10 +00001052 return strcmp(X.Keyword, Y.Keyword) < 0;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001053
1054 case Result::RK_Macro:
1055 return llvm::LowercaseString(X.Macro->getName()) <
1056 llvm::LowercaseString(Y.Macro->getName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001057 }
1058
1059 // Silence GCC warning.
1060 return false;
1061 }
1062 };
1063}
1064
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001065static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1066 ResultBuilder &Results) {
1067 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001068 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1069 MEnd = PP.macro_end();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001070 M != MEnd; ++M)
1071 Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1072 Results.ExitScope();
1073}
1074
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001075static void HandleCodeCompleteResults(Sema *S,
1076 CodeCompleteConsumer *CodeCompleter,
1077 CodeCompleteConsumer::Result *Results,
1078 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00001079 // Sort the results by rank/kind/etc.
1080 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1081
1082 if (CodeCompleter)
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001083 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001084}
1085
Douglas Gregor791215b2009-09-21 20:51:25 +00001086void Sema::CodeCompleteOrdinaryName(Scope *S) {
1087 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001088 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1089 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001090 if (CodeCompleter->includeMacros())
1091 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001092 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00001093}
1094
Douglas Gregor81b747b2009-09-17 21:32:03 +00001095void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1096 SourceLocation OpLoc,
1097 bool IsArrow) {
1098 if (!BaseE || !CodeCompleter)
1099 return;
1100
Douglas Gregor86d9a522009-09-21 16:56:56 +00001101 typedef CodeCompleteConsumer::Result Result;
1102
Douglas Gregor81b747b2009-09-17 21:32:03 +00001103 Expr *Base = static_cast<Expr *>(BaseE);
1104 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001105
1106 if (IsArrow) {
1107 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1108 BaseType = Ptr->getPointeeType();
1109 else if (BaseType->isObjCObjectPointerType())
1110 /*Do nothing*/ ;
1111 else
1112 return;
1113 }
1114
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001115 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001116 unsigned NextRank = 0;
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001117
1118 // If this isn't a record type, we are done.
1119 const RecordType *Record = BaseType->getAs<RecordType>();
1120 if (!Record)
Douglas Gregor86d9a522009-09-21 16:56:56 +00001121 return;
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001122
1123 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1124 Record->getDecl(), Results);
1125
1126 if (getLangOptions().CPlusPlus) {
1127 if (!Results.empty()) {
1128 // The "template" keyword can follow "->" or "." in the grammar.
1129 // However, we only want to suggest the template keyword if something
1130 // is dependent.
1131 bool IsDependent = BaseType->isDependentType();
1132 if (!IsDependent) {
1133 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1134 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1135 IsDependent = Ctx->isDependentContext();
1136 break;
1137 }
1138 }
1139
1140 if (IsDependent)
1141 Results.MaybeAddResult(Result("template", NextRank++));
1142 }
1143
1144 // We could have the start of a nested-name-specifier. Add those
1145 // results as well.
1146 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1147 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
1148 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001149 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001150
1151 // Add macros
1152 if (CodeCompleter->includeMacros())
1153 AddMacroResults(PP, NextRank, Results);
1154
1155 // Hand off the results found for code completion.
1156 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001157}
1158
Douglas Gregor374929f2009-09-18 15:37:17 +00001159void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1160 if (!CodeCompleter)
1161 return;
1162
Douglas Gregor86d9a522009-09-21 16:56:56 +00001163 typedef CodeCompleteConsumer::Result Result;
1164 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +00001165 switch ((DeclSpec::TST)TagSpec) {
1166 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001167 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +00001168 break;
1169
1170 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001171 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +00001172 break;
1173
1174 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00001175 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001176 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00001177 break;
1178
1179 default:
1180 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1181 return;
1182 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001183
1184 ResultBuilder Results(*this, Filter);
1185 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001186 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001187
1188 if (getLangOptions().CPlusPlus) {
1189 // We could have the start of a nested-name-specifier. Add those
1190 // results as well.
1191 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001192 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1193 NextRank, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001194 }
1195
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001196 if (CodeCompleter->includeMacros())
1197 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001198 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00001199}
1200
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001201void Sema::CodeCompleteCase(Scope *S) {
1202 if (getSwitchStack().empty() || !CodeCompleter)
1203 return;
1204
1205 SwitchStmt *Switch = getSwitchStack().back();
1206 if (!Switch->getCond()->getType()->isEnumeralType())
1207 return;
1208
1209 // Code-complete the cases of a switch statement over an enumeration type
1210 // by providing the list of
1211 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1212
1213 // Determine which enumerators we have already seen in the switch statement.
1214 // FIXME: Ideally, we would also be able to look *past* the code-completion
1215 // token, in case we are code-completing in the middle of the switch and not
1216 // at the end. However, we aren't able to do so at the moment.
1217 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001218 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001219 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1220 SC = SC->getNextSwitchCase()) {
1221 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1222 if (!Case)
1223 continue;
1224
1225 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1226 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1227 if (EnumConstantDecl *Enumerator
1228 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1229 // We look into the AST of the case statement to determine which
1230 // enumerator was named. Alternatively, we could compute the value of
1231 // the integral constant expression, then compare it against the
1232 // values of each enumerator. However, value-based approach would not
1233 // work as well with C++ templates where enumerators declared within a
1234 // template are type- and value-dependent.
1235 EnumeratorsSeen.insert(Enumerator);
1236
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001237 // If this is a qualified-id, keep track of the nested-name-specifier
1238 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001239 //
1240 // switch (TagD.getKind()) {
1241 // case TagDecl::TK_enum:
1242 // break;
1243 // case XXX
1244 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001245 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001246 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1247 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00001248 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001249 }
1250 }
1251
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001252 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1253 // If there are no prior enumerators in C++, check whether we have to
1254 // qualify the names of the enumerators that we suggest, because they
1255 // may not be visible in this scope.
1256 Qualifier = getRequiredQualification(Context, CurContext,
1257 Enum->getDeclContext());
1258
1259 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1260 }
1261
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001262 // Add any enumerators that have not yet been mentioned.
1263 ResultBuilder Results(*this);
1264 Results.EnterNewScope();
1265 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1266 EEnd = Enum->enumerator_end();
1267 E != EEnd; ++E) {
1268 if (EnumeratorsSeen.count(*E))
1269 continue;
1270
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001271 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001272 }
1273 Results.ExitScope();
1274
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001275 if (CodeCompleter->includeMacros())
1276 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001277 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001278}
1279
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001280namespace {
1281 struct IsBetterOverloadCandidate {
1282 Sema &S;
1283
1284 public:
1285 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1286
1287 bool
1288 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1289 return S.isBetterOverloadCandidate(X, Y);
1290 }
1291 };
1292}
1293
1294void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1295 ExprTy **ArgsIn, unsigned NumArgs) {
1296 if (!CodeCompleter)
1297 return;
1298
1299 Expr *Fn = (Expr *)FnIn;
1300 Expr **Args = (Expr **)ArgsIn;
1301
1302 // Ignore type-dependent call expressions entirely.
1303 if (Fn->isTypeDependent() ||
1304 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1305 return;
1306
1307 NamedDecl *Function;
1308 DeclarationName UnqualifiedName;
1309 NestedNameSpecifier *Qualifier;
1310 SourceRange QualifierRange;
1311 bool ArgumentDependentLookup;
1312 bool HasExplicitTemplateArgs;
John McCall833ca992009-10-29 08:12:44 +00001313 const TemplateArgumentLoc *ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001314 unsigned NumExplicitTemplateArgs;
1315
1316 DeconstructCallFunction(Fn,
1317 Function, UnqualifiedName, Qualifier, QualifierRange,
1318 ArgumentDependentLookup, HasExplicitTemplateArgs,
1319 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1320
1321
1322 // FIXME: What if we're calling something that isn't a function declaration?
1323 // FIXME: What if we're calling a pseudo-destructor?
1324 // FIXME: What if we're calling a member function?
1325
1326 // Build an overload candidate set based on the functions we find.
1327 OverloadCandidateSet CandidateSet;
1328 AddOverloadedCallCandidates(Function, UnqualifiedName,
1329 ArgumentDependentLookup, HasExplicitTemplateArgs,
1330 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1331 Args, NumArgs,
1332 CandidateSet,
1333 /*PartialOverloading=*/true);
1334
1335 // Sort the overload candidate set by placing the best overloads first.
1336 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1337 IsBetterOverloadCandidate(*this));
1338
1339 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05944382009-09-23 00:16:58 +00001340 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1341 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlsson90756302009-09-22 17:29:51 +00001342
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001343 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1344 CandEnd = CandidateSet.end();
1345 Cand != CandEnd; ++Cand) {
1346 if (Cand->Viable)
Douglas Gregor05944382009-09-23 00:16:58 +00001347 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001348 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001349 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
Douglas Gregor05944382009-09-23 00:16:58 +00001350 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001351}
1352
Douglas Gregor81b747b2009-09-17 21:32:03 +00001353void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1354 bool EnteringContext) {
1355 if (!SS.getScopeRep() || !CodeCompleter)
1356 return;
1357
Douglas Gregor86d9a522009-09-21 16:56:56 +00001358 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1359 if (!Ctx)
1360 return;
1361
1362 ResultBuilder Results(*this);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001363 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001364
1365 // The "template" keyword can follow "::" in the grammar, but only
1366 // put it into the grammar if the nested-name-specifier is dependent.
1367 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1368 if (!Results.empty() && NNS->isDependent())
1369 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1370
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001371 if (CodeCompleter->includeMacros())
1372 AddMacroResults(PP, NextRank + 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001373 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001374}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001375
1376void Sema::CodeCompleteUsing(Scope *S) {
1377 if (!CodeCompleter)
1378 return;
1379
Douglas Gregor86d9a522009-09-21 16:56:56 +00001380 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001381 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001382
1383 // If we aren't in class scope, we could see the "namespace" keyword.
1384 if (!S->isClassScope())
1385 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1386
1387 // After "using", we can see anything that would start a
1388 // nested-name-specifier.
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001389 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1390 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001391 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001392
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001393 if (CodeCompleter->includeMacros())
1394 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001395 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001396}
1397
1398void Sema::CodeCompleteUsingDirective(Scope *S) {
1399 if (!CodeCompleter)
1400 return;
1401
Douglas Gregor86d9a522009-09-21 16:56:56 +00001402 // After "using namespace", we expect to see a namespace name or namespace
1403 // alias.
1404 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001405 Results.EnterNewScope();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001406 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1407 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001408 Results.ExitScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001409 if (CodeCompleter->includeMacros())
1410 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001411 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001412}
1413
1414void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1415 if (!CodeCompleter)
1416 return;
1417
Douglas Gregor86d9a522009-09-21 16:56:56 +00001418 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1419 DeclContext *Ctx = (DeclContext *)S->getEntity();
1420 if (!S->getParent())
1421 Ctx = Context.getTranslationUnitDecl();
1422
1423 if (Ctx && Ctx->isFileContext()) {
1424 // We only want to see those namespaces that have already been defined
1425 // within this scope, because its likely that the user is creating an
1426 // extended namespace declaration. Keep track of the most recent
1427 // definition of each namespace.
1428 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1429 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1430 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1431 NS != NSEnd; ++NS)
1432 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1433
1434 // Add the most recent definition (or extended definition) of each
1435 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001436 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001437 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1438 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1439 NS != NSEnd; ++NS)
Douglas Gregor456c4a12009-09-21 20:12:40 +00001440 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1441 CurContext);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001442 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001443 }
1444
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001445 if (CodeCompleter->includeMacros())
1446 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001447 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001448}
1449
1450void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1451 if (!CodeCompleter)
1452 return;
1453
Douglas Gregor86d9a522009-09-21 16:56:56 +00001454 // After "namespace", we expect to see a namespace or alias.
1455 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001456 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1457 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001458 if (CodeCompleter->includeMacros())
1459 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001460 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001461}
1462
Douglas Gregored8d3222009-09-18 20:05:18 +00001463void Sema::CodeCompleteOperatorName(Scope *S) {
1464 if (!CodeCompleter)
1465 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001466
1467 typedef CodeCompleteConsumer::Result Result;
1468 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001469 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00001470
Douglas Gregor86d9a522009-09-21 16:56:56 +00001471 // Add the names of overloadable operators.
1472#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1473 if (std::strcmp(Spelling, "?")) \
1474 Results.MaybeAddResult(Result(Spelling, 0));
1475#include "clang/Basic/OperatorKinds.def"
1476
1477 // Add any type names visible from the current scope
1478 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001479 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001480
1481 // Add any type specifiers
1482 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1483
1484 // Add any nested-name-specifiers
1485 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001486 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1487 NextRank + 1, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001488 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001489
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001490 if (CodeCompleter->includeMacros())
1491 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001492 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00001493}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001494
Steve Naroffece8e712009-10-08 21:55:05 +00001495void Sema::CodeCompleteObjCProperty(Scope *S, ObjCDeclSpec &ODS) {
1496 if (!CodeCompleter)
1497 return;
1498 unsigned Attributes = ODS.getPropertyAttributes();
1499
1500 typedef CodeCompleteConsumer::Result Result;
1501 ResultBuilder Results(*this);
1502 Results.EnterNewScope();
1503 if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly))
1504 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
1505 if (!(Attributes & ObjCDeclSpec::DQ_PR_assign))
1506 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
1507 if (!(Attributes & ObjCDeclSpec::DQ_PR_readwrite))
1508 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
1509 if (!(Attributes & ObjCDeclSpec::DQ_PR_retain))
1510 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
1511 if (!(Attributes & ObjCDeclSpec::DQ_PR_copy))
1512 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
1513 if (!(Attributes & ObjCDeclSpec::DQ_PR_nonatomic))
1514 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
1515 if (!(Attributes & ObjCDeclSpec::DQ_PR_setter))
1516 Results.MaybeAddResult(CodeCompleteConsumer::Result("setter", 0));
1517 if (!(Attributes & ObjCDeclSpec::DQ_PR_getter))
1518 Results.MaybeAddResult(CodeCompleteConsumer::Result("getter", 0));
1519 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001520 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00001521}
Steve Naroffc4df6d22009-11-07 02:08:14 +00001522
1523void Sema::CodeCompleteObjCFactoryMethod(Scope *S, IdentifierInfo *FName) {
1524 typedef CodeCompleteConsumer::Result Result;
1525 ResultBuilder Results(*this);
1526 Results.EnterNewScope();
1527
1528 ObjCInterfaceDecl *CDecl = getObjCInterfaceDecl(FName);
1529
1530 while (CDecl != NULL) {
1531 for (ObjCInterfaceDecl::classmeth_iterator I = CDecl->classmeth_begin(),
1532 E = CDecl->classmeth_end();
1533 I != E; ++I) {
1534 Results.MaybeAddResult(Result(*I, 0), CurContext);
1535 }
1536 // Add class methods in protocols.
1537 const ObjCList<ObjCProtocolDecl> &Protocols=CDecl->getReferencedProtocols();
1538 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1539 E = Protocols.end(); I != E; ++I) {
1540 for (ObjCProtocolDecl::classmeth_iterator I2 = (*I)->classmeth_begin(),
1541 E2 = (*I)->classmeth_end();
1542 I2 != E2; ++I2) {
1543 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1544 }
1545 }
1546 // Add class methods in categories.
1547 ObjCCategoryDecl *CatDecl = CDecl->getCategoryList();
1548 while (CatDecl) {
1549 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
1550 E = CatDecl->classmeth_end();
1551 I != E; ++I) {
1552 Results.MaybeAddResult(Result(*I, 0), CurContext);
1553 }
1554 // Add a categories protocol methods.
1555 const ObjCList<ObjCProtocolDecl> &Protocols =
1556 CatDecl->getReferencedProtocols();
1557 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1558 E = Protocols.end(); I != E; ++I) {
1559 for (ObjCProtocolDecl::classmeth_iterator I2 = (*I)->classmeth_begin(),
1560 E2 = (*I)->classmeth_end();
1561 I2 != E2; ++I2) {
1562 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1563 }
1564 }
1565 CatDecl = CatDecl->getNextClassCategory();
1566 }
1567 CDecl = CDecl->getSuperClass();
1568 }
1569 Results.ExitScope();
1570 // This also suppresses remaining diagnostics.
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001571 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00001572}
1573
1574void Sema::CodeCompleteObjCInstanceMethod(Scope *S, ExprTy *Receiver) {
1575 typedef CodeCompleteConsumer::Result Result;
1576 ResultBuilder Results(*this);
1577 Results.EnterNewScope();
1578
1579 Expr *RecExpr = static_cast<Expr *>(Receiver);
1580 QualType RecType = RecExpr->getType();
1581
1582 const ObjCObjectPointerType* OCOPT = RecType->getAs<ObjCObjectPointerType>();
1583
1584 if (!OCOPT)
1585 return;
1586
1587 // FIXME: handle 'id', 'Class', and qualified types.
1588 ObjCInterfaceDecl *CDecl = OCOPT->getInterfaceDecl();
1589
1590 while (CDecl != NULL) {
1591 for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1592 E = CDecl->instmeth_end();
1593 I != E; ++I) {
1594 Results.MaybeAddResult(Result(*I, 0), CurContext);
1595 }
1596 // Add class methods in protocols.
1597 const ObjCList<ObjCProtocolDecl> &Protocols=CDecl->getReferencedProtocols();
1598 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1599 E = Protocols.end(); I != E; ++I) {
1600 for (ObjCProtocolDecl::instmeth_iterator I2 = (*I)->instmeth_begin(),
1601 E2 = (*I)->instmeth_end();
1602 I2 != E2; ++I2) {
1603 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1604 }
1605 }
1606 // Add class methods in categories.
1607 ObjCCategoryDecl *CatDecl = CDecl->getCategoryList();
1608 while (CatDecl) {
1609 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
1610 E = CatDecl->instmeth_end();
1611 I != E; ++I) {
1612 Results.MaybeAddResult(Result(*I, 0), CurContext);
1613 }
1614 // Add a categories protocol methods.
1615 const ObjCList<ObjCProtocolDecl> &Protocols =
1616 CatDecl->getReferencedProtocols();
1617 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1618 E = Protocols.end(); I != E; ++I) {
1619 for (ObjCProtocolDecl::instmeth_iterator I2 = (*I)->instmeth_begin(),
1620 E2 = (*I)->instmeth_end();
1621 I2 != E2; ++I2) {
1622 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1623 }
1624 }
1625 CatDecl = CatDecl->getNextClassCategory();
1626 }
1627 CDecl = CDecl->getSuperClass();
1628 }
1629 Results.ExitScope();
1630 // This also suppresses remaining diagnostics.
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001631 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00001632}