blob: e2aac775077e88c21a4a7924c4b1dc1001a207ab [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 Gregorf329c7c2009-10-30 16:50:04 +000016#include "clang/Lex/MacroInfo.h"
17#include "clang/Lex/Preprocessor.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000018#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore6688e62009-09-28 03:51:44 +000019#include "llvm/ADT/StringExtras.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000020#include <list>
21#include <map>
22#include <vector>
Douglas Gregor2436e712009-09-17 21:32:03 +000023
24using namespace clang;
25
Douglas Gregor3545ff42009-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 Gregor2af2f672009-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 Gregor3545ff42009-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 Gregor9d64c5e2009-09-21 20:51:25 +0000103 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor3545ff42009-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 Gregore412a5a2009-09-23 22:26:46 +0000111 bool IsMember(NamedDecl *ND) const;
Douglas Gregor3545ff42009-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 Gregor3545ff42009-09-21 16:56:56 +0000138 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
139}
140
Douglas Gregor2af2f672009-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 Gregor9eb77012009-11-07 00:00:49 +0000183 }
Douglas Gregor2af2f672009-09-21 20:12:40 +0000184 return Result;
185}
186
187void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
Douglas Gregor64b12b52009-09-22 23:31:26 +0000188 assert(!ShadowMaps.empty() && "Must enter into a results scope");
189
Douglas Gregor3545ff42009-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 Gregor58acf322009-10-09 22:16:47 +0000195
196 // Skip unnamed entities.
197 if (!R.Declaration->getDeclName())
198 return;
199
Douglas Gregor3545ff42009-09-21 16:56:56 +0000200 // Look through using declarations.
John McCall3f746822009-11-17 05:59:44 +0000201 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration))
Douglas Gregor5bf52692009-09-22 23:15:58 +0000202 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
203 CurContext);
Douglas Gregor3545ff42009-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 Gregor2af2f672009-09-21 20:12:40 +0000211 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
Douglas Gregor3545ff42009-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 Gregor58acf322009-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 Dunbar2c422dc92009-10-18 20:26:12 +0000232 //
233 // FIXME: Add predicate for this.
Douglas Gregor58acf322009-10-09 22:16:47 +0000234 if (Id->getLength() >= 2) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +0000235 const char *Name = Id->getNameStart();
Douglas Gregor58acf322009-10-09 22:16:47 +0000236 if (Name[0] == '_' &&
237 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
238 return;
239 }
Douglas Gregor3545ff42009-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 Gregor5bf52692009-09-22 23:15:58 +0000294 R.QualifierIsInformative = false;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000295
296 if (!R.Qualifier)
297 R.Qualifier = getRequiredQualification(SemaRef.Context,
298 CurContext,
299 R.Declaration->getDeclContext());
Douglas Gregor3545ff42009-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 Gregore412a5a2009-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 Gregor5bf52692009-09-22 23:15:58 +0000322 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000323 if (R.QualifierIsInformative && !R.Qualifier &&
324 !R.StartsNestedNameSpecifier) {
Douglas Gregor5bf52692009-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 Gregore412a5a2009-09-23 22:26:46 +0000334
Douglas Gregor3545ff42009-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 Gregor9d64c5e2009-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 Gregor3545ff42009-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 Gregore412a5a2009-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 Gregor3545ff42009-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 Gregor5bf52692009-09-22 23:15:58 +0000441/// \param Rank the rank given to results in this declaration context.
Douglas Gregor3545ff42009-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 Gregor5bf52692009-09-22 23:15:58 +0000449/// \param InBaseClass whether we are in a base class.
450///
Douglas Gregor3545ff42009-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 Gregor5bf52692009-09-22 23:15:58 +0000454 unsigned Rank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000455 DeclContext *CurContext,
456 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor5bf52692009-09-22 23:15:58 +0000457 ResultBuilder &Results,
458 bool InBaseClass = false) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000459 // Make sure we don't visit the same context twice.
460 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor5bf52692009-09-22 23:15:58 +0000461 return Rank;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000462
463 // Enumerate all of the results in this context.
Douglas Gregor5bf52692009-09-22 23:15:58 +0000464 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor3545ff42009-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 Gregor8caea942009-11-09 21:35:27 +0000469 DEnd = CurCtx->decls_end();
Douglas Gregor3545ff42009-09-21 16:56:56 +0000470 D != DEnd; ++D) {
471 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor5bf52692009-09-22 23:15:58 +0000472 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregor8caea942009-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 Gregor3545ff42009-09-21 16:56:56 +0000480 }
481 }
482
483 // Traverse the contexts of inherited classes.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000484 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
485 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
Douglas Gregor8caea942009-11-09 21:35:27 +0000486 BEnd = Record->bases_end();
Douglas Gregor3545ff42009-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 Gregor5bf52692009-09-22 23:15:58 +0000518 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
519 Results, /*InBaseClass=*/true);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000520 }
521 }
522
523 // FIXME: Look into base classes in Objective-C!
524
525 Results.ExitScope();
Douglas Gregor5bf52692009-09-22 23:15:58 +0000526 return Rank + 1;
Douglas Gregor3545ff42009-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 Gregor2af2f672009-09-21 20:12:40 +0000545 DeclContext *CurContext,
Douglas Gregor3545ff42009-09-21 16:56:56 +0000546 ResultBuilder &Results) {
547 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000548 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
549 Results);
Douglas Gregor3545ff42009-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 Gregor2af2f672009-09-21 20:12:40 +0000560/// \param CurContext the context from which lookup results will be found.
561///
Douglas Gregor3545ff42009-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 Gregor2af2f672009-09-21 20:12:40 +0000566 DeclContext *CurContext,
Douglas Gregor3545ff42009-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 Gregor2af2f672009-09-21 20:12:40 +0000588 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
589 Results);
Douglas Gregor3545ff42009-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 Gregor2af2f672009-09-21 20:12:40 +0000603 CurContext, Results);
Douglas Gregor3545ff42009-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 Gregor2af2f672009-09-21 20:12:40 +0000609 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
610 CurContext);
Douglas Gregor3545ff42009-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 Gregor2af2f672009-09-21 20:12:40 +0000618 CurContext, Results);
Douglas Gregor3545ff42009-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 Gregor9eb77012009-11-07 00:00:49 +0000676 typedef CodeCompletionString::Chunk Chunk;
677
Douglas Gregor3545ff42009-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 Gregor9eb77012009-11-07 00:00:49 +0000692 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-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 Gregorba449032009-09-22 21:42:17 +0000705
706 if (const FunctionProtoType *Proto
707 = Function->getType()->getAs<FunctionProtoType>())
708 if (Proto->isVariadic())
709 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor3545ff42009-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 Gregor9eb77012009-11-07 00:00:49 +0000717 typedef CodeCompletionString::Chunk Chunk;
718
Douglas Gregor3545ff42009-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 Gregor9eb77012009-11-07 00:00:49 +0000774 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000775
776 // Add the placeholder string.
777 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
778 }
779}
780
Douglas Gregorf2510672009-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 Gregor5bf52692009-09-22 23:15:58 +0000785 bool QualifierIsInformative,
Douglas Gregorf2510672009-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 Gregor5bf52692009-09-22 23:15:58 +0000795 if (QualifierIsInformative)
796 Result->AddInformativeChunk(PrintedNNS.c_str());
797 else
798 Result->AddTextChunk(PrintedNNS.c_str());
Douglas Gregorf2510672009-09-21 19:57:38 +0000799}
800
Douglas Gregor3545ff42009-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 Gregor9eb77012009-11-07 00:00:49 +0000809 typedef CodeCompletionString::Chunk Chunk;
810
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000811 if (Kind == RK_Keyword)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000812 return 0;
813
Douglas Gregorf329c7c2009-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 Gregor9eb77012009-11-07 00:00:49 +0000821 Result->AddTypedTextChunk(Macro->getName().str().c_str());
822 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf329c7c2009-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 Gregor9eb77012009-11-07 00:00:49 +0000826 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf329c7c2009-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 Gregor9eb77012009-11-07 00:00:49 +0000845 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000846 return Result;
847 }
848
849 assert(Kind == RK_Declaration && "Missed a macro kind?");
Douglas Gregor3545ff42009-09-21 16:56:56 +0000850 NamedDecl *ND = Declaration;
851
Douglas Gregor9eb77012009-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 Gregor3545ff42009-09-21 16:56:56 +0000859 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
860 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000861 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
862 S.Context);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000863 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
864 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000865 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000866 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000867 return Result;
868 }
869
870 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
871 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000872 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
873 S.Context);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000874 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor9eb77012009-11-07 00:00:49 +0000875 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
Douglas Gregor3545ff42009-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 Gregor9eb77012009-11-07 00:00:49 +0000899 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-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 Gregor9eb77012009-11-07 00:00:49 +0000911 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000912 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
913 LastDeducibleArgument);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000914 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000915 }
916
917 // Add the function parameters
Douglas Gregor9eb77012009-11-07 00:00:49 +0000918 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000919 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000920 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000921 return Result;
922 }
923
924 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
925 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000926 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
927 S.Context);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000928 Result->AddTypedTextChunk(Template->getNameAsString().c_str());
929 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000930 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000931 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000932 return Result;
933 }
934
Douglas Gregord3c5d792009-11-17 16:44:22 +0000935 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
936 CodeCompletionString *Result = new CodeCompletionString;
937 Selector Sel = Method->getSelector();
938 if (Sel.isUnarySelector()) {
939 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
940 return Result;
941 }
942
943 Result->AddTypedTextChunk(
944 Sel.getIdentifierInfoForSlot(0)->getName().str() + std::string(":"));
945 unsigned Idx = 0;
946 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
947 PEnd = Method->param_end();
948 P != PEnd; (void)++P, ++Idx) {
949 if (Idx > 0) {
950 std::string Keyword = " ";
951 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
952 Keyword += II->getName().str();
953 Keyword += ":";
954 Result->AddTextChunk(Keyword);
955 }
956
957 std::string Arg;
958 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
959 Arg = "(" + Arg + ")";
960 if (IdentifierInfo *II = (*P)->getIdentifier())
961 Arg += II->getName().str();
962 Result->AddPlaceholderChunk(Arg);
963 }
964
965 return Result;
966 }
967
Douglas Gregor9eb77012009-11-07 00:00:49 +0000968 if (Qualifier) {
Douglas Gregorf2510672009-09-21 19:57:38 +0000969 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000970 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
971 S.Context);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000972 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
Douglas Gregorf2510672009-09-21 19:57:38 +0000973 return Result;
974 }
975
Douglas Gregor3545ff42009-09-21 16:56:56 +0000976 return 0;
977}
978
Douglas Gregorf0f51982009-09-23 00:34:09 +0000979CodeCompletionString *
980CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
981 unsigned CurrentArg,
982 Sema &S) const {
Douglas Gregor9eb77012009-11-07 00:00:49 +0000983 typedef CodeCompletionString::Chunk Chunk;
984
Douglas Gregorf0f51982009-09-23 00:34:09 +0000985 CodeCompletionString *Result = new CodeCompletionString;
986 FunctionDecl *FDecl = getFunction();
987 const FunctionProtoType *Proto
988 = dyn_cast<FunctionProtoType>(getFunctionType());
989 if (!FDecl && !Proto) {
990 // Function without a prototype. Just give the return type and a
991 // highlighted ellipsis.
992 const FunctionType *FT = getFunctionType();
993 Result->AddTextChunk(
994 FT->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
Douglas Gregor9eb77012009-11-07 00:00:49 +0000995 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
996 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
997 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +0000998 return Result;
999 }
1000
1001 if (FDecl)
1002 Result->AddTextChunk(FDecl->getNameAsString().c_str());
1003 else
1004 Result->AddTextChunk(
1005 Proto->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
1006
Douglas Gregor9eb77012009-11-07 00:00:49 +00001007 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001008 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
1009 for (unsigned I = 0; I != NumParams; ++I) {
1010 if (I)
Douglas Gregor9eb77012009-11-07 00:00:49 +00001011 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001012
1013 std::string ArgString;
1014 QualType ArgType;
1015
1016 if (FDecl) {
1017 ArgString = FDecl->getParamDecl(I)->getNameAsString();
1018 ArgType = FDecl->getParamDecl(I)->getOriginalType();
1019 } else {
1020 ArgType = Proto->getArgType(I);
1021 }
1022
1023 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
1024
1025 if (I == CurrentArg)
Douglas Gregor9eb77012009-11-07 00:00:49 +00001026 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
1027 ArgString.c_str()));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001028 else
1029 Result->AddTextChunk(ArgString.c_str());
1030 }
1031
1032 if (Proto && Proto->isVariadic()) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001033 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001034 if (CurrentArg < NumParams)
1035 Result->AddTextChunk("...");
1036 else
Douglas Gregor9eb77012009-11-07 00:00:49 +00001037 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001038 }
Douglas Gregor9eb77012009-11-07 00:00:49 +00001039 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001040
1041 return Result;
1042}
1043
Douglas Gregor3545ff42009-09-21 16:56:56 +00001044namespace {
1045 struct SortCodeCompleteResult {
1046 typedef CodeCompleteConsumer::Result Result;
1047
Douglas Gregore6688e62009-09-28 03:51:44 +00001048 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
1049 if (X.getNameKind() != Y.getNameKind())
1050 return X.getNameKind() < Y.getNameKind();
1051
1052 return llvm::LowercaseString(X.getAsString())
1053 < llvm::LowercaseString(Y.getAsString());
1054 }
1055
Douglas Gregor3545ff42009-09-21 16:56:56 +00001056 bool operator()(const Result &X, const Result &Y) const {
1057 // Sort first by rank.
1058 if (X.Rank < Y.Rank)
1059 return true;
1060 else if (X.Rank > Y.Rank)
1061 return false;
1062
1063 // Result kinds are ordered by decreasing importance.
1064 if (X.Kind < Y.Kind)
1065 return true;
1066 else if (X.Kind > Y.Kind)
1067 return false;
1068
1069 // Non-hidden names precede hidden names.
1070 if (X.Hidden != Y.Hidden)
1071 return !X.Hidden;
1072
Douglas Gregore412a5a2009-09-23 22:26:46 +00001073 // Non-nested-name-specifiers precede nested-name-specifiers.
1074 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1075 return !X.StartsNestedNameSpecifier;
1076
Douglas Gregor3545ff42009-09-21 16:56:56 +00001077 // Ordering depends on the kind of result.
1078 switch (X.Kind) {
1079 case Result::RK_Declaration:
1080 // Order based on the declaration names.
Douglas Gregore6688e62009-09-28 03:51:44 +00001081 return isEarlierDeclarationName(X.Declaration->getDeclName(),
1082 Y.Declaration->getDeclName());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001083
1084 case Result::RK_Keyword:
Steve Naroff3b086302009-10-08 23:45:10 +00001085 return strcmp(X.Keyword, Y.Keyword) < 0;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001086
1087 case Result::RK_Macro:
1088 return llvm::LowercaseString(X.Macro->getName()) <
1089 llvm::LowercaseString(Y.Macro->getName());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001090 }
1091
1092 // Silence GCC warning.
1093 return false;
1094 }
1095 };
1096}
1097
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001098static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1099 ResultBuilder &Results) {
1100 Results.EnterNewScope();
Douglas Gregor9eb77012009-11-07 00:00:49 +00001101 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1102 MEnd = PP.macro_end();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001103 M != MEnd; ++M)
1104 Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1105 Results.ExitScope();
1106}
1107
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001108static void HandleCodeCompleteResults(Sema *S,
1109 CodeCompleteConsumer *CodeCompleter,
1110 CodeCompleteConsumer::Result *Results,
1111 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001112 // Sort the results by rank/kind/etc.
1113 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1114
1115 if (CodeCompleter)
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001116 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001117}
1118
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001119void Sema::CodeCompleteOrdinaryName(Scope *S) {
1120 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001121 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1122 0, CurContext, Results);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001123 if (CodeCompleter->includeMacros())
1124 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001125 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001126}
1127
Douglas Gregor2436e712009-09-17 21:32:03 +00001128void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1129 SourceLocation OpLoc,
1130 bool IsArrow) {
1131 if (!BaseE || !CodeCompleter)
1132 return;
1133
Douglas Gregor3545ff42009-09-21 16:56:56 +00001134 typedef CodeCompleteConsumer::Result Result;
1135
Douglas Gregor2436e712009-09-17 21:32:03 +00001136 Expr *Base = static_cast<Expr *>(BaseE);
1137 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001138
1139 if (IsArrow) {
1140 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1141 BaseType = Ptr->getPointeeType();
1142 else if (BaseType->isObjCObjectPointerType())
1143 /*Do nothing*/ ;
1144 else
1145 return;
1146 }
1147
Douglas Gregore412a5a2009-09-23 22:26:46 +00001148 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001149 unsigned NextRank = 0;
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001150
1151 // If this isn't a record type, we are done.
1152 const RecordType *Record = BaseType->getAs<RecordType>();
1153 if (!Record)
Douglas Gregor3545ff42009-09-21 16:56:56 +00001154 return;
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001155
1156 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1157 Record->getDecl(), Results);
1158
1159 if (getLangOptions().CPlusPlus) {
1160 if (!Results.empty()) {
1161 // The "template" keyword can follow "->" or "." in the grammar.
1162 // However, we only want to suggest the template keyword if something
1163 // is dependent.
1164 bool IsDependent = BaseType->isDependentType();
1165 if (!IsDependent) {
1166 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1167 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1168 IsDependent = Ctx->isDependentContext();
1169 break;
1170 }
1171 }
1172
1173 if (IsDependent)
1174 Results.MaybeAddResult(Result("template", NextRank++));
1175 }
1176
1177 // We could have the start of a nested-name-specifier. Add those
1178 // results as well.
1179 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1180 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
1181 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001182 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001183
1184 // Add macros
1185 if (CodeCompleter->includeMacros())
1186 AddMacroResults(PP, NextRank, Results);
1187
1188 // Hand off the results found for code completion.
1189 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00001190}
1191
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001192void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1193 if (!CodeCompleter)
1194 return;
1195
Douglas Gregor3545ff42009-09-21 16:56:56 +00001196 typedef CodeCompleteConsumer::Result Result;
1197 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001198 switch ((DeclSpec::TST)TagSpec) {
1199 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00001200 Filter = &ResultBuilder::IsEnum;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001201 break;
1202
1203 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00001204 Filter = &ResultBuilder::IsUnion;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001205 break;
1206
1207 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001208 case DeclSpec::TST_class:
Douglas Gregor3545ff42009-09-21 16:56:56 +00001209 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001210 break;
1211
1212 default:
1213 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1214 return;
1215 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001216
1217 ResultBuilder Results(*this, Filter);
1218 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor2af2f672009-09-21 20:12:40 +00001219 0, CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001220
1221 if (getLangOptions().CPlusPlus) {
1222 // We could have the start of a nested-name-specifier. Add those
1223 // results as well.
1224 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001225 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1226 NextRank, CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001227 }
1228
Douglas Gregor9eb77012009-11-07 00:00:49 +00001229 if (CodeCompleter->includeMacros())
1230 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001231 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001232}
1233
Douglas Gregord328d572009-09-21 18:10:23 +00001234void Sema::CodeCompleteCase(Scope *S) {
1235 if (getSwitchStack().empty() || !CodeCompleter)
1236 return;
1237
1238 SwitchStmt *Switch = getSwitchStack().back();
1239 if (!Switch->getCond()->getType()->isEnumeralType())
1240 return;
1241
1242 // Code-complete the cases of a switch statement over an enumeration type
1243 // by providing the list of
1244 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1245
1246 // Determine which enumerators we have already seen in the switch statement.
1247 // FIXME: Ideally, we would also be able to look *past* the code-completion
1248 // token, in case we are code-completing in the middle of the switch and not
1249 // at the end. However, we aren't able to do so at the moment.
1250 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorf2510672009-09-21 19:57:38 +00001251 NestedNameSpecifier *Qualifier = 0;
Douglas Gregord328d572009-09-21 18:10:23 +00001252 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1253 SC = SC->getNextSwitchCase()) {
1254 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1255 if (!Case)
1256 continue;
1257
1258 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1259 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1260 if (EnumConstantDecl *Enumerator
1261 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1262 // We look into the AST of the case statement to determine which
1263 // enumerator was named. Alternatively, we could compute the value of
1264 // the integral constant expression, then compare it against the
1265 // values of each enumerator. However, value-based approach would not
1266 // work as well with C++ templates where enumerators declared within a
1267 // template are type- and value-dependent.
1268 EnumeratorsSeen.insert(Enumerator);
1269
Douglas Gregorf2510672009-09-21 19:57:38 +00001270 // If this is a qualified-id, keep track of the nested-name-specifier
1271 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00001272 //
1273 // switch (TagD.getKind()) {
1274 // case TagDecl::TK_enum:
1275 // break;
1276 // case XXX
1277 //
Douglas Gregorf2510672009-09-21 19:57:38 +00001278 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00001279 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1280 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00001281 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00001282 }
1283 }
1284
Douglas Gregorf2510672009-09-21 19:57:38 +00001285 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1286 // If there are no prior enumerators in C++, check whether we have to
1287 // qualify the names of the enumerators that we suggest, because they
1288 // may not be visible in this scope.
1289 Qualifier = getRequiredQualification(Context, CurContext,
1290 Enum->getDeclContext());
1291
1292 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1293 }
1294
Douglas Gregord328d572009-09-21 18:10:23 +00001295 // Add any enumerators that have not yet been mentioned.
1296 ResultBuilder Results(*this);
1297 Results.EnterNewScope();
1298 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1299 EEnd = Enum->enumerator_end();
1300 E != EEnd; ++E) {
1301 if (EnumeratorsSeen.count(*E))
1302 continue;
1303
Douglas Gregorf2510672009-09-21 19:57:38 +00001304 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregord328d572009-09-21 18:10:23 +00001305 }
1306 Results.ExitScope();
1307
Douglas Gregor9eb77012009-11-07 00:00:49 +00001308 if (CodeCompleter->includeMacros())
1309 AddMacroResults(PP, 1, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001310 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00001311}
1312
Douglas Gregorcabea402009-09-22 15:41:20 +00001313namespace {
1314 struct IsBetterOverloadCandidate {
1315 Sema &S;
1316
1317 public:
1318 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1319
1320 bool
1321 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1322 return S.isBetterOverloadCandidate(X, Y);
1323 }
1324 };
1325}
1326
1327void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1328 ExprTy **ArgsIn, unsigned NumArgs) {
1329 if (!CodeCompleter)
1330 return;
1331
1332 Expr *Fn = (Expr *)FnIn;
1333 Expr **Args = (Expr **)ArgsIn;
1334
1335 // Ignore type-dependent call expressions entirely.
1336 if (Fn->isTypeDependent() ||
1337 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1338 return;
1339
1340 NamedDecl *Function;
1341 DeclarationName UnqualifiedName;
1342 NestedNameSpecifier *Qualifier;
1343 SourceRange QualifierRange;
1344 bool ArgumentDependentLookup;
1345 bool HasExplicitTemplateArgs;
John McCall0ad16662009-10-29 08:12:44 +00001346 const TemplateArgumentLoc *ExplicitTemplateArgs;
Douglas Gregorcabea402009-09-22 15:41:20 +00001347 unsigned NumExplicitTemplateArgs;
1348
1349 DeconstructCallFunction(Fn,
1350 Function, UnqualifiedName, Qualifier, QualifierRange,
1351 ArgumentDependentLookup, HasExplicitTemplateArgs,
1352 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1353
1354
1355 // FIXME: What if we're calling something that isn't a function declaration?
1356 // FIXME: What if we're calling a pseudo-destructor?
1357 // FIXME: What if we're calling a member function?
1358
1359 // Build an overload candidate set based on the functions we find.
1360 OverloadCandidateSet CandidateSet;
1361 AddOverloadedCallCandidates(Function, UnqualifiedName,
1362 ArgumentDependentLookup, HasExplicitTemplateArgs,
1363 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1364 Args, NumArgs,
1365 CandidateSet,
1366 /*PartialOverloading=*/true);
1367
1368 // Sort the overload candidate set by placing the best overloads first.
1369 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1370 IsBetterOverloadCandidate(*this));
1371
1372 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05f477c2009-09-23 00:16:58 +00001373 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1374 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlssone7ceb852009-09-22 17:29:51 +00001375
Douglas Gregorcabea402009-09-22 15:41:20 +00001376 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1377 CandEnd = CandidateSet.end();
1378 Cand != CandEnd; ++Cand) {
1379 if (Cand->Viable)
Douglas Gregor05f477c2009-09-23 00:16:58 +00001380 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregorcabea402009-09-22 15:41:20 +00001381 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001382 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
Douglas Gregor05f477c2009-09-23 00:16:58 +00001383 Results.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00001384}
1385
Douglas Gregor2436e712009-09-17 21:32:03 +00001386void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1387 bool EnteringContext) {
1388 if (!SS.getScopeRep() || !CodeCompleter)
1389 return;
1390
Douglas Gregor3545ff42009-09-21 16:56:56 +00001391 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1392 if (!Ctx)
1393 return;
1394
1395 ResultBuilder Results(*this);
Douglas Gregor2af2f672009-09-21 20:12:40 +00001396 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001397
1398 // The "template" keyword can follow "::" in the grammar, but only
1399 // put it into the grammar if the nested-name-specifier is dependent.
1400 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1401 if (!Results.empty() && NNS->isDependent())
1402 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1403
Douglas Gregor9eb77012009-11-07 00:00:49 +00001404 if (CodeCompleter->includeMacros())
1405 AddMacroResults(PP, NextRank + 1, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001406 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00001407}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001408
1409void Sema::CodeCompleteUsing(Scope *S) {
1410 if (!CodeCompleter)
1411 return;
1412
Douglas Gregor3545ff42009-09-21 16:56:56 +00001413 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001414 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001415
1416 // If we aren't in class scope, we could see the "namespace" keyword.
1417 if (!S->isClassScope())
1418 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1419
1420 // After "using", we can see anything that would start a
1421 // nested-name-specifier.
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001422 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1423 0, CurContext, Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001424 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001425
Douglas Gregor9eb77012009-11-07 00:00:49 +00001426 if (CodeCompleter->includeMacros())
1427 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001428 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001429}
1430
1431void Sema::CodeCompleteUsingDirective(Scope *S) {
1432 if (!CodeCompleter)
1433 return;
1434
Douglas Gregor3545ff42009-09-21 16:56:56 +00001435 // After "using namespace", we expect to see a namespace name or namespace
1436 // alias.
1437 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001438 Results.EnterNewScope();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001439 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1440 0, CurContext, Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001441 Results.ExitScope();
Douglas Gregor9eb77012009-11-07 00:00:49 +00001442 if (CodeCompleter->includeMacros())
1443 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001444 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001445}
1446
1447void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1448 if (!CodeCompleter)
1449 return;
1450
Douglas Gregor3545ff42009-09-21 16:56:56 +00001451 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1452 DeclContext *Ctx = (DeclContext *)S->getEntity();
1453 if (!S->getParent())
1454 Ctx = Context.getTranslationUnitDecl();
1455
1456 if (Ctx && Ctx->isFileContext()) {
1457 // We only want to see those namespaces that have already been defined
1458 // within this scope, because its likely that the user is creating an
1459 // extended namespace declaration. Keep track of the most recent
1460 // definition of each namespace.
1461 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1462 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1463 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1464 NS != NSEnd; ++NS)
1465 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1466
1467 // Add the most recent definition (or extended definition) of each
1468 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00001469 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001470 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1471 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1472 NS != NSEnd; ++NS)
Douglas Gregor2af2f672009-09-21 20:12:40 +00001473 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1474 CurContext);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001475 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001476 }
1477
Douglas Gregor9eb77012009-11-07 00:00:49 +00001478 if (CodeCompleter->includeMacros())
1479 AddMacroResults(PP, 1, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001480 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001481}
1482
1483void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1484 if (!CodeCompleter)
1485 return;
1486
Douglas Gregor3545ff42009-09-21 16:56:56 +00001487 // After "namespace", we expect to see a namespace or alias.
1488 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001489 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1490 0, CurContext, Results);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001491 if (CodeCompleter->includeMacros())
1492 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001493 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001494}
1495
Douglas Gregorc811ede2009-09-18 20:05:18 +00001496void Sema::CodeCompleteOperatorName(Scope *S) {
1497 if (!CodeCompleter)
1498 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001499
1500 typedef CodeCompleteConsumer::Result Result;
1501 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001502 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00001503
Douglas Gregor3545ff42009-09-21 16:56:56 +00001504 // Add the names of overloadable operators.
1505#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1506 if (std::strcmp(Spelling, "?")) \
1507 Results.MaybeAddResult(Result(Spelling, 0));
1508#include "clang/Basic/OperatorKinds.def"
1509
1510 // Add any type names visible from the current scope
1511 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor2af2f672009-09-21 20:12:40 +00001512 0, CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001513
1514 // Add any type specifiers
1515 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1516
1517 // Add any nested-name-specifiers
1518 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001519 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1520 NextRank + 1, CurContext, Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001521 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001522
Douglas Gregor9eb77012009-11-07 00:00:49 +00001523 if (CodeCompleter->includeMacros())
1524 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001525 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00001526}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001527
Steve Naroff936354c2009-10-08 21:55:05 +00001528void Sema::CodeCompleteObjCProperty(Scope *S, ObjCDeclSpec &ODS) {
1529 if (!CodeCompleter)
1530 return;
1531 unsigned Attributes = ODS.getPropertyAttributes();
1532
1533 typedef CodeCompleteConsumer::Result Result;
1534 ResultBuilder Results(*this);
1535 Results.EnterNewScope();
1536 if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly))
1537 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
1538 if (!(Attributes & ObjCDeclSpec::DQ_PR_assign))
1539 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
1540 if (!(Attributes & ObjCDeclSpec::DQ_PR_readwrite))
1541 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
1542 if (!(Attributes & ObjCDeclSpec::DQ_PR_retain))
1543 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
1544 if (!(Attributes & ObjCDeclSpec::DQ_PR_copy))
1545 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
1546 if (!(Attributes & ObjCDeclSpec::DQ_PR_nonatomic))
1547 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
1548 if (!(Attributes & ObjCDeclSpec::DQ_PR_setter))
1549 Results.MaybeAddResult(CodeCompleteConsumer::Result("setter", 0));
1550 if (!(Attributes & ObjCDeclSpec::DQ_PR_getter))
1551 Results.MaybeAddResult(CodeCompleteConsumer::Result("getter", 0));
1552 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001553 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00001554}
Steve Naroffeae65032009-11-07 02:08:14 +00001555
1556void Sema::CodeCompleteObjCFactoryMethod(Scope *S, IdentifierInfo *FName) {
1557 typedef CodeCompleteConsumer::Result Result;
1558 ResultBuilder Results(*this);
1559 Results.EnterNewScope();
1560
1561 ObjCInterfaceDecl *CDecl = getObjCInterfaceDecl(FName);
1562
1563 while (CDecl != NULL) {
1564 for (ObjCInterfaceDecl::classmeth_iterator I = CDecl->classmeth_begin(),
1565 E = CDecl->classmeth_end();
1566 I != E; ++I) {
1567 Results.MaybeAddResult(Result(*I, 0), CurContext);
1568 }
1569 // Add class methods in protocols.
1570 const ObjCList<ObjCProtocolDecl> &Protocols=CDecl->getReferencedProtocols();
1571 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1572 E = Protocols.end(); I != E; ++I) {
1573 for (ObjCProtocolDecl::classmeth_iterator I2 = (*I)->classmeth_begin(),
1574 E2 = (*I)->classmeth_end();
1575 I2 != E2; ++I2) {
1576 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1577 }
1578 }
1579 // Add class methods in categories.
1580 ObjCCategoryDecl *CatDecl = CDecl->getCategoryList();
1581 while (CatDecl) {
1582 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
1583 E = CatDecl->classmeth_end();
1584 I != E; ++I) {
1585 Results.MaybeAddResult(Result(*I, 0), CurContext);
1586 }
1587 // Add a categories protocol methods.
1588 const ObjCList<ObjCProtocolDecl> &Protocols =
1589 CatDecl->getReferencedProtocols();
1590 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1591 E = Protocols.end(); I != E; ++I) {
1592 for (ObjCProtocolDecl::classmeth_iterator I2 = (*I)->classmeth_begin(),
1593 E2 = (*I)->classmeth_end();
1594 I2 != E2; ++I2) {
1595 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1596 }
1597 }
1598 CatDecl = CatDecl->getNextClassCategory();
1599 }
1600 CDecl = CDecl->getSuperClass();
1601 }
1602 Results.ExitScope();
1603 // This also suppresses remaining diagnostics.
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001604 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00001605}
1606
1607void Sema::CodeCompleteObjCInstanceMethod(Scope *S, ExprTy *Receiver) {
1608 typedef CodeCompleteConsumer::Result Result;
1609 ResultBuilder Results(*this);
1610 Results.EnterNewScope();
1611
1612 Expr *RecExpr = static_cast<Expr *>(Receiver);
1613 QualType RecType = RecExpr->getType();
1614
1615 const ObjCObjectPointerType* OCOPT = RecType->getAs<ObjCObjectPointerType>();
1616
1617 if (!OCOPT)
1618 return;
1619
1620 // FIXME: handle 'id', 'Class', and qualified types.
1621 ObjCInterfaceDecl *CDecl = OCOPT->getInterfaceDecl();
1622
1623 while (CDecl != NULL) {
1624 for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1625 E = CDecl->instmeth_end();
1626 I != E; ++I) {
1627 Results.MaybeAddResult(Result(*I, 0), CurContext);
1628 }
1629 // Add class methods in protocols.
1630 const ObjCList<ObjCProtocolDecl> &Protocols=CDecl->getReferencedProtocols();
1631 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1632 E = Protocols.end(); I != E; ++I) {
1633 for (ObjCProtocolDecl::instmeth_iterator I2 = (*I)->instmeth_begin(),
1634 E2 = (*I)->instmeth_end();
1635 I2 != E2; ++I2) {
1636 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1637 }
1638 }
1639 // Add class methods in categories.
1640 ObjCCategoryDecl *CatDecl = CDecl->getCategoryList();
1641 while (CatDecl) {
1642 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
1643 E = CatDecl->instmeth_end();
1644 I != E; ++I) {
1645 Results.MaybeAddResult(Result(*I, 0), CurContext);
1646 }
1647 // Add a categories protocol methods.
1648 const ObjCList<ObjCProtocolDecl> &Protocols =
1649 CatDecl->getReferencedProtocols();
1650 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1651 E = Protocols.end(); I != E; ++I) {
1652 for (ObjCProtocolDecl::instmeth_iterator I2 = (*I)->instmeth_begin(),
1653 E2 = (*I)->instmeth_end();
1654 I2 != E2; ++I2) {
1655 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1656 }
1657 }
1658 CatDecl = CatDecl->getNextClassCategory();
1659 }
1660 CDecl = CDecl->getSuperClass();
1661 }
1662 Results.ExitScope();
1663 // This also suppresses remaining diagnostics.
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001664 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00001665}