blob: b386adb9df5788e1b64b1ccfbfe847f79591817d [file] [log] [blame]
Douglas Gregor81b747b2009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
13#include "Sema.h"
14#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000015#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000016#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000017#include "clang/Lex/MacroInfo.h"
18#include "clang/Lex/Preprocessor.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000019#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000020#include "llvm/ADT/StringExtras.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000021#include <list>
22#include <map>
23#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000024
25using namespace clang;
26
Douglas Gregor86d9a522009-09-21 16:56:56 +000027namespace {
28 /// \brief A container of code-completion results.
29 class ResultBuilder {
30 public:
31 /// \brief The type of a name-lookup filter, which can be provided to the
32 /// name-lookup routines to specify which declarations should be included in
33 /// the result set (when it returns true) and which declarations should be
34 /// filtered out (returns false).
35 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
36
37 typedef CodeCompleteConsumer::Result Result;
38
39 private:
40 /// \brief The actual results we have found.
41 std::vector<Result> Results;
42
43 /// \brief A record of all of the declarations we have found and placed
44 /// into the result set, used to ensure that no declaration ever gets into
45 /// the result set twice.
46 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
47
48 /// \brief A mapping from declaration names to the declarations that have
49 /// this name within a particular scope and their index within the list of
50 /// results.
51 typedef std::multimap<DeclarationName,
52 std::pair<NamedDecl *, unsigned> > ShadowMap;
53
54 /// \brief The semantic analysis object for which results are being
55 /// produced.
56 Sema &SemaRef;
57
58 /// \brief If non-NULL, a filter function used to remove any code-completion
59 /// results that are not desirable.
60 LookupFilter Filter;
61
62 /// \brief A list of shadow maps, which is used to model name hiding at
63 /// different levels of, e.g., the inheritance hierarchy.
64 std::list<ShadowMap> ShadowMaps;
65
66 public:
67 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
68 : SemaRef(SemaRef), Filter(Filter) { }
69
70 /// \brief Set the filter used for code-completion results.
71 void setFilter(LookupFilter Filter) {
72 this->Filter = Filter;
73 }
74
75 typedef std::vector<Result>::iterator iterator;
76 iterator begin() { return Results.begin(); }
77 iterator end() { return Results.end(); }
78
79 Result *data() { return Results.empty()? 0 : &Results.front(); }
80 unsigned size() const { return Results.size(); }
81 bool empty() const { return Results.empty(); }
82
83 /// \brief Add a new result to this result set (if it isn't already in one
84 /// of the shadow maps), or replace an existing result (for, e.g., a
85 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +000086 ///
87 /// \param R the result to add (if it is unique).
88 ///
89 /// \param R the context in which this result will be named.
90 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +000091
92 /// \brief Enter into a new scope.
93 void EnterNewScope();
94
95 /// \brief Exit from the current scope.
96 void ExitScope();
97
Douglas Gregor55385fe2009-11-18 04:19:12 +000098 /// \brief Ignore this declaration, if it is seen again.
99 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
100
Douglas Gregor86d9a522009-09-21 16:56:56 +0000101 /// \name Name lookup predicates
102 ///
103 /// These predicates can be passed to the name lookup functions to filter the
104 /// results of name lookup. All of the predicates have the same type, so that
105 ///
106 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000107 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000108 bool IsNestedNameSpecifier(NamedDecl *ND) const;
109 bool IsEnum(NamedDecl *ND) const;
110 bool IsClassOrStruct(NamedDecl *ND) const;
111 bool IsUnion(NamedDecl *ND) const;
112 bool IsNamespace(NamedDecl *ND) const;
113 bool IsNamespaceOrAlias(NamedDecl *ND) const;
114 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000115 bool IsMember(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000116 //@}
117 };
118}
119
120/// \brief Determines whether the given hidden result could be found with
121/// some extra work, e.g., by qualifying the name.
122///
123/// \param Hidden the declaration that is hidden by the currenly \p Visible
124/// declaration.
125///
126/// \param Visible the declaration with the same name that is already visible.
127///
128/// \returns true if the hidden result can be found by some mechanism,
129/// false otherwise.
130static bool canHiddenResultBeFound(const LangOptions &LangOpts,
131 NamedDecl *Hidden, NamedDecl *Visible) {
132 // In C, there is no way to refer to a hidden name.
133 if (!LangOpts.CPlusPlus)
134 return false;
135
136 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
137
138 // There is no way to qualify a name declared in a function or method.
139 if (HiddenCtx->isFunctionOrMethod())
140 return false;
141
Douglas Gregor86d9a522009-09-21 16:56:56 +0000142 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
143}
144
Douglas Gregor456c4a12009-09-21 20:12:40 +0000145/// \brief Compute the qualification required to get from the current context
146/// (\p CurContext) to the target context (\p TargetContext).
147///
148/// \param Context the AST context in which the qualification will be used.
149///
150/// \param CurContext the context where an entity is being named, which is
151/// typically based on the current scope.
152///
153/// \param TargetContext the context in which the named entity actually
154/// resides.
155///
156/// \returns a nested name specifier that refers into the target context, or
157/// NULL if no qualification is needed.
158static NestedNameSpecifier *
159getRequiredQualification(ASTContext &Context,
160 DeclContext *CurContext,
161 DeclContext *TargetContext) {
162 llvm::SmallVector<DeclContext *, 4> TargetParents;
163
164 for (DeclContext *CommonAncestor = TargetContext;
165 CommonAncestor && !CommonAncestor->Encloses(CurContext);
166 CommonAncestor = CommonAncestor->getLookupParent()) {
167 if (CommonAncestor->isTransparentContext() ||
168 CommonAncestor->isFunctionOrMethod())
169 continue;
170
171 TargetParents.push_back(CommonAncestor);
172 }
173
174 NestedNameSpecifier *Result = 0;
175 while (!TargetParents.empty()) {
176 DeclContext *Parent = TargetParents.back();
177 TargetParents.pop_back();
178
179 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
180 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
181 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
182 Result = NestedNameSpecifier::Create(Context, Result,
183 false,
184 Context.getTypeDeclType(TD).getTypePtr());
185 else
186 assert(Parent->isTranslationUnit());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000187 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000188 return Result;
189}
190
191void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
Douglas Gregor8e0a0e42009-09-22 23:31:26 +0000192 assert(!ShadowMaps.empty() && "Must enter into a results scope");
193
Douglas Gregor86d9a522009-09-21 16:56:56 +0000194 if (R.Kind != Result::RK_Declaration) {
195 // For non-declaration results, just add the result.
196 Results.push_back(R);
197 return;
198 }
Douglas Gregorf52cede2009-10-09 22:16:47 +0000199
200 // Skip unnamed entities.
201 if (!R.Declaration->getDeclName())
202 return;
203
Douglas Gregor86d9a522009-09-21 16:56:56 +0000204 // Look through using declarations.
John McCall9488ea12009-11-17 05:59:44 +0000205 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration))
Douglas Gregor0563c262009-09-22 23:15:58 +0000206 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
207 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000208
Douglas Gregor86d9a522009-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 Gregorf52cede2009-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 Dunbare013d682009-10-18 20:26:12 +0000225 //
226 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000227 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000228 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000229 if (Name[0] == '_' &&
230 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
231 return;
232 }
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000287 R.QualifierIsInformative = false;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000288
289 if (!R.Qualifier)
290 R.Qualifier = getRequiredQualification(SemaRef.Context,
291 CurContext,
292 R.Declaration->getDeclContext());
Douglas Gregor86d9a522009-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 Gregoreb5758b2009-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 Gregor0563c262009-09-22 23:15:58 +0000315 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000316 if (R.QualifierIsInformative && !R.Qualifier &&
317 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-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 Gregoreb5758b2009-09-23 22:26:46 +0000327
Douglas Gregor86d9a522009-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 Gregor791215b2009-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 Gregor86d9a522009-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 Gregoreb5758b2009-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 Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000434/// \param Rank the rank given to results in this declaration context.
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000442/// \param InBaseClass whether we are in a base class.
443///
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000447 unsigned Rank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000448 DeclContext *CurContext,
449 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor0563c262009-09-22 23:15:58 +0000450 ResultBuilder &Results,
451 bool InBaseClass = false) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000452 // Make sure we don't visit the same context twice.
453 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor0563c262009-09-22 23:15:58 +0000454 return Rank;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000455
456 // Enumerate all of the results in this context.
Douglas Gregor0563c262009-09-22 23:15:58 +0000457 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor86d9a522009-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 Gregorff4393c2009-11-09 21:35:27 +0000462 DEnd = CurCtx->decls_end();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000463 D != DEnd; ++D) {
464 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor0563c262009-09-22 23:15:58 +0000465 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregorff4393c2009-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 Gregor86d9a522009-09-21 16:56:56 +0000473 }
474 }
475
476 // Traverse the contexts of inherited classes.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000477 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
478 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
Douglas Gregorff4393c2009-11-09 21:35:27 +0000479 BEnd = Record->bases_end();
Douglas Gregor86d9a522009-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 Gregor0563c262009-09-22 23:15:58 +0000511 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
512 Results, /*InBaseClass=*/true);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000513 }
514 }
515
516 // FIXME: Look into base classes in Objective-C!
517
518 Results.ExitScope();
Douglas Gregor0563c262009-09-22 23:15:58 +0000519 return Rank + 1;
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000538 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000539 ResultBuilder &Results) {
540 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000541 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
542 Results);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000553/// \param CurContext the context from which lookup results will be found.
554///
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000559 DeclContext *CurContext,
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000581 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
582 Results);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000596 CurContext, Results);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000602 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
603 CurContext);
Douglas Gregor86d9a522009-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 Gregor456c4a12009-09-21 20:12:40 +0000611 CurContext, Results);
Douglas Gregor86d9a522009-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 Gregor0c8296d2009-11-07 00:00:49 +0000669 typedef CodeCompletionString::Chunk Chunk;
670
Douglas Gregor86d9a522009-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 Gregor0c8296d2009-11-07 00:00:49 +0000685 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-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 Kramer660cc182009-11-29 20:18:50 +0000696 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000697 }
Douglas Gregorb3d45252009-09-22 21:42:17 +0000698
699 if (const FunctionProtoType *Proto
700 = Function->getType()->getAs<FunctionProtoType>())
701 if (Proto->isVariadic())
702 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-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 Gregor0c8296d2009-11-07 00:00:49 +0000710 typedef CodeCompletionString::Chunk Chunk;
711
Douglas Gregor86d9a522009-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 Gregor0c8296d2009-11-07 00:00:49 +0000767 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000768
769 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +0000770 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000771 }
772}
773
Douglas Gregorb9d0ef72009-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 Gregor0563c262009-09-22 23:15:58 +0000778 bool QualifierIsInformative,
Douglas Gregorb9d0ef72009-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 Gregor0563c262009-09-22 23:15:58 +0000788 if (QualifierIsInformative)
Benjamin Kramer660cc182009-11-29 20:18:50 +0000789 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor0563c262009-09-22 23:15:58 +0000790 else
Benjamin Kramer660cc182009-11-29 20:18:50 +0000791 Result->AddTextChunk(PrintedNNS);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000792}
793
Douglas Gregor86d9a522009-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 Gregor0c8296d2009-11-07 00:00:49 +0000802 typedef CodeCompletionString::Chunk Chunk;
803
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000804 if (Kind == RK_Pattern)
805 return Pattern->Clone();
806
807 CodeCompletionString *Result = new CodeCompletionString;
808
809 if (Kind == RK_Keyword) {
810 Result->AddTypedTextChunk(Keyword);
811 return Result;
812 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000813
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000814 if (Kind == RK_Macro) {
815 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000816 assert(MI && "Not a macro?");
817
818 Result->AddTypedTextChunk(Macro->getName());
819
820 if (!MI->isFunctionLike())
821 return Result;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000822
823 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000824 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000825 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
826 A != AEnd; ++A) {
827 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000828 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000829
830 if (!MI->isVariadic() || A != AEnd - 1) {
831 // Non-variadic argument.
Benjamin Kramer660cc182009-11-29 20:18:50 +0000832 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000833 continue;
834 }
835
836 // Variadic argument; cope with the different between GNU and C99
837 // variadic macros, providing a single placeholder for the rest of the
838 // arguments.
839 if ((*A)->isStr("__VA_ARGS__"))
840 Result->AddPlaceholderChunk("...");
841 else {
842 std::string Arg = (*A)->getName();
843 Arg += "...";
Benjamin Kramer660cc182009-11-29 20:18:50 +0000844 Result->AddPlaceholderChunk(Arg);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000845 }
846 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000847 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000848 return Result;
849 }
850
851 assert(Kind == RK_Declaration && "Missed a macro kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000852 NamedDecl *ND = Declaration;
853
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000854 if (StartsNestedNameSpecifier) {
Benjamin Kramer660cc182009-11-29 20:18:50 +0000855 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000856 Result->AddTextChunk("::");
857 return Result;
858 }
859
Douglas Gregor86d9a522009-09-21 16:56:56 +0000860 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000861 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
862 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +0000863 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000864 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000865 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000866 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000867 return Result;
868 }
869
870 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000871 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
872 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000873 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramer660cc182009-11-29 20:18:50 +0000874 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000875
876 // Figure out which template parameters are deduced (or have default
877 // arguments).
878 llvm::SmallVector<bool, 16> Deduced;
879 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
880 unsigned LastDeducibleArgument;
881 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
882 --LastDeducibleArgument) {
883 if (!Deduced[LastDeducibleArgument - 1]) {
884 // C++0x: Figure out if the template argument has a default. If so,
885 // the user doesn't need to type this argument.
886 // FIXME: We need to abstract template parameters better!
887 bool HasDefaultArg = false;
888 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
889 LastDeducibleArgument - 1);
890 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
891 HasDefaultArg = TTP->hasDefaultArgument();
892 else if (NonTypeTemplateParmDecl *NTTP
893 = dyn_cast<NonTypeTemplateParmDecl>(Param))
894 HasDefaultArg = NTTP->hasDefaultArgument();
895 else {
896 assert(isa<TemplateTemplateParmDecl>(Param));
897 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000898 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000899 }
900
901 if (!HasDefaultArg)
902 break;
903 }
904 }
905
906 if (LastDeducibleArgument) {
907 // Some of the function template arguments cannot be deduced from a
908 // function call, so we introduce an explicit template argument list
909 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000910 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000911 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
912 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000913 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000914 }
915
916 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000917 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000918 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000919 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000920 return Result;
921 }
922
923 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000924 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
925 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +0000926 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000927 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000928 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000929 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000930 return Result;
931 }
932
Douglas Gregor9630eb62009-11-17 16:44:22 +0000933 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +0000934 Selector Sel = Method->getSelector();
935 if (Sel.isUnarySelector()) {
936 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
937 return Result;
938 }
939
Douglas Gregord3c68542009-11-19 01:08:35 +0000940 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
941 SelName += ':';
942 if (StartParameter == 0)
943 Result->AddTypedTextChunk(SelName);
944 else {
945 Result->AddInformativeChunk(SelName);
946
947 // If there is only one parameter, and we're past it, add an empty
948 // typed-text chunk since there is nothing to type.
949 if (Method->param_size() == 1)
950 Result->AddTypedTextChunk("");
951 }
Douglas Gregor9630eb62009-11-17 16:44:22 +0000952 unsigned Idx = 0;
953 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
954 PEnd = Method->param_end();
955 P != PEnd; (void)++P, ++Idx) {
956 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +0000957 std::string Keyword;
958 if (Idx > StartParameter)
959 Keyword = " ";
Douglas Gregor9630eb62009-11-17 16:44:22 +0000960 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
961 Keyword += II->getName().str();
962 Keyword += ":";
Douglas Gregor4ad96852009-11-19 07:41:15 +0000963 if (Idx < StartParameter || AllParametersAreInformative) {
Douglas Gregord3c68542009-11-19 01:08:35 +0000964 Result->AddInformativeChunk(Keyword);
965 } else if (Idx == StartParameter)
966 Result->AddTypedTextChunk(Keyword);
967 else
968 Result->AddTextChunk(Keyword);
Douglas Gregor9630eb62009-11-17 16:44:22 +0000969 }
Douglas Gregord3c68542009-11-19 01:08:35 +0000970
971 // If we're before the starting parameter, skip the placeholder.
972 if (Idx < StartParameter)
973 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +0000974
975 std::string Arg;
976 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
977 Arg = "(" + Arg + ")";
978 if (IdentifierInfo *II = (*P)->getIdentifier())
979 Arg += II->getName().str();
Douglas Gregor4ad96852009-11-19 07:41:15 +0000980 if (AllParametersAreInformative)
981 Result->AddInformativeChunk(Arg);
982 else
983 Result->AddPlaceholderChunk(Arg);
Douglas Gregor9630eb62009-11-17 16:44:22 +0000984 }
985
986 return Result;
987 }
988
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000989 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +0000990 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
991 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000992
993 Result->AddTypedTextChunk(ND->getNameAsString());
994 return Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000995}
996
Douglas Gregor86d802e2009-09-23 00:34:09 +0000997CodeCompletionString *
998CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
999 unsigned CurrentArg,
1000 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001001 typedef CodeCompletionString::Chunk Chunk;
1002
Douglas Gregor86d802e2009-09-23 00:34:09 +00001003 CodeCompletionString *Result = new CodeCompletionString;
1004 FunctionDecl *FDecl = getFunction();
1005 const FunctionProtoType *Proto
1006 = dyn_cast<FunctionProtoType>(getFunctionType());
1007 if (!FDecl && !Proto) {
1008 // Function without a prototype. Just give the return type and a
1009 // highlighted ellipsis.
1010 const FunctionType *FT = getFunctionType();
1011 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00001012 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001013 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1014 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1015 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001016 return Result;
1017 }
1018
1019 if (FDecl)
Benjamin Kramer660cc182009-11-29 20:18:50 +00001020 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregor86d802e2009-09-23 00:34:09 +00001021 else
1022 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00001023 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001024
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001025 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001026 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
1027 for (unsigned I = 0; I != NumParams; ++I) {
1028 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001029 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001030
1031 std::string ArgString;
1032 QualType ArgType;
1033
1034 if (FDecl) {
1035 ArgString = FDecl->getParamDecl(I)->getNameAsString();
1036 ArgType = FDecl->getParamDecl(I)->getOriginalType();
1037 } else {
1038 ArgType = Proto->getArgType(I);
1039 }
1040
1041 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
1042
1043 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001044 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramer660cc182009-11-29 20:18:50 +00001045 ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001046 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00001047 Result->AddTextChunk(ArgString);
Douglas Gregor86d802e2009-09-23 00:34:09 +00001048 }
1049
1050 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001051 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001052 if (CurrentArg < NumParams)
1053 Result->AddTextChunk("...");
1054 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001055 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001056 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001057 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001058
1059 return Result;
1060}
1061
Douglas Gregor86d9a522009-09-21 16:56:56 +00001062namespace {
1063 struct SortCodeCompleteResult {
1064 typedef CodeCompleteConsumer::Result Result;
1065
Douglas Gregor6a684032009-09-28 03:51:44 +00001066 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregor36ecb042009-11-17 23:22:23 +00001067 if (!X.getObjCSelector().isNull() && !Y.getObjCSelector().isNull()) {
1068 // Consider all selector kinds to be equivalent.
1069 } else if (X.getNameKind() != Y.getNameKind())
Douglas Gregor6a684032009-09-28 03:51:44 +00001070 return X.getNameKind() < Y.getNameKind();
1071
1072 return llvm::LowercaseString(X.getAsString())
1073 < llvm::LowercaseString(Y.getAsString());
1074 }
1075
Douglas Gregor86d9a522009-09-21 16:56:56 +00001076 bool operator()(const Result &X, const Result &Y) const {
1077 // Sort first by rank.
1078 if (X.Rank < Y.Rank)
1079 return true;
1080 else if (X.Rank > Y.Rank)
1081 return false;
1082
Douglas Gregor54f01612009-11-19 00:01:57 +00001083 // We use a special ordering for keywords and patterns, based on the
1084 // typed text.
1085 if ((X.Kind == Result::RK_Keyword || X.Kind == Result::RK_Pattern) &&
1086 (Y.Kind == Result::RK_Keyword || Y.Kind == Result::RK_Pattern)) {
1087 const char *XStr = (X.Kind == Result::RK_Keyword)? X.Keyword
1088 : X.Pattern->getTypedText();
1089 const char *YStr = (Y.Kind == Result::RK_Keyword)? Y.Keyword
1090 : Y.Pattern->getTypedText();
1091 return strcmp(XStr, YStr) < 0;
1092 }
1093
Douglas Gregor86d9a522009-09-21 16:56:56 +00001094 // Result kinds are ordered by decreasing importance.
1095 if (X.Kind < Y.Kind)
1096 return true;
1097 else if (X.Kind > Y.Kind)
1098 return false;
1099
1100 // Non-hidden names precede hidden names.
1101 if (X.Hidden != Y.Hidden)
1102 return !X.Hidden;
1103
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001104 // Non-nested-name-specifiers precede nested-name-specifiers.
1105 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1106 return !X.StartsNestedNameSpecifier;
1107
Douglas Gregor86d9a522009-09-21 16:56:56 +00001108 // Ordering depends on the kind of result.
1109 switch (X.Kind) {
1110 case Result::RK_Declaration:
1111 // Order based on the declaration names.
Douglas Gregor6a684032009-09-28 03:51:44 +00001112 return isEarlierDeclarationName(X.Declaration->getDeclName(),
1113 Y.Declaration->getDeclName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001114
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001115 case Result::RK_Macro:
1116 return llvm::LowercaseString(X.Macro->getName()) <
1117 llvm::LowercaseString(Y.Macro->getName());
Douglas Gregor54f01612009-11-19 00:01:57 +00001118
1119 case Result::RK_Keyword:
1120 case Result::RK_Pattern:
1121 llvm::llvm_unreachable("Result kinds handled above");
1122 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001123 }
1124
1125 // Silence GCC warning.
1126 return false;
1127 }
1128 };
1129}
1130
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001131static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1132 ResultBuilder &Results) {
1133 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001134 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1135 MEnd = PP.macro_end();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001136 M != MEnd; ++M)
1137 Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1138 Results.ExitScope();
1139}
1140
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001141static void HandleCodeCompleteResults(Sema *S,
1142 CodeCompleteConsumer *CodeCompleter,
1143 CodeCompleteConsumer::Result *Results,
1144 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00001145 // Sort the results by rank/kind/etc.
1146 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1147
1148 if (CodeCompleter)
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001149 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00001150
1151 for (unsigned I = 0; I != NumResults; ++I)
1152 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001153}
1154
Douglas Gregor791215b2009-09-21 20:51:25 +00001155void Sema::CodeCompleteOrdinaryName(Scope *S) {
1156 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001157 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1158 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001159 if (CodeCompleter->includeMacros())
1160 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001161 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00001162}
1163
Douglas Gregor95ac6552009-11-18 01:29:26 +00001164static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00001165 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00001166 DeclContext *CurContext,
1167 ResultBuilder &Results) {
1168 typedef CodeCompleteConsumer::Result Result;
1169
1170 // Add properties in this container.
1171 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
1172 PEnd = Container->prop_end();
1173 P != PEnd;
1174 ++P)
1175 Results.MaybeAddResult(Result(*P, 0), CurContext);
1176
1177 // Add properties in referenced protocols.
1178 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
1179 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
1180 PEnd = Protocol->protocol_end();
1181 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00001182 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001183 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00001184 if (AllowCategories) {
1185 // Look through categories.
1186 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
1187 Category; Category = Category->getNextClassCategory())
1188 AddObjCProperties(Category, AllowCategories, CurContext, Results);
1189 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00001190
1191 // Look through protocols.
1192 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
1193 E = IFace->protocol_end();
1194 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00001195 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001196
1197 // Look in the superclass.
1198 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00001199 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
1200 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001201 } else if (const ObjCCategoryDecl *Category
1202 = dyn_cast<ObjCCategoryDecl>(Container)) {
1203 // Look through protocols.
1204 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
1205 PEnd = Category->protocol_end();
1206 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00001207 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001208 }
1209}
1210
Douglas Gregor81b747b2009-09-17 21:32:03 +00001211void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1212 SourceLocation OpLoc,
1213 bool IsArrow) {
1214 if (!BaseE || !CodeCompleter)
1215 return;
1216
Douglas Gregor86d9a522009-09-21 16:56:56 +00001217 typedef CodeCompleteConsumer::Result Result;
1218
Douglas Gregor81b747b2009-09-17 21:32:03 +00001219 Expr *Base = static_cast<Expr *>(BaseE);
1220 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001221
1222 if (IsArrow) {
1223 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1224 BaseType = Ptr->getPointeeType();
1225 else if (BaseType->isObjCObjectPointerType())
1226 /*Do nothing*/ ;
1227 else
1228 return;
1229 }
1230
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001231 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001232 unsigned NextRank = 0;
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001233
Douglas Gregor95ac6552009-11-18 01:29:26 +00001234 Results.EnterNewScope();
1235 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
1236 // Access to a C/C++ class, struct, or union.
1237 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1238 Record->getDecl(), Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001239
Douglas Gregor95ac6552009-11-18 01:29:26 +00001240 if (getLangOptions().CPlusPlus) {
1241 if (!Results.empty()) {
1242 // The "template" keyword can follow "->" or "." in the grammar.
1243 // However, we only want to suggest the template keyword if something
1244 // is dependent.
1245 bool IsDependent = BaseType->isDependentType();
1246 if (!IsDependent) {
1247 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1248 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1249 IsDependent = Ctx->isDependentContext();
1250 break;
1251 }
1252 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001253
Douglas Gregor95ac6552009-11-18 01:29:26 +00001254 if (IsDependent)
1255 Results.MaybeAddResult(Result("template", NextRank++));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001256 }
1257
Douglas Gregor95ac6552009-11-18 01:29:26 +00001258 // We could have the start of a nested-name-specifier. Add those
1259 // results as well.
1260 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1261 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
1262 CurContext, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001263 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00001264 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
1265 // Objective-C property reference.
1266
1267 // Add property results based on our interface.
1268 const ObjCObjectPointerType *ObjCPtr
1269 = BaseType->getAsObjCInterfacePointerType();
1270 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00001271 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001272
1273 // Add properties from the protocols in a qualified interface.
1274 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
1275 E = ObjCPtr->qual_end();
1276 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00001277 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001278
1279 // FIXME: We could (should?) also look for "implicit" properties, identified
1280 // only by the presence of nullary and unary selectors.
1281 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
1282 (!IsArrow && BaseType->isObjCInterfaceType())) {
1283 // Objective-C instance variable access.
1284 ObjCInterfaceDecl *Class = 0;
1285 if (const ObjCObjectPointerType *ObjCPtr
1286 = BaseType->getAs<ObjCObjectPointerType>())
1287 Class = ObjCPtr->getInterfaceDecl();
1288 else
1289 Class = BaseType->getAs<ObjCInterfaceType>()->getDecl();
1290
1291 // Add all ivars from this class and its superclasses.
1292 for (; Class; Class = Class->getSuperClass()) {
1293 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
1294 IVarEnd = Class->ivar_end();
1295 IVar != IVarEnd; ++IVar)
1296 Results.MaybeAddResult(Result(*IVar, 0), CurContext);
1297 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001298 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00001299
1300 // FIXME: How do we cope with isa?
1301
1302 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001303
1304 // Add macros
1305 if (CodeCompleter->includeMacros())
1306 AddMacroResults(PP, NextRank, Results);
1307
1308 // Hand off the results found for code completion.
1309 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001310}
1311
Douglas Gregor374929f2009-09-18 15:37:17 +00001312void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1313 if (!CodeCompleter)
1314 return;
1315
Douglas Gregor86d9a522009-09-21 16:56:56 +00001316 typedef CodeCompleteConsumer::Result Result;
1317 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +00001318 switch ((DeclSpec::TST)TagSpec) {
1319 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001320 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +00001321 break;
1322
1323 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001324 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +00001325 break;
1326
1327 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00001328 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001329 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00001330 break;
1331
1332 default:
1333 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1334 return;
1335 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001336
1337 ResultBuilder Results(*this, Filter);
1338 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001339 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001340
1341 if (getLangOptions().CPlusPlus) {
1342 // We could have the start of a nested-name-specifier. Add those
1343 // results as well.
1344 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001345 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1346 NextRank, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001347 }
1348
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001349 if (CodeCompleter->includeMacros())
1350 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001351 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00001352}
1353
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001354void Sema::CodeCompleteCase(Scope *S) {
1355 if (getSwitchStack().empty() || !CodeCompleter)
1356 return;
1357
1358 SwitchStmt *Switch = getSwitchStack().back();
1359 if (!Switch->getCond()->getType()->isEnumeralType())
1360 return;
1361
1362 // Code-complete the cases of a switch statement over an enumeration type
1363 // by providing the list of
1364 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1365
1366 // Determine which enumerators we have already seen in the switch statement.
1367 // FIXME: Ideally, we would also be able to look *past* the code-completion
1368 // token, in case we are code-completing in the middle of the switch and not
1369 // at the end. However, we aren't able to do so at the moment.
1370 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001371 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001372 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1373 SC = SC->getNextSwitchCase()) {
1374 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1375 if (!Case)
1376 continue;
1377
1378 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1379 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1380 if (EnumConstantDecl *Enumerator
1381 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1382 // We look into the AST of the case statement to determine which
1383 // enumerator was named. Alternatively, we could compute the value of
1384 // the integral constant expression, then compare it against the
1385 // values of each enumerator. However, value-based approach would not
1386 // work as well with C++ templates where enumerators declared within a
1387 // template are type- and value-dependent.
1388 EnumeratorsSeen.insert(Enumerator);
1389
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001390 // If this is a qualified-id, keep track of the nested-name-specifier
1391 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001392 //
1393 // switch (TagD.getKind()) {
1394 // case TagDecl::TK_enum:
1395 // break;
1396 // case XXX
1397 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001398 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001399 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1400 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00001401 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001402 }
1403 }
1404
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001405 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1406 // If there are no prior enumerators in C++, check whether we have to
1407 // qualify the names of the enumerators that we suggest, because they
1408 // may not be visible in this scope.
1409 Qualifier = getRequiredQualification(Context, CurContext,
1410 Enum->getDeclContext());
1411
1412 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1413 }
1414
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001415 // Add any enumerators that have not yet been mentioned.
1416 ResultBuilder Results(*this);
1417 Results.EnterNewScope();
1418 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1419 EEnd = Enum->enumerator_end();
1420 E != EEnd; ++E) {
1421 if (EnumeratorsSeen.count(*E))
1422 continue;
1423
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001424 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001425 }
1426 Results.ExitScope();
1427
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001428 if (CodeCompleter->includeMacros())
1429 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001430 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001431}
1432
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001433namespace {
1434 struct IsBetterOverloadCandidate {
1435 Sema &S;
1436
1437 public:
1438 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1439
1440 bool
1441 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1442 return S.isBetterOverloadCandidate(X, Y);
1443 }
1444 };
1445}
1446
1447void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1448 ExprTy **ArgsIn, unsigned NumArgs) {
1449 if (!CodeCompleter)
1450 return;
1451
1452 Expr *Fn = (Expr *)FnIn;
1453 Expr **Args = (Expr **)ArgsIn;
1454
1455 // Ignore type-dependent call expressions entirely.
1456 if (Fn->isTypeDependent() ||
1457 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1458 return;
1459
John McCallba135432009-11-21 08:51:07 +00001460 llvm::SmallVector<NamedDecl*,8> Fns;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001461 DeclarationName UnqualifiedName;
1462 NestedNameSpecifier *Qualifier;
1463 SourceRange QualifierRange;
1464 bool ArgumentDependentLookup;
John McCall7453ed42009-11-22 00:44:51 +00001465 bool Overloaded;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001466 bool HasExplicitTemplateArgs;
John McCalld5532b62009-11-23 01:53:49 +00001467 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001468
John McCallba135432009-11-21 08:51:07 +00001469 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall7453ed42009-11-22 00:44:51 +00001470 ArgumentDependentLookup, Overloaded,
John McCalld5532b62009-11-23 01:53:49 +00001471 HasExplicitTemplateArgs, ExplicitTemplateArgs);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001472
1473
1474 // FIXME: What if we're calling something that isn't a function declaration?
1475 // FIXME: What if we're calling a pseudo-destructor?
1476 // FIXME: What if we're calling a member function?
1477
1478 // Build an overload candidate set based on the functions we find.
1479 OverloadCandidateSet CandidateSet;
John McCallba135432009-11-21 08:51:07 +00001480 AddOverloadedCallCandidates(Fns, UnqualifiedName,
John McCalld5532b62009-11-23 01:53:49 +00001481 ArgumentDependentLookup,
1482 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001483 Args, NumArgs,
1484 CandidateSet,
1485 /*PartialOverloading=*/true);
1486
1487 // Sort the overload candidate set by placing the best overloads first.
1488 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1489 IsBetterOverloadCandidate(*this));
1490
1491 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05944382009-09-23 00:16:58 +00001492 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1493 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlsson90756302009-09-22 17:29:51 +00001494
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001495 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1496 CandEnd = CandidateSet.end();
1497 Cand != CandEnd; ++Cand) {
1498 if (Cand->Viable)
Douglas Gregor05944382009-09-23 00:16:58 +00001499 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001500 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001501 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
Douglas Gregor05944382009-09-23 00:16:58 +00001502 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001503}
1504
Douglas Gregor81b747b2009-09-17 21:32:03 +00001505void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1506 bool EnteringContext) {
1507 if (!SS.getScopeRep() || !CodeCompleter)
1508 return;
1509
Douglas Gregor86d9a522009-09-21 16:56:56 +00001510 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1511 if (!Ctx)
1512 return;
1513
1514 ResultBuilder Results(*this);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001515 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001516
1517 // The "template" keyword can follow "::" in the grammar, but only
1518 // put it into the grammar if the nested-name-specifier is dependent.
1519 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1520 if (!Results.empty() && NNS->isDependent())
1521 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1522
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001523 if (CodeCompleter->includeMacros())
1524 AddMacroResults(PP, NextRank + 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001525 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001526}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001527
1528void Sema::CodeCompleteUsing(Scope *S) {
1529 if (!CodeCompleter)
1530 return;
1531
Douglas Gregor86d9a522009-09-21 16:56:56 +00001532 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001533 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001534
1535 // If we aren't in class scope, we could see the "namespace" keyword.
1536 if (!S->isClassScope())
1537 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1538
1539 // After "using", we can see anything that would start a
1540 // nested-name-specifier.
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001541 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1542 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001543 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001544
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001545 if (CodeCompleter->includeMacros())
1546 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001547 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001548}
1549
1550void Sema::CodeCompleteUsingDirective(Scope *S) {
1551 if (!CodeCompleter)
1552 return;
1553
Douglas Gregor86d9a522009-09-21 16:56:56 +00001554 // After "using namespace", we expect to see a namespace name or namespace
1555 // alias.
1556 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001557 Results.EnterNewScope();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001558 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1559 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001560 Results.ExitScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001561 if (CodeCompleter->includeMacros())
1562 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001563 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001564}
1565
1566void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1567 if (!CodeCompleter)
1568 return;
1569
Douglas Gregor86d9a522009-09-21 16:56:56 +00001570 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1571 DeclContext *Ctx = (DeclContext *)S->getEntity();
1572 if (!S->getParent())
1573 Ctx = Context.getTranslationUnitDecl();
1574
1575 if (Ctx && Ctx->isFileContext()) {
1576 // We only want to see those namespaces that have already been defined
1577 // within this scope, because its likely that the user is creating an
1578 // extended namespace declaration. Keep track of the most recent
1579 // definition of each namespace.
1580 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1581 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1582 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1583 NS != NSEnd; ++NS)
1584 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1585
1586 // Add the most recent definition (or extended definition) of each
1587 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001588 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001589 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1590 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1591 NS != NSEnd; ++NS)
Douglas Gregor456c4a12009-09-21 20:12:40 +00001592 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1593 CurContext);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001594 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001595 }
1596
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001597 if (CodeCompleter->includeMacros())
1598 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001599 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001600}
1601
1602void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1603 if (!CodeCompleter)
1604 return;
1605
Douglas Gregor86d9a522009-09-21 16:56:56 +00001606 // After "namespace", we expect to see a namespace or alias.
1607 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001608 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1609 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001610 if (CodeCompleter->includeMacros())
1611 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001612 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001613}
1614
Douglas Gregored8d3222009-09-18 20:05:18 +00001615void Sema::CodeCompleteOperatorName(Scope *S) {
1616 if (!CodeCompleter)
1617 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001618
1619 typedef CodeCompleteConsumer::Result Result;
1620 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001621 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00001622
Douglas Gregor86d9a522009-09-21 16:56:56 +00001623 // Add the names of overloadable operators.
1624#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1625 if (std::strcmp(Spelling, "?")) \
1626 Results.MaybeAddResult(Result(Spelling, 0));
1627#include "clang/Basic/OperatorKinds.def"
1628
1629 // Add any type names visible from the current scope
1630 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001631 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001632
1633 // Add any type specifiers
1634 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1635
1636 // Add any nested-name-specifiers
1637 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001638 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1639 NextRank + 1, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001640 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001641
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001642 if (CodeCompleter->includeMacros())
1643 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001644 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00001645}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001646
Douglas Gregor988358f2009-11-19 00:14:45 +00001647/// \brief Determine whether the addition of the given flag to an Objective-C
1648/// property's attributes will cause a conflict.
1649static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
1650 // Check if we've already added this flag.
1651 if (Attributes & NewFlag)
1652 return true;
1653
1654 Attributes |= NewFlag;
1655
1656 // Check for collisions with "readonly".
1657 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1658 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
1659 ObjCDeclSpec::DQ_PR_assign |
1660 ObjCDeclSpec::DQ_PR_copy |
1661 ObjCDeclSpec::DQ_PR_retain)))
1662 return true;
1663
1664 // Check for more than one of { assign, copy, retain }.
1665 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
1666 ObjCDeclSpec::DQ_PR_copy |
1667 ObjCDeclSpec::DQ_PR_retain);
1668 if (AssignCopyRetMask &&
1669 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
1670 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
1671 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
1672 return true;
1673
1674 return false;
1675}
1676
Douglas Gregora93b1082009-11-18 23:08:07 +00001677void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00001678 if (!CodeCompleter)
1679 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00001680
Steve Naroffece8e712009-10-08 21:55:05 +00001681 unsigned Attributes = ODS.getPropertyAttributes();
1682
1683 typedef CodeCompleteConsumer::Result Result;
1684 ResultBuilder Results(*this);
1685 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00001686 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
Steve Naroffece8e712009-10-08 21:55:05 +00001687 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001688 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
Steve Naroffece8e712009-10-08 21:55:05 +00001689 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001690 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
Steve Naroffece8e712009-10-08 21:55:05 +00001691 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001692 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
Steve Naroffece8e712009-10-08 21:55:05 +00001693 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001694 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
Steve Naroffece8e712009-10-08 21:55:05 +00001695 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001696 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
Steve Naroffece8e712009-10-08 21:55:05 +00001697 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001698 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00001699 CodeCompletionString *Setter = new CodeCompletionString;
1700 Setter->AddTypedTextChunk("setter");
1701 Setter->AddTextChunk(" = ");
1702 Setter->AddPlaceholderChunk("method");
1703 Results.MaybeAddResult(CodeCompleteConsumer::Result(Setter, 0));
1704 }
Douglas Gregor988358f2009-11-19 00:14:45 +00001705 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00001706 CodeCompletionString *Getter = new CodeCompletionString;
1707 Getter->AddTypedTextChunk("getter");
1708 Getter->AddTextChunk(" = ");
1709 Getter->AddPlaceholderChunk("method");
1710 Results.MaybeAddResult(CodeCompleteConsumer::Result(Getter, 0));
1711 }
Steve Naroffece8e712009-10-08 21:55:05 +00001712 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001713 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00001714}
Steve Naroffc4df6d22009-11-07 02:08:14 +00001715
Douglas Gregor4ad96852009-11-19 07:41:15 +00001716/// \brief Descripts the kind of Objective-C method that we want to find
1717/// via code completion.
1718enum ObjCMethodKind {
1719 MK_Any, //< Any kind of method, provided it means other specified criteria.
1720 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
1721 MK_OneArgSelector //< One-argument selector.
1722};
1723
1724static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
1725 ObjCMethodKind WantKind,
1726 IdentifierInfo **SelIdents,
1727 unsigned NumSelIdents) {
1728 Selector Sel = Method->getSelector();
1729 if (NumSelIdents > Sel.getNumArgs())
1730 return false;
1731
1732 switch (WantKind) {
1733 case MK_Any: break;
1734 case MK_ZeroArgSelector: return Sel.isUnarySelector();
1735 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
1736 }
1737
1738 for (unsigned I = 0; I != NumSelIdents; ++I)
1739 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
1740 return false;
1741
1742 return true;
1743}
1744
Douglas Gregor36ecb042009-11-17 23:22:23 +00001745/// \brief Add all of the Objective-C methods in the given Objective-C
1746/// container to the set of results.
1747///
1748/// The container will be a class, protocol, category, or implementation of
1749/// any of the above. This mether will recurse to include methods from
1750/// the superclasses of classes along with their categories, protocols, and
1751/// implementations.
1752///
1753/// \param Container the container in which we'll look to find methods.
1754///
1755/// \param WantInstance whether to add instance methods (only); if false, this
1756/// routine will add factory methods (only).
1757///
1758/// \param CurContext the context in which we're performing the lookup that
1759/// finds methods.
1760///
1761/// \param Results the structure into which we'll add results.
1762static void AddObjCMethods(ObjCContainerDecl *Container,
1763 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00001764 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00001765 IdentifierInfo **SelIdents,
1766 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00001767 DeclContext *CurContext,
1768 ResultBuilder &Results) {
1769 typedef CodeCompleteConsumer::Result Result;
1770 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
1771 MEnd = Container->meth_end();
1772 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00001773 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
1774 // Check whether the selector identifiers we've been given are a
1775 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00001776 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00001777 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00001778
Douglas Gregord3c68542009-11-19 01:08:35 +00001779 Result R = Result(*M, 0);
1780 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00001781 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregord3c68542009-11-19 01:08:35 +00001782 Results.MaybeAddResult(R, CurContext);
1783 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00001784 }
1785
1786 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
1787 if (!IFace)
1788 return;
1789
1790 // Add methods in protocols.
1791 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
1792 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1793 E = Protocols.end();
1794 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00001795 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord3c68542009-11-19 01:08:35 +00001796 CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001797
1798 // Add methods in categories.
1799 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
1800 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00001801 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
1802 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001803
1804 // Add a categories protocol methods.
1805 const ObjCList<ObjCProtocolDecl> &Protocols
1806 = CatDecl->getReferencedProtocols();
1807 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1808 E = Protocols.end();
1809 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00001810 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
1811 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001812
1813 // Add methods in category implementations.
1814 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00001815 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
1816 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001817 }
1818
1819 // Add methods in superclass.
1820 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00001821 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
1822 SelIdents, NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001823
1824 // Add methods in our implementation, if any.
1825 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00001826 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
1827 NumSelIdents, CurContext, Results);
1828}
1829
1830
1831void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
1832 DeclPtrTy *Methods,
1833 unsigned NumMethods) {
1834 typedef CodeCompleteConsumer::Result Result;
1835
1836 // Try to find the interface where getters might live.
1837 ObjCInterfaceDecl *Class
1838 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
1839 if (!Class) {
1840 if (ObjCCategoryDecl *Category
1841 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
1842 Class = Category->getClassInterface();
1843
1844 if (!Class)
1845 return;
1846 }
1847
1848 // Find all of the potential getters.
1849 ResultBuilder Results(*this);
1850 Results.EnterNewScope();
1851
1852 // FIXME: We need to do this because Objective-C methods don't get
1853 // pushed into DeclContexts early enough. Argh!
1854 for (unsigned I = 0; I != NumMethods; ++I) {
1855 if (ObjCMethodDecl *Method
1856 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
1857 if (Method->isInstanceMethod() &&
1858 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
1859 Result R = Result(Method, 0);
1860 R.AllParametersAreInformative = true;
1861 Results.MaybeAddResult(R, CurContext);
1862 }
1863 }
1864
1865 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
1866 Results.ExitScope();
1867 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
1868}
1869
1870void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
1871 DeclPtrTy *Methods,
1872 unsigned NumMethods) {
1873 typedef CodeCompleteConsumer::Result Result;
1874
1875 // Try to find the interface where setters might live.
1876 ObjCInterfaceDecl *Class
1877 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
1878 if (!Class) {
1879 if (ObjCCategoryDecl *Category
1880 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
1881 Class = Category->getClassInterface();
1882
1883 if (!Class)
1884 return;
1885 }
1886
1887 // Find all of the potential getters.
1888 ResultBuilder Results(*this);
1889 Results.EnterNewScope();
1890
1891 // FIXME: We need to do this because Objective-C methods don't get
1892 // pushed into DeclContexts early enough. Argh!
1893 for (unsigned I = 0; I != NumMethods; ++I) {
1894 if (ObjCMethodDecl *Method
1895 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
1896 if (Method->isInstanceMethod() &&
1897 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
1898 Result R = Result(Method, 0);
1899 R.AllParametersAreInformative = true;
1900 Results.MaybeAddResult(R, CurContext);
1901 }
1902 }
1903
1904 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
1905
1906 Results.ExitScope();
1907 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00001908}
1909
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001910void Sema::CodeCompleteObjCClassMessage(Scope *S, IdentifierInfo *FName,
Douglas Gregord3c68542009-11-19 01:08:35 +00001911 SourceLocation FNameLoc,
1912 IdentifierInfo **SelIdents,
1913 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00001914 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00001915 ObjCInterfaceDecl *CDecl = 0;
1916
Douglas Gregor24a069f2009-11-17 17:59:40 +00001917 if (FName->isStr("super")) {
1918 // We're sending a message to "super".
1919 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
1920 // Figure out which interface we're in.
1921 CDecl = CurMethod->getClassInterface();
1922 if (!CDecl)
1923 return;
1924
1925 // Find the superclass of this class.
1926 CDecl = CDecl->getSuperClass();
1927 if (!CDecl)
1928 return;
1929
1930 if (CurMethod->isInstanceMethod()) {
1931 // We are inside an instance method, which means that the message
1932 // send [super ...] is actually calling an instance method on the
1933 // current object. Build the super expression and handle this like
1934 // an instance method.
1935 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
1936 SuperTy = Context.getObjCObjectPointerType(SuperTy);
1937 OwningExprResult Super
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001938 = Owned(new (Context) ObjCSuperExpr(FNameLoc, SuperTy));
Douglas Gregord3c68542009-11-19 01:08:35 +00001939 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
1940 SelIdents, NumSelIdents);
Douglas Gregor24a069f2009-11-17 17:59:40 +00001941 }
1942
1943 // Okay, we're calling a factory method in our superclass.
1944 }
1945 }
1946
1947 // If the given name refers to an interface type, retrieve the
1948 // corresponding declaration.
1949 if (!CDecl)
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001950 if (TypeTy *Ty = getTypeName(*FName, FNameLoc, S, 0, false)) {
Douglas Gregor24a069f2009-11-17 17:59:40 +00001951 QualType T = GetTypeFromParser(Ty, 0);
1952 if (!T.isNull())
1953 if (const ObjCInterfaceType *Interface = T->getAs<ObjCInterfaceType>())
1954 CDecl = Interface->getDecl();
1955 }
1956
1957 if (!CDecl && FName->isStr("super")) {
1958 // "super" may be the name of a variable, in which case we are
1959 // probably calling an instance method.
John McCallf7a1a742009-11-24 19:00:30 +00001960 CXXScopeSpec SS;
1961 UnqualifiedId id;
1962 id.setIdentifier(FName, FNameLoc);
1963 OwningExprResult Super = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregord3c68542009-11-19 01:08:35 +00001964 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
1965 SelIdents, NumSelIdents);
Douglas Gregor24a069f2009-11-17 17:59:40 +00001966 }
1967
Douglas Gregor36ecb042009-11-17 23:22:23 +00001968 // Add all of the factory methods in this Objective-C class, its protocols,
1969 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00001970 ResultBuilder Results(*this);
1971 Results.EnterNewScope();
Douglas Gregor4ad96852009-11-19 07:41:15 +00001972 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
1973 Results);
Steve Naroffc4df6d22009-11-07 02:08:14 +00001974 Results.ExitScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00001975
Steve Naroffc4df6d22009-11-07 02:08:14 +00001976 // This also suppresses remaining diagnostics.
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001977 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00001978}
1979
Douglas Gregord3c68542009-11-19 01:08:35 +00001980void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
1981 IdentifierInfo **SelIdents,
1982 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00001983 typedef CodeCompleteConsumer::Result Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00001984
1985 Expr *RecExpr = static_cast<Expr *>(Receiver);
1986 QualType RecType = RecExpr->getType();
1987
Douglas Gregor36ecb042009-11-17 23:22:23 +00001988 // If necessary, apply function/array conversion to the receiver.
1989 // C99 6.7.5.3p[7,8].
1990 DefaultFunctionArrayConversion(RecExpr);
1991 QualType ReceiverType = RecExpr->getType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00001992
Douglas Gregor36ecb042009-11-17 23:22:23 +00001993 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType()) {
1994 // FIXME: We're messaging 'id'. Do we actually want to look up every method
1995 // in the universe?
1996 return;
1997 }
1998
Douglas Gregor36ecb042009-11-17 23:22:23 +00001999 // Build the set of methods we can see.
2000 ResultBuilder Results(*this);
2001 Results.EnterNewScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00002002
Douglas Gregorf74a4192009-11-18 00:06:18 +00002003 // Handle messages to Class. This really isn't a message to an instance
2004 // method, so we treat it the same way we would treat a message send to a
2005 // class method.
2006 if (ReceiverType->isObjCClassType() ||
2007 ReceiverType->isObjCQualifiedClassType()) {
2008 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
2009 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00002010 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
2011 CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00002012 }
2013 }
2014 // Handle messages to a qualified ID ("id<foo>").
2015 else if (const ObjCObjectPointerType *QualID
2016 = ReceiverType->getAsObjCQualifiedIdType()) {
2017 // Search protocols for instance methods.
2018 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
2019 E = QualID->qual_end();
2020 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002021 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
2022 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00002023 }
2024 // Handle messages to a pointer to interface type.
2025 else if (const ObjCObjectPointerType *IFacePtr
2026 = ReceiverType->getAsObjCInterfacePointerType()) {
2027 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00002028 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
2029 NumSelIdents, CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00002030
2031 // Search protocols for instance methods.
2032 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
2033 E = IFacePtr->qual_end();
2034 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002035 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
2036 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00002037 }
2038
Steve Naroffc4df6d22009-11-07 02:08:14 +00002039 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002040 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00002041}
Douglas Gregor55385fe2009-11-18 04:19:12 +00002042
2043/// \brief Add all of the protocol declarations that we find in the given
2044/// (translation unit) context.
2045static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00002046 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00002047 ResultBuilder &Results) {
2048 typedef CodeCompleteConsumer::Result Result;
2049
2050 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
2051 DEnd = Ctx->decls_end();
2052 D != DEnd; ++D) {
2053 // Record any protocols we find.
2054 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00002055 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
2056 Results.MaybeAddResult(Result(Proto, 0), CurContext);
Douglas Gregor55385fe2009-11-18 04:19:12 +00002057
2058 // Record any forward-declared protocols we find.
2059 if (ObjCForwardProtocolDecl *Forward
2060 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2061 for (ObjCForwardProtocolDecl::protocol_iterator
2062 P = Forward->protocol_begin(),
2063 PEnd = Forward->protocol_end();
2064 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00002065 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
2066 Results.MaybeAddResult(Result(*P, 0), CurContext);
Douglas Gregor55385fe2009-11-18 04:19:12 +00002067 }
2068 }
2069}
2070
2071void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
2072 unsigned NumProtocols) {
2073 ResultBuilder Results(*this);
2074 Results.EnterNewScope();
2075
2076 // Tell the result set to ignore all of the protocols we have
2077 // already seen.
2078 for (unsigned I = 0; I != NumProtocols; ++I)
2079 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first))
2080 Results.Ignore(Protocol);
2081
2082 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00002083 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
2084 Results);
2085
2086 Results.ExitScope();
2087 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2088}
2089
2090void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
2091 ResultBuilder Results(*this);
2092 Results.EnterNewScope();
2093
2094 // Add all protocols.
2095 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
2096 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00002097
2098 Results.ExitScope();
2099 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2100}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00002101
2102/// \brief Add all of the Objective-C interface declarations that we find in
2103/// the given (translation unit) context.
2104static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
2105 bool OnlyForwardDeclarations,
2106 bool OnlyUnimplemented,
2107 ResultBuilder &Results) {
2108 typedef CodeCompleteConsumer::Result Result;
2109
2110 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
2111 DEnd = Ctx->decls_end();
2112 D != DEnd; ++D) {
2113 // Record any interfaces we find.
2114 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
2115 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
2116 (!OnlyUnimplemented || !Class->getImplementation()))
2117 Results.MaybeAddResult(Result(Class, 0), CurContext);
2118
2119 // Record any forward-declared interfaces we find.
2120 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
2121 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
2122 C != CEnd; ++C)
2123 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
2124 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
2125 Results.MaybeAddResult(Result(C->getInterface(), 0), CurContext);
2126 }
2127 }
2128}
2129
2130void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
2131 ResultBuilder Results(*this);
2132 Results.EnterNewScope();
2133
2134 // Add all classes.
2135 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
2136 false, Results);
2137
2138 Results.ExitScope();
2139 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2140}
2141
2142void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName) {
2143 ResultBuilder Results(*this);
2144 Results.EnterNewScope();
2145
2146 // Make sure that we ignore the class we're currently defining.
2147 NamedDecl *CurClass
2148 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00002149 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00002150 Results.Ignore(CurClass);
2151
2152 // Add all classes.
2153 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
2154 false, Results);
2155
2156 Results.ExitScope();
2157 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2158}
2159
2160void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
2161 ResultBuilder Results(*this);
2162 Results.EnterNewScope();
2163
2164 // Add all unimplemented classes.
2165 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
2166 true, Results);
2167
2168 Results.ExitScope();
2169 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2170}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00002171
2172void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
2173 IdentifierInfo *ClassName) {
2174 typedef CodeCompleteConsumer::Result Result;
2175
2176 ResultBuilder Results(*this);
2177
2178 // Ignore any categories we find that have already been implemented by this
2179 // interface.
2180 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
2181 NamedDecl *CurClass
2182 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
2183 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
2184 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
2185 Category = Category->getNextClassCategory())
2186 CategoryNames.insert(Category->getIdentifier());
2187
2188 // Add all of the categories we know about.
2189 Results.EnterNewScope();
2190 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
2191 for (DeclContext::decl_iterator D = TU->decls_begin(),
2192 DEnd = TU->decls_end();
2193 D != DEnd; ++D)
2194 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
2195 if (CategoryNames.insert(Category->getIdentifier()))
2196 Results.MaybeAddResult(Result(Category, 0), CurContext);
2197 Results.ExitScope();
2198
2199 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2200}
2201
2202void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
2203 IdentifierInfo *ClassName) {
2204 typedef CodeCompleteConsumer::Result Result;
2205
2206 // Find the corresponding interface. If we couldn't find the interface, the
2207 // program itself is ill-formed. However, we'll try to be helpful still by
2208 // providing the list of all of the categories we know about.
2209 NamedDecl *CurClass
2210 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
2211 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
2212 if (!Class)
2213 return CodeCompleteObjCInterfaceCategory(S, ClassName);
2214
2215 ResultBuilder Results(*this);
2216
2217 // Add all of the categories that have have corresponding interface
2218 // declarations in this class and any of its superclasses, except for
2219 // already-implemented categories in the class itself.
2220 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
2221 Results.EnterNewScope();
2222 bool IgnoreImplemented = true;
2223 while (Class) {
2224 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
2225 Category = Category->getNextClassCategory())
2226 if ((!IgnoreImplemented || !Category->getImplementation()) &&
2227 CategoryNames.insert(Category->getIdentifier()))
2228 Results.MaybeAddResult(Result(Category, 0), CurContext);
2229
2230 Class = Class->getSuperClass();
2231 IgnoreImplemented = false;
2232 }
2233 Results.ExitScope();
2234
2235 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2236}
Douglas Gregor322328b2009-11-18 22:32:06 +00002237
Douglas Gregor424b2a52009-11-18 22:56:13 +00002238void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
Douglas Gregor322328b2009-11-18 22:32:06 +00002239 typedef CodeCompleteConsumer::Result Result;
2240 ResultBuilder Results(*this);
2241
2242 // Figure out where this @synthesize lives.
2243 ObjCContainerDecl *Container
2244 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
2245 if (!Container ||
2246 (!isa<ObjCImplementationDecl>(Container) &&
2247 !isa<ObjCCategoryImplDecl>(Container)))
2248 return;
2249
2250 // Ignore any properties that have already been implemented.
2251 for (DeclContext::decl_iterator D = Container->decls_begin(),
2252 DEnd = Container->decls_end();
2253 D != DEnd; ++D)
2254 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
2255 Results.Ignore(PropertyImpl->getPropertyDecl());
2256
2257 // Add any properties that we find.
2258 Results.EnterNewScope();
2259 if (ObjCImplementationDecl *ClassImpl
2260 = dyn_cast<ObjCImplementationDecl>(Container))
2261 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
2262 Results);
2263 else
2264 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
2265 false, CurContext, Results);
2266 Results.ExitScope();
2267
2268 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2269}
2270
2271void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
2272 IdentifierInfo *PropertyName,
2273 DeclPtrTy ObjCImpDecl) {
2274 typedef CodeCompleteConsumer::Result Result;
2275 ResultBuilder Results(*this);
2276
2277 // Figure out where this @synthesize lives.
2278 ObjCContainerDecl *Container
2279 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
2280 if (!Container ||
2281 (!isa<ObjCImplementationDecl>(Container) &&
2282 !isa<ObjCCategoryImplDecl>(Container)))
2283 return;
2284
2285 // Figure out which interface we're looking into.
2286 ObjCInterfaceDecl *Class = 0;
2287 if (ObjCImplementationDecl *ClassImpl
2288 = dyn_cast<ObjCImplementationDecl>(Container))
2289 Class = ClassImpl->getClassInterface();
2290 else
2291 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
2292 ->getClassInterface();
2293
2294 // Add all of the instance variables in this class and its superclasses.
2295 Results.EnterNewScope();
2296 for(; Class; Class = Class->getSuperClass()) {
2297 // FIXME: We could screen the type of each ivar for compatibility with
2298 // the property, but is that being too paternal?
2299 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
2300 IVarEnd = Class->ivar_end();
2301 IVar != IVarEnd; ++IVar)
2302 Results.MaybeAddResult(Result(*IVar, 0), CurContext);
2303 }
2304 Results.ExitScope();
2305
2306 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2307}