blob: 567cd2091dbe4cc6d8c97abc2f57f09a41160aaa [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 Gregor2b0cc122009-12-05 09:08:56 +00001067 Selector XSel = X.getObjCSelector();
1068 Selector YSel = Y.getObjCSelector();
1069 if (!XSel.isNull() && !YSel.isNull()) {
1070 // We are comparing two selectors.
1071 unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
1072 if (N == 0)
1073 ++N;
1074 for (unsigned I = 0; I != N; ++I) {
1075 IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
1076 IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
1077 if (!XId || !YId)
1078 return XId && !YId;
1079
1080 switch (XId->getName().compare_lower(YId->getName())) {
1081 case -1: return true;
1082 case 1: return false;
1083 default: break;
1084 }
1085 }
1086
1087 return XSel.getNumArgs() < YSel.getNumArgs();
1088 }
1089
1090 // For non-selectors, order by kind.
1091 if (X.getNameKind() != Y.getNameKind())
Douglas Gregor6a684032009-09-28 03:51:44 +00001092 return X.getNameKind() < Y.getNameKind();
1093
Douglas Gregor2b0cc122009-12-05 09:08:56 +00001094 // Order identifiers by comparison of their lowercased names.
1095 if (IdentifierInfo *XId = X.getAsIdentifierInfo())
1096 return XId->getName().compare_lower(
1097 Y.getAsIdentifierInfo()->getName()) < 0;
1098
1099 // Order overloaded operators by the order in which they appear
1100 // in our list of operators.
1101 if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
1102 return XOp < Y.getCXXOverloadedOperator();
1103
1104 // Order C++0x user-defined literal operators lexically by their
1105 // lowercased suffixes.
1106 if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
1107 return XLit->getName().compare_lower(
1108 Y.getCXXLiteralIdentifier()->getName()) < 0;
1109
1110 // The only stable ordering we have is to turn the name into a
1111 // string and then compare the lower-case strings. This is
1112 // inefficient, but thankfully does not happen too often.
Douglas Gregor6a684032009-09-28 03:51:44 +00001113 return llvm::LowercaseString(X.getAsString())
1114 < llvm::LowercaseString(Y.getAsString());
1115 }
1116
Douglas Gregor86d9a522009-09-21 16:56:56 +00001117 bool operator()(const Result &X, const Result &Y) const {
1118 // Sort first by rank.
1119 if (X.Rank < Y.Rank)
1120 return true;
1121 else if (X.Rank > Y.Rank)
1122 return false;
1123
Douglas Gregor54f01612009-11-19 00:01:57 +00001124 // We use a special ordering for keywords and patterns, based on the
1125 // typed text.
1126 if ((X.Kind == Result::RK_Keyword || X.Kind == Result::RK_Pattern) &&
1127 (Y.Kind == Result::RK_Keyword || Y.Kind == Result::RK_Pattern)) {
1128 const char *XStr = (X.Kind == Result::RK_Keyword)? X.Keyword
1129 : X.Pattern->getTypedText();
1130 const char *YStr = (Y.Kind == Result::RK_Keyword)? Y.Keyword
1131 : Y.Pattern->getTypedText();
Douglas Gregor2b0cc122009-12-05 09:08:56 +00001132 return strcasecmp(XStr, YStr) < 0;
Douglas Gregor54f01612009-11-19 00:01:57 +00001133 }
1134
Douglas Gregor86d9a522009-09-21 16:56:56 +00001135 // Result kinds are ordered by decreasing importance.
1136 if (X.Kind < Y.Kind)
1137 return true;
1138 else if (X.Kind > Y.Kind)
1139 return false;
1140
1141 // Non-hidden names precede hidden names.
1142 if (X.Hidden != Y.Hidden)
1143 return !X.Hidden;
1144
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001145 // Non-nested-name-specifiers precede nested-name-specifiers.
1146 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1147 return !X.StartsNestedNameSpecifier;
1148
Douglas Gregor86d9a522009-09-21 16:56:56 +00001149 // Ordering depends on the kind of result.
1150 switch (X.Kind) {
1151 case Result::RK_Declaration:
1152 // Order based on the declaration names.
Douglas Gregor6a684032009-09-28 03:51:44 +00001153 return isEarlierDeclarationName(X.Declaration->getDeclName(),
1154 Y.Declaration->getDeclName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001155
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001156 case Result::RK_Macro:
Douglas Gregor2b0cc122009-12-05 09:08:56 +00001157 return X.Macro->getName().compare_lower(Y.Macro->getName()) < 0;
Douglas Gregor54f01612009-11-19 00:01:57 +00001158
1159 case Result::RK_Keyword:
1160 case Result::RK_Pattern:
1161 llvm::llvm_unreachable("Result kinds handled above");
1162 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001163 }
1164
1165 // Silence GCC warning.
1166 return false;
1167 }
1168 };
1169}
1170
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001171static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1172 ResultBuilder &Results) {
1173 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001174 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1175 MEnd = PP.macro_end();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001176 M != MEnd; ++M)
1177 Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1178 Results.ExitScope();
1179}
1180
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001181static void HandleCodeCompleteResults(Sema *S,
1182 CodeCompleteConsumer *CodeCompleter,
1183 CodeCompleteConsumer::Result *Results,
1184 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00001185 // Sort the results by rank/kind/etc.
1186 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1187
1188 if (CodeCompleter)
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001189 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00001190
1191 for (unsigned I = 0; I != NumResults; ++I)
1192 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001193}
1194
Douglas Gregor791215b2009-09-21 20:51:25 +00001195void Sema::CodeCompleteOrdinaryName(Scope *S) {
1196 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001197 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1198 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001199 if (CodeCompleter->includeMacros())
1200 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001201 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00001202}
1203
Douglas Gregor95ac6552009-11-18 01:29:26 +00001204static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00001205 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00001206 DeclContext *CurContext,
1207 ResultBuilder &Results) {
1208 typedef CodeCompleteConsumer::Result Result;
1209
1210 // Add properties in this container.
1211 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
1212 PEnd = Container->prop_end();
1213 P != PEnd;
1214 ++P)
1215 Results.MaybeAddResult(Result(*P, 0), CurContext);
1216
1217 // Add properties in referenced protocols.
1218 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
1219 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
1220 PEnd = Protocol->protocol_end();
1221 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00001222 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001223 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00001224 if (AllowCategories) {
1225 // Look through categories.
1226 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
1227 Category; Category = Category->getNextClassCategory())
1228 AddObjCProperties(Category, AllowCategories, CurContext, Results);
1229 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00001230
1231 // Look through protocols.
1232 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
1233 E = IFace->protocol_end();
1234 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00001235 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001236
1237 // Look in the superclass.
1238 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00001239 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
1240 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001241 } else if (const ObjCCategoryDecl *Category
1242 = dyn_cast<ObjCCategoryDecl>(Container)) {
1243 // Look through protocols.
1244 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
1245 PEnd = Category->protocol_end();
1246 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00001247 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001248 }
1249}
1250
Douglas Gregor81b747b2009-09-17 21:32:03 +00001251void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1252 SourceLocation OpLoc,
1253 bool IsArrow) {
1254 if (!BaseE || !CodeCompleter)
1255 return;
1256
Douglas Gregor86d9a522009-09-21 16:56:56 +00001257 typedef CodeCompleteConsumer::Result Result;
1258
Douglas Gregor81b747b2009-09-17 21:32:03 +00001259 Expr *Base = static_cast<Expr *>(BaseE);
1260 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001261
1262 if (IsArrow) {
1263 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1264 BaseType = Ptr->getPointeeType();
1265 else if (BaseType->isObjCObjectPointerType())
1266 /*Do nothing*/ ;
1267 else
1268 return;
1269 }
1270
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001271 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001272 unsigned NextRank = 0;
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001273
Douglas Gregor95ac6552009-11-18 01:29:26 +00001274 Results.EnterNewScope();
1275 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
1276 // Access to a C/C++ class, struct, or union.
1277 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1278 Record->getDecl(), Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001279
Douglas Gregor95ac6552009-11-18 01:29:26 +00001280 if (getLangOptions().CPlusPlus) {
1281 if (!Results.empty()) {
1282 // The "template" keyword can follow "->" or "." in the grammar.
1283 // However, we only want to suggest the template keyword if something
1284 // is dependent.
1285 bool IsDependent = BaseType->isDependentType();
1286 if (!IsDependent) {
1287 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1288 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1289 IsDependent = Ctx->isDependentContext();
1290 break;
1291 }
1292 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001293
Douglas Gregor95ac6552009-11-18 01:29:26 +00001294 if (IsDependent)
1295 Results.MaybeAddResult(Result("template", NextRank++));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001296 }
1297
Douglas Gregor95ac6552009-11-18 01:29:26 +00001298 // We could have the start of a nested-name-specifier. Add those
1299 // results as well.
1300 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1301 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
1302 CurContext, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001303 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00001304 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
1305 // Objective-C property reference.
1306
1307 // Add property results based on our interface.
1308 const ObjCObjectPointerType *ObjCPtr
1309 = BaseType->getAsObjCInterfacePointerType();
1310 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00001311 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001312
1313 // Add properties from the protocols in a qualified interface.
1314 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
1315 E = ObjCPtr->qual_end();
1316 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00001317 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001318
1319 // FIXME: We could (should?) also look for "implicit" properties, identified
1320 // only by the presence of nullary and unary selectors.
1321 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
1322 (!IsArrow && BaseType->isObjCInterfaceType())) {
1323 // Objective-C instance variable access.
1324 ObjCInterfaceDecl *Class = 0;
1325 if (const ObjCObjectPointerType *ObjCPtr
1326 = BaseType->getAs<ObjCObjectPointerType>())
1327 Class = ObjCPtr->getInterfaceDecl();
1328 else
1329 Class = BaseType->getAs<ObjCInterfaceType>()->getDecl();
1330
1331 // Add all ivars from this class and its superclasses.
1332 for (; Class; Class = Class->getSuperClass()) {
1333 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
1334 IVarEnd = Class->ivar_end();
1335 IVar != IVarEnd; ++IVar)
1336 Results.MaybeAddResult(Result(*IVar, 0), CurContext);
1337 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001338 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00001339
1340 // FIXME: How do we cope with isa?
1341
1342 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001343
1344 // Add macros
1345 if (CodeCompleter->includeMacros())
1346 AddMacroResults(PP, NextRank, Results);
1347
1348 // Hand off the results found for code completion.
1349 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001350}
1351
Douglas Gregor374929f2009-09-18 15:37:17 +00001352void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1353 if (!CodeCompleter)
1354 return;
1355
Douglas Gregor86d9a522009-09-21 16:56:56 +00001356 typedef CodeCompleteConsumer::Result Result;
1357 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +00001358 switch ((DeclSpec::TST)TagSpec) {
1359 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001360 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +00001361 break;
1362
1363 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001364 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +00001365 break;
1366
1367 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00001368 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001369 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00001370 break;
1371
1372 default:
1373 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1374 return;
1375 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001376
1377 ResultBuilder Results(*this, Filter);
1378 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001379 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001380
1381 if (getLangOptions().CPlusPlus) {
1382 // We could have the start of a nested-name-specifier. Add those
1383 // results as well.
1384 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001385 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1386 NextRank, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001387 }
1388
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001389 if (CodeCompleter->includeMacros())
1390 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001391 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00001392}
1393
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001394void Sema::CodeCompleteCase(Scope *S) {
1395 if (getSwitchStack().empty() || !CodeCompleter)
1396 return;
1397
1398 SwitchStmt *Switch = getSwitchStack().back();
1399 if (!Switch->getCond()->getType()->isEnumeralType())
1400 return;
1401
1402 // Code-complete the cases of a switch statement over an enumeration type
1403 // by providing the list of
1404 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1405
1406 // Determine which enumerators we have already seen in the switch statement.
1407 // FIXME: Ideally, we would also be able to look *past* the code-completion
1408 // token, in case we are code-completing in the middle of the switch and not
1409 // at the end. However, we aren't able to do so at the moment.
1410 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001411 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001412 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1413 SC = SC->getNextSwitchCase()) {
1414 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1415 if (!Case)
1416 continue;
1417
1418 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1419 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1420 if (EnumConstantDecl *Enumerator
1421 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1422 // We look into the AST of the case statement to determine which
1423 // enumerator was named. Alternatively, we could compute the value of
1424 // the integral constant expression, then compare it against the
1425 // values of each enumerator. However, value-based approach would not
1426 // work as well with C++ templates where enumerators declared within a
1427 // template are type- and value-dependent.
1428 EnumeratorsSeen.insert(Enumerator);
1429
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001430 // If this is a qualified-id, keep track of the nested-name-specifier
1431 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001432 //
1433 // switch (TagD.getKind()) {
1434 // case TagDecl::TK_enum:
1435 // break;
1436 // case XXX
1437 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001438 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001439 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1440 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00001441 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001442 }
1443 }
1444
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001445 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1446 // If there are no prior enumerators in C++, check whether we have to
1447 // qualify the names of the enumerators that we suggest, because they
1448 // may not be visible in this scope.
1449 Qualifier = getRequiredQualification(Context, CurContext,
1450 Enum->getDeclContext());
1451
1452 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1453 }
1454
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001455 // Add any enumerators that have not yet been mentioned.
1456 ResultBuilder Results(*this);
1457 Results.EnterNewScope();
1458 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1459 EEnd = Enum->enumerator_end();
1460 E != EEnd; ++E) {
1461 if (EnumeratorsSeen.count(*E))
1462 continue;
1463
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001464 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001465 }
1466 Results.ExitScope();
1467
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001468 if (CodeCompleter->includeMacros())
1469 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001470 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001471}
1472
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001473namespace {
1474 struct IsBetterOverloadCandidate {
1475 Sema &S;
1476
1477 public:
1478 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1479
1480 bool
1481 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1482 return S.isBetterOverloadCandidate(X, Y);
1483 }
1484 };
1485}
1486
1487void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1488 ExprTy **ArgsIn, unsigned NumArgs) {
1489 if (!CodeCompleter)
1490 return;
1491
1492 Expr *Fn = (Expr *)FnIn;
1493 Expr **Args = (Expr **)ArgsIn;
1494
1495 // Ignore type-dependent call expressions entirely.
1496 if (Fn->isTypeDependent() ||
1497 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1498 return;
1499
John McCallba135432009-11-21 08:51:07 +00001500 llvm::SmallVector<NamedDecl*,8> Fns;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001501 DeclarationName UnqualifiedName;
1502 NestedNameSpecifier *Qualifier;
1503 SourceRange QualifierRange;
1504 bool ArgumentDependentLookup;
John McCall7453ed42009-11-22 00:44:51 +00001505 bool Overloaded;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001506 bool HasExplicitTemplateArgs;
John McCalld5532b62009-11-23 01:53:49 +00001507 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001508
John McCallba135432009-11-21 08:51:07 +00001509 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall7453ed42009-11-22 00:44:51 +00001510 ArgumentDependentLookup, Overloaded,
John McCalld5532b62009-11-23 01:53:49 +00001511 HasExplicitTemplateArgs, ExplicitTemplateArgs);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001512
1513
1514 // FIXME: What if we're calling something that isn't a function declaration?
1515 // FIXME: What if we're calling a pseudo-destructor?
1516 // FIXME: What if we're calling a member function?
1517
1518 // Build an overload candidate set based on the functions we find.
1519 OverloadCandidateSet CandidateSet;
John McCallba135432009-11-21 08:51:07 +00001520 AddOverloadedCallCandidates(Fns, UnqualifiedName,
John McCalld5532b62009-11-23 01:53:49 +00001521 ArgumentDependentLookup,
1522 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001523 Args, NumArgs,
1524 CandidateSet,
1525 /*PartialOverloading=*/true);
1526
1527 // Sort the overload candidate set by placing the best overloads first.
1528 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1529 IsBetterOverloadCandidate(*this));
1530
1531 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05944382009-09-23 00:16:58 +00001532 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1533 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlsson90756302009-09-22 17:29:51 +00001534
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001535 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1536 CandEnd = CandidateSet.end();
1537 Cand != CandEnd; ++Cand) {
1538 if (Cand->Viable)
Douglas Gregor05944382009-09-23 00:16:58 +00001539 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001540 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001541 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
Douglas Gregor05944382009-09-23 00:16:58 +00001542 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001543}
1544
Douglas Gregor81b747b2009-09-17 21:32:03 +00001545void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1546 bool EnteringContext) {
1547 if (!SS.getScopeRep() || !CodeCompleter)
1548 return;
1549
Douglas Gregor86d9a522009-09-21 16:56:56 +00001550 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1551 if (!Ctx)
1552 return;
1553
1554 ResultBuilder Results(*this);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001555 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001556
1557 // The "template" keyword can follow "::" in the grammar, but only
1558 // put it into the grammar if the nested-name-specifier is dependent.
1559 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1560 if (!Results.empty() && NNS->isDependent())
1561 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1562
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001563 if (CodeCompleter->includeMacros())
1564 AddMacroResults(PP, NextRank + 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001565 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001566}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001567
1568void Sema::CodeCompleteUsing(Scope *S) {
1569 if (!CodeCompleter)
1570 return;
1571
Douglas Gregor86d9a522009-09-21 16:56:56 +00001572 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001573 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001574
1575 // If we aren't in class scope, we could see the "namespace" keyword.
1576 if (!S->isClassScope())
1577 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1578
1579 // After "using", we can see anything that would start a
1580 // nested-name-specifier.
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001581 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1582 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001583 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001584
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001585 if (CodeCompleter->includeMacros())
1586 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001587 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001588}
1589
1590void Sema::CodeCompleteUsingDirective(Scope *S) {
1591 if (!CodeCompleter)
1592 return;
1593
Douglas Gregor86d9a522009-09-21 16:56:56 +00001594 // After "using namespace", we expect to see a namespace name or namespace
1595 // alias.
1596 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001597 Results.EnterNewScope();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001598 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1599 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001600 Results.ExitScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001601 if (CodeCompleter->includeMacros())
1602 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001603 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001604}
1605
1606void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1607 if (!CodeCompleter)
1608 return;
1609
Douglas Gregor86d9a522009-09-21 16:56:56 +00001610 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1611 DeclContext *Ctx = (DeclContext *)S->getEntity();
1612 if (!S->getParent())
1613 Ctx = Context.getTranslationUnitDecl();
1614
1615 if (Ctx && Ctx->isFileContext()) {
1616 // We only want to see those namespaces that have already been defined
1617 // within this scope, because its likely that the user is creating an
1618 // extended namespace declaration. Keep track of the most recent
1619 // definition of each namespace.
1620 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1621 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1622 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1623 NS != NSEnd; ++NS)
1624 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1625
1626 // Add the most recent definition (or extended definition) of each
1627 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001628 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001629 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1630 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1631 NS != NSEnd; ++NS)
Douglas Gregor456c4a12009-09-21 20:12:40 +00001632 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1633 CurContext);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001634 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001635 }
1636
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001637 if (CodeCompleter->includeMacros())
1638 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001639 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001640}
1641
1642void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1643 if (!CodeCompleter)
1644 return;
1645
Douglas Gregor86d9a522009-09-21 16:56:56 +00001646 // After "namespace", we expect to see a namespace or alias.
1647 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001648 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1649 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001650 if (CodeCompleter->includeMacros())
1651 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001652 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001653}
1654
Douglas Gregored8d3222009-09-18 20:05:18 +00001655void Sema::CodeCompleteOperatorName(Scope *S) {
1656 if (!CodeCompleter)
1657 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001658
1659 typedef CodeCompleteConsumer::Result Result;
1660 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001661 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00001662
Douglas Gregor86d9a522009-09-21 16:56:56 +00001663 // Add the names of overloadable operators.
1664#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1665 if (std::strcmp(Spelling, "?")) \
1666 Results.MaybeAddResult(Result(Spelling, 0));
1667#include "clang/Basic/OperatorKinds.def"
1668
1669 // Add any type names visible from the current scope
1670 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001671 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001672
1673 // Add any type specifiers
1674 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1675
1676 // Add any nested-name-specifiers
1677 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001678 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1679 NextRank + 1, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001680 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001681
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001682 if (CodeCompleter->includeMacros())
1683 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001684 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00001685}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001686
Douglas Gregor988358f2009-11-19 00:14:45 +00001687/// \brief Determine whether the addition of the given flag to an Objective-C
1688/// property's attributes will cause a conflict.
1689static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
1690 // Check if we've already added this flag.
1691 if (Attributes & NewFlag)
1692 return true;
1693
1694 Attributes |= NewFlag;
1695
1696 // Check for collisions with "readonly".
1697 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1698 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
1699 ObjCDeclSpec::DQ_PR_assign |
1700 ObjCDeclSpec::DQ_PR_copy |
1701 ObjCDeclSpec::DQ_PR_retain)))
1702 return true;
1703
1704 // Check for more than one of { assign, copy, retain }.
1705 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
1706 ObjCDeclSpec::DQ_PR_copy |
1707 ObjCDeclSpec::DQ_PR_retain);
1708 if (AssignCopyRetMask &&
1709 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
1710 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
1711 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
1712 return true;
1713
1714 return false;
1715}
1716
Douglas Gregora93b1082009-11-18 23:08:07 +00001717void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00001718 if (!CodeCompleter)
1719 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00001720
Steve Naroffece8e712009-10-08 21:55:05 +00001721 unsigned Attributes = ODS.getPropertyAttributes();
1722
1723 typedef CodeCompleteConsumer::Result Result;
1724 ResultBuilder Results(*this);
1725 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00001726 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
Steve Naroffece8e712009-10-08 21:55:05 +00001727 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001728 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
Steve Naroffece8e712009-10-08 21:55:05 +00001729 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001730 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
Steve Naroffece8e712009-10-08 21:55:05 +00001731 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001732 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
Steve Naroffece8e712009-10-08 21:55:05 +00001733 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001734 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
Steve Naroffece8e712009-10-08 21:55:05 +00001735 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001736 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
Steve Naroffece8e712009-10-08 21:55:05 +00001737 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00001738 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00001739 CodeCompletionString *Setter = new CodeCompletionString;
1740 Setter->AddTypedTextChunk("setter");
1741 Setter->AddTextChunk(" = ");
1742 Setter->AddPlaceholderChunk("method");
1743 Results.MaybeAddResult(CodeCompleteConsumer::Result(Setter, 0));
1744 }
Douglas Gregor988358f2009-11-19 00:14:45 +00001745 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00001746 CodeCompletionString *Getter = new CodeCompletionString;
1747 Getter->AddTypedTextChunk("getter");
1748 Getter->AddTextChunk(" = ");
1749 Getter->AddPlaceholderChunk("method");
1750 Results.MaybeAddResult(CodeCompleteConsumer::Result(Getter, 0));
1751 }
Steve Naroffece8e712009-10-08 21:55:05 +00001752 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001753 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00001754}
Steve Naroffc4df6d22009-11-07 02:08:14 +00001755
Douglas Gregor4ad96852009-11-19 07:41:15 +00001756/// \brief Descripts the kind of Objective-C method that we want to find
1757/// via code completion.
1758enum ObjCMethodKind {
1759 MK_Any, //< Any kind of method, provided it means other specified criteria.
1760 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
1761 MK_OneArgSelector //< One-argument selector.
1762};
1763
1764static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
1765 ObjCMethodKind WantKind,
1766 IdentifierInfo **SelIdents,
1767 unsigned NumSelIdents) {
1768 Selector Sel = Method->getSelector();
1769 if (NumSelIdents > Sel.getNumArgs())
1770 return false;
1771
1772 switch (WantKind) {
1773 case MK_Any: break;
1774 case MK_ZeroArgSelector: return Sel.isUnarySelector();
1775 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
1776 }
1777
1778 for (unsigned I = 0; I != NumSelIdents; ++I)
1779 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
1780 return false;
1781
1782 return true;
1783}
1784
Douglas Gregor36ecb042009-11-17 23:22:23 +00001785/// \brief Add all of the Objective-C methods in the given Objective-C
1786/// container to the set of results.
1787///
1788/// The container will be a class, protocol, category, or implementation of
1789/// any of the above. This mether will recurse to include methods from
1790/// the superclasses of classes along with their categories, protocols, and
1791/// implementations.
1792///
1793/// \param Container the container in which we'll look to find methods.
1794///
1795/// \param WantInstance whether to add instance methods (only); if false, this
1796/// routine will add factory methods (only).
1797///
1798/// \param CurContext the context in which we're performing the lookup that
1799/// finds methods.
1800///
1801/// \param Results the structure into which we'll add results.
1802static void AddObjCMethods(ObjCContainerDecl *Container,
1803 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00001804 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00001805 IdentifierInfo **SelIdents,
1806 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00001807 DeclContext *CurContext,
1808 ResultBuilder &Results) {
1809 typedef CodeCompleteConsumer::Result Result;
1810 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
1811 MEnd = Container->meth_end();
1812 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00001813 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
1814 // Check whether the selector identifiers we've been given are a
1815 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00001816 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00001817 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00001818
Douglas Gregord3c68542009-11-19 01:08:35 +00001819 Result R = Result(*M, 0);
1820 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00001821 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregord3c68542009-11-19 01:08:35 +00001822 Results.MaybeAddResult(R, CurContext);
1823 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00001824 }
1825
1826 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
1827 if (!IFace)
1828 return;
1829
1830 // Add methods in protocols.
1831 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
1832 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1833 E = Protocols.end();
1834 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00001835 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord3c68542009-11-19 01:08:35 +00001836 CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001837
1838 // Add methods in categories.
1839 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
1840 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00001841 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
1842 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001843
1844 // Add a categories protocol methods.
1845 const ObjCList<ObjCProtocolDecl> &Protocols
1846 = CatDecl->getReferencedProtocols();
1847 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1848 E = Protocols.end();
1849 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00001850 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
1851 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001852
1853 // Add methods in category implementations.
1854 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00001855 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
1856 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001857 }
1858
1859 // Add methods in superclass.
1860 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00001861 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
1862 SelIdents, NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00001863
1864 // Add methods in our implementation, if any.
1865 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00001866 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
1867 NumSelIdents, CurContext, Results);
1868}
1869
1870
1871void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
1872 DeclPtrTy *Methods,
1873 unsigned NumMethods) {
1874 typedef CodeCompleteConsumer::Result Result;
1875
1876 // Try to find the interface where getters might live.
1877 ObjCInterfaceDecl *Class
1878 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
1879 if (!Class) {
1880 if (ObjCCategoryDecl *Category
1881 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
1882 Class = Category->getClassInterface();
1883
1884 if (!Class)
1885 return;
1886 }
1887
1888 // Find all of the potential getters.
1889 ResultBuilder Results(*this);
1890 Results.EnterNewScope();
1891
1892 // FIXME: We need to do this because Objective-C methods don't get
1893 // pushed into DeclContexts early enough. Argh!
1894 for (unsigned I = 0; I != NumMethods; ++I) {
1895 if (ObjCMethodDecl *Method
1896 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
1897 if (Method->isInstanceMethod() &&
1898 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
1899 Result R = Result(Method, 0);
1900 R.AllParametersAreInformative = true;
1901 Results.MaybeAddResult(R, CurContext);
1902 }
1903 }
1904
1905 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
1906 Results.ExitScope();
1907 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
1908}
1909
1910void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
1911 DeclPtrTy *Methods,
1912 unsigned NumMethods) {
1913 typedef CodeCompleteConsumer::Result Result;
1914
1915 // Try to find the interface where setters might live.
1916 ObjCInterfaceDecl *Class
1917 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
1918 if (!Class) {
1919 if (ObjCCategoryDecl *Category
1920 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
1921 Class = Category->getClassInterface();
1922
1923 if (!Class)
1924 return;
1925 }
1926
1927 // Find all of the potential getters.
1928 ResultBuilder Results(*this);
1929 Results.EnterNewScope();
1930
1931 // FIXME: We need to do this because Objective-C methods don't get
1932 // pushed into DeclContexts early enough. Argh!
1933 for (unsigned I = 0; I != NumMethods; ++I) {
1934 if (ObjCMethodDecl *Method
1935 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
1936 if (Method->isInstanceMethod() &&
1937 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
1938 Result R = Result(Method, 0);
1939 R.AllParametersAreInformative = true;
1940 Results.MaybeAddResult(R, CurContext);
1941 }
1942 }
1943
1944 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
1945
1946 Results.ExitScope();
1947 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00001948}
1949
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001950void Sema::CodeCompleteObjCClassMessage(Scope *S, IdentifierInfo *FName,
Douglas Gregord3c68542009-11-19 01:08:35 +00001951 SourceLocation FNameLoc,
1952 IdentifierInfo **SelIdents,
1953 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00001954 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00001955 ObjCInterfaceDecl *CDecl = 0;
1956
Douglas Gregor24a069f2009-11-17 17:59:40 +00001957 if (FName->isStr("super")) {
1958 // We're sending a message to "super".
1959 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
1960 // Figure out which interface we're in.
1961 CDecl = CurMethod->getClassInterface();
1962 if (!CDecl)
1963 return;
1964
1965 // Find the superclass of this class.
1966 CDecl = CDecl->getSuperClass();
1967 if (!CDecl)
1968 return;
1969
1970 if (CurMethod->isInstanceMethod()) {
1971 // We are inside an instance method, which means that the message
1972 // send [super ...] is actually calling an instance method on the
1973 // current object. Build the super expression and handle this like
1974 // an instance method.
1975 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
1976 SuperTy = Context.getObjCObjectPointerType(SuperTy);
1977 OwningExprResult Super
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001978 = Owned(new (Context) ObjCSuperExpr(FNameLoc, SuperTy));
Douglas Gregord3c68542009-11-19 01:08:35 +00001979 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
1980 SelIdents, NumSelIdents);
Douglas Gregor24a069f2009-11-17 17:59:40 +00001981 }
1982
1983 // Okay, we're calling a factory method in our superclass.
1984 }
1985 }
1986
1987 // If the given name refers to an interface type, retrieve the
1988 // corresponding declaration.
1989 if (!CDecl)
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001990 if (TypeTy *Ty = getTypeName(*FName, FNameLoc, S, 0, false)) {
Douglas Gregor24a069f2009-11-17 17:59:40 +00001991 QualType T = GetTypeFromParser(Ty, 0);
1992 if (!T.isNull())
1993 if (const ObjCInterfaceType *Interface = T->getAs<ObjCInterfaceType>())
1994 CDecl = Interface->getDecl();
1995 }
1996
1997 if (!CDecl && FName->isStr("super")) {
1998 // "super" may be the name of a variable, in which case we are
1999 // probably calling an instance method.
John McCallf7a1a742009-11-24 19:00:30 +00002000 CXXScopeSpec SS;
2001 UnqualifiedId id;
2002 id.setIdentifier(FName, FNameLoc);
2003 OwningExprResult Super = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregord3c68542009-11-19 01:08:35 +00002004 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
2005 SelIdents, NumSelIdents);
Douglas Gregor24a069f2009-11-17 17:59:40 +00002006 }
2007
Douglas Gregor36ecb042009-11-17 23:22:23 +00002008 // Add all of the factory methods in this Objective-C class, its protocols,
2009 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00002010 ResultBuilder Results(*this);
2011 Results.EnterNewScope();
Douglas Gregor4ad96852009-11-19 07:41:15 +00002012 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
2013 Results);
Steve Naroffc4df6d22009-11-07 02:08:14 +00002014 Results.ExitScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00002015
Steve Naroffc4df6d22009-11-07 02:08:14 +00002016 // This also suppresses remaining diagnostics.
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002017 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00002018}
2019
Douglas Gregord3c68542009-11-19 01:08:35 +00002020void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
2021 IdentifierInfo **SelIdents,
2022 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00002023 typedef CodeCompleteConsumer::Result Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00002024
2025 Expr *RecExpr = static_cast<Expr *>(Receiver);
2026 QualType RecType = RecExpr->getType();
2027
Douglas Gregor36ecb042009-11-17 23:22:23 +00002028 // If necessary, apply function/array conversion to the receiver.
2029 // C99 6.7.5.3p[7,8].
2030 DefaultFunctionArrayConversion(RecExpr);
2031 QualType ReceiverType = RecExpr->getType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00002032
Douglas Gregor36ecb042009-11-17 23:22:23 +00002033 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType()) {
2034 // FIXME: We're messaging 'id'. Do we actually want to look up every method
2035 // in the universe?
2036 return;
2037 }
2038
Douglas Gregor36ecb042009-11-17 23:22:23 +00002039 // Build the set of methods we can see.
2040 ResultBuilder Results(*this);
2041 Results.EnterNewScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00002042
Douglas Gregorf74a4192009-11-18 00:06:18 +00002043 // Handle messages to Class. This really isn't a message to an instance
2044 // method, so we treat it the same way we would treat a message send to a
2045 // class method.
2046 if (ReceiverType->isObjCClassType() ||
2047 ReceiverType->isObjCQualifiedClassType()) {
2048 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
2049 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00002050 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
2051 CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00002052 }
2053 }
2054 // Handle messages to a qualified ID ("id<foo>").
2055 else if (const ObjCObjectPointerType *QualID
2056 = ReceiverType->getAsObjCQualifiedIdType()) {
2057 // Search protocols for instance methods.
2058 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
2059 E = QualID->qual_end();
2060 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002061 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
2062 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00002063 }
2064 // Handle messages to a pointer to interface type.
2065 else if (const ObjCObjectPointerType *IFacePtr
2066 = ReceiverType->getAsObjCInterfacePointerType()) {
2067 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00002068 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
2069 NumSelIdents, CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00002070
2071 // Search protocols for instance methods.
2072 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
2073 E = IFacePtr->qual_end();
2074 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002075 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
2076 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00002077 }
2078
Steve Naroffc4df6d22009-11-07 02:08:14 +00002079 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002080 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00002081}
Douglas Gregor55385fe2009-11-18 04:19:12 +00002082
2083/// \brief Add all of the protocol declarations that we find in the given
2084/// (translation unit) context.
2085static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00002086 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00002087 ResultBuilder &Results) {
2088 typedef CodeCompleteConsumer::Result Result;
2089
2090 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
2091 DEnd = Ctx->decls_end();
2092 D != DEnd; ++D) {
2093 // Record any protocols we find.
2094 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00002095 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
2096 Results.MaybeAddResult(Result(Proto, 0), CurContext);
Douglas Gregor55385fe2009-11-18 04:19:12 +00002097
2098 // Record any forward-declared protocols we find.
2099 if (ObjCForwardProtocolDecl *Forward
2100 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2101 for (ObjCForwardProtocolDecl::protocol_iterator
2102 P = Forward->protocol_begin(),
2103 PEnd = Forward->protocol_end();
2104 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00002105 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
2106 Results.MaybeAddResult(Result(*P, 0), CurContext);
Douglas Gregor55385fe2009-11-18 04:19:12 +00002107 }
2108 }
2109}
2110
2111void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
2112 unsigned NumProtocols) {
2113 ResultBuilder Results(*this);
2114 Results.EnterNewScope();
2115
2116 // Tell the result set to ignore all of the protocols we have
2117 // already seen.
2118 for (unsigned I = 0; I != NumProtocols; ++I)
2119 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first))
2120 Results.Ignore(Protocol);
2121
2122 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00002123 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
2124 Results);
2125
2126 Results.ExitScope();
2127 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2128}
2129
2130void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
2131 ResultBuilder Results(*this);
2132 Results.EnterNewScope();
2133
2134 // Add all protocols.
2135 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
2136 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00002137
2138 Results.ExitScope();
2139 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2140}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00002141
2142/// \brief Add all of the Objective-C interface declarations that we find in
2143/// the given (translation unit) context.
2144static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
2145 bool OnlyForwardDeclarations,
2146 bool OnlyUnimplemented,
2147 ResultBuilder &Results) {
2148 typedef CodeCompleteConsumer::Result Result;
2149
2150 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
2151 DEnd = Ctx->decls_end();
2152 D != DEnd; ++D) {
2153 // Record any interfaces we find.
2154 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
2155 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
2156 (!OnlyUnimplemented || !Class->getImplementation()))
2157 Results.MaybeAddResult(Result(Class, 0), CurContext);
2158
2159 // Record any forward-declared interfaces we find.
2160 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
2161 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
2162 C != CEnd; ++C)
2163 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
2164 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
2165 Results.MaybeAddResult(Result(C->getInterface(), 0), CurContext);
2166 }
2167 }
2168}
2169
2170void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
2171 ResultBuilder Results(*this);
2172 Results.EnterNewScope();
2173
2174 // Add all classes.
2175 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
2176 false, Results);
2177
2178 Results.ExitScope();
2179 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2180}
2181
2182void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName) {
2183 ResultBuilder Results(*this);
2184 Results.EnterNewScope();
2185
2186 // Make sure that we ignore the class we're currently defining.
2187 NamedDecl *CurClass
2188 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00002189 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00002190 Results.Ignore(CurClass);
2191
2192 // Add all classes.
2193 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
2194 false, Results);
2195
2196 Results.ExitScope();
2197 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2198}
2199
2200void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
2201 ResultBuilder Results(*this);
2202 Results.EnterNewScope();
2203
2204 // Add all unimplemented classes.
2205 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
2206 true, Results);
2207
2208 Results.ExitScope();
2209 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2210}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00002211
2212void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
2213 IdentifierInfo *ClassName) {
2214 typedef CodeCompleteConsumer::Result Result;
2215
2216 ResultBuilder Results(*this);
2217
2218 // Ignore any categories we find that have already been implemented by this
2219 // interface.
2220 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
2221 NamedDecl *CurClass
2222 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
2223 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
2224 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
2225 Category = Category->getNextClassCategory())
2226 CategoryNames.insert(Category->getIdentifier());
2227
2228 // Add all of the categories we know about.
2229 Results.EnterNewScope();
2230 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
2231 for (DeclContext::decl_iterator D = TU->decls_begin(),
2232 DEnd = TU->decls_end();
2233 D != DEnd; ++D)
2234 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
2235 if (CategoryNames.insert(Category->getIdentifier()))
2236 Results.MaybeAddResult(Result(Category, 0), CurContext);
2237 Results.ExitScope();
2238
2239 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2240}
2241
2242void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
2243 IdentifierInfo *ClassName) {
2244 typedef CodeCompleteConsumer::Result Result;
2245
2246 // Find the corresponding interface. If we couldn't find the interface, the
2247 // program itself is ill-formed. However, we'll try to be helpful still by
2248 // providing the list of all of the categories we know about.
2249 NamedDecl *CurClass
2250 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
2251 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
2252 if (!Class)
2253 return CodeCompleteObjCInterfaceCategory(S, ClassName);
2254
2255 ResultBuilder Results(*this);
2256
2257 // Add all of the categories that have have corresponding interface
2258 // declarations in this class and any of its superclasses, except for
2259 // already-implemented categories in the class itself.
2260 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
2261 Results.EnterNewScope();
2262 bool IgnoreImplemented = true;
2263 while (Class) {
2264 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
2265 Category = Category->getNextClassCategory())
2266 if ((!IgnoreImplemented || !Category->getImplementation()) &&
2267 CategoryNames.insert(Category->getIdentifier()))
2268 Results.MaybeAddResult(Result(Category, 0), CurContext);
2269
2270 Class = Class->getSuperClass();
2271 IgnoreImplemented = false;
2272 }
2273 Results.ExitScope();
2274
2275 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2276}
Douglas Gregor322328b2009-11-18 22:32:06 +00002277
Douglas Gregor424b2a52009-11-18 22:56:13 +00002278void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
Douglas Gregor322328b2009-11-18 22:32:06 +00002279 typedef CodeCompleteConsumer::Result Result;
2280 ResultBuilder Results(*this);
2281
2282 // Figure out where this @synthesize lives.
2283 ObjCContainerDecl *Container
2284 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
2285 if (!Container ||
2286 (!isa<ObjCImplementationDecl>(Container) &&
2287 !isa<ObjCCategoryImplDecl>(Container)))
2288 return;
2289
2290 // Ignore any properties that have already been implemented.
2291 for (DeclContext::decl_iterator D = Container->decls_begin(),
2292 DEnd = Container->decls_end();
2293 D != DEnd; ++D)
2294 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
2295 Results.Ignore(PropertyImpl->getPropertyDecl());
2296
2297 // Add any properties that we find.
2298 Results.EnterNewScope();
2299 if (ObjCImplementationDecl *ClassImpl
2300 = dyn_cast<ObjCImplementationDecl>(Container))
2301 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
2302 Results);
2303 else
2304 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
2305 false, CurContext, Results);
2306 Results.ExitScope();
2307
2308 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2309}
2310
2311void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
2312 IdentifierInfo *PropertyName,
2313 DeclPtrTy ObjCImpDecl) {
2314 typedef CodeCompleteConsumer::Result Result;
2315 ResultBuilder Results(*this);
2316
2317 // Figure out where this @synthesize lives.
2318 ObjCContainerDecl *Container
2319 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
2320 if (!Container ||
2321 (!isa<ObjCImplementationDecl>(Container) &&
2322 !isa<ObjCCategoryImplDecl>(Container)))
2323 return;
2324
2325 // Figure out which interface we're looking into.
2326 ObjCInterfaceDecl *Class = 0;
2327 if (ObjCImplementationDecl *ClassImpl
2328 = dyn_cast<ObjCImplementationDecl>(Container))
2329 Class = ClassImpl->getClassInterface();
2330 else
2331 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
2332 ->getClassInterface();
2333
2334 // Add all of the instance variables in this class and its superclasses.
2335 Results.EnterNewScope();
2336 for(; Class; Class = Class->getSuperClass()) {
2337 // FIXME: We could screen the type of each ivar for compatibility with
2338 // the property, but is that being too paternal?
2339 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
2340 IVarEnd = Class->ivar_end();
2341 IVar != IVarEnd; ++IVar)
2342 Results.MaybeAddResult(Result(*IVar, 0), CurContext);
2343 }
2344 Results.ExitScope();
2345
2346 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2347}