blob: e1a5790a8b7889715bf66a1cfa00f33bc77d2e8d [file] [log] [blame]
Douglas Gregor2436e712009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
13#include "Sema.h"
14#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregorf2510672009-09-21 19:57:38 +000015#include "clang/AST/ExprCXX.h"
Douglas Gregor8ce33212009-11-17 17:59:40 +000016#include "clang/AST/ExprObjC.h"
Douglas Gregorf329c7c2009-10-30 16:50:04 +000017#include "clang/Lex/MacroInfo.h"
18#include "clang/Lex/Preprocessor.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000019#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore6688e62009-09-28 03:51:44 +000020#include "llvm/ADT/StringExtras.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000021#include <list>
22#include <map>
23#include <vector>
Douglas Gregor2436e712009-09-17 21:32:03 +000024
25using namespace clang;
26
Douglas Gregor3545ff42009-09-21 16:56:56 +000027namespace {
28 /// \brief A container of code-completion results.
29 class ResultBuilder {
30 public:
31 /// \brief The type of a name-lookup filter, which can be provided to the
32 /// name-lookup routines to specify which declarations should be included in
33 /// the result set (when it returns true) and which declarations should be
34 /// filtered out (returns false).
35 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
36
37 typedef CodeCompleteConsumer::Result Result;
38
39 private:
40 /// \brief The actual results we have found.
41 std::vector<Result> Results;
42
43 /// \brief A record of all of the declarations we have found and placed
44 /// into the result set, used to ensure that no declaration ever gets into
45 /// the result set twice.
46 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
47
48 /// \brief A mapping from declaration names to the declarations that have
49 /// this name within a particular scope and their index within the list of
50 /// results.
51 typedef std::multimap<DeclarationName,
52 std::pair<NamedDecl *, unsigned> > ShadowMap;
53
54 /// \brief The semantic analysis object for which results are being
55 /// produced.
56 Sema &SemaRef;
57
58 /// \brief If non-NULL, a filter function used to remove any code-completion
59 /// results that are not desirable.
60 LookupFilter Filter;
61
62 /// \brief A list of shadow maps, which is used to model name hiding at
63 /// different levels of, e.g., the inheritance hierarchy.
64 std::list<ShadowMap> ShadowMaps;
65
66 public:
67 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
68 : SemaRef(SemaRef), Filter(Filter) { }
69
70 /// \brief Set the filter used for code-completion results.
71 void setFilter(LookupFilter Filter) {
72 this->Filter = Filter;
73 }
74
75 typedef std::vector<Result>::iterator iterator;
76 iterator begin() { return Results.begin(); }
77 iterator end() { return Results.end(); }
78
79 Result *data() { return Results.empty()? 0 : &Results.front(); }
80 unsigned size() const { return Results.size(); }
81 bool empty() const { return Results.empty(); }
82
83 /// \brief Add a new result to this result set (if it isn't already in one
84 /// of the shadow maps), or replace an existing result (for, e.g., a
85 /// redeclaration).
Douglas Gregor2af2f672009-09-21 20:12:40 +000086 ///
87 /// \param R the result to add (if it is unique).
88 ///
89 /// \param R the context in which this result will be named.
90 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor3545ff42009-09-21 16:56:56 +000091
92 /// \brief Enter into a new scope.
93 void EnterNewScope();
94
95 /// \brief Exit from the current scope.
96 void ExitScope();
97
Douglas Gregorbaf69612009-11-18 04:19:12 +000098 /// \brief Ignore this declaration, if it is seen again.
99 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
100
Douglas Gregor3545ff42009-09-21 16:56:56 +0000101 /// \name Name lookup predicates
102 ///
103 /// These predicates can be passed to the name lookup functions to filter the
104 /// results of name lookup. All of the predicates have the same type, so that
105 ///
106 //@{
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000107 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000108 bool IsNestedNameSpecifier(NamedDecl *ND) const;
109 bool IsEnum(NamedDecl *ND) const;
110 bool IsClassOrStruct(NamedDecl *ND) const;
111 bool IsUnion(NamedDecl *ND) const;
112 bool IsNamespace(NamedDecl *ND) const;
113 bool IsNamespaceOrAlias(NamedDecl *ND) const;
114 bool IsType(NamedDecl *ND) const;
Douglas Gregore412a5a2009-09-23 22:26:46 +0000115 bool IsMember(NamedDecl *ND) const;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000116 //@}
117 };
118}
119
120/// \brief Determines whether the given hidden result could be found with
121/// some extra work, e.g., by qualifying the name.
122///
123/// \param Hidden the declaration that is hidden by the currenly \p Visible
124/// declaration.
125///
126/// \param Visible the declaration with the same name that is already visible.
127///
128/// \returns true if the hidden result can be found by some mechanism,
129/// false otherwise.
130static bool canHiddenResultBeFound(const LangOptions &LangOpts,
131 NamedDecl *Hidden, NamedDecl *Visible) {
132 // In C, there is no way to refer to a hidden name.
133 if (!LangOpts.CPlusPlus)
134 return false;
135
136 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
137
138 // There is no way to qualify a name declared in a function or method.
139 if (HiddenCtx->isFunctionOrMethod())
140 return false;
141
Douglas Gregor3545ff42009-09-21 16:56:56 +0000142 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
143}
144
Douglas Gregor2af2f672009-09-21 20:12:40 +0000145/// \brief Compute the qualification required to get from the current context
146/// (\p CurContext) to the target context (\p TargetContext).
147///
148/// \param Context the AST context in which the qualification will be used.
149///
150/// \param CurContext the context where an entity is being named, which is
151/// typically based on the current scope.
152///
153/// \param TargetContext the context in which the named entity actually
154/// resides.
155///
156/// \returns a nested name specifier that refers into the target context, or
157/// NULL if no qualification is needed.
158static NestedNameSpecifier *
159getRequiredQualification(ASTContext &Context,
160 DeclContext *CurContext,
161 DeclContext *TargetContext) {
162 llvm::SmallVector<DeclContext *, 4> TargetParents;
163
164 for (DeclContext *CommonAncestor = TargetContext;
165 CommonAncestor && !CommonAncestor->Encloses(CurContext);
166 CommonAncestor = CommonAncestor->getLookupParent()) {
167 if (CommonAncestor->isTransparentContext() ||
168 CommonAncestor->isFunctionOrMethod())
169 continue;
170
171 TargetParents.push_back(CommonAncestor);
172 }
173
174 NestedNameSpecifier *Result = 0;
175 while (!TargetParents.empty()) {
176 DeclContext *Parent = TargetParents.back();
177 TargetParents.pop_back();
178
179 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
180 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
181 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
182 Result = NestedNameSpecifier::Create(Context, Result,
183 false,
184 Context.getTypeDeclType(TD).getTypePtr());
185 else
186 assert(Parent->isTranslationUnit());
Douglas Gregor9eb77012009-11-07 00:00:49 +0000187 }
Douglas Gregor2af2f672009-09-21 20:12:40 +0000188 return Result;
189}
190
191void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
Douglas Gregor64b12b52009-09-22 23:31:26 +0000192 assert(!ShadowMaps.empty() && "Must enter into a results scope");
193
Douglas Gregor3545ff42009-09-21 16:56:56 +0000194 if (R.Kind != Result::RK_Declaration) {
195 // For non-declaration results, just add the result.
196 Results.push_back(R);
197 return;
198 }
Douglas Gregor58acf322009-10-09 22:16:47 +0000199
200 // Skip unnamed entities.
201 if (!R.Declaration->getDeclName())
202 return;
203
Douglas Gregor3545ff42009-09-21 16:56:56 +0000204 // Look through using declarations.
John McCall3f746822009-11-17 05:59:44 +0000205 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration))
Douglas Gregor5bf52692009-09-22 23:15:58 +0000206 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
207 CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000208
Douglas Gregor3545ff42009-09-21 16:56:56 +0000209 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
210 unsigned IDNS = CanonDecl->getIdentifierNamespace();
211
212 // Friend declarations and declarations introduced due to friends are never
213 // added as results.
214 if (isa<FriendDecl>(CanonDecl) ||
215 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
216 return;
217
218 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
219 // __va_list_tag is a freak of nature. Find it and skip it.
220 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
221 return;
222
Douglas Gregor58acf322009-10-09 22:16:47 +0000223 // Filter out names reserved for the implementation (C99 7.1.3,
224 // C++ [lib.global.names]). Users don't need to see those.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +0000225 //
226 // FIXME: Add predicate for this.
Douglas Gregor58acf322009-10-09 22:16:47 +0000227 if (Id->getLength() >= 2) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +0000228 const char *Name = Id->getNameStart();
Douglas Gregor58acf322009-10-09 22:16:47 +0000229 if (Name[0] == '_' &&
230 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
231 return;
232 }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000233 }
234
235 // C++ constructors are never found by name lookup.
236 if (isa<CXXConstructorDecl>(CanonDecl))
237 return;
238
239 // Filter out any unwanted results.
240 if (Filter && !(this->*Filter)(R.Declaration))
241 return;
242
243 ShadowMap &SMap = ShadowMaps.back();
244 ShadowMap::iterator I, IEnd;
245 for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
246 I != IEnd; ++I) {
247 NamedDecl *ND = I->second.first;
248 unsigned Index = I->second.second;
249 if (ND->getCanonicalDecl() == CanonDecl) {
250 // This is a redeclaration. Always pick the newer declaration.
251 I->second.first = R.Declaration;
252 Results[Index].Declaration = R.Declaration;
253
254 // Pick the best rank of the two.
255 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
256
257 // We're done.
258 return;
259 }
260 }
261
262 // This is a new declaration in this scope. However, check whether this
263 // declaration name is hidden by a similarly-named declaration in an outer
264 // scope.
265 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
266 --SMEnd;
267 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
268 for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
269 I != IEnd; ++I) {
270 // A tag declaration does not hide a non-tag declaration.
271 if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
272 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
273 Decl::IDNS_ObjCProtocol)))
274 continue;
275
276 // Protocols are in distinct namespaces from everything else.
277 if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
278 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
279 I->second.first->getIdentifierNamespace() != IDNS)
280 continue;
281
282 // The newly-added result is hidden by an entry in the shadow map.
283 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
284 I->second.first)) {
285 // Note that this result was hidden.
286 R.Hidden = true;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000287 R.QualifierIsInformative = false;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000288
289 if (!R.Qualifier)
290 R.Qualifier = getRequiredQualification(SemaRef.Context,
291 CurContext,
292 R.Declaration->getDeclContext());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000293 } else {
294 // This result was hidden and cannot be found; don't bother adding
295 // it.
296 return;
297 }
298
299 break;
300 }
301 }
302
303 // Make sure that any given declaration only shows up in the result set once.
304 if (!AllDeclsFound.insert(CanonDecl))
305 return;
306
Douglas Gregore412a5a2009-09-23 22:26:46 +0000307 // If the filter is for nested-name-specifiers, then this result starts a
308 // nested-name-specifier.
309 if ((Filter == &ResultBuilder::IsNestedNameSpecifier) ||
310 (Filter == &ResultBuilder::IsMember &&
311 isa<CXXRecordDecl>(R.Declaration) &&
312 cast<CXXRecordDecl>(R.Declaration)->isInjectedClassName()))
313 R.StartsNestedNameSpecifier = true;
314
Douglas Gregor5bf52692009-09-22 23:15:58 +0000315 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000316 if (R.QualifierIsInformative && !R.Qualifier &&
317 !R.StartsNestedNameSpecifier) {
Douglas Gregor5bf52692009-09-22 23:15:58 +0000318 DeclContext *Ctx = R.Declaration->getDeclContext();
319 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
320 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
321 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
322 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
323 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
324 else
325 R.QualifierIsInformative = false;
326 }
Douglas Gregore412a5a2009-09-23 22:26:46 +0000327
Douglas Gregor3545ff42009-09-21 16:56:56 +0000328 // Insert this result into the set of results and into the current shadow
329 // map.
330 SMap.insert(std::make_pair(R.Declaration->getDeclName(),
331 std::make_pair(R.Declaration, Results.size())));
332 Results.push_back(R);
333}
334
335/// \brief Enter into a new scope.
336void ResultBuilder::EnterNewScope() {
337 ShadowMaps.push_back(ShadowMap());
338}
339
340/// \brief Exit from the current scope.
341void ResultBuilder::ExitScope() {
342 ShadowMaps.pop_back();
343}
344
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000345/// \brief Determines whether this given declaration will be found by
346/// ordinary name lookup.
347bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
348 unsigned IDNS = Decl::IDNS_Ordinary;
349 if (SemaRef.getLangOptions().CPlusPlus)
350 IDNS |= Decl::IDNS_Tag;
351
352 return ND->getIdentifierNamespace() & IDNS;
353}
354
Douglas Gregor3545ff42009-09-21 16:56:56 +0000355/// \brief Determines whether the given declaration is suitable as the
356/// start of a C++ nested-name-specifier, e.g., a class or namespace.
357bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
358 // Allow us to find class templates, too.
359 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
360 ND = ClassTemplate->getTemplatedDecl();
361
362 return SemaRef.isAcceptableNestedNameSpecifier(ND);
363}
364
365/// \brief Determines whether the given declaration is an enumeration.
366bool ResultBuilder::IsEnum(NamedDecl *ND) const {
367 return isa<EnumDecl>(ND);
368}
369
370/// \brief Determines whether the given declaration is a class or struct.
371bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
372 // Allow us to find class templates, too.
373 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
374 ND = ClassTemplate->getTemplatedDecl();
375
376 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
377 return RD->getTagKind() == TagDecl::TK_class ||
378 RD->getTagKind() == TagDecl::TK_struct;
379
380 return false;
381}
382
383/// \brief Determines whether the given declaration is a union.
384bool ResultBuilder::IsUnion(NamedDecl *ND) const {
385 // Allow us to find class templates, too.
386 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
387 ND = ClassTemplate->getTemplatedDecl();
388
389 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
390 return RD->getTagKind() == TagDecl::TK_union;
391
392 return false;
393}
394
395/// \brief Determines whether the given declaration is a namespace.
396bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
397 return isa<NamespaceDecl>(ND);
398}
399
400/// \brief Determines whether the given declaration is a namespace or
401/// namespace alias.
402bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
403 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
404}
405
406/// \brief Brief determines whether the given declaration is a namespace or
407/// namespace alias.
408bool ResultBuilder::IsType(NamedDecl *ND) const {
409 return isa<TypeDecl>(ND);
410}
411
Douglas Gregore412a5a2009-09-23 22:26:46 +0000412/// \brief Since every declaration found within a class is a member that we
413/// care about, always returns true. This predicate exists mostly to
414/// communicate to the result builder that we are performing a lookup for
415/// member access.
416bool ResultBuilder::IsMember(NamedDecl *ND) const {
417 return true;
418}
419
Douglas Gregor3545ff42009-09-21 16:56:56 +0000420// Find the next outer declaration context corresponding to this scope.
421static DeclContext *findOuterContext(Scope *S) {
422 for (S = S->getParent(); S; S = S->getParent())
423 if (S->getEntity())
424 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
425
426 return 0;
427}
428
429/// \brief Collect the results of searching for members within the given
430/// declaration context.
431///
432/// \param Ctx the declaration context from which we will gather results.
433///
Douglas Gregor5bf52692009-09-22 23:15:58 +0000434/// \param Rank the rank given to results in this declaration context.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000435///
436/// \param Visited the set of declaration contexts that have already been
437/// visited. Declaration contexts will only be visited once.
438///
439/// \param Results the result set that will be extended with any results
440/// found within this declaration context (and, for a C++ class, its bases).
441///
Douglas Gregor5bf52692009-09-22 23:15:58 +0000442/// \param InBaseClass whether we are in a base class.
443///
Douglas Gregor3545ff42009-09-21 16:56:56 +0000444/// \returns the next higher rank value, after considering all of the
445/// names within this declaration context.
446static unsigned CollectMemberLookupResults(DeclContext *Ctx,
Douglas Gregor5bf52692009-09-22 23:15:58 +0000447 unsigned Rank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000448 DeclContext *CurContext,
449 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor5bf52692009-09-22 23:15:58 +0000450 ResultBuilder &Results,
451 bool InBaseClass = false) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000452 // Make sure we don't visit the same context twice.
453 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor5bf52692009-09-22 23:15:58 +0000454 return Rank;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000455
456 // Enumerate all of the results in this context.
Douglas Gregor5bf52692009-09-22 23:15:58 +0000457 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000458 Results.EnterNewScope();
459 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
460 CurCtx = CurCtx->getNextContext()) {
461 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregor8caea942009-11-09 21:35:27 +0000462 DEnd = CurCtx->decls_end();
Douglas Gregor3545ff42009-09-21 16:56:56 +0000463 D != DEnd; ++D) {
464 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor5bf52692009-09-22 23:15:58 +0000465 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregor8caea942009-11-09 21:35:27 +0000466
467 // Visit transparent contexts inside this context.
468 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
469 if (InnerCtx->isTransparentContext())
470 CollectMemberLookupResults(InnerCtx, Rank, CurContext, Visited,
471 Results, InBaseClass);
472 }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000473 }
474 }
475
476 // Traverse the contexts of inherited classes.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000477 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
478 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
Douglas Gregor8caea942009-11-09 21:35:27 +0000479 BEnd = Record->bases_end();
Douglas Gregor3545ff42009-09-21 16:56:56 +0000480 B != BEnd; ++B) {
481 QualType BaseType = B->getType();
482
483 // Don't look into dependent bases, because name lookup can't look
484 // there anyway.
485 if (BaseType->isDependentType())
486 continue;
487
488 const RecordType *Record = BaseType->getAs<RecordType>();
489 if (!Record)
490 continue;
491
492 // FIXME: It would be nice to be able to determine whether referencing
493 // a particular member would be ambiguous. For example, given
494 //
495 // struct A { int member; };
496 // struct B { int member; };
497 // struct C : A, B { };
498 //
499 // void f(C *c) { c->### }
500 // accessing 'member' would result in an ambiguity. However, code
501 // completion could be smart enough to qualify the member with the
502 // base class, e.g.,
503 //
504 // c->B::member
505 //
506 // or
507 //
508 // c->A::member
509
510 // Collect results from this base class (and its bases).
Douglas Gregor5bf52692009-09-22 23:15:58 +0000511 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
512 Results, /*InBaseClass=*/true);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000513 }
514 }
515
516 // FIXME: Look into base classes in Objective-C!
517
518 Results.ExitScope();
Douglas Gregor5bf52692009-09-22 23:15:58 +0000519 return Rank + 1;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000520}
521
522/// \brief Collect the results of searching for members within the given
523/// declaration context.
524///
525/// \param Ctx the declaration context from which we will gather results.
526///
527/// \param InitialRank the initial rank given to results in this declaration
528/// context. Larger rank values will be used for, e.g., members found in
529/// base classes.
530///
531/// \param Results the result set that will be extended with any results
532/// found within this declaration context (and, for a C++ class, its bases).
533///
534/// \returns the next higher rank value, after considering all of the
535/// names within this declaration context.
536static unsigned CollectMemberLookupResults(DeclContext *Ctx,
537 unsigned InitialRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000538 DeclContext *CurContext,
Douglas Gregor3545ff42009-09-21 16:56:56 +0000539 ResultBuilder &Results) {
540 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000541 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
542 Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000543}
544
545/// \brief Collect the results of searching for declarations within the given
546/// scope and its parent scopes.
547///
548/// \param S the scope in which we will start looking for declarations.
549///
550/// \param InitialRank the initial rank given to results in this scope.
551/// Larger rank values will be used for results found in parent scopes.
552///
Douglas Gregor2af2f672009-09-21 20:12:40 +0000553/// \param CurContext the context from which lookup results will be found.
554///
Douglas Gregor3545ff42009-09-21 16:56:56 +0000555/// \param Results the builder object that will receive each result.
556static unsigned CollectLookupResults(Scope *S,
557 TranslationUnitDecl *TranslationUnit,
558 unsigned InitialRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000559 DeclContext *CurContext,
Douglas Gregor3545ff42009-09-21 16:56:56 +0000560 ResultBuilder &Results) {
561 if (!S)
562 return InitialRank;
563
564 // FIXME: Using directives!
565
566 unsigned NextRank = InitialRank;
567 Results.EnterNewScope();
568 if (S->getEntity() &&
569 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
570 // Look into this scope's declaration context, along with any of its
571 // parent lookup contexts (e.g., enclosing classes), up to the point
572 // where we hit the context stored in the next outer scope.
573 DeclContext *Ctx = (DeclContext *)S->getEntity();
574 DeclContext *OuterCtx = findOuterContext(S);
575
576 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
577 Ctx = Ctx->getLookupParent()) {
578 if (Ctx->isFunctionOrMethod())
579 continue;
580
Douglas Gregor2af2f672009-09-21 20:12:40 +0000581 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
582 Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000583 }
584 } else if (!S->getParent()) {
585 // Look into the translation unit scope. We walk through the translation
586 // unit's declaration context, because the Scope itself won't have all of
587 // the declarations if we loaded a precompiled header.
588 // FIXME: We would like the translation unit's Scope object to point to the
589 // translation unit, so we don't need this special "if" branch. However,
590 // doing so would force the normal C++ name-lookup code to look into the
591 // translation unit decl when the IdentifierInfo chains would suffice.
592 // Once we fix that problem (which is part of a more general "don't look
593 // in DeclContexts unless we have to" optimization), we can eliminate the
594 // TranslationUnit parameter entirely.
595 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000596 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000597 } else {
598 // Walk through the declarations in this Scope.
599 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
600 D != DEnd; ++D) {
601 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
Douglas Gregor2af2f672009-09-21 20:12:40 +0000602 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
603 CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000604 }
605
606 NextRank = NextRank + 1;
607 }
608
609 // Lookup names in the parent scope.
610 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000611 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000612 Results.ExitScope();
613
614 return NextRank;
615}
616
617/// \brief Add type specifiers for the current language as keyword results.
618static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
619 ResultBuilder &Results) {
620 typedef CodeCompleteConsumer::Result Result;
621 Results.MaybeAddResult(Result("short", Rank));
622 Results.MaybeAddResult(Result("long", Rank));
623 Results.MaybeAddResult(Result("signed", Rank));
624 Results.MaybeAddResult(Result("unsigned", Rank));
625 Results.MaybeAddResult(Result("void", Rank));
626 Results.MaybeAddResult(Result("char", Rank));
627 Results.MaybeAddResult(Result("int", Rank));
628 Results.MaybeAddResult(Result("float", Rank));
629 Results.MaybeAddResult(Result("double", Rank));
630 Results.MaybeAddResult(Result("enum", Rank));
631 Results.MaybeAddResult(Result("struct", Rank));
632 Results.MaybeAddResult(Result("union", Rank));
633
634 if (LangOpts.C99) {
635 // C99-specific
636 Results.MaybeAddResult(Result("_Complex", Rank));
637 Results.MaybeAddResult(Result("_Imaginary", Rank));
638 Results.MaybeAddResult(Result("_Bool", Rank));
639 }
640
641 if (LangOpts.CPlusPlus) {
642 // C++-specific
643 Results.MaybeAddResult(Result("bool", Rank));
644 Results.MaybeAddResult(Result("class", Rank));
645 Results.MaybeAddResult(Result("typename", Rank));
646 Results.MaybeAddResult(Result("wchar_t", Rank));
647
648 if (LangOpts.CPlusPlus0x) {
649 Results.MaybeAddResult(Result("char16_t", Rank));
650 Results.MaybeAddResult(Result("char32_t", Rank));
651 Results.MaybeAddResult(Result("decltype", Rank));
652 }
653 }
654
655 // GNU extensions
656 if (LangOpts.GNUMode) {
657 // FIXME: Enable when we actually support decimal floating point.
658 // Results.MaybeAddResult(Result("_Decimal32", Rank));
659 // Results.MaybeAddResult(Result("_Decimal64", Rank));
660 // Results.MaybeAddResult(Result("_Decimal128", Rank));
661 Results.MaybeAddResult(Result("typeof", Rank));
662 }
663}
664
665/// \brief Add function parameter chunks to the given code completion string.
666static void AddFunctionParameterChunks(ASTContext &Context,
667 FunctionDecl *Function,
668 CodeCompletionString *Result) {
Douglas Gregor9eb77012009-11-07 00:00:49 +0000669 typedef CodeCompletionString::Chunk Chunk;
670
Douglas Gregor3545ff42009-09-21 16:56:56 +0000671 CodeCompletionString *CCStr = Result;
672
673 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
674 ParmVarDecl *Param = Function->getParamDecl(P);
675
676 if (Param->hasDefaultArg()) {
677 // When we see an optional default argument, put that argument and
678 // the remaining default arguments into a new, optional string.
679 CodeCompletionString *Opt = new CodeCompletionString;
680 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
681 CCStr = Opt;
682 }
683
684 if (P != 0)
Douglas Gregor9eb77012009-11-07 00:00:49 +0000685 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000686
687 // Format the placeholder string.
688 std::string PlaceholderStr;
689 if (Param->getIdentifier())
690 PlaceholderStr = Param->getIdentifier()->getName();
691
692 Param->getType().getAsStringInternal(PlaceholderStr,
693 Context.PrintingPolicy);
694
695 // Add the placeholder string.
Benjamin Kramerb33a97c2009-11-29 20:18:50 +0000696 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000697 }
Douglas Gregorba449032009-09-22 21:42:17 +0000698
699 if (const FunctionProtoType *Proto
700 = Function->getType()->getAs<FunctionProtoType>())
701 if (Proto->isVariadic())
702 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor3545ff42009-09-21 16:56:56 +0000703}
704
705/// \brief Add template parameter chunks to the given code completion string.
706static void AddTemplateParameterChunks(ASTContext &Context,
707 TemplateDecl *Template,
708 CodeCompletionString *Result,
709 unsigned MaxParameters = 0) {
Douglas Gregor9eb77012009-11-07 00:00:49 +0000710 typedef CodeCompletionString::Chunk Chunk;
711
Douglas Gregor3545ff42009-09-21 16:56:56 +0000712 CodeCompletionString *CCStr = Result;
713 bool FirstParameter = true;
714
715 TemplateParameterList *Params = Template->getTemplateParameters();
716 TemplateParameterList::iterator PEnd = Params->end();
717 if (MaxParameters)
718 PEnd = Params->begin() + MaxParameters;
719 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
720 bool HasDefaultArg = false;
721 std::string PlaceholderStr;
722 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
723 if (TTP->wasDeclaredWithTypename())
724 PlaceholderStr = "typename";
725 else
726 PlaceholderStr = "class";
727
728 if (TTP->getIdentifier()) {
729 PlaceholderStr += ' ';
730 PlaceholderStr += TTP->getIdentifier()->getName();
731 }
732
733 HasDefaultArg = TTP->hasDefaultArgument();
734 } else if (NonTypeTemplateParmDecl *NTTP
735 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
736 if (NTTP->getIdentifier())
737 PlaceholderStr = NTTP->getIdentifier()->getName();
738 NTTP->getType().getAsStringInternal(PlaceholderStr,
739 Context.PrintingPolicy);
740 HasDefaultArg = NTTP->hasDefaultArgument();
741 } else {
742 assert(isa<TemplateTemplateParmDecl>(*P));
743 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
744
745 // Since putting the template argument list into the placeholder would
746 // be very, very long, we just use an abbreviation.
747 PlaceholderStr = "template<...> class";
748 if (TTP->getIdentifier()) {
749 PlaceholderStr += ' ';
750 PlaceholderStr += TTP->getIdentifier()->getName();
751 }
752
753 HasDefaultArg = TTP->hasDefaultArgument();
754 }
755
756 if (HasDefaultArg) {
757 // When we see an optional default argument, put that argument and
758 // the remaining default arguments into a new, optional string.
759 CodeCompletionString *Opt = new CodeCompletionString;
760 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
761 CCStr = Opt;
762 }
763
764 if (FirstParameter)
765 FirstParameter = false;
766 else
Douglas Gregor9eb77012009-11-07 00:00:49 +0000767 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000768
769 // Add the placeholder string.
Benjamin Kramerb33a97c2009-11-29 20:18:50 +0000770 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000771 }
772}
773
Douglas Gregorf2510672009-09-21 19:57:38 +0000774/// \brief Add a qualifier to the given code-completion string, if the
775/// provided nested-name-specifier is non-NULL.
776void AddQualifierToCompletionString(CodeCompletionString *Result,
777 NestedNameSpecifier *Qualifier,
Douglas Gregor5bf52692009-09-22 23:15:58 +0000778 bool QualifierIsInformative,
Douglas Gregorf2510672009-09-21 19:57:38 +0000779 ASTContext &Context) {
780 if (!Qualifier)
781 return;
782
783 std::string PrintedNNS;
784 {
785 llvm::raw_string_ostream OS(PrintedNNS);
786 Qualifier->print(OS, Context.PrintingPolicy);
787 }
Douglas Gregor5bf52692009-09-22 23:15:58 +0000788 if (QualifierIsInformative)
Benjamin Kramerb33a97c2009-11-29 20:18:50 +0000789 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor5bf52692009-09-22 23:15:58 +0000790 else
Benjamin Kramerb33a97c2009-11-29 20:18:50 +0000791 Result->AddTextChunk(PrintedNNS);
Douglas Gregorf2510672009-09-21 19:57:38 +0000792}
793
Douglas Gregor3545ff42009-09-21 16:56:56 +0000794/// \brief If possible, create a new code completion string for the given
795/// result.
796///
797/// \returns Either a new, heap-allocated code completion string describing
798/// how to use this result, or NULL to indicate that the string or name of the
799/// result is all that is needed.
800CodeCompletionString *
801CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
Douglas Gregor9eb77012009-11-07 00:00:49 +0000802 typedef CodeCompletionString::Chunk Chunk;
803
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000804 if (Kind == RK_Keyword)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000805 return 0;
806
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000807 if (Kind == RK_Macro) {
808 MacroInfo *MI = S.PP.getMacroInfo(Macro);
809 if (!MI || !MI->isFunctionLike())
810 return 0;
811
812 // Format a function-like macro with placeholders for the arguments.
813 CodeCompletionString *Result = new CodeCompletionString;
Benjamin Kramerb33a97c2009-11-29 20:18:50 +0000814 Result->AddTypedTextChunk(Macro->getName());
Douglas Gregor9eb77012009-11-07 00:00:49 +0000815 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000816 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
817 A != AEnd; ++A) {
818 if (A != MI->arg_begin())
Douglas Gregor9eb77012009-11-07 00:00:49 +0000819 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000820
821 if (!MI->isVariadic() || A != AEnd - 1) {
822 // Non-variadic argument.
Benjamin Kramerb33a97c2009-11-29 20:18:50 +0000823 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000824 continue;
825 }
826
827 // Variadic argument; cope with the different between GNU and C99
828 // variadic macros, providing a single placeholder for the rest of the
829 // arguments.
830 if ((*A)->isStr("__VA_ARGS__"))
831 Result->AddPlaceholderChunk("...");
832 else {
833 std::string Arg = (*A)->getName();
834 Arg += "...";
Benjamin Kramerb33a97c2009-11-29 20:18:50 +0000835 Result->AddPlaceholderChunk(Arg);
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000836 }
837 }
Douglas Gregor9eb77012009-11-07 00:00:49 +0000838 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000839 return Result;
840 }
841
842 assert(Kind == RK_Declaration && "Missed a macro kind?");
Douglas Gregor3545ff42009-09-21 16:56:56 +0000843 NamedDecl *ND = Declaration;
844
Douglas Gregor9eb77012009-11-07 00:00:49 +0000845 if (StartsNestedNameSpecifier) {
846 CodeCompletionString *Result = new CodeCompletionString;
Benjamin Kramerb33a97c2009-11-29 20:18:50 +0000847 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor9eb77012009-11-07 00:00:49 +0000848 Result->AddTextChunk("::");
849 return Result;
850 }
851
Douglas Gregor3545ff42009-09-21 16:56:56 +0000852 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
853 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000854 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
855 S.Context);
Benjamin Kramerb33a97c2009-11-29 20:18:50 +0000856 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor9eb77012009-11-07 00:00:49 +0000857 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000858 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000859 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000860 return Result;
861 }
862
863 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
864 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000865 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
866 S.Context);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000867 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramerb33a97c2009-11-29 20:18:50 +0000868 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000869
870 // Figure out which template parameters are deduced (or have default
871 // arguments).
872 llvm::SmallVector<bool, 16> Deduced;
873 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
874 unsigned LastDeducibleArgument;
875 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
876 --LastDeducibleArgument) {
877 if (!Deduced[LastDeducibleArgument - 1]) {
878 // C++0x: Figure out if the template argument has a default. If so,
879 // the user doesn't need to type this argument.
880 // FIXME: We need to abstract template parameters better!
881 bool HasDefaultArg = false;
882 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
883 LastDeducibleArgument - 1);
884 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
885 HasDefaultArg = TTP->hasDefaultArgument();
886 else if (NonTypeTemplateParmDecl *NTTP
887 = dyn_cast<NonTypeTemplateParmDecl>(Param))
888 HasDefaultArg = NTTP->hasDefaultArgument();
889 else {
890 assert(isa<TemplateTemplateParmDecl>(Param));
891 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +0000892 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +0000893 }
894
895 if (!HasDefaultArg)
896 break;
897 }
898 }
899
900 if (LastDeducibleArgument) {
901 // Some of the function template arguments cannot be deduced from a
902 // function call, so we introduce an explicit template argument list
903 // containing all of the arguments up to the first deducible argument.
Douglas Gregor9eb77012009-11-07 00:00:49 +0000904 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000905 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
906 LastDeducibleArgument);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000907 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000908 }
909
910 // Add the function parameters
Douglas Gregor9eb77012009-11-07 00:00:49 +0000911 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000912 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000913 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000914 return Result;
915 }
916
917 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
918 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000919 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
920 S.Context);
Benjamin Kramerb33a97c2009-11-29 20:18:50 +0000921 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor9eb77012009-11-07 00:00:49 +0000922 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000923 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +0000924 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +0000925 return Result;
926 }
927
Douglas Gregord3c5d792009-11-17 16:44:22 +0000928 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
929 CodeCompletionString *Result = new CodeCompletionString;
930 Selector Sel = Method->getSelector();
931 if (Sel.isUnarySelector()) {
932 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
933 return Result;
934 }
935
Douglas Gregor1b605f72009-11-19 01:08:35 +0000936 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
937 SelName += ':';
938 if (StartParameter == 0)
939 Result->AddTypedTextChunk(SelName);
940 else {
941 Result->AddInformativeChunk(SelName);
942
943 // If there is only one parameter, and we're past it, add an empty
944 // typed-text chunk since there is nothing to type.
945 if (Method->param_size() == 1)
946 Result->AddTypedTextChunk("");
947 }
Douglas Gregord3c5d792009-11-17 16:44:22 +0000948 unsigned Idx = 0;
949 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
950 PEnd = Method->param_end();
951 P != PEnd; (void)++P, ++Idx) {
952 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +0000953 std::string Keyword;
954 if (Idx > StartParameter)
955 Keyword = " ";
Douglas Gregord3c5d792009-11-17 16:44:22 +0000956 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
957 Keyword += II->getName().str();
958 Keyword += ":";
Douglas Gregorc8537c52009-11-19 07:41:15 +0000959 if (Idx < StartParameter || AllParametersAreInformative) {
Douglas Gregor1b605f72009-11-19 01:08:35 +0000960 Result->AddInformativeChunk(Keyword);
961 } else if (Idx == StartParameter)
962 Result->AddTypedTextChunk(Keyword);
963 else
964 Result->AddTextChunk(Keyword);
Douglas Gregord3c5d792009-11-17 16:44:22 +0000965 }
Douglas Gregor1b605f72009-11-19 01:08:35 +0000966
967 // If we're before the starting parameter, skip the placeholder.
968 if (Idx < StartParameter)
969 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +0000970
971 std::string Arg;
972 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
973 Arg = "(" + Arg + ")";
974 if (IdentifierInfo *II = (*P)->getIdentifier())
975 Arg += II->getName().str();
Douglas Gregorc8537c52009-11-19 07:41:15 +0000976 if (AllParametersAreInformative)
977 Result->AddInformativeChunk(Arg);
978 else
979 Result->AddPlaceholderChunk(Arg);
Douglas Gregord3c5d792009-11-17 16:44:22 +0000980 }
981
982 return Result;
983 }
984
Douglas Gregor9eb77012009-11-07 00:00:49 +0000985 if (Qualifier) {
Douglas Gregorf2510672009-09-21 19:57:38 +0000986 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000987 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
988 S.Context);
Benjamin Kramerb33a97c2009-11-29 20:18:50 +0000989 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregorf2510672009-09-21 19:57:38 +0000990 return Result;
991 }
992
Douglas Gregor3545ff42009-09-21 16:56:56 +0000993 return 0;
994}
995
Douglas Gregorf0f51982009-09-23 00:34:09 +0000996CodeCompletionString *
997CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
998 unsigned CurrentArg,
999 Sema &S) const {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001000 typedef CodeCompletionString::Chunk Chunk;
1001
Douglas Gregorf0f51982009-09-23 00:34:09 +00001002 CodeCompletionString *Result = new CodeCompletionString;
1003 FunctionDecl *FDecl = getFunction();
1004 const FunctionProtoType *Proto
1005 = dyn_cast<FunctionProtoType>(getFunctionType());
1006 if (!FDecl && !Proto) {
1007 // Function without a prototype. Just give the return type and a
1008 // highlighted ellipsis.
1009 const FunctionType *FT = getFunctionType();
1010 Result->AddTextChunk(
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001011 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor9eb77012009-11-07 00:00:49 +00001012 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1013 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1014 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001015 return Result;
1016 }
1017
1018 if (FDecl)
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001019 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregorf0f51982009-09-23 00:34:09 +00001020 else
1021 Result->AddTextChunk(
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001022 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001023
Douglas Gregor9eb77012009-11-07 00:00:49 +00001024 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001025 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
1026 for (unsigned I = 0; I != NumParams; ++I) {
1027 if (I)
Douglas Gregor9eb77012009-11-07 00:00:49 +00001028 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001029
1030 std::string ArgString;
1031 QualType ArgType;
1032
1033 if (FDecl) {
1034 ArgString = FDecl->getParamDecl(I)->getNameAsString();
1035 ArgType = FDecl->getParamDecl(I)->getOriginalType();
1036 } else {
1037 ArgType = Proto->getArgType(I);
1038 }
1039
1040 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
1041
1042 if (I == CurrentArg)
Douglas Gregor9eb77012009-11-07 00:00:49 +00001043 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001044 ArgString));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001045 else
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001046 Result->AddTextChunk(ArgString);
Douglas Gregorf0f51982009-09-23 00:34:09 +00001047 }
1048
1049 if (Proto && Proto->isVariadic()) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001050 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001051 if (CurrentArg < NumParams)
1052 Result->AddTextChunk("...");
1053 else
Douglas Gregor9eb77012009-11-07 00:00:49 +00001054 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001055 }
Douglas Gregor9eb77012009-11-07 00:00:49 +00001056 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00001057
1058 return Result;
1059}
1060
Douglas Gregor3545ff42009-09-21 16:56:56 +00001061namespace {
1062 struct SortCodeCompleteResult {
1063 typedef CodeCompleteConsumer::Result Result;
1064
Douglas Gregore6688e62009-09-28 03:51:44 +00001065 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001066 if (!X.getObjCSelector().isNull() && !Y.getObjCSelector().isNull()) {
1067 // Consider all selector kinds to be equivalent.
1068 } else if (X.getNameKind() != Y.getNameKind())
Douglas Gregore6688e62009-09-28 03:51:44 +00001069 return X.getNameKind() < Y.getNameKind();
1070
1071 return llvm::LowercaseString(X.getAsString())
1072 < llvm::LowercaseString(Y.getAsString());
1073 }
1074
Douglas Gregor3545ff42009-09-21 16:56:56 +00001075 bool operator()(const Result &X, const Result &Y) const {
1076 // Sort first by rank.
1077 if (X.Rank < Y.Rank)
1078 return true;
1079 else if (X.Rank > Y.Rank)
1080 return false;
1081
Douglas Gregor45f83ee2009-11-19 00:01:57 +00001082 // We use a special ordering for keywords and patterns, based on the
1083 // typed text.
1084 if ((X.Kind == Result::RK_Keyword || X.Kind == Result::RK_Pattern) &&
1085 (Y.Kind == Result::RK_Keyword || Y.Kind == Result::RK_Pattern)) {
1086 const char *XStr = (X.Kind == Result::RK_Keyword)? X.Keyword
1087 : X.Pattern->getTypedText();
1088 const char *YStr = (Y.Kind == Result::RK_Keyword)? Y.Keyword
1089 : Y.Pattern->getTypedText();
1090 return strcmp(XStr, YStr) < 0;
1091 }
1092
Douglas Gregor3545ff42009-09-21 16:56:56 +00001093 // Result kinds are ordered by decreasing importance.
1094 if (X.Kind < Y.Kind)
1095 return true;
1096 else if (X.Kind > Y.Kind)
1097 return false;
1098
1099 // Non-hidden names precede hidden names.
1100 if (X.Hidden != Y.Hidden)
1101 return !X.Hidden;
1102
Douglas Gregore412a5a2009-09-23 22:26:46 +00001103 // Non-nested-name-specifiers precede nested-name-specifiers.
1104 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1105 return !X.StartsNestedNameSpecifier;
1106
Douglas Gregor3545ff42009-09-21 16:56:56 +00001107 // Ordering depends on the kind of result.
1108 switch (X.Kind) {
1109 case Result::RK_Declaration:
1110 // Order based on the declaration names.
Douglas Gregore6688e62009-09-28 03:51:44 +00001111 return isEarlierDeclarationName(X.Declaration->getDeclName(),
1112 Y.Declaration->getDeclName());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001113
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001114 case Result::RK_Macro:
1115 return llvm::LowercaseString(X.Macro->getName()) <
1116 llvm::LowercaseString(Y.Macro->getName());
Douglas Gregor45f83ee2009-11-19 00:01:57 +00001117
1118 case Result::RK_Keyword:
1119 case Result::RK_Pattern:
1120 llvm::llvm_unreachable("Result kinds handled above");
1121 break;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001122 }
1123
1124 // Silence GCC warning.
1125 return false;
1126 }
1127 };
1128}
1129
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001130static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1131 ResultBuilder &Results) {
1132 Results.EnterNewScope();
Douglas Gregor9eb77012009-11-07 00:00:49 +00001133 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1134 MEnd = PP.macro_end();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001135 M != MEnd; ++M)
1136 Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1137 Results.ExitScope();
1138}
1139
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001140static void HandleCodeCompleteResults(Sema *S,
1141 CodeCompleteConsumer *CodeCompleter,
1142 CodeCompleteConsumer::Result *Results,
1143 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00001144 // Sort the results by rank/kind/etc.
1145 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1146
1147 if (CodeCompleter)
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001148 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor45f83ee2009-11-19 00:01:57 +00001149
1150 for (unsigned I = 0; I != NumResults; ++I)
1151 Results[I].Destroy();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001152}
1153
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001154void Sema::CodeCompleteOrdinaryName(Scope *S) {
1155 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001156 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1157 0, CurContext, Results);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001158 if (CodeCompleter->includeMacros())
1159 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001160 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001161}
1162
Douglas Gregor9291bad2009-11-18 01:29:26 +00001163static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00001164 bool AllowCategories,
Douglas Gregor9291bad2009-11-18 01:29:26 +00001165 DeclContext *CurContext,
1166 ResultBuilder &Results) {
1167 typedef CodeCompleteConsumer::Result Result;
1168
1169 // Add properties in this container.
1170 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
1171 PEnd = Container->prop_end();
1172 P != PEnd;
1173 ++P)
1174 Results.MaybeAddResult(Result(*P, 0), CurContext);
1175
1176 // Add properties in referenced protocols.
1177 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
1178 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
1179 PEnd = Protocol->protocol_end();
1180 P != PEnd; ++P)
Douglas Gregor5d649882009-11-18 22:32:06 +00001181 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00001182 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00001183 if (AllowCategories) {
1184 // Look through categories.
1185 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
1186 Category; Category = Category->getNextClassCategory())
1187 AddObjCProperties(Category, AllowCategories, CurContext, Results);
1188 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00001189
1190 // Look through protocols.
1191 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
1192 E = IFace->protocol_end();
1193 I != E; ++I)
Douglas Gregor5d649882009-11-18 22:32:06 +00001194 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00001195
1196 // Look in the superclass.
1197 if (IFace->getSuperClass())
Douglas Gregor5d649882009-11-18 22:32:06 +00001198 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
1199 Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00001200 } else if (const ObjCCategoryDecl *Category
1201 = dyn_cast<ObjCCategoryDecl>(Container)) {
1202 // Look through protocols.
1203 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
1204 PEnd = Category->protocol_end();
1205 P != PEnd; ++P)
Douglas Gregor5d649882009-11-18 22:32:06 +00001206 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00001207 }
1208}
1209
Douglas Gregor2436e712009-09-17 21:32:03 +00001210void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1211 SourceLocation OpLoc,
1212 bool IsArrow) {
1213 if (!BaseE || !CodeCompleter)
1214 return;
1215
Douglas Gregor3545ff42009-09-21 16:56:56 +00001216 typedef CodeCompleteConsumer::Result Result;
1217
Douglas Gregor2436e712009-09-17 21:32:03 +00001218 Expr *Base = static_cast<Expr *>(BaseE);
1219 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001220
1221 if (IsArrow) {
1222 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1223 BaseType = Ptr->getPointeeType();
1224 else if (BaseType->isObjCObjectPointerType())
1225 /*Do nothing*/ ;
1226 else
1227 return;
1228 }
1229
Douglas Gregore412a5a2009-09-23 22:26:46 +00001230 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001231 unsigned NextRank = 0;
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001232
Douglas Gregor9291bad2009-11-18 01:29:26 +00001233 Results.EnterNewScope();
1234 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
1235 // Access to a C/C++ class, struct, or union.
1236 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1237 Record->getDecl(), Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001238
Douglas Gregor9291bad2009-11-18 01:29:26 +00001239 if (getLangOptions().CPlusPlus) {
1240 if (!Results.empty()) {
1241 // The "template" keyword can follow "->" or "." in the grammar.
1242 // However, we only want to suggest the template keyword if something
1243 // is dependent.
1244 bool IsDependent = BaseType->isDependentType();
1245 if (!IsDependent) {
1246 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1247 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1248 IsDependent = Ctx->isDependentContext();
1249 break;
1250 }
1251 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001252
Douglas Gregor9291bad2009-11-18 01:29:26 +00001253 if (IsDependent)
1254 Results.MaybeAddResult(Result("template", NextRank++));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001255 }
1256
Douglas Gregor9291bad2009-11-18 01:29:26 +00001257 // We could have the start of a nested-name-specifier. Add those
1258 // results as well.
1259 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1260 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
1261 CurContext, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001262 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00001263 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
1264 // Objective-C property reference.
1265
1266 // Add property results based on our interface.
1267 const ObjCObjectPointerType *ObjCPtr
1268 = BaseType->getAsObjCInterfacePointerType();
1269 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor5d649882009-11-18 22:32:06 +00001270 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00001271
1272 // Add properties from the protocols in a qualified interface.
1273 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
1274 E = ObjCPtr->qual_end();
1275 I != E; ++I)
Douglas Gregor5d649882009-11-18 22:32:06 +00001276 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00001277
1278 // FIXME: We could (should?) also look for "implicit" properties, identified
1279 // only by the presence of nullary and unary selectors.
1280 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
1281 (!IsArrow && BaseType->isObjCInterfaceType())) {
1282 // Objective-C instance variable access.
1283 ObjCInterfaceDecl *Class = 0;
1284 if (const ObjCObjectPointerType *ObjCPtr
1285 = BaseType->getAs<ObjCObjectPointerType>())
1286 Class = ObjCPtr->getInterfaceDecl();
1287 else
1288 Class = BaseType->getAs<ObjCInterfaceType>()->getDecl();
1289
1290 // Add all ivars from this class and its superclasses.
1291 for (; Class; Class = Class->getSuperClass()) {
1292 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
1293 IVarEnd = Class->ivar_end();
1294 IVar != IVarEnd; ++IVar)
1295 Results.MaybeAddResult(Result(*IVar, 0), CurContext);
1296 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001297 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00001298
1299 // FIXME: How do we cope with isa?
1300
1301 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001302
1303 // Add macros
1304 if (CodeCompleter->includeMacros())
1305 AddMacroResults(PP, NextRank, Results);
1306
1307 // Hand off the results found for code completion.
1308 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00001309}
1310
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001311void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1312 if (!CodeCompleter)
1313 return;
1314
Douglas Gregor3545ff42009-09-21 16:56:56 +00001315 typedef CodeCompleteConsumer::Result Result;
1316 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001317 switch ((DeclSpec::TST)TagSpec) {
1318 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00001319 Filter = &ResultBuilder::IsEnum;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001320 break;
1321
1322 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00001323 Filter = &ResultBuilder::IsUnion;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001324 break;
1325
1326 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001327 case DeclSpec::TST_class:
Douglas Gregor3545ff42009-09-21 16:56:56 +00001328 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001329 break;
1330
1331 default:
1332 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1333 return;
1334 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001335
1336 ResultBuilder Results(*this, Filter);
1337 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor2af2f672009-09-21 20:12:40 +00001338 0, CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001339
1340 if (getLangOptions().CPlusPlus) {
1341 // We could have the start of a nested-name-specifier. Add those
1342 // results as well.
1343 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001344 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1345 NextRank, CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001346 }
1347
Douglas Gregor9eb77012009-11-07 00:00:49 +00001348 if (CodeCompleter->includeMacros())
1349 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001350 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001351}
1352
Douglas Gregord328d572009-09-21 18:10:23 +00001353void Sema::CodeCompleteCase(Scope *S) {
1354 if (getSwitchStack().empty() || !CodeCompleter)
1355 return;
1356
1357 SwitchStmt *Switch = getSwitchStack().back();
1358 if (!Switch->getCond()->getType()->isEnumeralType())
1359 return;
1360
1361 // Code-complete the cases of a switch statement over an enumeration type
1362 // by providing the list of
1363 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1364
1365 // Determine which enumerators we have already seen in the switch statement.
1366 // FIXME: Ideally, we would also be able to look *past* the code-completion
1367 // token, in case we are code-completing in the middle of the switch and not
1368 // at the end. However, we aren't able to do so at the moment.
1369 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorf2510672009-09-21 19:57:38 +00001370 NestedNameSpecifier *Qualifier = 0;
Douglas Gregord328d572009-09-21 18:10:23 +00001371 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1372 SC = SC->getNextSwitchCase()) {
1373 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1374 if (!Case)
1375 continue;
1376
1377 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1378 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1379 if (EnumConstantDecl *Enumerator
1380 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1381 // We look into the AST of the case statement to determine which
1382 // enumerator was named. Alternatively, we could compute the value of
1383 // the integral constant expression, then compare it against the
1384 // values of each enumerator. However, value-based approach would not
1385 // work as well with C++ templates where enumerators declared within a
1386 // template are type- and value-dependent.
1387 EnumeratorsSeen.insert(Enumerator);
1388
Douglas Gregorf2510672009-09-21 19:57:38 +00001389 // If this is a qualified-id, keep track of the nested-name-specifier
1390 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00001391 //
1392 // switch (TagD.getKind()) {
1393 // case TagDecl::TK_enum:
1394 // break;
1395 // case XXX
1396 //
Douglas Gregorf2510672009-09-21 19:57:38 +00001397 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00001398 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1399 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00001400 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00001401 }
1402 }
1403
Douglas Gregorf2510672009-09-21 19:57:38 +00001404 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1405 // If there are no prior enumerators in C++, check whether we have to
1406 // qualify the names of the enumerators that we suggest, because they
1407 // may not be visible in this scope.
1408 Qualifier = getRequiredQualification(Context, CurContext,
1409 Enum->getDeclContext());
1410
1411 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1412 }
1413
Douglas Gregord328d572009-09-21 18:10:23 +00001414 // Add any enumerators that have not yet been mentioned.
1415 ResultBuilder Results(*this);
1416 Results.EnterNewScope();
1417 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1418 EEnd = Enum->enumerator_end();
1419 E != EEnd; ++E) {
1420 if (EnumeratorsSeen.count(*E))
1421 continue;
1422
Douglas Gregorf2510672009-09-21 19:57:38 +00001423 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregord328d572009-09-21 18:10:23 +00001424 }
1425 Results.ExitScope();
1426
Douglas Gregor9eb77012009-11-07 00:00:49 +00001427 if (CodeCompleter->includeMacros())
1428 AddMacroResults(PP, 1, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001429 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00001430}
1431
Douglas Gregorcabea402009-09-22 15:41:20 +00001432namespace {
1433 struct IsBetterOverloadCandidate {
1434 Sema &S;
1435
1436 public:
1437 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1438
1439 bool
1440 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1441 return S.isBetterOverloadCandidate(X, Y);
1442 }
1443 };
1444}
1445
1446void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1447 ExprTy **ArgsIn, unsigned NumArgs) {
1448 if (!CodeCompleter)
1449 return;
1450
1451 Expr *Fn = (Expr *)FnIn;
1452 Expr **Args = (Expr **)ArgsIn;
1453
1454 // Ignore type-dependent call expressions entirely.
1455 if (Fn->isTypeDependent() ||
1456 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1457 return;
1458
John McCalld14a8642009-11-21 08:51:07 +00001459 llvm::SmallVector<NamedDecl*,8> Fns;
Douglas Gregorcabea402009-09-22 15:41:20 +00001460 DeclarationName UnqualifiedName;
1461 NestedNameSpecifier *Qualifier;
1462 SourceRange QualifierRange;
1463 bool ArgumentDependentLookup;
John McCall283b9012009-11-22 00:44:51 +00001464 bool Overloaded;
Douglas Gregorcabea402009-09-22 15:41:20 +00001465 bool HasExplicitTemplateArgs;
John McCall6b51f282009-11-23 01:53:49 +00001466 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregorcabea402009-09-22 15:41:20 +00001467
John McCalld14a8642009-11-21 08:51:07 +00001468 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall283b9012009-11-22 00:44:51 +00001469 ArgumentDependentLookup, Overloaded,
John McCall6b51f282009-11-23 01:53:49 +00001470 HasExplicitTemplateArgs, ExplicitTemplateArgs);
Douglas Gregorcabea402009-09-22 15:41:20 +00001471
1472
1473 // FIXME: What if we're calling something that isn't a function declaration?
1474 // FIXME: What if we're calling a pseudo-destructor?
1475 // FIXME: What if we're calling a member function?
1476
1477 // Build an overload candidate set based on the functions we find.
1478 OverloadCandidateSet CandidateSet;
John McCalld14a8642009-11-21 08:51:07 +00001479 AddOverloadedCallCandidates(Fns, UnqualifiedName,
John McCall6b51f282009-11-23 01:53:49 +00001480 ArgumentDependentLookup,
1481 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregorcabea402009-09-22 15:41:20 +00001482 Args, NumArgs,
1483 CandidateSet,
1484 /*PartialOverloading=*/true);
1485
1486 // Sort the overload candidate set by placing the best overloads first.
1487 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1488 IsBetterOverloadCandidate(*this));
1489
1490 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05f477c2009-09-23 00:16:58 +00001491 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1492 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlssone7ceb852009-09-22 17:29:51 +00001493
Douglas Gregorcabea402009-09-22 15:41:20 +00001494 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1495 CandEnd = CandidateSet.end();
1496 Cand != CandEnd; ++Cand) {
1497 if (Cand->Viable)
Douglas Gregor05f477c2009-09-23 00:16:58 +00001498 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregorcabea402009-09-22 15:41:20 +00001499 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001500 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
Douglas Gregor05f477c2009-09-23 00:16:58 +00001501 Results.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00001502}
1503
Douglas Gregor2436e712009-09-17 21:32:03 +00001504void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1505 bool EnteringContext) {
1506 if (!SS.getScopeRep() || !CodeCompleter)
1507 return;
1508
Douglas Gregor3545ff42009-09-21 16:56:56 +00001509 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1510 if (!Ctx)
1511 return;
1512
1513 ResultBuilder Results(*this);
Douglas Gregor2af2f672009-09-21 20:12:40 +00001514 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001515
1516 // The "template" keyword can follow "::" in the grammar, but only
1517 // put it into the grammar if the nested-name-specifier is dependent.
1518 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1519 if (!Results.empty() && NNS->isDependent())
1520 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1521
Douglas Gregor9eb77012009-11-07 00:00:49 +00001522 if (CodeCompleter->includeMacros())
1523 AddMacroResults(PP, NextRank + 1, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001524 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00001525}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001526
1527void Sema::CodeCompleteUsing(Scope *S) {
1528 if (!CodeCompleter)
1529 return;
1530
Douglas Gregor3545ff42009-09-21 16:56:56 +00001531 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001532 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001533
1534 // If we aren't in class scope, we could see the "namespace" keyword.
1535 if (!S->isClassScope())
1536 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1537
1538 // After "using", we can see anything that would start a
1539 // nested-name-specifier.
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001540 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1541 0, CurContext, Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001542 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001543
Douglas Gregor9eb77012009-11-07 00:00:49 +00001544 if (CodeCompleter->includeMacros())
1545 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001546 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001547}
1548
1549void Sema::CodeCompleteUsingDirective(Scope *S) {
1550 if (!CodeCompleter)
1551 return;
1552
Douglas Gregor3545ff42009-09-21 16:56:56 +00001553 // After "using namespace", we expect to see a namespace name or namespace
1554 // alias.
1555 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001556 Results.EnterNewScope();
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001557 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1558 0, CurContext, Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001559 Results.ExitScope();
Douglas Gregor9eb77012009-11-07 00:00:49 +00001560 if (CodeCompleter->includeMacros())
1561 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001562 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001563}
1564
1565void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1566 if (!CodeCompleter)
1567 return;
1568
Douglas Gregor3545ff42009-09-21 16:56:56 +00001569 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1570 DeclContext *Ctx = (DeclContext *)S->getEntity();
1571 if (!S->getParent())
1572 Ctx = Context.getTranslationUnitDecl();
1573
1574 if (Ctx && Ctx->isFileContext()) {
1575 // We only want to see those namespaces that have already been defined
1576 // within this scope, because its likely that the user is creating an
1577 // extended namespace declaration. Keep track of the most recent
1578 // definition of each namespace.
1579 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1580 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1581 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1582 NS != NSEnd; ++NS)
1583 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1584
1585 // Add the most recent definition (or extended definition) of each
1586 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00001587 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001588 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1589 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1590 NS != NSEnd; ++NS)
Douglas Gregor2af2f672009-09-21 20:12:40 +00001591 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1592 CurContext);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001593 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001594 }
1595
Douglas Gregor9eb77012009-11-07 00:00:49 +00001596 if (CodeCompleter->includeMacros())
1597 AddMacroResults(PP, 1, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001598 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001599}
1600
1601void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1602 if (!CodeCompleter)
1603 return;
1604
Douglas Gregor3545ff42009-09-21 16:56:56 +00001605 // After "namespace", we expect to see a namespace or alias.
1606 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001607 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1608 0, CurContext, Results);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001609 if (CodeCompleter->includeMacros())
1610 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001611 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001612}
1613
Douglas Gregorc811ede2009-09-18 20:05:18 +00001614void Sema::CodeCompleteOperatorName(Scope *S) {
1615 if (!CodeCompleter)
1616 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001617
1618 typedef CodeCompleteConsumer::Result Result;
1619 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001620 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00001621
Douglas Gregor3545ff42009-09-21 16:56:56 +00001622 // Add the names of overloadable operators.
1623#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1624 if (std::strcmp(Spelling, "?")) \
1625 Results.MaybeAddResult(Result(Spelling, 0));
1626#include "clang/Basic/OperatorKinds.def"
1627
1628 // Add any type names visible from the current scope
1629 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor2af2f672009-09-21 20:12:40 +00001630 0, CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001631
1632 // Add any type specifiers
1633 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1634
1635 // Add any nested-name-specifiers
1636 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001637 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1638 NextRank + 1, CurContext, Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00001639 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001640
Douglas Gregor9eb77012009-11-07 00:00:49 +00001641 if (CodeCompleter->includeMacros())
1642 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001643 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00001644}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001645
Douglas Gregore6078da2009-11-19 00:14:45 +00001646/// \brief Determine whether the addition of the given flag to an Objective-C
1647/// property's attributes will cause a conflict.
1648static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
1649 // Check if we've already added this flag.
1650 if (Attributes & NewFlag)
1651 return true;
1652
1653 Attributes |= NewFlag;
1654
1655 // Check for collisions with "readonly".
1656 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1657 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
1658 ObjCDeclSpec::DQ_PR_assign |
1659 ObjCDeclSpec::DQ_PR_copy |
1660 ObjCDeclSpec::DQ_PR_retain)))
1661 return true;
1662
1663 // Check for more than one of { assign, copy, retain }.
1664 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
1665 ObjCDeclSpec::DQ_PR_copy |
1666 ObjCDeclSpec::DQ_PR_retain);
1667 if (AssignCopyRetMask &&
1668 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
1669 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
1670 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
1671 return true;
1672
1673 return false;
1674}
1675
Douglas Gregor36029f42009-11-18 23:08:07 +00001676void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00001677 if (!CodeCompleter)
1678 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00001679
Steve Naroff936354c2009-10-08 21:55:05 +00001680 unsigned Attributes = ODS.getPropertyAttributes();
1681
1682 typedef CodeCompleteConsumer::Result Result;
1683 ResultBuilder Results(*this);
1684 Results.EnterNewScope();
Douglas Gregore6078da2009-11-19 00:14:45 +00001685 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
Steve Naroff936354c2009-10-08 21:55:05 +00001686 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
Douglas Gregore6078da2009-11-19 00:14:45 +00001687 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
Steve Naroff936354c2009-10-08 21:55:05 +00001688 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
Douglas Gregore6078da2009-11-19 00:14:45 +00001689 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
Steve Naroff936354c2009-10-08 21:55:05 +00001690 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
Douglas Gregore6078da2009-11-19 00:14:45 +00001691 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
Steve Naroff936354c2009-10-08 21:55:05 +00001692 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
Douglas Gregore6078da2009-11-19 00:14:45 +00001693 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
Steve Naroff936354c2009-10-08 21:55:05 +00001694 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
Douglas Gregore6078da2009-11-19 00:14:45 +00001695 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
Steve Naroff936354c2009-10-08 21:55:05 +00001696 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
Douglas Gregore6078da2009-11-19 00:14:45 +00001697 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor45f83ee2009-11-19 00:01:57 +00001698 CodeCompletionString *Setter = new CodeCompletionString;
1699 Setter->AddTypedTextChunk("setter");
1700 Setter->AddTextChunk(" = ");
1701 Setter->AddPlaceholderChunk("method");
1702 Results.MaybeAddResult(CodeCompleteConsumer::Result(Setter, 0));
1703 }
Douglas Gregore6078da2009-11-19 00:14:45 +00001704 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor45f83ee2009-11-19 00:01:57 +00001705 CodeCompletionString *Getter = new CodeCompletionString;
1706 Getter->AddTypedTextChunk("getter");
1707 Getter->AddTextChunk(" = ");
1708 Getter->AddPlaceholderChunk("method");
1709 Results.MaybeAddResult(CodeCompleteConsumer::Result(Getter, 0));
1710 }
Steve Naroff936354c2009-10-08 21:55:05 +00001711 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001712 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00001713}
Steve Naroffeae65032009-11-07 02:08:14 +00001714
Douglas Gregorc8537c52009-11-19 07:41:15 +00001715/// \brief Descripts the kind of Objective-C method that we want to find
1716/// via code completion.
1717enum ObjCMethodKind {
1718 MK_Any, //< Any kind of method, provided it means other specified criteria.
1719 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
1720 MK_OneArgSelector //< One-argument selector.
1721};
1722
1723static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
1724 ObjCMethodKind WantKind,
1725 IdentifierInfo **SelIdents,
1726 unsigned NumSelIdents) {
1727 Selector Sel = Method->getSelector();
1728 if (NumSelIdents > Sel.getNumArgs())
1729 return false;
1730
1731 switch (WantKind) {
1732 case MK_Any: break;
1733 case MK_ZeroArgSelector: return Sel.isUnarySelector();
1734 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
1735 }
1736
1737 for (unsigned I = 0; I != NumSelIdents; ++I)
1738 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
1739 return false;
1740
1741 return true;
1742}
1743
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001744/// \brief Add all of the Objective-C methods in the given Objective-C
1745/// container to the set of results.
1746///
1747/// The container will be a class, protocol, category, or implementation of
1748/// any of the above. This mether will recurse to include methods from
1749/// the superclasses of classes along with their categories, protocols, and
1750/// implementations.
1751///
1752/// \param Container the container in which we'll look to find methods.
1753///
1754/// \param WantInstance whether to add instance methods (only); if false, this
1755/// routine will add factory methods (only).
1756///
1757/// \param CurContext the context in which we're performing the lookup that
1758/// finds methods.
1759///
1760/// \param Results the structure into which we'll add results.
1761static void AddObjCMethods(ObjCContainerDecl *Container,
1762 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00001763 ObjCMethodKind WantKind,
Douglas Gregor1b605f72009-11-19 01:08:35 +00001764 IdentifierInfo **SelIdents,
1765 unsigned NumSelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001766 DeclContext *CurContext,
1767 ResultBuilder &Results) {
1768 typedef CodeCompleteConsumer::Result Result;
1769 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
1770 MEnd = Container->meth_end();
1771 M != MEnd; ++M) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00001772 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
1773 // Check whether the selector identifiers we've been given are a
1774 // subset of the identifiers for this particular method.
Douglas Gregorc8537c52009-11-19 07:41:15 +00001775 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregor1b605f72009-11-19 01:08:35 +00001776 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00001777
Douglas Gregor1b605f72009-11-19 01:08:35 +00001778 Result R = Result(*M, 0);
1779 R.StartParameter = NumSelIdents;
Douglas Gregorc8537c52009-11-19 07:41:15 +00001780 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor1b605f72009-11-19 01:08:35 +00001781 Results.MaybeAddResult(R, CurContext);
1782 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001783 }
1784
1785 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
1786 if (!IFace)
1787 return;
1788
1789 // Add methods in protocols.
1790 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
1791 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1792 E = Protocols.end();
1793 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00001794 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregor1b605f72009-11-19 01:08:35 +00001795 CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001796
1797 // Add methods in categories.
1798 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
1799 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00001800 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
1801 NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001802
1803 // Add a categories protocol methods.
1804 const ObjCList<ObjCProtocolDecl> &Protocols
1805 = CatDecl->getReferencedProtocols();
1806 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1807 E = Protocols.end();
1808 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00001809 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
1810 NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001811
1812 // Add methods in category implementations.
1813 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00001814 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
1815 NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001816 }
1817
1818 // Add methods in superclass.
1819 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00001820 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
1821 SelIdents, NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001822
1823 // Add methods in our implementation, if any.
1824 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00001825 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
1826 NumSelIdents, CurContext, Results);
1827}
1828
1829
1830void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
1831 DeclPtrTy *Methods,
1832 unsigned NumMethods) {
1833 typedef CodeCompleteConsumer::Result Result;
1834
1835 // Try to find the interface where getters might live.
1836 ObjCInterfaceDecl *Class
1837 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
1838 if (!Class) {
1839 if (ObjCCategoryDecl *Category
1840 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
1841 Class = Category->getClassInterface();
1842
1843 if (!Class)
1844 return;
1845 }
1846
1847 // Find all of the potential getters.
1848 ResultBuilder Results(*this);
1849 Results.EnterNewScope();
1850
1851 // FIXME: We need to do this because Objective-C methods don't get
1852 // pushed into DeclContexts early enough. Argh!
1853 for (unsigned I = 0; I != NumMethods; ++I) {
1854 if (ObjCMethodDecl *Method
1855 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
1856 if (Method->isInstanceMethod() &&
1857 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
1858 Result R = Result(Method, 0);
1859 R.AllParametersAreInformative = true;
1860 Results.MaybeAddResult(R, CurContext);
1861 }
1862 }
1863
1864 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
1865 Results.ExitScope();
1866 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
1867}
1868
1869void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
1870 DeclPtrTy *Methods,
1871 unsigned NumMethods) {
1872 typedef CodeCompleteConsumer::Result Result;
1873
1874 // Try to find the interface where setters might live.
1875 ObjCInterfaceDecl *Class
1876 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
1877 if (!Class) {
1878 if (ObjCCategoryDecl *Category
1879 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
1880 Class = Category->getClassInterface();
1881
1882 if (!Class)
1883 return;
1884 }
1885
1886 // Find all of the potential getters.
1887 ResultBuilder Results(*this);
1888 Results.EnterNewScope();
1889
1890 // FIXME: We need to do this because Objective-C methods don't get
1891 // pushed into DeclContexts early enough. Argh!
1892 for (unsigned I = 0; I != NumMethods; ++I) {
1893 if (ObjCMethodDecl *Method
1894 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
1895 if (Method->isInstanceMethod() &&
1896 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
1897 Result R = Result(Method, 0);
1898 R.AllParametersAreInformative = true;
1899 Results.MaybeAddResult(R, CurContext);
1900 }
1901 }
1902
1903 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
1904
1905 Results.ExitScope();
1906 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001907}
1908
Douglas Gregor090dd182009-11-17 23:31:36 +00001909void Sema::CodeCompleteObjCClassMessage(Scope *S, IdentifierInfo *FName,
Douglas Gregor1b605f72009-11-19 01:08:35 +00001910 SourceLocation FNameLoc,
1911 IdentifierInfo **SelIdents,
1912 unsigned NumSelIdents) {
Steve Naroffeae65032009-11-07 02:08:14 +00001913 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor8ce33212009-11-17 17:59:40 +00001914 ObjCInterfaceDecl *CDecl = 0;
1915
Douglas Gregor8ce33212009-11-17 17:59:40 +00001916 if (FName->isStr("super")) {
1917 // We're sending a message to "super".
1918 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
1919 // Figure out which interface we're in.
1920 CDecl = CurMethod->getClassInterface();
1921 if (!CDecl)
1922 return;
1923
1924 // Find the superclass of this class.
1925 CDecl = CDecl->getSuperClass();
1926 if (!CDecl)
1927 return;
1928
1929 if (CurMethod->isInstanceMethod()) {
1930 // We are inside an instance method, which means that the message
1931 // send [super ...] is actually calling an instance method on the
1932 // current object. Build the super expression and handle this like
1933 // an instance method.
1934 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
1935 SuperTy = Context.getObjCObjectPointerType(SuperTy);
1936 OwningExprResult Super
Douglas Gregor090dd182009-11-17 23:31:36 +00001937 = Owned(new (Context) ObjCSuperExpr(FNameLoc, SuperTy));
Douglas Gregor1b605f72009-11-19 01:08:35 +00001938 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
1939 SelIdents, NumSelIdents);
Douglas Gregor8ce33212009-11-17 17:59:40 +00001940 }
1941
1942 // Okay, we're calling a factory method in our superclass.
1943 }
1944 }
1945
1946 // If the given name refers to an interface type, retrieve the
1947 // corresponding declaration.
1948 if (!CDecl)
Douglas Gregor090dd182009-11-17 23:31:36 +00001949 if (TypeTy *Ty = getTypeName(*FName, FNameLoc, S, 0, false)) {
Douglas Gregor8ce33212009-11-17 17:59:40 +00001950 QualType T = GetTypeFromParser(Ty, 0);
1951 if (!T.isNull())
1952 if (const ObjCInterfaceType *Interface = T->getAs<ObjCInterfaceType>())
1953 CDecl = Interface->getDecl();
1954 }
1955
1956 if (!CDecl && FName->isStr("super")) {
1957 // "super" may be the name of a variable, in which case we are
1958 // probably calling an instance method.
John McCalle66edc12009-11-24 19:00:30 +00001959 CXXScopeSpec SS;
1960 UnqualifiedId id;
1961 id.setIdentifier(FName, FNameLoc);
1962 OwningExprResult Super = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor1b605f72009-11-19 01:08:35 +00001963 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
1964 SelIdents, NumSelIdents);
Douglas Gregor8ce33212009-11-17 17:59:40 +00001965 }
1966
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001967 // Add all of the factory methods in this Objective-C class, its protocols,
1968 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00001969 ResultBuilder Results(*this);
1970 Results.EnterNewScope();
Douglas Gregorc8537c52009-11-19 07:41:15 +00001971 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
1972 Results);
Steve Naroffeae65032009-11-07 02:08:14 +00001973 Results.ExitScope();
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001974
Steve Naroffeae65032009-11-07 02:08:14 +00001975 // This also suppresses remaining diagnostics.
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00001976 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00001977}
1978
Douglas Gregor1b605f72009-11-19 01:08:35 +00001979void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
1980 IdentifierInfo **SelIdents,
1981 unsigned NumSelIdents) {
Steve Naroffeae65032009-11-07 02:08:14 +00001982 typedef CodeCompleteConsumer::Result Result;
Steve Naroffeae65032009-11-07 02:08:14 +00001983
1984 Expr *RecExpr = static_cast<Expr *>(Receiver);
1985 QualType RecType = RecExpr->getType();
1986
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001987 // If necessary, apply function/array conversion to the receiver.
1988 // C99 6.7.5.3p[7,8].
1989 DefaultFunctionArrayConversion(RecExpr);
1990 QualType ReceiverType = RecExpr->getType();
Steve Naroffeae65032009-11-07 02:08:14 +00001991
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001992 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType()) {
1993 // FIXME: We're messaging 'id'. Do we actually want to look up every method
1994 // in the universe?
1995 return;
1996 }
1997
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00001998 // Build the set of methods we can see.
1999 ResultBuilder Results(*this);
2000 Results.EnterNewScope();
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00002001
Douglas Gregora3329fa2009-11-18 00:06:18 +00002002 // Handle messages to Class. This really isn't a message to an instance
2003 // method, so we treat it the same way we would treat a message send to a
2004 // class method.
2005 if (ReceiverType->isObjCClassType() ||
2006 ReceiverType->isObjCQualifiedClassType()) {
2007 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
2008 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregorc8537c52009-11-19 07:41:15 +00002009 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
2010 CurContext, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00002011 }
2012 }
2013 // Handle messages to a qualified ID ("id<foo>").
2014 else if (const ObjCObjectPointerType *QualID
2015 = ReceiverType->getAsObjCQualifiedIdType()) {
2016 // Search protocols for instance methods.
2017 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
2018 E = QualID->qual_end();
2019 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00002020 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
2021 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00002022 }
2023 // Handle messages to a pointer to interface type.
2024 else if (const ObjCObjectPointerType *IFacePtr
2025 = ReceiverType->getAsObjCInterfacePointerType()) {
2026 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00002027 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
2028 NumSelIdents, CurContext, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00002029
2030 // Search protocols for instance methods.
2031 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
2032 E = IFacePtr->qual_end();
2033 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00002034 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
2035 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00002036 }
2037
Steve Naroffeae65032009-11-07 02:08:14 +00002038 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002039 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00002040}
Douglas Gregorbaf69612009-11-18 04:19:12 +00002041
2042/// \brief Add all of the protocol declarations that we find in the given
2043/// (translation unit) context.
2044static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00002045 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00002046 ResultBuilder &Results) {
2047 typedef CodeCompleteConsumer::Result Result;
2048
2049 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
2050 DEnd = Ctx->decls_end();
2051 D != DEnd; ++D) {
2052 // Record any protocols we find.
2053 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor5b4671c2009-11-18 04:49:41 +00002054 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
2055 Results.MaybeAddResult(Result(Proto, 0), CurContext);
Douglas Gregorbaf69612009-11-18 04:19:12 +00002056
2057 // Record any forward-declared protocols we find.
2058 if (ObjCForwardProtocolDecl *Forward
2059 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2060 for (ObjCForwardProtocolDecl::protocol_iterator
2061 P = Forward->protocol_begin(),
2062 PEnd = Forward->protocol_end();
2063 P != PEnd; ++P)
Douglas Gregor5b4671c2009-11-18 04:49:41 +00002064 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
2065 Results.MaybeAddResult(Result(*P, 0), CurContext);
Douglas Gregorbaf69612009-11-18 04:19:12 +00002066 }
2067 }
2068}
2069
2070void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
2071 unsigned NumProtocols) {
2072 ResultBuilder Results(*this);
2073 Results.EnterNewScope();
2074
2075 // Tell the result set to ignore all of the protocols we have
2076 // already seen.
2077 for (unsigned I = 0; I != NumProtocols; ++I)
2078 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first))
2079 Results.Ignore(Protocol);
2080
2081 // Add all protocols.
Douglas Gregor5b4671c2009-11-18 04:49:41 +00002082 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
2083 Results);
2084
2085 Results.ExitScope();
2086 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2087}
2088
2089void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
2090 ResultBuilder Results(*this);
2091 Results.EnterNewScope();
2092
2093 // Add all protocols.
2094 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
2095 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00002096
2097 Results.ExitScope();
2098 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2099}
Douglas Gregor49c22a72009-11-18 16:26:39 +00002100
2101/// \brief Add all of the Objective-C interface declarations that we find in
2102/// the given (translation unit) context.
2103static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
2104 bool OnlyForwardDeclarations,
2105 bool OnlyUnimplemented,
2106 ResultBuilder &Results) {
2107 typedef CodeCompleteConsumer::Result Result;
2108
2109 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
2110 DEnd = Ctx->decls_end();
2111 D != DEnd; ++D) {
2112 // Record any interfaces we find.
2113 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
2114 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
2115 (!OnlyUnimplemented || !Class->getImplementation()))
2116 Results.MaybeAddResult(Result(Class, 0), CurContext);
2117
2118 // Record any forward-declared interfaces we find.
2119 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
2120 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
2121 C != CEnd; ++C)
2122 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
2123 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
2124 Results.MaybeAddResult(Result(C->getInterface(), 0), CurContext);
2125 }
2126 }
2127}
2128
2129void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
2130 ResultBuilder Results(*this);
2131 Results.EnterNewScope();
2132
2133 // Add all classes.
2134 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
2135 false, Results);
2136
2137 Results.ExitScope();
2138 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2139}
2140
2141void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName) {
2142 ResultBuilder Results(*this);
2143 Results.EnterNewScope();
2144
2145 // Make sure that we ignore the class we're currently defining.
2146 NamedDecl *CurClass
2147 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00002148 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00002149 Results.Ignore(CurClass);
2150
2151 // Add all classes.
2152 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
2153 false, Results);
2154
2155 Results.ExitScope();
2156 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2157}
2158
2159void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
2160 ResultBuilder Results(*this);
2161 Results.EnterNewScope();
2162
2163 // Add all unimplemented classes.
2164 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
2165 true, Results);
2166
2167 Results.ExitScope();
2168 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2169}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00002170
2171void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
2172 IdentifierInfo *ClassName) {
2173 typedef CodeCompleteConsumer::Result Result;
2174
2175 ResultBuilder Results(*this);
2176
2177 // Ignore any categories we find that have already been implemented by this
2178 // interface.
2179 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
2180 NamedDecl *CurClass
2181 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
2182 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
2183 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
2184 Category = Category->getNextClassCategory())
2185 CategoryNames.insert(Category->getIdentifier());
2186
2187 // Add all of the categories we know about.
2188 Results.EnterNewScope();
2189 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
2190 for (DeclContext::decl_iterator D = TU->decls_begin(),
2191 DEnd = TU->decls_end();
2192 D != DEnd; ++D)
2193 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
2194 if (CategoryNames.insert(Category->getIdentifier()))
2195 Results.MaybeAddResult(Result(Category, 0), CurContext);
2196 Results.ExitScope();
2197
2198 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2199}
2200
2201void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
2202 IdentifierInfo *ClassName) {
2203 typedef CodeCompleteConsumer::Result Result;
2204
2205 // Find the corresponding interface. If we couldn't find the interface, the
2206 // program itself is ill-formed. However, we'll try to be helpful still by
2207 // providing the list of all of the categories we know about.
2208 NamedDecl *CurClass
2209 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
2210 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
2211 if (!Class)
2212 return CodeCompleteObjCInterfaceCategory(S, ClassName);
2213
2214 ResultBuilder Results(*this);
2215
2216 // Add all of the categories that have have corresponding interface
2217 // declarations in this class and any of its superclasses, except for
2218 // already-implemented categories in the class itself.
2219 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
2220 Results.EnterNewScope();
2221 bool IgnoreImplemented = true;
2222 while (Class) {
2223 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
2224 Category = Category->getNextClassCategory())
2225 if ((!IgnoreImplemented || !Category->getImplementation()) &&
2226 CategoryNames.insert(Category->getIdentifier()))
2227 Results.MaybeAddResult(Result(Category, 0), CurContext);
2228
2229 Class = Class->getSuperClass();
2230 IgnoreImplemented = false;
2231 }
2232 Results.ExitScope();
2233
2234 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2235}
Douglas Gregor5d649882009-11-18 22:32:06 +00002236
Douglas Gregor52e78bd2009-11-18 22:56:13 +00002237void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
Douglas Gregor5d649882009-11-18 22:32:06 +00002238 typedef CodeCompleteConsumer::Result Result;
2239 ResultBuilder Results(*this);
2240
2241 // Figure out where this @synthesize lives.
2242 ObjCContainerDecl *Container
2243 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
2244 if (!Container ||
2245 (!isa<ObjCImplementationDecl>(Container) &&
2246 !isa<ObjCCategoryImplDecl>(Container)))
2247 return;
2248
2249 // Ignore any properties that have already been implemented.
2250 for (DeclContext::decl_iterator D = Container->decls_begin(),
2251 DEnd = Container->decls_end();
2252 D != DEnd; ++D)
2253 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
2254 Results.Ignore(PropertyImpl->getPropertyDecl());
2255
2256 // Add any properties that we find.
2257 Results.EnterNewScope();
2258 if (ObjCImplementationDecl *ClassImpl
2259 = dyn_cast<ObjCImplementationDecl>(Container))
2260 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
2261 Results);
2262 else
2263 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
2264 false, CurContext, Results);
2265 Results.ExitScope();
2266
2267 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2268}
2269
2270void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
2271 IdentifierInfo *PropertyName,
2272 DeclPtrTy ObjCImpDecl) {
2273 typedef CodeCompleteConsumer::Result Result;
2274 ResultBuilder Results(*this);
2275
2276 // Figure out where this @synthesize lives.
2277 ObjCContainerDecl *Container
2278 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
2279 if (!Container ||
2280 (!isa<ObjCImplementationDecl>(Container) &&
2281 !isa<ObjCCategoryImplDecl>(Container)))
2282 return;
2283
2284 // Figure out which interface we're looking into.
2285 ObjCInterfaceDecl *Class = 0;
2286 if (ObjCImplementationDecl *ClassImpl
2287 = dyn_cast<ObjCImplementationDecl>(Container))
2288 Class = ClassImpl->getClassInterface();
2289 else
2290 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
2291 ->getClassInterface();
2292
2293 // Add all of the instance variables in this class and its superclasses.
2294 Results.EnterNewScope();
2295 for(; Class; Class = Class->getSuperClass()) {
2296 // FIXME: We could screen the type of each ivar for compatibility with
2297 // the property, but is that being too paternal?
2298 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
2299 IVarEnd = Class->ivar_end();
2300 IVar != IVarEnd; ++IVar)
2301 Results.MaybeAddResult(Result(*IVar, 0), CurContext);
2302 }
2303 Results.ExitScope();
2304
2305 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2306}