blob: 203b421c913be83e89826d28c65074a07a09564e [file] [log] [blame]
Douglas Gregor81b747b2009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
13#include "Sema.h"
14#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000015#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000016#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000017#include "clang/Lex/MacroInfo.h"
18#include "clang/Lex/Preprocessor.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000019#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000020#include "llvm/ADT/StringExtras.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000021#include <list>
22#include <map>
23#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000024
25using namespace clang;
26
Douglas Gregor86d9a522009-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 Gregor456c4a12009-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 Gregor86d9a522009-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 Gregor55385fe2009-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 Gregor86d9a522009-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 Gregor791215b2009-09-21 20:51:25 +0000107 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000108 bool IsNestedNameSpecifier(NamedDecl *ND) const;
109 bool IsEnum(NamedDecl *ND) const;
110 bool IsClassOrStruct(NamedDecl *ND) const;
111 bool IsUnion(NamedDecl *ND) const;
112 bool IsNamespace(NamedDecl *ND) const;
113 bool IsNamespaceOrAlias(NamedDecl *ND) const;
114 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000115 bool IsMember(NamedDecl *ND) const;
Douglas Gregor86d9a522009-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 Gregor86d9a522009-09-21 16:56:56 +0000142 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
143}
144
Douglas Gregor456c4a12009-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 Gregor0c8296d2009-11-07 00:00:49 +0000187 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000188 return Result;
189}
190
191void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
Douglas Gregor8e0a0e42009-09-22 23:31:26 +0000192 assert(!ShadowMaps.empty() && "Must enter into a results scope");
193
Douglas Gregor86d9a522009-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 Gregorf52cede2009-10-09 22:16:47 +0000199
200 // Skip unnamed entities.
201 if (!R.Declaration->getDeclName())
202 return;
203
Douglas Gregor86d9a522009-09-21 16:56:56 +0000204 // Look through using declarations.
John McCall9488ea12009-11-17 05:59:44 +0000205 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration))
Douglas Gregor0563c262009-09-22 23:15:58 +0000206 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
207 CurContext);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000215 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
Douglas Gregor86d9a522009-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 Gregorf52cede2009-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 Dunbare013d682009-10-18 20:26:12 +0000236 //
237 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000238 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000239 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000240 if (Name[0] == '_' &&
241 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
242 return;
243 }
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000298 R.QualifierIsInformative = false;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000299
300 if (!R.Qualifier)
301 R.Qualifier = getRequiredQualification(SemaRef.Context,
302 CurContext,
303 R.Declaration->getDeclContext());
Douglas Gregor86d9a522009-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 Gregoreb5758b2009-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 Gregor0563c262009-09-22 23:15:58 +0000326 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000327 if (R.QualifierIsInformative && !R.Qualifier &&
328 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-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 Gregoreb5758b2009-09-23 22:26:46 +0000338
Douglas Gregor86d9a522009-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 Gregor791215b2009-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 Gregor86d9a522009-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 Gregoreb5758b2009-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 Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000445/// \param Rank the rank given to results in this declaration context.
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000453/// \param InBaseClass whether we are in a base class.
454///
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000458 unsigned Rank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000459 DeclContext *CurContext,
460 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor0563c262009-09-22 23:15:58 +0000461 ResultBuilder &Results,
462 bool InBaseClass = false) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000463 // Make sure we don't visit the same context twice.
464 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor0563c262009-09-22 23:15:58 +0000465 return Rank;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000466
467 // Enumerate all of the results in this context.
Douglas Gregor0563c262009-09-22 23:15:58 +0000468 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor86d9a522009-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 Gregorff4393c2009-11-09 21:35:27 +0000473 DEnd = CurCtx->decls_end();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000474 D != DEnd; ++D) {
475 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor0563c262009-09-22 23:15:58 +0000476 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregorff4393c2009-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 Gregor86d9a522009-09-21 16:56:56 +0000484 }
485 }
486
487 // Traverse the contexts of inherited classes.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000488 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
489 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
Douglas Gregorff4393c2009-11-09 21:35:27 +0000490 BEnd = Record->bases_end();
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000522 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
523 Results, /*InBaseClass=*/true);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000524 }
525 }
526
527 // FIXME: Look into base classes in Objective-C!
528
529 Results.ExitScope();
Douglas Gregor0563c262009-09-22 23:15:58 +0000530 return Rank + 1;
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000549 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000550 ResultBuilder &Results) {
551 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000552 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
553 Results);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000564/// \param CurContext the context from which lookup results will be found.
565///
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000570 DeclContext *CurContext,
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000592 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
593 Results);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000607 CurContext, Results);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000613 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
614 CurContext);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000622 CurContext, Results);
Douglas Gregor86d9a522009-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 Gregor0c8296d2009-11-07 00:00:49 +0000680 typedef CodeCompletionString::Chunk Chunk;
681
Douglas Gregor86d9a522009-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 Gregor0c8296d2009-11-07 00:00:49 +0000696 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-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 Gregorb3d45252009-09-22 21:42:17 +0000709
710 if (const FunctionProtoType *Proto
711 = Function->getType()->getAs<FunctionProtoType>())
712 if (Proto->isVariadic())
713 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-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 Gregor0c8296d2009-11-07 00:00:49 +0000721 typedef CodeCompletionString::Chunk Chunk;
722
Douglas Gregor86d9a522009-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 Gregor0c8296d2009-11-07 00:00:49 +0000778 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000779
780 // Add the placeholder string.
781 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
782 }
783}
784
Douglas Gregorb9d0ef72009-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 Gregor0563c262009-09-22 23:15:58 +0000789 bool QualifierIsInformative,
Douglas Gregorb9d0ef72009-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 Gregor0563c262009-09-22 23:15:58 +0000799 if (QualifierIsInformative)
800 Result->AddInformativeChunk(PrintedNNS.c_str());
801 else
802 Result->AddTextChunk(PrintedNNS.c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000803}
804
Douglas Gregor86d9a522009-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 Gregor0c8296d2009-11-07 00:00:49 +0000813 typedef CodeCompletionString::Chunk Chunk;
814
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000815 if (Kind == RK_Keyword)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000816 return 0;
817
Douglas Gregor3f7c7f42009-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 Gregor0c8296d2009-11-07 00:00:49 +0000825 Result->AddTypedTextChunk(Macro->getName().str().c_str());
826 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-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 Gregor0c8296d2009-11-07 00:00:49 +0000830 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-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 Gregor0c8296d2009-11-07 00:00:49 +0000849 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000850 return Result;
851 }
852
853 assert(Kind == RK_Declaration && "Missed a macro kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000854 NamedDecl *ND = Declaration;
855
Douglas Gregor0c8296d2009-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 Gregor86d9a522009-09-21 16:56:56 +0000863 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
864 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000865 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
866 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000867 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
868 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000869 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000870 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000871 return Result;
872 }
873
874 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
875 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000876 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
877 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000878 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000879 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
Douglas Gregor86d9a522009-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 Gregor0c8296d2009-11-07 00:00:49 +0000903 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-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 Gregor0c8296d2009-11-07 00:00:49 +0000915 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000916 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
917 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000918 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000919 }
920
921 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000922 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000923 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000924 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000925 return Result;
926 }
927
928 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
929 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000930 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
931 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000932 Result->AddTypedTextChunk(Template->getNameAsString().c_str());
933 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000934 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000935 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000936 return Result;
937 }
938
Douglas Gregor9630eb62009-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
Douglas Gregord3c68542009-11-19 01:08:35 +0000947 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
948 SelName += ':';
949 if (StartParameter == 0)
950 Result->AddTypedTextChunk(SelName);
951 else {
952 Result->AddInformativeChunk(SelName);
953
954 // If there is only one parameter, and we're past it, add an empty
955 // typed-text chunk since there is nothing to type.
956 if (Method->param_size() == 1)
957 Result->AddTypedTextChunk("");
958 }
Douglas Gregor9630eb62009-11-17 16:44:22 +0000959 unsigned Idx = 0;
960 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
961 PEnd = Method->param_end();
962 P != PEnd; (void)++P, ++Idx) {
963 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +0000964 std::string Keyword;
965 if (Idx > StartParameter)
966 Keyword = " ";
Douglas Gregor9630eb62009-11-17 16:44:22 +0000967 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
968 Keyword += II->getName().str();
969 Keyword += ":";
Douglas Gregor4ad96852009-11-19 07:41:15 +0000970 if (Idx < StartParameter || AllParametersAreInformative) {
Douglas Gregord3c68542009-11-19 01:08:35 +0000971 Result->AddInformativeChunk(Keyword);
972 } else if (Idx == StartParameter)
973 Result->AddTypedTextChunk(Keyword);
974 else
975 Result->AddTextChunk(Keyword);
Douglas Gregor9630eb62009-11-17 16:44:22 +0000976 }
Douglas Gregord3c68542009-11-19 01:08:35 +0000977
978 // If we're before the starting parameter, skip the placeholder.
979 if (Idx < StartParameter)
980 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +0000981
982 std::string Arg;
983 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
984 Arg = "(" + Arg + ")";
985 if (IdentifierInfo *II = (*P)->getIdentifier())
986 Arg += II->getName().str();
Douglas Gregor4ad96852009-11-19 07:41:15 +0000987 if (AllParametersAreInformative)
988 Result->AddInformativeChunk(Arg);
989 else
990 Result->AddPlaceholderChunk(Arg);
Douglas Gregor9630eb62009-11-17 16:44:22 +0000991 }
992
993 return Result;
994 }
995
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000996 if (Qualifier) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000997 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000998 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
999 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001000 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001001 return Result;
1002 }
1003
Douglas Gregor86d9a522009-09-21 16:56:56 +00001004 return 0;
1005}
1006
Douglas Gregor86d802e2009-09-23 00:34:09 +00001007CodeCompletionString *
1008CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
1009 unsigned CurrentArg,
1010 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001011 typedef CodeCompletionString::Chunk Chunk;
1012
Douglas Gregor86d802e2009-09-23 00:34:09 +00001013 CodeCompletionString *Result = new CodeCompletionString;
1014 FunctionDecl *FDecl = getFunction();
1015 const FunctionProtoType *Proto
1016 = dyn_cast<FunctionProtoType>(getFunctionType());
1017 if (!FDecl && !Proto) {
1018 // Function without a prototype. Just give the return type and a
1019 // highlighted ellipsis.
1020 const FunctionType *FT = getFunctionType();
1021 Result->AddTextChunk(
1022 FT->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001023 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1024 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1025 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001026 return Result;
1027 }
1028
1029 if (FDecl)
1030 Result->AddTextChunk(FDecl->getNameAsString().c_str());
1031 else
1032 Result->AddTextChunk(
1033 Proto->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
1034
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001035 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001036 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
1037 for (unsigned I = 0; I != NumParams; ++I) {
1038 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001039 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001040
1041 std::string ArgString;
1042 QualType ArgType;
1043
1044 if (FDecl) {
1045 ArgString = FDecl->getParamDecl(I)->getNameAsString();
1046 ArgType = FDecl->getParamDecl(I)->getOriginalType();
1047 } else {
1048 ArgType = Proto->getArgType(I);
1049 }
1050
1051 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
1052
1053 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001054 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
1055 ArgString.c_str()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001056 else
1057 Result->AddTextChunk(ArgString.c_str());
1058 }
1059
1060 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001061 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001062 if (CurrentArg < NumParams)
1063 Result->AddTextChunk("...");
1064 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001065 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001066 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001067 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001068
1069 return Result;
1070}
1071
Douglas Gregor86d9a522009-09-21 16:56:56 +00001072namespace {
1073 struct SortCodeCompleteResult {
1074 typedef CodeCompleteConsumer::Result Result;
1075
Douglas Gregor6a684032009-09-28 03:51:44 +00001076 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregor36ecb042009-11-17 23:22:23 +00001077 if (!X.getObjCSelector().isNull() && !Y.getObjCSelector().isNull()) {
1078 // Consider all selector kinds to be equivalent.
1079 } else if (X.getNameKind() != Y.getNameKind())
Douglas Gregor6a684032009-09-28 03:51:44 +00001080 return X.getNameKind() < Y.getNameKind();
1081
1082 return llvm::LowercaseString(X.getAsString())
1083 < llvm::LowercaseString(Y.getAsString());
1084 }
1085
Douglas Gregor86d9a522009-09-21 16:56:56 +00001086 bool operator()(const Result &X, const Result &Y) const {
1087 // Sort first by rank.
1088 if (X.Rank < Y.Rank)
1089 return true;
1090 else if (X.Rank > Y.Rank)
1091 return false;
1092
Douglas Gregor54f01612009-11-19 00:01:57 +00001093 // We use a special ordering for keywords and patterns, based on the
1094 // typed text.
1095 if ((X.Kind == Result::RK_Keyword || X.Kind == Result::RK_Pattern) &&
1096 (Y.Kind == Result::RK_Keyword || Y.Kind == Result::RK_Pattern)) {
1097 const char *XStr = (X.Kind == Result::RK_Keyword)? X.Keyword
1098 : X.Pattern->getTypedText();
1099 const char *YStr = (Y.Kind == Result::RK_Keyword)? Y.Keyword
1100 : Y.Pattern->getTypedText();
1101 return strcmp(XStr, YStr) < 0;
1102 }
1103
Douglas Gregor86d9a522009-09-21 16:56:56 +00001104 // Result kinds are ordered by decreasing importance.
1105 if (X.Kind < Y.Kind)
1106 return true;
1107 else if (X.Kind > Y.Kind)
1108 return false;
1109
1110 // Non-hidden names precede hidden names.
1111 if (X.Hidden != Y.Hidden)
1112 return !X.Hidden;
1113
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001114 // Non-nested-name-specifiers precede nested-name-specifiers.
1115 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1116 return !X.StartsNestedNameSpecifier;
1117
Douglas Gregor86d9a522009-09-21 16:56:56 +00001118 // Ordering depends on the kind of result.
1119 switch (X.Kind) {
1120 case Result::RK_Declaration:
1121 // Order based on the declaration names.
Douglas Gregor6a684032009-09-28 03:51:44 +00001122 return isEarlierDeclarationName(X.Declaration->getDeclName(),
1123 Y.Declaration->getDeclName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001124
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001125 case Result::RK_Macro:
1126 return llvm::LowercaseString(X.Macro->getName()) <
1127 llvm::LowercaseString(Y.Macro->getName());
Douglas Gregor54f01612009-11-19 00:01:57 +00001128
1129 case Result::RK_Keyword:
1130 case Result::RK_Pattern:
1131 llvm::llvm_unreachable("Result kinds handled above");
1132 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001133 }
1134
1135 // Silence GCC warning.
1136 return false;
1137 }
1138 };
1139}
1140
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001141static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1142 ResultBuilder &Results) {
1143 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001144 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1145 MEnd = PP.macro_end();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001146 M != MEnd; ++M)
1147 Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1148 Results.ExitScope();
1149}
1150
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001151static void HandleCodeCompleteResults(Sema *S,
1152 CodeCompleteConsumer *CodeCompleter,
1153 CodeCompleteConsumer::Result *Results,
1154 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00001155 // Sort the results by rank/kind/etc.
1156 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1157
1158 if (CodeCompleter)
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001159 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00001160
1161 for (unsigned I = 0; I != NumResults; ++I)
1162 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001163}
1164
Douglas Gregor791215b2009-09-21 20:51:25 +00001165void Sema::CodeCompleteOrdinaryName(Scope *S) {
1166 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001167 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1168 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001169 if (CodeCompleter->includeMacros())
1170 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001171 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00001172}
1173
Douglas Gregor95ac6552009-11-18 01:29:26 +00001174static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00001175 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00001176 DeclContext *CurContext,
1177 ResultBuilder &Results) {
1178 typedef CodeCompleteConsumer::Result Result;
1179
1180 // Add properties in this container.
1181 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
1182 PEnd = Container->prop_end();
1183 P != PEnd;
1184 ++P)
1185 Results.MaybeAddResult(Result(*P, 0), CurContext);
1186
1187 // Add properties in referenced protocols.
1188 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
1189 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
1190 PEnd = Protocol->protocol_end();
1191 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00001192 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001193 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00001194 if (AllowCategories) {
1195 // Look through categories.
1196 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
1197 Category; Category = Category->getNextClassCategory())
1198 AddObjCProperties(Category, AllowCategories, CurContext, Results);
1199 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00001200
1201 // Look through protocols.
1202 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
1203 E = IFace->protocol_end();
1204 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00001205 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001206
1207 // Look in the superclass.
1208 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00001209 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
1210 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001211 } else if (const ObjCCategoryDecl *Category
1212 = dyn_cast<ObjCCategoryDecl>(Container)) {
1213 // Look through protocols.
1214 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
1215 PEnd = Category->protocol_end();
1216 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00001217 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001218 }
1219}
1220
Douglas Gregor81b747b2009-09-17 21:32:03 +00001221void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1222 SourceLocation OpLoc,
1223 bool IsArrow) {
1224 if (!BaseE || !CodeCompleter)
1225 return;
1226
Douglas Gregor86d9a522009-09-21 16:56:56 +00001227 typedef CodeCompleteConsumer::Result Result;
1228
Douglas Gregor81b747b2009-09-17 21:32:03 +00001229 Expr *Base = static_cast<Expr *>(BaseE);
1230 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001231
1232 if (IsArrow) {
1233 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1234 BaseType = Ptr->getPointeeType();
1235 else if (BaseType->isObjCObjectPointerType())
1236 /*Do nothing*/ ;
1237 else
1238 return;
1239 }
1240
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001241 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001242 unsigned NextRank = 0;
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001243
Douglas Gregor95ac6552009-11-18 01:29:26 +00001244 Results.EnterNewScope();
1245 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
1246 // Access to a C/C++ class, struct, or union.
1247 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1248 Record->getDecl(), Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001249
Douglas Gregor95ac6552009-11-18 01:29:26 +00001250 if (getLangOptions().CPlusPlus) {
1251 if (!Results.empty()) {
1252 // The "template" keyword can follow "->" or "." in the grammar.
1253 // However, we only want to suggest the template keyword if something
1254 // is dependent.
1255 bool IsDependent = BaseType->isDependentType();
1256 if (!IsDependent) {
1257 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1258 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1259 IsDependent = Ctx->isDependentContext();
1260 break;
1261 }
1262 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001263
Douglas Gregor95ac6552009-11-18 01:29:26 +00001264 if (IsDependent)
1265 Results.MaybeAddResult(Result("template", NextRank++));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001266 }
1267
Douglas Gregor95ac6552009-11-18 01:29:26 +00001268 // We could have the start of a nested-name-specifier. Add those
1269 // results as well.
1270 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1271 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
1272 CurContext, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001273 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00001274 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
1275 // Objective-C property reference.
1276
1277 // Add property results based on our interface.
1278 const ObjCObjectPointerType *ObjCPtr
1279 = BaseType->getAsObjCInterfacePointerType();
1280 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00001281 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001282
1283 // Add properties from the protocols in a qualified interface.
1284 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
1285 E = ObjCPtr->qual_end();
1286 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00001287 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001288
1289 // FIXME: We could (should?) also look for "implicit" properties, identified
1290 // only by the presence of nullary and unary selectors.
1291 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
1292 (!IsArrow && BaseType->isObjCInterfaceType())) {
1293 // Objective-C instance variable access.
1294 ObjCInterfaceDecl *Class = 0;
1295 if (const ObjCObjectPointerType *ObjCPtr
1296 = BaseType->getAs<ObjCObjectPointerType>())
1297 Class = ObjCPtr->getInterfaceDecl();
1298 else
1299 Class = BaseType->getAs<ObjCInterfaceType>()->getDecl();
1300
1301 // Add all ivars from this class and its superclasses.
1302 for (; Class; Class = Class->getSuperClass()) {
1303 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
1304 IVarEnd = Class->ivar_end();
1305 IVar != IVarEnd; ++IVar)
1306 Results.MaybeAddResult(Result(*IVar, 0), CurContext);
1307 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001308 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00001309
1310 // FIXME: How do we cope with isa?
1311
1312 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001313
1314 // Add macros
1315 if (CodeCompleter->includeMacros())
1316 AddMacroResults(PP, NextRank, Results);
1317
1318 // Hand off the results found for code completion.
1319 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001320}
1321
Douglas Gregor374929f2009-09-18 15:37:17 +00001322void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1323 if (!CodeCompleter)
1324 return;
1325
Douglas Gregor86d9a522009-09-21 16:56:56 +00001326 typedef CodeCompleteConsumer::Result Result;
1327 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +00001328 switch ((DeclSpec::TST)TagSpec) {
1329 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001330 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +00001331 break;
1332
1333 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001334 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +00001335 break;
1336
1337 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00001338 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001339 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00001340 break;
1341
1342 default:
1343 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1344 return;
1345 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001346
1347 ResultBuilder Results(*this, Filter);
1348 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001349 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001350
1351 if (getLangOptions().CPlusPlus) {
1352 // We could have the start of a nested-name-specifier. Add those
1353 // results as well.
1354 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001355 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1356 NextRank, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001357 }
1358
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001359 if (CodeCompleter->includeMacros())
1360 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001361 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00001362}
1363
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001364void Sema::CodeCompleteCase(Scope *S) {
1365 if (getSwitchStack().empty() || !CodeCompleter)
1366 return;
1367
1368 SwitchStmt *Switch = getSwitchStack().back();
1369 if (!Switch->getCond()->getType()->isEnumeralType())
1370 return;
1371
1372 // Code-complete the cases of a switch statement over an enumeration type
1373 // by providing the list of
1374 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1375
1376 // Determine which enumerators we have already seen in the switch statement.
1377 // FIXME: Ideally, we would also be able to look *past* the code-completion
1378 // token, in case we are code-completing in the middle of the switch and not
1379 // at the end. However, we aren't able to do so at the moment.
1380 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001381 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001382 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1383 SC = SC->getNextSwitchCase()) {
1384 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1385 if (!Case)
1386 continue;
1387
1388 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1389 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1390 if (EnumConstantDecl *Enumerator
1391 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1392 // We look into the AST of the case statement to determine which
1393 // enumerator was named. Alternatively, we could compute the value of
1394 // the integral constant expression, then compare it against the
1395 // values of each enumerator. However, value-based approach would not
1396 // work as well with C++ templates where enumerators declared within a
1397 // template are type- and value-dependent.
1398 EnumeratorsSeen.insert(Enumerator);
1399
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001400 // If this is a qualified-id, keep track of the nested-name-specifier
1401 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001402 //
1403 // switch (TagD.getKind()) {
1404 // case TagDecl::TK_enum:
1405 // break;
1406 // case XXX
1407 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001408 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001409 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1410 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00001411 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001412 }
1413 }
1414
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001415 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1416 // If there are no prior enumerators in C++, check whether we have to
1417 // qualify the names of the enumerators that we suggest, because they
1418 // may not be visible in this scope.
1419 Qualifier = getRequiredQualification(Context, CurContext,
1420 Enum->getDeclContext());
1421
1422 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1423 }
1424
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001425 // Add any enumerators that have not yet been mentioned.
1426 ResultBuilder Results(*this);
1427 Results.EnterNewScope();
1428 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1429 EEnd = Enum->enumerator_end();
1430 E != EEnd; ++E) {
1431 if (EnumeratorsSeen.count(*E))
1432 continue;
1433
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001434 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001435 }
1436 Results.ExitScope();
1437
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001438 if (CodeCompleter->includeMacros())
1439 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001440 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001441}
1442
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001443namespace {
1444 struct IsBetterOverloadCandidate {
1445 Sema &S;
1446
1447 public:
1448 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1449
1450 bool
1451 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1452 return S.isBetterOverloadCandidate(X, Y);
1453 }
1454 };
1455}
1456
1457void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1458 ExprTy **ArgsIn, unsigned NumArgs) {
1459 if (!CodeCompleter)
1460 return;
1461
1462 Expr *Fn = (Expr *)FnIn;
1463 Expr **Args = (Expr **)ArgsIn;
1464
1465 // Ignore type-dependent call expressions entirely.
1466 if (Fn->isTypeDependent() ||
1467 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1468 return;
1469
John McCallba135432009-11-21 08:51:07 +00001470 llvm::SmallVector<NamedDecl*,8> Fns;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001471 DeclarationName UnqualifiedName;
1472 NestedNameSpecifier *Qualifier;
1473 SourceRange QualifierRange;
1474 bool ArgumentDependentLookup;
1475 bool HasExplicitTemplateArgs;
John McCall833ca992009-10-29 08:12:44 +00001476 const TemplateArgumentLoc *ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001477 unsigned NumExplicitTemplateArgs;
1478
John McCallba135432009-11-21 08:51:07 +00001479 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001480 ArgumentDependentLookup, HasExplicitTemplateArgs,
1481 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1482
1483
1484 // FIXME: What if we're calling something that isn't a function declaration?
1485 // FIXME: What if we're calling a pseudo-destructor?
1486 // FIXME: What if we're calling a member function?
1487
1488 // Build an overload candidate set based on the functions we find.
1489 OverloadCandidateSet CandidateSet;
John McCallba135432009-11-21 08:51:07 +00001490 AddOverloadedCallCandidates(Fns, UnqualifiedName,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001491 ArgumentDependentLookup, HasExplicitTemplateArgs,
1492 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1493 Args, NumArgs,
1494 CandidateSet,
1495 /*PartialOverloading=*/true);
1496
1497 // Sort the overload candidate set by placing the best overloads first.
1498 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1499 IsBetterOverloadCandidate(*this));
1500
1501 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05944382009-09-23 00:16:58 +00001502 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1503 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlsson90756302009-09-22 17:29:51 +00001504
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001505 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1506 CandEnd = CandidateSet.end();
1507 Cand != CandEnd; ++Cand) {
1508 if (Cand->Viable)
Douglas Gregor05944382009-09-23 00:16:58 +00001509 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001510 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001511 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
Douglas Gregor05944382009-09-23 00:16:58 +00001512 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001513}
1514
Douglas Gregor81b747b2009-09-17 21:32:03 +00001515void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1516 bool EnteringContext) {
1517 if (!SS.getScopeRep() || !CodeCompleter)
1518 return;
1519
Douglas Gregor86d9a522009-09-21 16:56:56 +00001520 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1521 if (!Ctx)
1522 return;
1523
1524 ResultBuilder Results(*this);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001525 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001526
1527 // The "template" keyword can follow "::" in the grammar, but only
1528 // put it into the grammar if the nested-name-specifier is dependent.
1529 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1530 if (!Results.empty() && NNS->isDependent())
1531 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1532
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001533 if (CodeCompleter->includeMacros())
1534 AddMacroResults(PP, NextRank + 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001535 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001536}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001537
1538void Sema::CodeCompleteUsing(Scope *S) {
1539 if (!CodeCompleter)
1540 return;
1541
Douglas Gregor86d9a522009-09-21 16:56:56 +00001542 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001543 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001544
1545 // If we aren't in class scope, we could see the "namespace" keyword.
1546 if (!S->isClassScope())
1547 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1548
1549 // After "using", we can see anything that would start a
1550 // nested-name-specifier.
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001551 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1552 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001553 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001554
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001555 if (CodeCompleter->includeMacros())
1556 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001557 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001558}
1559
1560void Sema::CodeCompleteUsingDirective(Scope *S) {
1561 if (!CodeCompleter)
1562 return;
1563
Douglas Gregor86d9a522009-09-21 16:56:56 +00001564 // After "using namespace", we expect to see a namespace name or namespace
1565 // alias.
1566 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001567 Results.EnterNewScope();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001568 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1569 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001570 Results.ExitScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001571 if (CodeCompleter->includeMacros())
1572 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001573 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001574}
1575
1576void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1577 if (!CodeCompleter)
1578 return;
1579
Douglas Gregor86d9a522009-09-21 16:56:56 +00001580 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1581 DeclContext *Ctx = (DeclContext *)S->getEntity();
1582 if (!S->getParent())
1583 Ctx = Context.getTranslationUnitDecl();
1584
1585 if (Ctx && Ctx->isFileContext()) {
1586 // We only want to see those namespaces that have already been defined
1587 // within this scope, because its likely that the user is creating an
1588 // extended namespace declaration. Keep track of the most recent
1589 // definition of each namespace.
1590 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1591 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1592 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1593 NS != NSEnd; ++NS)
1594 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1595
1596 // Add the most recent definition (or extended definition) of each
1597 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001598 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001599 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1600 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1601 NS != NSEnd; ++NS)
Douglas Gregor456c4a12009-09-21 20:12:40 +00001602 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1603 CurContext);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001604 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001605 }
1606
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001607 if (CodeCompleter->includeMacros())
1608 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001609 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001610}
1611
1612void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1613 if (!CodeCompleter)
1614 return;
1615
Douglas Gregor86d9a522009-09-21 16:56:56 +00001616 // After "namespace", we expect to see a namespace or alias.
1617 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001618 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1619 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001620 if (CodeCompleter->includeMacros())
1621 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001622 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001623}
1624
Douglas Gregored8d3222009-09-18 20:05:18 +00001625void Sema::CodeCompleteOperatorName(Scope *S) {
1626 if (!CodeCompleter)
1627 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001628
1629 typedef CodeCompleteConsumer::Result Result;
1630 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001631 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00001632
Douglas Gregor86d9a522009-09-21 16:56:56 +00001633 // Add the names of overloadable operators.
1634#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1635 if (std::strcmp(Spelling, "?")) \
1636 Results.MaybeAddResult(Result(Spelling, 0));
1637#include "clang/Basic/OperatorKinds.def"
1638
1639 // Add any type names visible from the current scope
1640 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001641 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001642
1643 // Add any type specifiers
1644 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1645
1646 // Add any nested-name-specifiers
1647 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001648 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1649 NextRank + 1, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001650 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001651
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001652 if (CodeCompleter->includeMacros())
1653 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001654 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00001655}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001656
Douglas Gregor988358f2009-11-19 00:14:45 +00001657/// \brief Determine whether the addition of the given flag to an Objective-C
1658/// property's attributes will cause a conflict.
1659static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
1660 // Check if we've already added this flag.
1661 if (Attributes & NewFlag)
1662 return true;
1663
1664 Attributes |= NewFlag;
1665
1666 // Check for collisions with "readonly".
1667 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1668 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
1669 ObjCDeclSpec::DQ_PR_assign |
1670 ObjCDeclSpec::DQ_PR_copy |
1671 ObjCDeclSpec::DQ_PR_retain)))
1672 return true;
1673
1674 // Check for more than one of { assign, copy, retain }.
1675 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
1676 ObjCDeclSpec::DQ_PR_copy |
1677 ObjCDeclSpec::DQ_PR_retain);
1678 if (AssignCopyRetMask &&
1679 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
1680 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
1681 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
1682 return true;
1683
1684 return false;
1685}
1686
Douglas Gregora93b1082009-11-18 23:08:07 +00001687void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00001688 if (!CodeCompleter)
1689 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00001690
Steve Naroffece8e712009-10-08 21:55:05 +00001691 unsigned Attributes = ODS.getPropertyAttributes();
1692
1693 typedef CodeCompleteConsumer::Result Result;
1694 ResultBuilder Results(*this);
1695 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00001696 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
Steve Naroffece8e712009-10-08 21:55:05 +00001697 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001698 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
Steve Naroffece8e712009-10-08 21:55:05 +00001699 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001700 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
Steve Naroffece8e712009-10-08 21:55:05 +00001701 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001702 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
Steve Naroffece8e712009-10-08 21:55:05 +00001703 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001704 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
Steve Naroffece8e712009-10-08 21:55:05 +00001705 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001706 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
Steve Naroffece8e712009-10-08 21:55:05 +00001707 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001708 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00001709 CodeCompletionString *Setter = new CodeCompletionString;
1710 Setter->AddTypedTextChunk("setter");
1711 Setter->AddTextChunk(" = ");
1712 Setter->AddPlaceholderChunk("method");
1713 Results.MaybeAddResult(CodeCompleteConsumer::Result(Setter, 0));
1714 }
Douglas Gregor988358f2009-11-19 00:14:45 +00001715 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00001716 CodeCompletionString *Getter = new CodeCompletionString;
1717 Getter->AddTypedTextChunk("getter");
1718 Getter->AddTextChunk(" = ");
1719 Getter->AddPlaceholderChunk("method");
1720 Results.MaybeAddResult(CodeCompleteConsumer::Result(Getter, 0));
1721 }
Steve Naroffece8e712009-10-08 21:55:05 +00001722 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001723 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00001724}
Steve Naroffc4df6d22009-11-07 02:08:14 +00001725
Douglas Gregor4ad96852009-11-19 07:41:15 +00001726/// \brief Descripts the kind of Objective-C method that we want to find
1727/// via code completion.
1728enum ObjCMethodKind {
1729 MK_Any, //< Any kind of method, provided it means other specified criteria.
1730 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
1731 MK_OneArgSelector //< One-argument selector.
1732};
1733
1734static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
1735 ObjCMethodKind WantKind,
1736 IdentifierInfo **SelIdents,
1737 unsigned NumSelIdents) {
1738 Selector Sel = Method->getSelector();
1739 if (NumSelIdents > Sel.getNumArgs())
1740 return false;
1741
1742 switch (WantKind) {
1743 case MK_Any: break;
1744 case MK_ZeroArgSelector: return Sel.isUnarySelector();
1745 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
1746 }
1747
1748 for (unsigned I = 0; I != NumSelIdents; ++I)
1749 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
1750 return false;
1751
1752 return true;
1753}
1754
Douglas Gregor36ecb042009-11-17 23:22:23 +00001755/// \brief Add all of the Objective-C methods in the given Objective-C
1756/// container to the set of results.
1757///
1758/// The container will be a class, protocol, category, or implementation of
1759/// any of the above. This mether will recurse to include methods from
1760/// the superclasses of classes along with their categories, protocols, and
1761/// implementations.
1762///
1763/// \param Container the container in which we'll look to find methods.
1764///
1765/// \param WantInstance whether to add instance methods (only); if false, this
1766/// routine will add factory methods (only).
1767///
1768/// \param CurContext the context in which we're performing the lookup that
1769/// finds methods.
1770///
1771/// \param Results the structure into which we'll add results.
1772static void AddObjCMethods(ObjCContainerDecl *Container,
1773 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00001774 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00001775 IdentifierInfo **SelIdents,
1776 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00001777 DeclContext *CurContext,
1778 ResultBuilder &Results) {
1779 typedef CodeCompleteConsumer::Result Result;
1780 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
1781 MEnd = Container->meth_end();
1782 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00001783 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
1784 // Check whether the selector identifiers we've been given are a
1785 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00001786 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00001787 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00001788
Douglas Gregord3c68542009-11-19 01:08:35 +00001789 Result R = Result(*M, 0);
1790 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00001791 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregord3c68542009-11-19 01:08:35 +00001792 Results.MaybeAddResult(R, CurContext);
1793 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00001794 }
1795
1796 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
1797 if (!IFace)
1798 return;
1799
1800 // Add methods in protocols.
1801 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
1802 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1803 E = Protocols.end();
1804 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00001805 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord3c68542009-11-19 01:08:35 +00001806 CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001807
1808 // Add methods in categories.
1809 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
1810 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00001811 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
1812 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001813
1814 // Add a categories protocol methods.
1815 const ObjCList<ObjCProtocolDecl> &Protocols
1816 = CatDecl->getReferencedProtocols();
1817 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1818 E = Protocols.end();
1819 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00001820 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
1821 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001822
1823 // Add methods in category implementations.
1824 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00001825 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
1826 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001827 }
1828
1829 // Add methods in superclass.
1830 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00001831 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
1832 SelIdents, NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001833
1834 // Add methods in our implementation, if any.
1835 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00001836 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
1837 NumSelIdents, CurContext, Results);
1838}
1839
1840
1841void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
1842 DeclPtrTy *Methods,
1843 unsigned NumMethods) {
1844 typedef CodeCompleteConsumer::Result Result;
1845
1846 // Try to find the interface where getters might live.
1847 ObjCInterfaceDecl *Class
1848 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
1849 if (!Class) {
1850 if (ObjCCategoryDecl *Category
1851 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
1852 Class = Category->getClassInterface();
1853
1854 if (!Class)
1855 return;
1856 }
1857
1858 // Find all of the potential getters.
1859 ResultBuilder Results(*this);
1860 Results.EnterNewScope();
1861
1862 // FIXME: We need to do this because Objective-C methods don't get
1863 // pushed into DeclContexts early enough. Argh!
1864 for (unsigned I = 0; I != NumMethods; ++I) {
1865 if (ObjCMethodDecl *Method
1866 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
1867 if (Method->isInstanceMethod() &&
1868 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
1869 Result R = Result(Method, 0);
1870 R.AllParametersAreInformative = true;
1871 Results.MaybeAddResult(R, CurContext);
1872 }
1873 }
1874
1875 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
1876 Results.ExitScope();
1877 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
1878}
1879
1880void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
1881 DeclPtrTy *Methods,
1882 unsigned NumMethods) {
1883 typedef CodeCompleteConsumer::Result Result;
1884
1885 // Try to find the interface where setters might live.
1886 ObjCInterfaceDecl *Class
1887 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
1888 if (!Class) {
1889 if (ObjCCategoryDecl *Category
1890 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
1891 Class = Category->getClassInterface();
1892
1893 if (!Class)
1894 return;
1895 }
1896
1897 // Find all of the potential getters.
1898 ResultBuilder Results(*this);
1899 Results.EnterNewScope();
1900
1901 // FIXME: We need to do this because Objective-C methods don't get
1902 // pushed into DeclContexts early enough. Argh!
1903 for (unsigned I = 0; I != NumMethods; ++I) {
1904 if (ObjCMethodDecl *Method
1905 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
1906 if (Method->isInstanceMethod() &&
1907 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
1908 Result R = Result(Method, 0);
1909 R.AllParametersAreInformative = true;
1910 Results.MaybeAddResult(R, CurContext);
1911 }
1912 }
1913
1914 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
1915
1916 Results.ExitScope();
1917 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00001918}
1919
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001920void Sema::CodeCompleteObjCClassMessage(Scope *S, IdentifierInfo *FName,
Douglas Gregord3c68542009-11-19 01:08:35 +00001921 SourceLocation FNameLoc,
1922 IdentifierInfo **SelIdents,
1923 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00001924 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00001925 ObjCInterfaceDecl *CDecl = 0;
1926
Douglas Gregor24a069f2009-11-17 17:59:40 +00001927 if (FName->isStr("super")) {
1928 // We're sending a message to "super".
1929 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
1930 // Figure out which interface we're in.
1931 CDecl = CurMethod->getClassInterface();
1932 if (!CDecl)
1933 return;
1934
1935 // Find the superclass of this class.
1936 CDecl = CDecl->getSuperClass();
1937 if (!CDecl)
1938 return;
1939
1940 if (CurMethod->isInstanceMethod()) {
1941 // We are inside an instance method, which means that the message
1942 // send [super ...] is actually calling an instance method on the
1943 // current object. Build the super expression and handle this like
1944 // an instance method.
1945 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
1946 SuperTy = Context.getObjCObjectPointerType(SuperTy);
1947 OwningExprResult Super
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001948 = Owned(new (Context) ObjCSuperExpr(FNameLoc, SuperTy));
Douglas Gregord3c68542009-11-19 01:08:35 +00001949 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
1950 SelIdents, NumSelIdents);
Douglas Gregor24a069f2009-11-17 17:59:40 +00001951 }
1952
1953 // Okay, we're calling a factory method in our superclass.
1954 }
1955 }
1956
1957 // If the given name refers to an interface type, retrieve the
1958 // corresponding declaration.
1959 if (!CDecl)
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001960 if (TypeTy *Ty = getTypeName(*FName, FNameLoc, S, 0, false)) {
Douglas Gregor24a069f2009-11-17 17:59:40 +00001961 QualType T = GetTypeFromParser(Ty, 0);
1962 if (!T.isNull())
1963 if (const ObjCInterfaceType *Interface = T->getAs<ObjCInterfaceType>())
1964 CDecl = Interface->getDecl();
1965 }
1966
1967 if (!CDecl && FName->isStr("super")) {
1968 // "super" may be the name of a variable, in which case we are
1969 // probably calling an instance method.
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001970 OwningExprResult Super = ActOnDeclarationNameExpr(S, FNameLoc, FName,
Douglas Gregor24a069f2009-11-17 17:59:40 +00001971 false, 0, false);
Douglas Gregord3c68542009-11-19 01:08:35 +00001972 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
1973 SelIdents, NumSelIdents);
Douglas Gregor24a069f2009-11-17 17:59:40 +00001974 }
1975
Douglas Gregor36ecb042009-11-17 23:22:23 +00001976 // Add all of the factory methods in this Objective-C class, its protocols,
1977 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00001978 ResultBuilder Results(*this);
1979 Results.EnterNewScope();
Douglas Gregor4ad96852009-11-19 07:41:15 +00001980 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
1981 Results);
Steve Naroffc4df6d22009-11-07 02:08:14 +00001982 Results.ExitScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00001983
Steve Naroffc4df6d22009-11-07 02:08:14 +00001984 // This also suppresses remaining diagnostics.
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001985 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00001986}
1987
Douglas Gregord3c68542009-11-19 01:08:35 +00001988void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
1989 IdentifierInfo **SelIdents,
1990 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00001991 typedef CodeCompleteConsumer::Result Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00001992
1993 Expr *RecExpr = static_cast<Expr *>(Receiver);
1994 QualType RecType = RecExpr->getType();
1995
Douglas Gregor36ecb042009-11-17 23:22:23 +00001996 // If necessary, apply function/array conversion to the receiver.
1997 // C99 6.7.5.3p[7,8].
1998 DefaultFunctionArrayConversion(RecExpr);
1999 QualType ReceiverType = RecExpr->getType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00002000
Douglas Gregor36ecb042009-11-17 23:22:23 +00002001 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType()) {
2002 // FIXME: We're messaging 'id'. Do we actually want to look up every method
2003 // in the universe?
2004 return;
2005 }
2006
Douglas Gregor36ecb042009-11-17 23:22:23 +00002007 // Build the set of methods we can see.
2008 ResultBuilder Results(*this);
2009 Results.EnterNewScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00002010
Douglas Gregorf74a4192009-11-18 00:06:18 +00002011 // Handle messages to Class. This really isn't a message to an instance
2012 // method, so we treat it the same way we would treat a message send to a
2013 // class method.
2014 if (ReceiverType->isObjCClassType() ||
2015 ReceiverType->isObjCQualifiedClassType()) {
2016 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
2017 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00002018 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
2019 CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00002020 }
2021 }
2022 // Handle messages to a qualified ID ("id<foo>").
2023 else if (const ObjCObjectPointerType *QualID
2024 = ReceiverType->getAsObjCQualifiedIdType()) {
2025 // Search protocols for instance methods.
2026 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
2027 E = QualID->qual_end();
2028 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002029 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
2030 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00002031 }
2032 // Handle messages to a pointer to interface type.
2033 else if (const ObjCObjectPointerType *IFacePtr
2034 = ReceiverType->getAsObjCInterfacePointerType()) {
2035 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00002036 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
2037 NumSelIdents, CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00002038
2039 // Search protocols for instance methods.
2040 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
2041 E = IFacePtr->qual_end();
2042 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002043 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
2044 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00002045 }
2046
Steve Naroffc4df6d22009-11-07 02:08:14 +00002047 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002048 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00002049}
Douglas Gregor55385fe2009-11-18 04:19:12 +00002050
2051/// \brief Add all of the protocol declarations that we find in the given
2052/// (translation unit) context.
2053static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00002054 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00002055 ResultBuilder &Results) {
2056 typedef CodeCompleteConsumer::Result Result;
2057
2058 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
2059 DEnd = Ctx->decls_end();
2060 D != DEnd; ++D) {
2061 // Record any protocols we find.
2062 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00002063 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
2064 Results.MaybeAddResult(Result(Proto, 0), CurContext);
Douglas Gregor55385fe2009-11-18 04:19:12 +00002065
2066 // Record any forward-declared protocols we find.
2067 if (ObjCForwardProtocolDecl *Forward
2068 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2069 for (ObjCForwardProtocolDecl::protocol_iterator
2070 P = Forward->protocol_begin(),
2071 PEnd = Forward->protocol_end();
2072 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00002073 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
2074 Results.MaybeAddResult(Result(*P, 0), CurContext);
Douglas Gregor55385fe2009-11-18 04:19:12 +00002075 }
2076 }
2077}
2078
2079void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
2080 unsigned NumProtocols) {
2081 ResultBuilder Results(*this);
2082 Results.EnterNewScope();
2083
2084 // Tell the result set to ignore all of the protocols we have
2085 // already seen.
2086 for (unsigned I = 0; I != NumProtocols; ++I)
2087 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first))
2088 Results.Ignore(Protocol);
2089
2090 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00002091 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
2092 Results);
2093
2094 Results.ExitScope();
2095 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2096}
2097
2098void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
2099 ResultBuilder Results(*this);
2100 Results.EnterNewScope();
2101
2102 // Add all protocols.
2103 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
2104 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00002105
2106 Results.ExitScope();
2107 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2108}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00002109
2110/// \brief Add all of the Objective-C interface declarations that we find in
2111/// the given (translation unit) context.
2112static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
2113 bool OnlyForwardDeclarations,
2114 bool OnlyUnimplemented,
2115 ResultBuilder &Results) {
2116 typedef CodeCompleteConsumer::Result Result;
2117
2118 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
2119 DEnd = Ctx->decls_end();
2120 D != DEnd; ++D) {
2121 // Record any interfaces we find.
2122 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
2123 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
2124 (!OnlyUnimplemented || !Class->getImplementation()))
2125 Results.MaybeAddResult(Result(Class, 0), CurContext);
2126
2127 // Record any forward-declared interfaces we find.
2128 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
2129 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
2130 C != CEnd; ++C)
2131 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
2132 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
2133 Results.MaybeAddResult(Result(C->getInterface(), 0), CurContext);
2134 }
2135 }
2136}
2137
2138void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
2139 ResultBuilder Results(*this);
2140 Results.EnterNewScope();
2141
2142 // Add all classes.
2143 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
2144 false, Results);
2145
2146 Results.ExitScope();
2147 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2148}
2149
2150void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName) {
2151 ResultBuilder Results(*this);
2152 Results.EnterNewScope();
2153
2154 // Make sure that we ignore the class we're currently defining.
2155 NamedDecl *CurClass
2156 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00002157 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00002158 Results.Ignore(CurClass);
2159
2160 // Add all classes.
2161 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
2162 false, Results);
2163
2164 Results.ExitScope();
2165 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2166}
2167
2168void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
2169 ResultBuilder Results(*this);
2170 Results.EnterNewScope();
2171
2172 // Add all unimplemented classes.
2173 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
2174 true, Results);
2175
2176 Results.ExitScope();
2177 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2178}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00002179
2180void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
2181 IdentifierInfo *ClassName) {
2182 typedef CodeCompleteConsumer::Result Result;
2183
2184 ResultBuilder Results(*this);
2185
2186 // Ignore any categories we find that have already been implemented by this
2187 // interface.
2188 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
2189 NamedDecl *CurClass
2190 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
2191 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
2192 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
2193 Category = Category->getNextClassCategory())
2194 CategoryNames.insert(Category->getIdentifier());
2195
2196 // Add all of the categories we know about.
2197 Results.EnterNewScope();
2198 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
2199 for (DeclContext::decl_iterator D = TU->decls_begin(),
2200 DEnd = TU->decls_end();
2201 D != DEnd; ++D)
2202 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
2203 if (CategoryNames.insert(Category->getIdentifier()))
2204 Results.MaybeAddResult(Result(Category, 0), CurContext);
2205 Results.ExitScope();
2206
2207 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2208}
2209
2210void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
2211 IdentifierInfo *ClassName) {
2212 typedef CodeCompleteConsumer::Result Result;
2213
2214 // Find the corresponding interface. If we couldn't find the interface, the
2215 // program itself is ill-formed. However, we'll try to be helpful still by
2216 // providing the list of all of the categories we know about.
2217 NamedDecl *CurClass
2218 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
2219 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
2220 if (!Class)
2221 return CodeCompleteObjCInterfaceCategory(S, ClassName);
2222
2223 ResultBuilder Results(*this);
2224
2225 // Add all of the categories that have have corresponding interface
2226 // declarations in this class and any of its superclasses, except for
2227 // already-implemented categories in the class itself.
2228 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
2229 Results.EnterNewScope();
2230 bool IgnoreImplemented = true;
2231 while (Class) {
2232 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
2233 Category = Category->getNextClassCategory())
2234 if ((!IgnoreImplemented || !Category->getImplementation()) &&
2235 CategoryNames.insert(Category->getIdentifier()))
2236 Results.MaybeAddResult(Result(Category, 0), CurContext);
2237
2238 Class = Class->getSuperClass();
2239 IgnoreImplemented = false;
2240 }
2241 Results.ExitScope();
2242
2243 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2244}
Douglas Gregor322328b2009-11-18 22:32:06 +00002245
Douglas Gregor424b2a52009-11-18 22:56:13 +00002246void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
Douglas Gregor322328b2009-11-18 22:32:06 +00002247 typedef CodeCompleteConsumer::Result Result;
2248 ResultBuilder Results(*this);
2249
2250 // Figure out where this @synthesize lives.
2251 ObjCContainerDecl *Container
2252 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
2253 if (!Container ||
2254 (!isa<ObjCImplementationDecl>(Container) &&
2255 !isa<ObjCCategoryImplDecl>(Container)))
2256 return;
2257
2258 // Ignore any properties that have already been implemented.
2259 for (DeclContext::decl_iterator D = Container->decls_begin(),
2260 DEnd = Container->decls_end();
2261 D != DEnd; ++D)
2262 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
2263 Results.Ignore(PropertyImpl->getPropertyDecl());
2264
2265 // Add any properties that we find.
2266 Results.EnterNewScope();
2267 if (ObjCImplementationDecl *ClassImpl
2268 = dyn_cast<ObjCImplementationDecl>(Container))
2269 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
2270 Results);
2271 else
2272 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
2273 false, CurContext, Results);
2274 Results.ExitScope();
2275
2276 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2277}
2278
2279void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
2280 IdentifierInfo *PropertyName,
2281 DeclPtrTy ObjCImpDecl) {
2282 typedef CodeCompleteConsumer::Result Result;
2283 ResultBuilder Results(*this);
2284
2285 // Figure out where this @synthesize lives.
2286 ObjCContainerDecl *Container
2287 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
2288 if (!Container ||
2289 (!isa<ObjCImplementationDecl>(Container) &&
2290 !isa<ObjCCategoryImplDecl>(Container)))
2291 return;
2292
2293 // Figure out which interface we're looking into.
2294 ObjCInterfaceDecl *Class = 0;
2295 if (ObjCImplementationDecl *ClassImpl
2296 = dyn_cast<ObjCImplementationDecl>(Container))
2297 Class = ClassImpl->getClassInterface();
2298 else
2299 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
2300 ->getClassInterface();
2301
2302 // Add all of the instance variables in this class and its superclasses.
2303 Results.EnterNewScope();
2304 for(; Class; Class = Class->getSuperClass()) {
2305 // FIXME: We could screen the type of each ivar for compatibility with
2306 // the property, but is that being too paternal?
2307 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
2308 IVarEnd = Class->ivar_end();
2309 IVar != IVarEnd; ++IVar)
2310 Results.MaybeAddResult(Result(*IVar, 0), CurContext);
2311 }
2312 Results.ExitScope();
2313
2314 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2315}