blob: f3f7d3f40559ec673e67a4a4b1f25545406a3f02 [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 Gregor8ce33212009-11-17 17:59:40 +000016#include "clang/AST/ExprObjC.h"
Douglas Gregorf329c7c2009-10-30 16:50:04 +000017#include "clang/Lex/MacroInfo.h"
18#include "clang/Lex/Preprocessor.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000019#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore6688e62009-09-28 03:51:44 +000020#include "llvm/ADT/StringExtras.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000021#include <list>
22#include <map>
23#include <vector>
Douglas Gregor2436e712009-09-17 21:32:03 +000024
25using namespace clang;
26
Douglas Gregor3545ff42009-09-21 16:56:56 +000027namespace {
28 /// \brief A container of code-completion results.
29 class ResultBuilder {
30 public:
31 /// \brief The type of a name-lookup filter, which can be provided to the
32 /// name-lookup routines to specify which declarations should be included in
33 /// the result set (when it returns true) and which declarations should be
34 /// filtered out (returns false).
35 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
36
37 typedef CodeCompleteConsumer::Result Result;
38
39 private:
40 /// \brief The actual results we have found.
41 std::vector<Result> Results;
42
43 /// \brief A record of all of the declarations we have found and placed
44 /// into the result set, used to ensure that no declaration ever gets into
45 /// the result set twice.
46 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
47
48 /// \brief A mapping from declaration names to the declarations that have
49 /// this name within a particular scope and their index within the list of
50 /// results.
51 typedef std::multimap<DeclarationName,
52 std::pair<NamedDecl *, unsigned> > ShadowMap;
53
54 /// \brief The semantic analysis object for which results are being
55 /// produced.
56 Sema &SemaRef;
57
58 /// \brief If non-NULL, a filter function used to remove any code-completion
59 /// results that are not desirable.
60 LookupFilter Filter;
61
62 /// \brief A list of shadow maps, which is used to model name hiding at
63 /// different levels of, e.g., the inheritance hierarchy.
64 std::list<ShadowMap> ShadowMaps;
65
66 public:
67 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
68 : SemaRef(SemaRef), Filter(Filter) { }
69
70 /// \brief Set the filter used for code-completion results.
71 void setFilter(LookupFilter Filter) {
72 this->Filter = Filter;
73 }
74
75 typedef std::vector<Result>::iterator iterator;
76 iterator begin() { return Results.begin(); }
77 iterator end() { return Results.end(); }
78
79 Result *data() { return Results.empty()? 0 : &Results.front(); }
80 unsigned size() const { return Results.size(); }
81 bool empty() const { return Results.empty(); }
82
83 /// \brief Add a new result to this result set (if it isn't already in one
84 /// of the shadow maps), or replace an existing result (for, e.g., a
85 /// redeclaration).
Douglas Gregor2af2f672009-09-21 20:12:40 +000086 ///
87 /// \param R the result to add (if it is unique).
88 ///
89 /// \param R the context in which this result will be named.
90 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor3545ff42009-09-21 16:56:56 +000091
92 /// \brief Enter into a new scope.
93 void EnterNewScope();
94
95 /// \brief Exit from the current scope.
96 void ExitScope();
97
Douglas Gregorbaf69612009-11-18 04:19:12 +000098 /// \brief Ignore this declaration, if it is seen again.
99 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
100
Douglas Gregor3545ff42009-09-21 16:56:56 +0000101 /// \name Name lookup predicates
102 ///
103 /// These predicates can be passed to the name lookup functions to filter the
104 /// results of name lookup. All of the predicates have the same type, so that
105 ///
106 //@{
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000107 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000108 bool IsNestedNameSpecifier(NamedDecl *ND) const;
109 bool IsEnum(NamedDecl *ND) const;
110 bool IsClassOrStruct(NamedDecl *ND) const;
111 bool IsUnion(NamedDecl *ND) const;
112 bool IsNamespace(NamedDecl *ND) const;
113 bool IsNamespaceOrAlias(NamedDecl *ND) const;
114 bool IsType(NamedDecl *ND) const;
Douglas Gregore412a5a2009-09-23 22:26:46 +0000115 bool IsMember(NamedDecl *ND) const;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000116 //@}
117 };
118}
119
120/// \brief Determines whether the given hidden result could be found with
121/// some extra work, e.g., by qualifying the name.
122///
123/// \param Hidden the declaration that is hidden by the currenly \p Visible
124/// declaration.
125///
126/// \param Visible the declaration with the same name that is already visible.
127///
128/// \returns true if the hidden result can be found by some mechanism,
129/// false otherwise.
130static bool canHiddenResultBeFound(const LangOptions &LangOpts,
131 NamedDecl *Hidden, NamedDecl *Visible) {
132 // In C, there is no way to refer to a hidden name.
133 if (!LangOpts.CPlusPlus)
134 return false;
135
136 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
137
138 // There is no way to qualify a name declared in a function or method.
139 if (HiddenCtx->isFunctionOrMethod())
140 return false;
141
Douglas Gregor3545ff42009-09-21 16:56:56 +0000142 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
143}
144
Douglas Gregor2af2f672009-09-21 20:12:40 +0000145/// \brief Compute the qualification required to get from the current context
146/// (\p CurContext) to the target context (\p TargetContext).
147///
148/// \param Context the AST context in which the qualification will be used.
149///
150/// \param CurContext the context where an entity is being named, which is
151/// typically based on the current scope.
152///
153/// \param TargetContext the context in which the named entity actually
154/// resides.
155///
156/// \returns a nested name specifier that refers into the target context, or
157/// NULL if no qualification is needed.
158static NestedNameSpecifier *
159getRequiredQualification(ASTContext &Context,
160 DeclContext *CurContext,
161 DeclContext *TargetContext) {
162 llvm::SmallVector<DeclContext *, 4> TargetParents;
163
164 for (DeclContext *CommonAncestor = TargetContext;
165 CommonAncestor && !CommonAncestor->Encloses(CurContext);
166 CommonAncestor = CommonAncestor->getLookupParent()) {
167 if (CommonAncestor->isTransparentContext() ||
168 CommonAncestor->isFunctionOrMethod())
169 continue;
170
171 TargetParents.push_back(CommonAncestor);
172 }
173
174 NestedNameSpecifier *Result = 0;
175 while (!TargetParents.empty()) {
176 DeclContext *Parent = TargetParents.back();
177 TargetParents.pop_back();
178
179 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
180 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
181 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
182 Result = NestedNameSpecifier::Create(Context, Result,
183 false,
184 Context.getTypeDeclType(TD).getTypePtr());
185 else
186 assert(Parent->isTranslationUnit());
Douglas Gregor9eb77012009-11-07 00:00:49 +0000187 }
Douglas Gregor2af2f672009-09-21 20:12:40 +0000188 return Result;
189}
190
191void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
Douglas Gregor64b12b52009-09-22 23:31:26 +0000192 assert(!ShadowMaps.empty() && "Must enter into a results scope");
193
Douglas Gregor3545ff42009-09-21 16:56:56 +0000194 if (R.Kind != Result::RK_Declaration) {
195 // For non-declaration results, just add the result.
196 Results.push_back(R);
197 return;
198 }
Douglas Gregor58acf322009-10-09 22:16:47 +0000199
200 // Skip unnamed entities.
201 if (!R.Declaration->getDeclName())
202 return;
203
Douglas Gregor3545ff42009-09-21 16:56:56 +0000204 // Look through using declarations.
John McCall3f746822009-11-17 05:59:44 +0000205 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration))
Douglas Gregor5bf52692009-09-22 23:15:58 +0000206 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
207 CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000208
209 // Handle each declaration in an overload set separately.
210 if (OverloadedFunctionDecl *Ovl
211 = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) {
212 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
213 FEnd = Ovl->function_end();
214 F != FEnd; ++F)
Douglas Gregor2af2f672009-09-21 20:12:40 +0000215 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000216
217 return;
218 }
219
220 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
221 unsigned IDNS = CanonDecl->getIdentifierNamespace();
222
223 // Friend declarations and declarations introduced due to friends are never
224 // added as results.
225 if (isa<FriendDecl>(CanonDecl) ||
226 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
227 return;
228
229 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
230 // __va_list_tag is a freak of nature. Find it and skip it.
231 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
232 return;
233
Douglas Gregor58acf322009-10-09 22:16:47 +0000234 // Filter out names reserved for the implementation (C99 7.1.3,
235 // C++ [lib.global.names]). Users don't need to see those.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +0000236 //
237 // FIXME: Add predicate for this.
Douglas Gregor58acf322009-10-09 22:16:47 +0000238 if (Id->getLength() >= 2) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +0000239 const char *Name = Id->getNameStart();
Douglas Gregor58acf322009-10-09 22:16:47 +0000240 if (Name[0] == '_' &&
241 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
242 return;
243 }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000244 }
245
246 // C++ constructors are never found by name lookup.
247 if (isa<CXXConstructorDecl>(CanonDecl))
248 return;
249
250 // Filter out any unwanted results.
251 if (Filter && !(this->*Filter)(R.Declaration))
252 return;
253
254 ShadowMap &SMap = ShadowMaps.back();
255 ShadowMap::iterator I, IEnd;
256 for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
257 I != IEnd; ++I) {
258 NamedDecl *ND = I->second.first;
259 unsigned Index = I->second.second;
260 if (ND->getCanonicalDecl() == CanonDecl) {
261 // This is a redeclaration. Always pick the newer declaration.
262 I->second.first = R.Declaration;
263 Results[Index].Declaration = R.Declaration;
264
265 // Pick the best rank of the two.
266 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
267
268 // We're done.
269 return;
270 }
271 }
272
273 // This is a new declaration in this scope. However, check whether this
274 // declaration name is hidden by a similarly-named declaration in an outer
275 // scope.
276 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
277 --SMEnd;
278 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
279 for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
280 I != IEnd; ++I) {
281 // A tag declaration does not hide a non-tag declaration.
282 if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
283 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
284 Decl::IDNS_ObjCProtocol)))
285 continue;
286
287 // Protocols are in distinct namespaces from everything else.
288 if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
289 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
290 I->second.first->getIdentifierNamespace() != IDNS)
291 continue;
292
293 // The newly-added result is hidden by an entry in the shadow map.
294 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
295 I->second.first)) {
296 // Note that this result was hidden.
297 R.Hidden = true;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000298 R.QualifierIsInformative = false;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000299
300 if (!R.Qualifier)
301 R.Qualifier = getRequiredQualification(SemaRef.Context,
302 CurContext,
303 R.Declaration->getDeclContext());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000304 } else {
305 // This result was hidden and cannot be found; don't bother adding
306 // it.
307 return;
308 }
309
310 break;
311 }
312 }
313
314 // Make sure that any given declaration only shows up in the result set once.
315 if (!AllDeclsFound.insert(CanonDecl))
316 return;
317
Douglas Gregore412a5a2009-09-23 22:26:46 +0000318 // If the filter is for nested-name-specifiers, then this result starts a
319 // nested-name-specifier.
320 if ((Filter == &ResultBuilder::IsNestedNameSpecifier) ||
321 (Filter == &ResultBuilder::IsMember &&
322 isa<CXXRecordDecl>(R.Declaration) &&
323 cast<CXXRecordDecl>(R.Declaration)->isInjectedClassName()))
324 R.StartsNestedNameSpecifier = true;
325
Douglas Gregor5bf52692009-09-22 23:15:58 +0000326 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000327 if (R.QualifierIsInformative && !R.Qualifier &&
328 !R.StartsNestedNameSpecifier) {
Douglas Gregor5bf52692009-09-22 23:15:58 +0000329 DeclContext *Ctx = R.Declaration->getDeclContext();
330 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
331 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
332 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
333 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
334 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
335 else
336 R.QualifierIsInformative = false;
337 }
Douglas Gregore412a5a2009-09-23 22:26:46 +0000338
Douglas Gregor3545ff42009-09-21 16:56:56 +0000339 // Insert this result into the set of results and into the current shadow
340 // map.
341 SMap.insert(std::make_pair(R.Declaration->getDeclName(),
342 std::make_pair(R.Declaration, Results.size())));
343 Results.push_back(R);
344}
345
346/// \brief Enter into a new scope.
347void ResultBuilder::EnterNewScope() {
348 ShadowMaps.push_back(ShadowMap());
349}
350
351/// \brief Exit from the current scope.
352void ResultBuilder::ExitScope() {
353 ShadowMaps.pop_back();
354}
355
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000356/// \brief Determines whether this given declaration will be found by
357/// ordinary name lookup.
358bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
359 unsigned IDNS = Decl::IDNS_Ordinary;
360 if (SemaRef.getLangOptions().CPlusPlus)
361 IDNS |= Decl::IDNS_Tag;
362
363 return ND->getIdentifierNamespace() & IDNS;
364}
365
Douglas Gregor3545ff42009-09-21 16:56:56 +0000366/// \brief Determines whether the given declaration is suitable as the
367/// start of a C++ nested-name-specifier, e.g., a class or namespace.
368bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
369 // Allow us to find class templates, too.
370 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
371 ND = ClassTemplate->getTemplatedDecl();
372
373 return SemaRef.isAcceptableNestedNameSpecifier(ND);
374}
375
376/// \brief Determines whether the given declaration is an enumeration.
377bool ResultBuilder::IsEnum(NamedDecl *ND) const {
378 return isa<EnumDecl>(ND);
379}
380
381/// \brief Determines whether the given declaration is a class or struct.
382bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
383 // Allow us to find class templates, too.
384 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
385 ND = ClassTemplate->getTemplatedDecl();
386
387 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
388 return RD->getTagKind() == TagDecl::TK_class ||
389 RD->getTagKind() == TagDecl::TK_struct;
390
391 return false;
392}
393
394/// \brief Determines whether the given declaration is a union.
395bool ResultBuilder::IsUnion(NamedDecl *ND) const {
396 // Allow us to find class templates, too.
397 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
398 ND = ClassTemplate->getTemplatedDecl();
399
400 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
401 return RD->getTagKind() == TagDecl::TK_union;
402
403 return false;
404}
405
406/// \brief Determines whether the given declaration is a namespace.
407bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
408 return isa<NamespaceDecl>(ND);
409}
410
411/// \brief Determines whether the given declaration is a namespace or
412/// namespace alias.
413bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
414 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
415}
416
417/// \brief Brief determines whether the given declaration is a namespace or
418/// namespace alias.
419bool ResultBuilder::IsType(NamedDecl *ND) const {
420 return isa<TypeDecl>(ND);
421}
422
Douglas Gregore412a5a2009-09-23 22:26:46 +0000423/// \brief Since every declaration found within a class is a member that we
424/// care about, always returns true. This predicate exists mostly to
425/// communicate to the result builder that we are performing a lookup for
426/// member access.
427bool ResultBuilder::IsMember(NamedDecl *ND) const {
428 return true;
429}
430
Douglas Gregor3545ff42009-09-21 16:56:56 +0000431// Find the next outer declaration context corresponding to this scope.
432static DeclContext *findOuterContext(Scope *S) {
433 for (S = S->getParent(); S; S = S->getParent())
434 if (S->getEntity())
435 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
436
437 return 0;
438}
439
440/// \brief Collect the results of searching for members within the given
441/// declaration context.
442///
443/// \param Ctx the declaration context from which we will gather results.
444///
Douglas Gregor5bf52692009-09-22 23:15:58 +0000445/// \param Rank the rank given to results in this declaration context.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000446///
447/// \param Visited the set of declaration contexts that have already been
448/// visited. Declaration contexts will only be visited once.
449///
450/// \param Results the result set that will be extended with any results
451/// found within this declaration context (and, for a C++ class, its bases).
452///
Douglas Gregor5bf52692009-09-22 23:15:58 +0000453/// \param InBaseClass whether we are in a base class.
454///
Douglas Gregor3545ff42009-09-21 16:56:56 +0000455/// \returns the next higher rank value, after considering all of the
456/// names within this declaration context.
457static unsigned CollectMemberLookupResults(DeclContext *Ctx,
Douglas Gregor5bf52692009-09-22 23:15:58 +0000458 unsigned Rank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000459 DeclContext *CurContext,
460 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor5bf52692009-09-22 23:15:58 +0000461 ResultBuilder &Results,
462 bool InBaseClass = false) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000463 // Make sure we don't visit the same context twice.
464 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor5bf52692009-09-22 23:15:58 +0000465 return Rank;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000466
467 // Enumerate all of the results in this context.
Douglas Gregor5bf52692009-09-22 23:15:58 +0000468 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000469 Results.EnterNewScope();
470 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
471 CurCtx = CurCtx->getNextContext()) {
472 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor8caea942009-11-09 21:35:27 +0000473 DEnd = CurCtx->decls_end();
Douglas Gregor3545ff42009-09-21 16:56:56 +0000474 D != DEnd; ++D) {
475 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor5bf52692009-09-22 23:15:58 +0000476 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregor8caea942009-11-09 21:35:27 +0000477
478 // Visit transparent contexts inside this context.
479 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
480 if (InnerCtx->isTransparentContext())
481 CollectMemberLookupResults(InnerCtx, Rank, CurContext, Visited,
482 Results, InBaseClass);
483 }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000484 }
485 }
486
487 // Traverse the contexts of inherited classes.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000488 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
489 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
Douglas Gregor8caea942009-11-09 21:35:27 +0000490 BEnd = Record->bases_end();
Douglas Gregor3545ff42009-09-21 16:56:56 +0000491 B != BEnd; ++B) {
492 QualType BaseType = B->getType();
493
494 // Don't look into dependent bases, because name lookup can't look
495 // there anyway.
496 if (BaseType->isDependentType())
497 continue;
498
499 const RecordType *Record = BaseType->getAs<RecordType>();
500 if (!Record)
501 continue;
502
503 // FIXME: It would be nice to be able to determine whether referencing
504 // a particular member would be ambiguous. For example, given
505 //
506 // struct A { int member; };
507 // struct B { int member; };
508 // struct C : A, B { };
509 //
510 // void f(C *c) { c->### }
511 // accessing 'member' would result in an ambiguity. However, code
512 // completion could be smart enough to qualify the member with the
513 // base class, e.g.,
514 //
515 // c->B::member
516 //
517 // or
518 //
519 // c->A::member
520
521 // Collect results from this base class (and its bases).
Douglas Gregor5bf52692009-09-22 23:15:58 +0000522 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
523 Results, /*InBaseClass=*/true);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000524 }
525 }
526
527 // FIXME: Look into base classes in Objective-C!
528
529 Results.ExitScope();
Douglas Gregor5bf52692009-09-22 23:15:58 +0000530 return Rank + 1;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000531}
532
533/// \brief Collect the results of searching for members within the given
534/// declaration context.
535///
536/// \param Ctx the declaration context from which we will gather results.
537///
538/// \param InitialRank the initial rank given to results in this declaration
539/// context. Larger rank values will be used for, e.g., members found in
540/// base classes.
541///
542/// \param Results the result set that will be extended with any results
543/// found within this declaration context (and, for a C++ class, its bases).
544///
545/// \returns the next higher rank value, after considering all of the
546/// names within this declaration context.
547static unsigned CollectMemberLookupResults(DeclContext *Ctx,
548 unsigned InitialRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000549 DeclContext *CurContext,
Douglas Gregor3545ff42009-09-21 16:56:56 +0000550 ResultBuilder &Results) {
551 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000552 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
553 Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000554}
555
556/// \brief Collect the results of searching for declarations within the given
557/// scope and its parent scopes.
558///
559/// \param S the scope in which we will start looking for declarations.
560///
561/// \param InitialRank the initial rank given to results in this scope.
562/// Larger rank values will be used for results found in parent scopes.
563///
Douglas Gregor2af2f672009-09-21 20:12:40 +0000564/// \param CurContext the context from which lookup results will be found.
565///
Douglas Gregor3545ff42009-09-21 16:56:56 +0000566/// \param Results the builder object that will receive each result.
567static unsigned CollectLookupResults(Scope *S,
568 TranslationUnitDecl *TranslationUnit,
569 unsigned InitialRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000570 DeclContext *CurContext,
Douglas Gregor3545ff42009-09-21 16:56:56 +0000571 ResultBuilder &Results) {
572 if (!S)
573 return InitialRank;
574
575 // FIXME: Using directives!
576
577 unsigned NextRank = InitialRank;
578 Results.EnterNewScope();
579 if (S->getEntity() &&
580 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
581 // Look into this scope's declaration context, along with any of its
582 // parent lookup contexts (e.g., enclosing classes), up to the point
583 // where we hit the context stored in the next outer scope.
584 DeclContext *Ctx = (DeclContext *)S->getEntity();
585 DeclContext *OuterCtx = findOuterContext(S);
586
587 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
588 Ctx = Ctx->getLookupParent()) {
589 if (Ctx->isFunctionOrMethod())
590 continue;
591
Douglas Gregor2af2f672009-09-21 20:12:40 +0000592 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
593 Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000594 }
595 } else if (!S->getParent()) {
596 // Look into the translation unit scope. We walk through the translation
597 // unit's declaration context, because the Scope itself won't have all of
598 // the declarations if we loaded a precompiled header.
599 // FIXME: We would like the translation unit's Scope object to point to the
600 // translation unit, so we don't need this special "if" branch. However,
601 // doing so would force the normal C++ name-lookup code to look into the
602 // translation unit decl when the IdentifierInfo chains would suffice.
603 // Once we fix that problem (which is part of a more general "don't look
604 // in DeclContexts unless we have to" optimization), we can eliminate the
605 // TranslationUnit parameter entirely.
606 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000607 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000608 } else {
609 // Walk through the declarations in this Scope.
610 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
611 D != DEnd; ++D) {
612 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
Douglas Gregor2af2f672009-09-21 20:12:40 +0000613 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
614 CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000615 }
616
617 NextRank = NextRank + 1;
618 }
619
620 // Lookup names in the parent scope.
621 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000622 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000623 Results.ExitScope();
624
625 return NextRank;
626}
627
628/// \brief Add type specifiers for the current language as keyword results.
629static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
630 ResultBuilder &Results) {
631 typedef CodeCompleteConsumer::Result Result;
632 Results.MaybeAddResult(Result("short", Rank));
633 Results.MaybeAddResult(Result("long", Rank));
634 Results.MaybeAddResult(Result("signed", Rank));
635 Results.MaybeAddResult(Result("unsigned", Rank));
636 Results.MaybeAddResult(Result("void", Rank));
637 Results.MaybeAddResult(Result("char", Rank));
638 Results.MaybeAddResult(Result("int", Rank));
639 Results.MaybeAddResult(Result("float", Rank));
640 Results.MaybeAddResult(Result("double", Rank));
641 Results.MaybeAddResult(Result("enum", Rank));
642 Results.MaybeAddResult(Result("struct", Rank));
643 Results.MaybeAddResult(Result("union", Rank));
644
645 if (LangOpts.C99) {
646 // C99-specific
647 Results.MaybeAddResult(Result("_Complex", Rank));
648 Results.MaybeAddResult(Result("_Imaginary", Rank));
649 Results.MaybeAddResult(Result("_Bool", Rank));
650 }
651
652 if (LangOpts.CPlusPlus) {
653 // C++-specific
654 Results.MaybeAddResult(Result("bool", Rank));
655 Results.MaybeAddResult(Result("class", Rank));
656 Results.MaybeAddResult(Result("typename", Rank));
657 Results.MaybeAddResult(Result("wchar_t", Rank));
658
659 if (LangOpts.CPlusPlus0x) {
660 Results.MaybeAddResult(Result("char16_t", Rank));
661 Results.MaybeAddResult(Result("char32_t", Rank));
662 Results.MaybeAddResult(Result("decltype", Rank));
663 }
664 }
665
666 // GNU extensions
667 if (LangOpts.GNUMode) {
668 // FIXME: Enable when we actually support decimal floating point.
669 // Results.MaybeAddResult(Result("_Decimal32", Rank));
670 // Results.MaybeAddResult(Result("_Decimal64", Rank));
671 // Results.MaybeAddResult(Result("_Decimal128", Rank));
672 Results.MaybeAddResult(Result("typeof", Rank));
673 }
674}
675
676/// \brief Add function parameter chunks to the given code completion string.
677static void AddFunctionParameterChunks(ASTContext &Context,
678 FunctionDecl *Function,
679 CodeCompletionString *Result) {
Douglas Gregor9eb77012009-11-07 00:00:49 +0000680 typedef CodeCompletionString::Chunk Chunk;
681
Douglas Gregor3545ff42009-09-21 16:56:56 +0000682 CodeCompletionString *CCStr = Result;
683
684 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
685 ParmVarDecl *Param = Function->getParamDecl(P);
686
687 if (Param->hasDefaultArg()) {
688 // When we see an optional default argument, put that argument and
689 // the remaining default arguments into a new, optional string.
690 CodeCompletionString *Opt = new CodeCompletionString;
691 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
692 CCStr = Opt;
693 }
694
695 if (P != 0)
Douglas Gregor9eb77012009-11-07 00:00:49 +0000696 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000697
698 // Format the placeholder string.
699 std::string PlaceholderStr;
700 if (Param->getIdentifier())
701 PlaceholderStr = Param->getIdentifier()->getName();
702
703 Param->getType().getAsStringInternal(PlaceholderStr,
704 Context.PrintingPolicy);
705
706 // Add the placeholder string.
707 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
708 }
Douglas Gregorba449032009-09-22 21:42:17 +0000709
710 if (const FunctionProtoType *Proto
711 = Function->getType()->getAs<FunctionProtoType>())
712 if (Proto->isVariadic())
713 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor3545ff42009-09-21 16:56:56 +0000714}
715
716/// \brief Add template parameter chunks to the given code completion string.
717static void AddTemplateParameterChunks(ASTContext &Context,
718 TemplateDecl *Template,
719 CodeCompletionString *Result,
720 unsigned MaxParameters = 0) {
Douglas Gregor9eb77012009-11-07 00:00:49 +0000721 typedef CodeCompletionString::Chunk Chunk;
722
Douglas Gregor3545ff42009-09-21 16:56:56 +0000723 CodeCompletionString *CCStr = Result;
724 bool FirstParameter = true;
725
726 TemplateParameterList *Params = Template->getTemplateParameters();
727 TemplateParameterList::iterator PEnd = Params->end();
728 if (MaxParameters)
729 PEnd = Params->begin() + MaxParameters;
730 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
731 bool HasDefaultArg = false;
732 std::string PlaceholderStr;
733 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
734 if (TTP->wasDeclaredWithTypename())
735 PlaceholderStr = "typename";
736 else
737 PlaceholderStr = "class";
738
739 if (TTP->getIdentifier()) {
740 PlaceholderStr += ' ';
741 PlaceholderStr += TTP->getIdentifier()->getName();
742 }
743
744 HasDefaultArg = TTP->hasDefaultArgument();
745 } else if (NonTypeTemplateParmDecl *NTTP
746 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
747 if (NTTP->getIdentifier())
748 PlaceholderStr = NTTP->getIdentifier()->getName();
749 NTTP->getType().getAsStringInternal(PlaceholderStr,
750 Context.PrintingPolicy);
751 HasDefaultArg = NTTP->hasDefaultArgument();
752 } else {
753 assert(isa<TemplateTemplateParmDecl>(*P));
754 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
755
756 // Since putting the template argument list into the placeholder would
757 // be very, very long, we just use an abbreviation.
758 PlaceholderStr = "template<...> class";
759 if (TTP->getIdentifier()) {
760 PlaceholderStr += ' ';
761 PlaceholderStr += TTP->getIdentifier()->getName();
762 }
763
764 HasDefaultArg = TTP->hasDefaultArgument();
765 }
766
767 if (HasDefaultArg) {
768 // When we see an optional default argument, put that argument and
769 // the remaining default arguments into a new, optional string.
770 CodeCompletionString *Opt = new CodeCompletionString;
771 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
772 CCStr = Opt;
773 }
774
775 if (FirstParameter)
776 FirstParameter = false;
777 else
Douglas Gregor9eb77012009-11-07 00:00:49 +0000778 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000779
780 // Add the placeholder string.
781 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
782 }
783}
784
Douglas Gregorf2510672009-09-21 19:57:38 +0000785/// \brief Add a qualifier to the given code-completion string, if the
786/// provided nested-name-specifier is non-NULL.
787void AddQualifierToCompletionString(CodeCompletionString *Result,
788 NestedNameSpecifier *Qualifier,
Douglas Gregor5bf52692009-09-22 23:15:58 +0000789 bool QualifierIsInformative,
Douglas Gregorf2510672009-09-21 19:57:38 +0000790 ASTContext &Context) {
791 if (!Qualifier)
792 return;
793
794 std::string PrintedNNS;
795 {
796 llvm::raw_string_ostream OS(PrintedNNS);
797 Qualifier->print(OS, Context.PrintingPolicy);
798 }
Douglas Gregor5bf52692009-09-22 23:15:58 +0000799 if (QualifierIsInformative)
800 Result->AddInformativeChunk(PrintedNNS.c_str());
801 else
802 Result->AddTextChunk(PrintedNNS.c_str());
Douglas Gregorf2510672009-09-21 19:57:38 +0000803}
804
Douglas Gregor3545ff42009-09-21 16:56:56 +0000805/// \brief If possible, create a new code completion string for the given
806/// result.
807///
808/// \returns Either a new, heap-allocated code completion string describing
809/// how to use this result, or NULL to indicate that the string or name of the
810/// result is all that is needed.
811CodeCompletionString *
812CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
Douglas Gregor9eb77012009-11-07 00:00:49 +0000813 typedef CodeCompletionString::Chunk Chunk;
814
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000815 if (Kind == RK_Keyword)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000816 return 0;
817
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000818 if (Kind == RK_Macro) {
819 MacroInfo *MI = S.PP.getMacroInfo(Macro);
820 if (!MI || !MI->isFunctionLike())
821 return 0;
822
823 // Format a function-like macro with placeholders for the arguments.
824 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor9eb77012009-11-07 00:00:49 +0000825 Result->AddTypedTextChunk(Macro->getName().str().c_str());
826 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000827 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
828 A != AEnd; ++A) {
829 if (A != MI->arg_begin())
Douglas Gregor9eb77012009-11-07 00:00:49 +0000830 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000831
832 if (!MI->isVariadic() || A != AEnd - 1) {
833 // Non-variadic argument.
834 Result->AddPlaceholderChunk((*A)->getName().str().c_str());
835 continue;
836 }
837
838 // Variadic argument; cope with the different between GNU and C99
839 // variadic macros, providing a single placeholder for the rest of the
840 // arguments.
841 if ((*A)->isStr("__VA_ARGS__"))
842 Result->AddPlaceholderChunk("...");
843 else {
844 std::string Arg = (*A)->getName();
845 Arg += "...";
846 Result->AddPlaceholderChunk(Arg.c_str());
847 }
848 }
Douglas Gregor9eb77012009-11-07 00:00:49 +0000849 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000850 return Result;
851 }
852
853 assert(Kind == RK_Declaration && "Missed a macro kind?");
Douglas Gregor3545ff42009-09-21 16:56:56 +0000854 NamedDecl *ND = Declaration;
855
Douglas Gregor9eb77012009-11-07 00:00:49 +0000856 if (StartsNestedNameSpecifier) {
857 CodeCompletionString *Result = new CodeCompletionString;
858 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
859 Result->AddTextChunk("::");
860 return Result;
861 }
862
Douglas Gregor3545ff42009-09-21 16:56:56 +0000863 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
864 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000865 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
866 S.Context);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000867 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
868 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000869 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000870 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000871 return Result;
872 }
873
874 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
875 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000876 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
877 S.Context);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000878 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor9eb77012009-11-07 00:00:49 +0000879 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000880
881 // Figure out which template parameters are deduced (or have default
882 // arguments).
883 llvm::SmallVector<bool, 16> Deduced;
884 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
885 unsigned LastDeducibleArgument;
886 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
887 --LastDeducibleArgument) {
888 if (!Deduced[LastDeducibleArgument - 1]) {
889 // C++0x: Figure out if the template argument has a default. If so,
890 // the user doesn't need to type this argument.
891 // FIXME: We need to abstract template parameters better!
892 bool HasDefaultArg = false;
893 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
894 LastDeducibleArgument - 1);
895 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
896 HasDefaultArg = TTP->hasDefaultArgument();
897 else if (NonTypeTemplateParmDecl *NTTP
898 = dyn_cast<NonTypeTemplateParmDecl>(Param))
899 HasDefaultArg = NTTP->hasDefaultArgument();
900 else {
901 assert(isa<TemplateTemplateParmDecl>(Param));
902 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +0000903 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +0000904 }
905
906 if (!HasDefaultArg)
907 break;
908 }
909 }
910
911 if (LastDeducibleArgument) {
912 // Some of the function template arguments cannot be deduced from a
913 // function call, so we introduce an explicit template argument list
914 // containing all of the arguments up to the first deducible argument.
Douglas Gregor9eb77012009-11-07 00:00:49 +0000915 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000916 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
917 LastDeducibleArgument);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000918 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000919 }
920
921 // Add the function parameters
Douglas Gregor9eb77012009-11-07 00:00:49 +0000922 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000923 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000924 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000925 return Result;
926 }
927
928 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
929 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000930 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
931 S.Context);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000932 Result->AddTypedTextChunk(Template->getNameAsString().c_str());
933 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000934 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000935 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000936 return Result;
937 }
938
Douglas Gregord3c5d792009-11-17 16:44:22 +0000939 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
940 CodeCompletionString *Result = new CodeCompletionString;
941 Selector Sel = Method->getSelector();
942 if (Sel.isUnarySelector()) {
943 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
944 return Result;
945 }
946
947 Result->AddTypedTextChunk(
948 Sel.getIdentifierInfoForSlot(0)->getName().str() + std::string(":"));
949 unsigned Idx = 0;
950 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
951 PEnd = Method->param_end();
952 P != PEnd; (void)++P, ++Idx) {
953 if (Idx > 0) {
954 std::string Keyword = " ";
955 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
956 Keyword += II->getName().str();
957 Keyword += ":";
958 Result->AddTextChunk(Keyword);
959 }
960
961 std::string Arg;
962 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
963 Arg = "(" + Arg + ")";
964 if (IdentifierInfo *II = (*P)->getIdentifier())
965 Arg += II->getName().str();
966 Result->AddPlaceholderChunk(Arg);
967 }
968
969 return Result;
970 }
971
Douglas Gregor9eb77012009-11-07 00:00:49 +0000972 if (Qualifier) {
Douglas Gregorf2510672009-09-21 19:57:38 +0000973 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000974 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
975 S.Context);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000976 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
Douglas Gregorf2510672009-09-21 19:57:38 +0000977 return Result;
978 }
979
Douglas Gregor3545ff42009-09-21 16:56:56 +0000980 return 0;
981}
982
Douglas Gregorf0f51982009-09-23 00:34:09 +0000983CodeCompletionString *
984CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
985 unsigned CurrentArg,
986 Sema &S) const {
Douglas Gregor9eb77012009-11-07 00:00:49 +0000987 typedef CodeCompletionString::Chunk Chunk;
988
Douglas Gregorf0f51982009-09-23 00:34:09 +0000989 CodeCompletionString *Result = new CodeCompletionString;
990 FunctionDecl *FDecl = getFunction();
991 const FunctionProtoType *Proto
992 = dyn_cast<FunctionProtoType>(getFunctionType());
993 if (!FDecl && !Proto) {
994 // Function without a prototype. Just give the return type and a
995 // highlighted ellipsis.
996 const FunctionType *FT = getFunctionType();
997 Result->AddTextChunk(
998 FT->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
Douglas Gregor9eb77012009-11-07 00:00:49 +0000999 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1000 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1001 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001002 return Result;
1003 }
1004
1005 if (FDecl)
1006 Result->AddTextChunk(FDecl->getNameAsString().c_str());
1007 else
1008 Result->AddTextChunk(
1009 Proto->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
1010
Douglas Gregor9eb77012009-11-07 00:00:49 +00001011 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001012 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
1013 for (unsigned I = 0; I != NumParams; ++I) {
1014 if (I)
Douglas Gregor9eb77012009-11-07 00:00:49 +00001015 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001016
1017 std::string ArgString;
1018 QualType ArgType;
1019
1020 if (FDecl) {
1021 ArgString = FDecl->getParamDecl(I)->getNameAsString();
1022 ArgType = FDecl->getParamDecl(I)->getOriginalType();
1023 } else {
1024 ArgType = Proto->getArgType(I);
1025 }
1026
1027 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
1028
1029 if (I == CurrentArg)
Douglas Gregor9eb77012009-11-07 00:00:49 +00001030 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
1031 ArgString.c_str()));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001032 else
1033 Result->AddTextChunk(ArgString.c_str());
1034 }
1035
1036 if (Proto && Proto->isVariadic()) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001037 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001038 if (CurrentArg < NumParams)
1039 Result->AddTextChunk("...");
1040 else
Douglas Gregor9eb77012009-11-07 00:00:49 +00001041 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001042 }
Douglas Gregor9eb77012009-11-07 00:00:49 +00001043 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001044
1045 return Result;
1046}
1047
Douglas Gregor3545ff42009-09-21 16:56:56 +00001048namespace {
1049 struct SortCodeCompleteResult {
1050 typedef CodeCompleteConsumer::Result Result;
1051
Douglas Gregore6688e62009-09-28 03:51:44 +00001052 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001053 if (!X.getObjCSelector().isNull() && !Y.getObjCSelector().isNull()) {
1054 // Consider all selector kinds to be equivalent.
1055 } else if (X.getNameKind() != Y.getNameKind())
Douglas Gregore6688e62009-09-28 03:51:44 +00001056 return X.getNameKind() < Y.getNameKind();
1057
1058 return llvm::LowercaseString(X.getAsString())
1059 < llvm::LowercaseString(Y.getAsString());
1060 }
1061
Douglas Gregor3545ff42009-09-21 16:56:56 +00001062 bool operator()(const Result &X, const Result &Y) const {
1063 // Sort first by rank.
1064 if (X.Rank < Y.Rank)
1065 return true;
1066 else if (X.Rank > Y.Rank)
1067 return false;
1068
Douglas Gregor45f83ee2009-11-19 00:01:57 +00001069 // We use a special ordering for keywords and patterns, based on the
1070 // typed text.
1071 if ((X.Kind == Result::RK_Keyword || X.Kind == Result::RK_Pattern) &&
1072 (Y.Kind == Result::RK_Keyword || Y.Kind == Result::RK_Pattern)) {
1073 const char *XStr = (X.Kind == Result::RK_Keyword)? X.Keyword
1074 : X.Pattern->getTypedText();
1075 const char *YStr = (Y.Kind == Result::RK_Keyword)? Y.Keyword
1076 : Y.Pattern->getTypedText();
1077 return strcmp(XStr, YStr) < 0;
1078 }
1079
Douglas Gregor3545ff42009-09-21 16:56:56 +00001080 // Result kinds are ordered by decreasing importance.
1081 if (X.Kind < Y.Kind)
1082 return true;
1083 else if (X.Kind > Y.Kind)
1084 return false;
1085
1086 // Non-hidden names precede hidden names.
1087 if (X.Hidden != Y.Hidden)
1088 return !X.Hidden;
1089
Douglas Gregore412a5a2009-09-23 22:26:46 +00001090 // Non-nested-name-specifiers precede nested-name-specifiers.
1091 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1092 return !X.StartsNestedNameSpecifier;
1093
Douglas Gregor3545ff42009-09-21 16:56:56 +00001094 // Ordering depends on the kind of result.
1095 switch (X.Kind) {
1096 case Result::RK_Declaration:
1097 // Order based on the declaration names.
Douglas Gregore6688e62009-09-28 03:51:44 +00001098 return isEarlierDeclarationName(X.Declaration->getDeclName(),
1099 Y.Declaration->getDeclName());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001100
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001101 case Result::RK_Macro:
1102 return llvm::LowercaseString(X.Macro->getName()) <
1103 llvm::LowercaseString(Y.Macro->getName());
Douglas Gregor45f83ee2009-11-19 00:01:57 +00001104
1105 case Result::RK_Keyword:
1106 case Result::RK_Pattern:
1107 llvm::llvm_unreachable("Result kinds handled above");
1108 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001109 }
1110
1111 // Silence GCC warning.
1112 return false;
1113 }
1114 };
1115}
1116
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001117static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1118 ResultBuilder &Results) {
1119 Results.EnterNewScope();
Douglas Gregor9eb77012009-11-07 00:00:49 +00001120 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1121 MEnd = PP.macro_end();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001122 M != MEnd; ++M)
1123 Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1124 Results.ExitScope();
1125}
1126
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001127static void HandleCodeCompleteResults(Sema *S,
1128 CodeCompleteConsumer *CodeCompleter,
1129 CodeCompleteConsumer::Result *Results,
1130 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001131 // Sort the results by rank/kind/etc.
1132 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1133
1134 if (CodeCompleter)
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001135 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor45f83ee2009-11-19 00:01:57 +00001136
1137 for (unsigned I = 0; I != NumResults; ++I)
1138 Results[I].Destroy();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001139}
1140
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001141void Sema::CodeCompleteOrdinaryName(Scope *S) {
1142 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001143 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1144 0, CurContext, Results);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001145 if (CodeCompleter->includeMacros())
1146 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001147 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001148}
1149
Douglas Gregor9291bad2009-11-18 01:29:26 +00001150static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00001151 bool AllowCategories,
Douglas Gregor9291bad2009-11-18 01:29:26 +00001152 DeclContext *CurContext,
1153 ResultBuilder &Results) {
1154 typedef CodeCompleteConsumer::Result Result;
1155
1156 // Add properties in this container.
1157 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
1158 PEnd = Container->prop_end();
1159 P != PEnd;
1160 ++P)
1161 Results.MaybeAddResult(Result(*P, 0), CurContext);
1162
1163 // Add properties in referenced protocols.
1164 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
1165 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
1166 PEnd = Protocol->protocol_end();
1167 P != PEnd; ++P)
Douglas Gregor5d649882009-11-18 22:32:06 +00001168 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00001169 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00001170 if (AllowCategories) {
1171 // Look through categories.
1172 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
1173 Category; Category = Category->getNextClassCategory())
1174 AddObjCProperties(Category, AllowCategories, CurContext, Results);
1175 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00001176
1177 // Look through protocols.
1178 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
1179 E = IFace->protocol_end();
1180 I != E; ++I)
Douglas Gregor5d649882009-11-18 22:32:06 +00001181 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00001182
1183 // Look in the superclass.
1184 if (IFace->getSuperClass())
Douglas Gregor5d649882009-11-18 22:32:06 +00001185 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
1186 Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00001187 } else if (const ObjCCategoryDecl *Category
1188 = dyn_cast<ObjCCategoryDecl>(Container)) {
1189 // Look through protocols.
1190 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
1191 PEnd = Category->protocol_end();
1192 P != PEnd; ++P)
Douglas Gregor5d649882009-11-18 22:32:06 +00001193 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00001194 }
1195}
1196
Douglas Gregor2436e712009-09-17 21:32:03 +00001197void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1198 SourceLocation OpLoc,
1199 bool IsArrow) {
1200 if (!BaseE || !CodeCompleter)
1201 return;
1202
Douglas Gregor3545ff42009-09-21 16:56:56 +00001203 typedef CodeCompleteConsumer::Result Result;
1204
Douglas Gregor2436e712009-09-17 21:32:03 +00001205 Expr *Base = static_cast<Expr *>(BaseE);
1206 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001207
1208 if (IsArrow) {
1209 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1210 BaseType = Ptr->getPointeeType();
1211 else if (BaseType->isObjCObjectPointerType())
1212 /*Do nothing*/ ;
1213 else
1214 return;
1215 }
1216
Douglas Gregore412a5a2009-09-23 22:26:46 +00001217 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001218 unsigned NextRank = 0;
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001219
Douglas Gregor9291bad2009-11-18 01:29:26 +00001220 Results.EnterNewScope();
1221 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
1222 // Access to a C/C++ class, struct, or union.
1223 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1224 Record->getDecl(), Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001225
Douglas Gregor9291bad2009-11-18 01:29:26 +00001226 if (getLangOptions().CPlusPlus) {
1227 if (!Results.empty()) {
1228 // The "template" keyword can follow "->" or "." in the grammar.
1229 // However, we only want to suggest the template keyword if something
1230 // is dependent.
1231 bool IsDependent = BaseType->isDependentType();
1232 if (!IsDependent) {
1233 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1234 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1235 IsDependent = Ctx->isDependentContext();
1236 break;
1237 }
1238 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001239
Douglas Gregor9291bad2009-11-18 01:29:26 +00001240 if (IsDependent)
1241 Results.MaybeAddResult(Result("template", NextRank++));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001242 }
1243
Douglas Gregor9291bad2009-11-18 01:29:26 +00001244 // We could have the start of a nested-name-specifier. Add those
1245 // results as well.
1246 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1247 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
1248 CurContext, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001249 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00001250 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
1251 // Objective-C property reference.
1252
1253 // Add property results based on our interface.
1254 const ObjCObjectPointerType *ObjCPtr
1255 = BaseType->getAsObjCInterfacePointerType();
1256 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor5d649882009-11-18 22:32:06 +00001257 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00001258
1259 // Add properties from the protocols in a qualified interface.
1260 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
1261 E = ObjCPtr->qual_end();
1262 I != E; ++I)
Douglas Gregor5d649882009-11-18 22:32:06 +00001263 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00001264
1265 // FIXME: We could (should?) also look for "implicit" properties, identified
1266 // only by the presence of nullary and unary selectors.
1267 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
1268 (!IsArrow && BaseType->isObjCInterfaceType())) {
1269 // Objective-C instance variable access.
1270 ObjCInterfaceDecl *Class = 0;
1271 if (const ObjCObjectPointerType *ObjCPtr
1272 = BaseType->getAs<ObjCObjectPointerType>())
1273 Class = ObjCPtr->getInterfaceDecl();
1274 else
1275 Class = BaseType->getAs<ObjCInterfaceType>()->getDecl();
1276
1277 // Add all ivars from this class and its superclasses.
1278 for (; Class; Class = Class->getSuperClass()) {
1279 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
1280 IVarEnd = Class->ivar_end();
1281 IVar != IVarEnd; ++IVar)
1282 Results.MaybeAddResult(Result(*IVar, 0), CurContext);
1283 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001284 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00001285
1286 // FIXME: How do we cope with isa?
1287
1288 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001289
1290 // Add macros
1291 if (CodeCompleter->includeMacros())
1292 AddMacroResults(PP, NextRank, Results);
1293
1294 // Hand off the results found for code completion.
1295 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00001296}
1297
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001298void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1299 if (!CodeCompleter)
1300 return;
1301
Douglas Gregor3545ff42009-09-21 16:56:56 +00001302 typedef CodeCompleteConsumer::Result Result;
1303 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001304 switch ((DeclSpec::TST)TagSpec) {
1305 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00001306 Filter = &ResultBuilder::IsEnum;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001307 break;
1308
1309 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00001310 Filter = &ResultBuilder::IsUnion;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001311 break;
1312
1313 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001314 case DeclSpec::TST_class:
Douglas Gregor3545ff42009-09-21 16:56:56 +00001315 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001316 break;
1317
1318 default:
1319 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1320 return;
1321 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001322
1323 ResultBuilder Results(*this, Filter);
1324 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor2af2f672009-09-21 20:12:40 +00001325 0, CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001326
1327 if (getLangOptions().CPlusPlus) {
1328 // We could have the start of a nested-name-specifier. Add those
1329 // results as well.
1330 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001331 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1332 NextRank, CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001333 }
1334
Douglas Gregor9eb77012009-11-07 00:00:49 +00001335 if (CodeCompleter->includeMacros())
1336 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001337 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001338}
1339
Douglas Gregord328d572009-09-21 18:10:23 +00001340void Sema::CodeCompleteCase(Scope *S) {
1341 if (getSwitchStack().empty() || !CodeCompleter)
1342 return;
1343
1344 SwitchStmt *Switch = getSwitchStack().back();
1345 if (!Switch->getCond()->getType()->isEnumeralType())
1346 return;
1347
1348 // Code-complete the cases of a switch statement over an enumeration type
1349 // by providing the list of
1350 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1351
1352 // Determine which enumerators we have already seen in the switch statement.
1353 // FIXME: Ideally, we would also be able to look *past* the code-completion
1354 // token, in case we are code-completing in the middle of the switch and not
1355 // at the end. However, we aren't able to do so at the moment.
1356 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorf2510672009-09-21 19:57:38 +00001357 NestedNameSpecifier *Qualifier = 0;
Douglas Gregord328d572009-09-21 18:10:23 +00001358 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1359 SC = SC->getNextSwitchCase()) {
1360 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1361 if (!Case)
1362 continue;
1363
1364 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1365 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1366 if (EnumConstantDecl *Enumerator
1367 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1368 // We look into the AST of the case statement to determine which
1369 // enumerator was named. Alternatively, we could compute the value of
1370 // the integral constant expression, then compare it against the
1371 // values of each enumerator. However, value-based approach would not
1372 // work as well with C++ templates where enumerators declared within a
1373 // template are type- and value-dependent.
1374 EnumeratorsSeen.insert(Enumerator);
1375
Douglas Gregorf2510672009-09-21 19:57:38 +00001376 // If this is a qualified-id, keep track of the nested-name-specifier
1377 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00001378 //
1379 // switch (TagD.getKind()) {
1380 // case TagDecl::TK_enum:
1381 // break;
1382 // case XXX
1383 //
Douglas Gregorf2510672009-09-21 19:57:38 +00001384 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00001385 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1386 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00001387 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00001388 }
1389 }
1390
Douglas Gregorf2510672009-09-21 19:57:38 +00001391 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1392 // If there are no prior enumerators in C++, check whether we have to
1393 // qualify the names of the enumerators that we suggest, because they
1394 // may not be visible in this scope.
1395 Qualifier = getRequiredQualification(Context, CurContext,
1396 Enum->getDeclContext());
1397
1398 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1399 }
1400
Douglas Gregord328d572009-09-21 18:10:23 +00001401 // Add any enumerators that have not yet been mentioned.
1402 ResultBuilder Results(*this);
1403 Results.EnterNewScope();
1404 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1405 EEnd = Enum->enumerator_end();
1406 E != EEnd; ++E) {
1407 if (EnumeratorsSeen.count(*E))
1408 continue;
1409
Douglas Gregorf2510672009-09-21 19:57:38 +00001410 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregord328d572009-09-21 18:10:23 +00001411 }
1412 Results.ExitScope();
1413
Douglas Gregor9eb77012009-11-07 00:00:49 +00001414 if (CodeCompleter->includeMacros())
1415 AddMacroResults(PP, 1, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001416 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00001417}
1418
Douglas Gregorcabea402009-09-22 15:41:20 +00001419namespace {
1420 struct IsBetterOverloadCandidate {
1421 Sema &S;
1422
1423 public:
1424 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1425
1426 bool
1427 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1428 return S.isBetterOverloadCandidate(X, Y);
1429 }
1430 };
1431}
1432
1433void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1434 ExprTy **ArgsIn, unsigned NumArgs) {
1435 if (!CodeCompleter)
1436 return;
1437
1438 Expr *Fn = (Expr *)FnIn;
1439 Expr **Args = (Expr **)ArgsIn;
1440
1441 // Ignore type-dependent call expressions entirely.
1442 if (Fn->isTypeDependent() ||
1443 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1444 return;
1445
1446 NamedDecl *Function;
1447 DeclarationName UnqualifiedName;
1448 NestedNameSpecifier *Qualifier;
1449 SourceRange QualifierRange;
1450 bool ArgumentDependentLookup;
1451 bool HasExplicitTemplateArgs;
John McCall0ad16662009-10-29 08:12:44 +00001452 const TemplateArgumentLoc *ExplicitTemplateArgs;
Douglas Gregorcabea402009-09-22 15:41:20 +00001453 unsigned NumExplicitTemplateArgs;
1454
1455 DeconstructCallFunction(Fn,
1456 Function, UnqualifiedName, Qualifier, QualifierRange,
1457 ArgumentDependentLookup, HasExplicitTemplateArgs,
1458 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1459
1460
1461 // FIXME: What if we're calling something that isn't a function declaration?
1462 // FIXME: What if we're calling a pseudo-destructor?
1463 // FIXME: What if we're calling a member function?
1464
1465 // Build an overload candidate set based on the functions we find.
1466 OverloadCandidateSet CandidateSet;
1467 AddOverloadedCallCandidates(Function, UnqualifiedName,
1468 ArgumentDependentLookup, HasExplicitTemplateArgs,
1469 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1470 Args, NumArgs,
1471 CandidateSet,
1472 /*PartialOverloading=*/true);
1473
1474 // Sort the overload candidate set by placing the best overloads first.
1475 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1476 IsBetterOverloadCandidate(*this));
1477
1478 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05f477c2009-09-23 00:16:58 +00001479 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1480 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlssone7ceb852009-09-22 17:29:51 +00001481
Douglas Gregorcabea402009-09-22 15:41:20 +00001482 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1483 CandEnd = CandidateSet.end();
1484 Cand != CandEnd; ++Cand) {
1485 if (Cand->Viable)
Douglas Gregor05f477c2009-09-23 00:16:58 +00001486 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregorcabea402009-09-22 15:41:20 +00001487 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001488 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
Douglas Gregor05f477c2009-09-23 00:16:58 +00001489 Results.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00001490}
1491
Douglas Gregor2436e712009-09-17 21:32:03 +00001492void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1493 bool EnteringContext) {
1494 if (!SS.getScopeRep() || !CodeCompleter)
1495 return;
1496
Douglas Gregor3545ff42009-09-21 16:56:56 +00001497 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1498 if (!Ctx)
1499 return;
1500
1501 ResultBuilder Results(*this);
Douglas Gregor2af2f672009-09-21 20:12:40 +00001502 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001503
1504 // The "template" keyword can follow "::" in the grammar, but only
1505 // put it into the grammar if the nested-name-specifier is dependent.
1506 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1507 if (!Results.empty() && NNS->isDependent())
1508 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1509
Douglas Gregor9eb77012009-11-07 00:00:49 +00001510 if (CodeCompleter->includeMacros())
1511 AddMacroResults(PP, NextRank + 1, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001512 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00001513}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001514
1515void Sema::CodeCompleteUsing(Scope *S) {
1516 if (!CodeCompleter)
1517 return;
1518
Douglas Gregor3545ff42009-09-21 16:56:56 +00001519 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001520 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001521
1522 // If we aren't in class scope, we could see the "namespace" keyword.
1523 if (!S->isClassScope())
1524 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1525
1526 // After "using", we can see anything that would start a
1527 // nested-name-specifier.
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001528 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1529 0, CurContext, Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001530 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001531
Douglas Gregor9eb77012009-11-07 00:00:49 +00001532 if (CodeCompleter->includeMacros())
1533 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001534 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001535}
1536
1537void Sema::CodeCompleteUsingDirective(Scope *S) {
1538 if (!CodeCompleter)
1539 return;
1540
Douglas Gregor3545ff42009-09-21 16:56:56 +00001541 // After "using namespace", we expect to see a namespace name or namespace
1542 // alias.
1543 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001544 Results.EnterNewScope();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001545 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1546 0, CurContext, Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001547 Results.ExitScope();
Douglas Gregor9eb77012009-11-07 00:00:49 +00001548 if (CodeCompleter->includeMacros())
1549 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001550 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001551}
1552
1553void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1554 if (!CodeCompleter)
1555 return;
1556
Douglas Gregor3545ff42009-09-21 16:56:56 +00001557 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1558 DeclContext *Ctx = (DeclContext *)S->getEntity();
1559 if (!S->getParent())
1560 Ctx = Context.getTranslationUnitDecl();
1561
1562 if (Ctx && Ctx->isFileContext()) {
1563 // We only want to see those namespaces that have already been defined
1564 // within this scope, because its likely that the user is creating an
1565 // extended namespace declaration. Keep track of the most recent
1566 // definition of each namespace.
1567 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1568 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1569 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1570 NS != NSEnd; ++NS)
1571 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1572
1573 // Add the most recent definition (or extended definition) of each
1574 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00001575 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001576 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1577 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1578 NS != NSEnd; ++NS)
Douglas Gregor2af2f672009-09-21 20:12:40 +00001579 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1580 CurContext);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001581 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001582 }
1583
Douglas Gregor9eb77012009-11-07 00:00:49 +00001584 if (CodeCompleter->includeMacros())
1585 AddMacroResults(PP, 1, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001586 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001587}
1588
1589void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1590 if (!CodeCompleter)
1591 return;
1592
Douglas Gregor3545ff42009-09-21 16:56:56 +00001593 // After "namespace", we expect to see a namespace or alias.
1594 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001595 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1596 0, CurContext, Results);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001597 if (CodeCompleter->includeMacros())
1598 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001599 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001600}
1601
Douglas Gregorc811ede2009-09-18 20:05:18 +00001602void Sema::CodeCompleteOperatorName(Scope *S) {
1603 if (!CodeCompleter)
1604 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001605
1606 typedef CodeCompleteConsumer::Result Result;
1607 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001608 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00001609
Douglas Gregor3545ff42009-09-21 16:56:56 +00001610 // Add the names of overloadable operators.
1611#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1612 if (std::strcmp(Spelling, "?")) \
1613 Results.MaybeAddResult(Result(Spelling, 0));
1614#include "clang/Basic/OperatorKinds.def"
1615
1616 // Add any type names visible from the current scope
1617 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor2af2f672009-09-21 20:12:40 +00001618 0, CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001619
1620 // Add any type specifiers
1621 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1622
1623 // Add any nested-name-specifiers
1624 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001625 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1626 NextRank + 1, CurContext, Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001627 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001628
Douglas Gregor9eb77012009-11-07 00:00:49 +00001629 if (CodeCompleter->includeMacros())
1630 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001631 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00001632}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001633
Douglas Gregor36029f42009-11-18 23:08:07 +00001634void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00001635 if (!CodeCompleter)
1636 return;
1637 unsigned Attributes = ODS.getPropertyAttributes();
1638
1639 typedef CodeCompleteConsumer::Result Result;
1640 ResultBuilder Results(*this);
1641 Results.EnterNewScope();
1642 if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly))
1643 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
1644 if (!(Attributes & ObjCDeclSpec::DQ_PR_assign))
1645 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
1646 if (!(Attributes & ObjCDeclSpec::DQ_PR_readwrite))
1647 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
1648 if (!(Attributes & ObjCDeclSpec::DQ_PR_retain))
1649 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
1650 if (!(Attributes & ObjCDeclSpec::DQ_PR_copy))
1651 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
1652 if (!(Attributes & ObjCDeclSpec::DQ_PR_nonatomic))
1653 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00001654 if (!(Attributes & ObjCDeclSpec::DQ_PR_setter)) {
1655 CodeCompletionString *Setter = new CodeCompletionString;
1656 Setter->AddTypedTextChunk("setter");
1657 Setter->AddTextChunk(" = ");
1658 Setter->AddPlaceholderChunk("method");
1659 Results.MaybeAddResult(CodeCompleteConsumer::Result(Setter, 0));
1660 }
1661 if (!(Attributes & ObjCDeclSpec::DQ_PR_getter)) {
1662 CodeCompletionString *Getter = new CodeCompletionString;
1663 Getter->AddTypedTextChunk("getter");
1664 Getter->AddTextChunk(" = ");
1665 Getter->AddPlaceholderChunk("method");
1666 Results.MaybeAddResult(CodeCompleteConsumer::Result(Getter, 0));
1667 }
Steve Naroff936354c2009-10-08 21:55:05 +00001668 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001669 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00001670}
Steve Naroffeae65032009-11-07 02:08:14 +00001671
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001672/// \brief Add all of the Objective-C methods in the given Objective-C
1673/// container to the set of results.
1674///
1675/// The container will be a class, protocol, category, or implementation of
1676/// any of the above. This mether will recurse to include methods from
1677/// the superclasses of classes along with their categories, protocols, and
1678/// implementations.
1679///
1680/// \param Container the container in which we'll look to find methods.
1681///
1682/// \param WantInstance whether to add instance methods (only); if false, this
1683/// routine will add factory methods (only).
1684///
1685/// \param CurContext the context in which we're performing the lookup that
1686/// finds methods.
1687///
1688/// \param Results the structure into which we'll add results.
1689static void AddObjCMethods(ObjCContainerDecl *Container,
1690 bool WantInstanceMethods,
1691 DeclContext *CurContext,
1692 ResultBuilder &Results) {
1693 typedef CodeCompleteConsumer::Result Result;
1694 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
1695 MEnd = Container->meth_end();
1696 M != MEnd; ++M) {
1697 if ((*M)->isInstanceMethod() == WantInstanceMethods)
1698 Results.MaybeAddResult(Result(*M, 0), CurContext);
1699 }
1700
1701 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
1702 if (!IFace)
1703 return;
1704
1705 // Add methods in protocols.
1706 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
1707 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1708 E = Protocols.end();
1709 I != E; ++I)
1710 AddObjCMethods(*I, WantInstanceMethods, CurContext, Results);
1711
1712 // Add methods in categories.
1713 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
1714 CatDecl = CatDecl->getNextClassCategory()) {
1715 AddObjCMethods(CatDecl, WantInstanceMethods, CurContext, Results);
1716
1717 // Add a categories protocol methods.
1718 const ObjCList<ObjCProtocolDecl> &Protocols
1719 = CatDecl->getReferencedProtocols();
1720 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1721 E = Protocols.end();
1722 I != E; ++I)
1723 AddObjCMethods(*I, WantInstanceMethods, CurContext, Results);
1724
1725 // Add methods in category implementations.
1726 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
1727 AddObjCMethods(Impl, WantInstanceMethods, CurContext, Results);
1728 }
1729
1730 // Add methods in superclass.
1731 if (IFace->getSuperClass())
1732 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, CurContext,
1733 Results);
1734
1735 // Add methods in our implementation, if any.
1736 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
1737 AddObjCMethods(Impl, WantInstanceMethods, CurContext, Results);
1738}
1739
Douglas Gregor090dd182009-11-17 23:31:36 +00001740void Sema::CodeCompleteObjCClassMessage(Scope *S, IdentifierInfo *FName,
1741 SourceLocation FNameLoc) {
Steve Naroffeae65032009-11-07 02:08:14 +00001742 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor8ce33212009-11-17 17:59:40 +00001743 ObjCInterfaceDecl *CDecl = 0;
1744
Douglas Gregor8ce33212009-11-17 17:59:40 +00001745 if (FName->isStr("super")) {
1746 // We're sending a message to "super".
1747 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
1748 // Figure out which interface we're in.
1749 CDecl = CurMethod->getClassInterface();
1750 if (!CDecl)
1751 return;
1752
1753 // Find the superclass of this class.
1754 CDecl = CDecl->getSuperClass();
1755 if (!CDecl)
1756 return;
1757
1758 if (CurMethod->isInstanceMethod()) {
1759 // We are inside an instance method, which means that the message
1760 // send [super ...] is actually calling an instance method on the
1761 // current object. Build the super expression and handle this like
1762 // an instance method.
1763 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
1764 SuperTy = Context.getObjCObjectPointerType(SuperTy);
1765 OwningExprResult Super
Douglas Gregor090dd182009-11-17 23:31:36 +00001766 = Owned(new (Context) ObjCSuperExpr(FNameLoc, SuperTy));
1767 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get());
Douglas Gregor8ce33212009-11-17 17:59:40 +00001768 }
1769
1770 // Okay, we're calling a factory method in our superclass.
1771 }
1772 }
1773
1774 // If the given name refers to an interface type, retrieve the
1775 // corresponding declaration.
1776 if (!CDecl)
Douglas Gregor090dd182009-11-17 23:31:36 +00001777 if (TypeTy *Ty = getTypeName(*FName, FNameLoc, S, 0, false)) {
Douglas Gregor8ce33212009-11-17 17:59:40 +00001778 QualType T = GetTypeFromParser(Ty, 0);
1779 if (!T.isNull())
1780 if (const ObjCInterfaceType *Interface = T->getAs<ObjCInterfaceType>())
1781 CDecl = Interface->getDecl();
1782 }
1783
1784 if (!CDecl && FName->isStr("super")) {
1785 // "super" may be the name of a variable, in which case we are
1786 // probably calling an instance method.
Douglas Gregor090dd182009-11-17 23:31:36 +00001787 OwningExprResult Super = ActOnDeclarationNameExpr(S, FNameLoc, FName,
Douglas Gregor8ce33212009-11-17 17:59:40 +00001788 false, 0, false);
Douglas Gregor090dd182009-11-17 23:31:36 +00001789 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get());
Douglas Gregor8ce33212009-11-17 17:59:40 +00001790 }
1791
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001792 // Add all of the factory methods in this Objective-C class, its protocols,
1793 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00001794 ResultBuilder Results(*this);
1795 Results.EnterNewScope();
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001796 AddObjCMethods(CDecl, false, CurContext, Results);
Steve Naroffeae65032009-11-07 02:08:14 +00001797 Results.ExitScope();
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001798
Steve Naroffeae65032009-11-07 02:08:14 +00001799 // This also suppresses remaining diagnostics.
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001800 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00001801}
1802
Douglas Gregor090dd182009-11-17 23:31:36 +00001803void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver) {
Steve Naroffeae65032009-11-07 02:08:14 +00001804 typedef CodeCompleteConsumer::Result Result;
Steve Naroffeae65032009-11-07 02:08:14 +00001805
1806 Expr *RecExpr = static_cast<Expr *>(Receiver);
1807 QualType RecType = RecExpr->getType();
1808
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001809 // If necessary, apply function/array conversion to the receiver.
1810 // C99 6.7.5.3p[7,8].
1811 DefaultFunctionArrayConversion(RecExpr);
1812 QualType ReceiverType = RecExpr->getType();
Steve Naroffeae65032009-11-07 02:08:14 +00001813
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001814 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType()) {
1815 // FIXME: We're messaging 'id'. Do we actually want to look up every method
1816 // in the universe?
1817 return;
1818 }
1819
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001820 // Build the set of methods we can see.
1821 ResultBuilder Results(*this);
1822 Results.EnterNewScope();
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001823
Douglas Gregora3329fa2009-11-18 00:06:18 +00001824 // Handle messages to Class. This really isn't a message to an instance
1825 // method, so we treat it the same way we would treat a message send to a
1826 // class method.
1827 if (ReceiverType->isObjCClassType() ||
1828 ReceiverType->isObjCQualifiedClassType()) {
1829 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
1830 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
1831 AddObjCMethods(ClassDecl, false, CurContext, Results);
1832 }
1833 }
1834 // Handle messages to a qualified ID ("id<foo>").
1835 else if (const ObjCObjectPointerType *QualID
1836 = ReceiverType->getAsObjCQualifiedIdType()) {
1837 // Search protocols for instance methods.
1838 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
1839 E = QualID->qual_end();
1840 I != E; ++I)
1841 AddObjCMethods(*I, true, CurContext, Results);
1842 }
1843 // Handle messages to a pointer to interface type.
1844 else if (const ObjCObjectPointerType *IFacePtr
1845 = ReceiverType->getAsObjCInterfacePointerType()) {
1846 // Search the class, its superclasses, etc., for instance methods.
1847 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, CurContext, Results);
1848
1849 // Search protocols for instance methods.
1850 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
1851 E = IFacePtr->qual_end();
1852 I != E; ++I)
1853 AddObjCMethods(*I, true, CurContext, Results);
1854 }
1855
Steve Naroffeae65032009-11-07 02:08:14 +00001856 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001857 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00001858}
Douglas Gregorbaf69612009-11-18 04:19:12 +00001859
1860/// \brief Add all of the protocol declarations that we find in the given
1861/// (translation unit) context.
1862static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00001863 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00001864 ResultBuilder &Results) {
1865 typedef CodeCompleteConsumer::Result Result;
1866
1867 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
1868 DEnd = Ctx->decls_end();
1869 D != DEnd; ++D) {
1870 // Record any protocols we find.
1871 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor5b4671c2009-11-18 04:49:41 +00001872 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
1873 Results.MaybeAddResult(Result(Proto, 0), CurContext);
Douglas Gregorbaf69612009-11-18 04:19:12 +00001874
1875 // Record any forward-declared protocols we find.
1876 if (ObjCForwardProtocolDecl *Forward
1877 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
1878 for (ObjCForwardProtocolDecl::protocol_iterator
1879 P = Forward->protocol_begin(),
1880 PEnd = Forward->protocol_end();
1881 P != PEnd; ++P)
Douglas Gregor5b4671c2009-11-18 04:49:41 +00001882 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
1883 Results.MaybeAddResult(Result(*P, 0), CurContext);
Douglas Gregorbaf69612009-11-18 04:19:12 +00001884 }
1885 }
1886}
1887
1888void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
1889 unsigned NumProtocols) {
1890 ResultBuilder Results(*this);
1891 Results.EnterNewScope();
1892
1893 // Tell the result set to ignore all of the protocols we have
1894 // already seen.
1895 for (unsigned I = 0; I != NumProtocols; ++I)
1896 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first))
1897 Results.Ignore(Protocol);
1898
1899 // Add all protocols.
Douglas Gregor5b4671c2009-11-18 04:49:41 +00001900 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
1901 Results);
1902
1903 Results.ExitScope();
1904 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1905}
1906
1907void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
1908 ResultBuilder Results(*this);
1909 Results.EnterNewScope();
1910
1911 // Add all protocols.
1912 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
1913 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00001914
1915 Results.ExitScope();
1916 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1917}
Douglas Gregor49c22a72009-11-18 16:26:39 +00001918
1919/// \brief Add all of the Objective-C interface declarations that we find in
1920/// the given (translation unit) context.
1921static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
1922 bool OnlyForwardDeclarations,
1923 bool OnlyUnimplemented,
1924 ResultBuilder &Results) {
1925 typedef CodeCompleteConsumer::Result Result;
1926
1927 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
1928 DEnd = Ctx->decls_end();
1929 D != DEnd; ++D) {
1930 // Record any interfaces we find.
1931 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
1932 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
1933 (!OnlyUnimplemented || !Class->getImplementation()))
1934 Results.MaybeAddResult(Result(Class, 0), CurContext);
1935
1936 // Record any forward-declared interfaces we find.
1937 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
1938 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
1939 C != CEnd; ++C)
1940 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
1941 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
1942 Results.MaybeAddResult(Result(C->getInterface(), 0), CurContext);
1943 }
1944 }
1945}
1946
1947void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
1948 ResultBuilder Results(*this);
1949 Results.EnterNewScope();
1950
1951 // Add all classes.
1952 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
1953 false, Results);
1954
1955 Results.ExitScope();
1956 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1957}
1958
1959void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName) {
1960 ResultBuilder Results(*this);
1961 Results.EnterNewScope();
1962
1963 // Make sure that we ignore the class we're currently defining.
1964 NamedDecl *CurClass
1965 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00001966 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00001967 Results.Ignore(CurClass);
1968
1969 // Add all classes.
1970 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
1971 false, Results);
1972
1973 Results.ExitScope();
1974 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1975}
1976
1977void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
1978 ResultBuilder Results(*this);
1979 Results.EnterNewScope();
1980
1981 // Add all unimplemented classes.
1982 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
1983 true, Results);
1984
1985 Results.ExitScope();
1986 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1987}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00001988
1989void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
1990 IdentifierInfo *ClassName) {
1991 typedef CodeCompleteConsumer::Result Result;
1992
1993 ResultBuilder Results(*this);
1994
1995 // Ignore any categories we find that have already been implemented by this
1996 // interface.
1997 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
1998 NamedDecl *CurClass
1999 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
2000 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
2001 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
2002 Category = Category->getNextClassCategory())
2003 CategoryNames.insert(Category->getIdentifier());
2004
2005 // Add all of the categories we know about.
2006 Results.EnterNewScope();
2007 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
2008 for (DeclContext::decl_iterator D = TU->decls_begin(),
2009 DEnd = TU->decls_end();
2010 D != DEnd; ++D)
2011 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
2012 if (CategoryNames.insert(Category->getIdentifier()))
2013 Results.MaybeAddResult(Result(Category, 0), CurContext);
2014 Results.ExitScope();
2015
2016 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2017}
2018
2019void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
2020 IdentifierInfo *ClassName) {
2021 typedef CodeCompleteConsumer::Result Result;
2022
2023 // Find the corresponding interface. If we couldn't find the interface, the
2024 // program itself is ill-formed. However, we'll try to be helpful still by
2025 // providing the list of all of the categories we know about.
2026 NamedDecl *CurClass
2027 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
2028 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
2029 if (!Class)
2030 return CodeCompleteObjCInterfaceCategory(S, ClassName);
2031
2032 ResultBuilder Results(*this);
2033
2034 // Add all of the categories that have have corresponding interface
2035 // declarations in this class and any of its superclasses, except for
2036 // already-implemented categories in the class itself.
2037 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
2038 Results.EnterNewScope();
2039 bool IgnoreImplemented = true;
2040 while (Class) {
2041 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
2042 Category = Category->getNextClassCategory())
2043 if ((!IgnoreImplemented || !Category->getImplementation()) &&
2044 CategoryNames.insert(Category->getIdentifier()))
2045 Results.MaybeAddResult(Result(Category, 0), CurContext);
2046
2047 Class = Class->getSuperClass();
2048 IgnoreImplemented = false;
2049 }
2050 Results.ExitScope();
2051
2052 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2053}
Douglas Gregor5d649882009-11-18 22:32:06 +00002054
Douglas Gregor52e78bd2009-11-18 22:56:13 +00002055void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
Douglas Gregor5d649882009-11-18 22:32:06 +00002056 typedef CodeCompleteConsumer::Result Result;
2057 ResultBuilder Results(*this);
2058
2059 // Figure out where this @synthesize lives.
2060 ObjCContainerDecl *Container
2061 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
2062 if (!Container ||
2063 (!isa<ObjCImplementationDecl>(Container) &&
2064 !isa<ObjCCategoryImplDecl>(Container)))
2065 return;
2066
2067 // Ignore any properties that have already been implemented.
2068 for (DeclContext::decl_iterator D = Container->decls_begin(),
2069 DEnd = Container->decls_end();
2070 D != DEnd; ++D)
2071 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
2072 Results.Ignore(PropertyImpl->getPropertyDecl());
2073
2074 // Add any properties that we find.
2075 Results.EnterNewScope();
2076 if (ObjCImplementationDecl *ClassImpl
2077 = dyn_cast<ObjCImplementationDecl>(Container))
2078 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
2079 Results);
2080 else
2081 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
2082 false, CurContext, Results);
2083 Results.ExitScope();
2084
2085 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2086}
2087
2088void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
2089 IdentifierInfo *PropertyName,
2090 DeclPtrTy ObjCImpDecl) {
2091 typedef CodeCompleteConsumer::Result Result;
2092 ResultBuilder Results(*this);
2093
2094 // Figure out where this @synthesize lives.
2095 ObjCContainerDecl *Container
2096 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
2097 if (!Container ||
2098 (!isa<ObjCImplementationDecl>(Container) &&
2099 !isa<ObjCCategoryImplDecl>(Container)))
2100 return;
2101
2102 // Figure out which interface we're looking into.
2103 ObjCInterfaceDecl *Class = 0;
2104 if (ObjCImplementationDecl *ClassImpl
2105 = dyn_cast<ObjCImplementationDecl>(Container))
2106 Class = ClassImpl->getClassInterface();
2107 else
2108 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
2109 ->getClassInterface();
2110
2111 // Add all of the instance variables in this class and its superclasses.
2112 Results.EnterNewScope();
2113 for(; Class; Class = Class->getSuperClass()) {
2114 // FIXME: We could screen the type of each ivar for compatibility with
2115 // the property, but is that being too paternal?
2116 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
2117 IVarEnd = Class->ivar_end();
2118 IVar != IVarEnd; ++IVar)
2119 Results.MaybeAddResult(Result(*IVar, 0), CurContext);
2120 }
2121 Results.ExitScope();
2122
2123 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2124}