blob: be1ddddd69953b51a3d02984a29faf2f54ac1c3f [file] [log] [blame]
Douglas Gregor81b747b2009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
13#include "Sema.h"
14#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000015#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000016#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000017#include "clang/Lex/MacroInfo.h"
18#include "clang/Lex/Preprocessor.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000019#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000020#include "llvm/ADT/StringExtras.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000021#include <list>
22#include <map>
23#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000024
25using namespace clang;
26
Douglas Gregor86d9a522009-09-21 16:56:56 +000027namespace {
28 /// \brief A container of code-completion results.
29 class ResultBuilder {
30 public:
31 /// \brief The type of a name-lookup filter, which can be provided to the
32 /// name-lookup routines to specify which declarations should be included in
33 /// the result set (when it returns true) and which declarations should be
34 /// filtered out (returns false).
35 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
36
37 typedef CodeCompleteConsumer::Result Result;
38
39 private:
40 /// \brief The actual results we have found.
41 std::vector<Result> Results;
42
43 /// \brief A record of all of the declarations we have found and placed
44 /// into the result set, used to ensure that no declaration ever gets into
45 /// the result set twice.
46 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
47
48 /// \brief A mapping from declaration names to the declarations that have
49 /// this name within a particular scope and their index within the list of
50 /// results.
51 typedef std::multimap<DeclarationName,
52 std::pair<NamedDecl *, unsigned> > ShadowMap;
53
54 /// \brief The semantic analysis object for which results are being
55 /// produced.
56 Sema &SemaRef;
57
58 /// \brief If non-NULL, a filter function used to remove any code-completion
59 /// results that are not desirable.
60 LookupFilter Filter;
61
62 /// \brief A list of shadow maps, which is used to model name hiding at
63 /// different levels of, e.g., the inheritance hierarchy.
64 std::list<ShadowMap> ShadowMaps;
65
66 public:
67 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
68 : SemaRef(SemaRef), Filter(Filter) { }
69
70 /// \brief Set the filter used for code-completion results.
71 void setFilter(LookupFilter Filter) {
72 this->Filter = Filter;
73 }
74
75 typedef std::vector<Result>::iterator iterator;
76 iterator begin() { return Results.begin(); }
77 iterator end() { return Results.end(); }
78
79 Result *data() { return Results.empty()? 0 : &Results.front(); }
80 unsigned size() const { return Results.size(); }
81 bool empty() const { return Results.empty(); }
82
83 /// \brief Add a new result to this result set (if it isn't already in one
84 /// of the shadow maps), or replace an existing result (for, e.g., a
85 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +000086 ///
87 /// \param R the result to add (if it is unique).
88 ///
89 /// \param R the context in which this result will be named.
90 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +000091
92 /// \brief Enter into a new scope.
93 void EnterNewScope();
94
95 /// \brief Exit from the current scope.
96 void ExitScope();
97
Douglas Gregor55385fe2009-11-18 04:19:12 +000098 /// \brief Ignore this declaration, if it is seen again.
99 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
100
Douglas Gregor86d9a522009-09-21 16:56:56 +0000101 /// \name Name lookup predicates
102 ///
103 /// These predicates can be passed to the name lookup functions to filter the
104 /// results of name lookup. All of the predicates have the same type, so that
105 ///
106 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000107 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000108 bool IsNestedNameSpecifier(NamedDecl *ND) const;
109 bool IsEnum(NamedDecl *ND) const;
110 bool IsClassOrStruct(NamedDecl *ND) const;
111 bool IsUnion(NamedDecl *ND) const;
112 bool IsNamespace(NamedDecl *ND) const;
113 bool IsNamespaceOrAlias(NamedDecl *ND) const;
114 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000115 bool IsMember(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000116 //@}
117 };
118}
119
120/// \brief Determines whether the given hidden result could be found with
121/// some extra work, e.g., by qualifying the name.
122///
123/// \param Hidden the declaration that is hidden by the currenly \p Visible
124/// declaration.
125///
126/// \param Visible the declaration with the same name that is already visible.
127///
128/// \returns true if the hidden result can be found by some mechanism,
129/// false otherwise.
130static bool canHiddenResultBeFound(const LangOptions &LangOpts,
131 NamedDecl *Hidden, NamedDecl *Visible) {
132 // In C, there is no way to refer to a hidden name.
133 if (!LangOpts.CPlusPlus)
134 return false;
135
136 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
137
138 // There is no way to qualify a name declared in a function or method.
139 if (HiddenCtx->isFunctionOrMethod())
140 return false;
141
Douglas Gregor86d9a522009-09-21 16:56:56 +0000142 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
143}
144
Douglas Gregor456c4a12009-09-21 20:12:40 +0000145/// \brief Compute the qualification required to get from the current context
146/// (\p CurContext) to the target context (\p TargetContext).
147///
148/// \param Context the AST context in which the qualification will be used.
149///
150/// \param CurContext the context where an entity is being named, which is
151/// typically based on the current scope.
152///
153/// \param TargetContext the context in which the named entity actually
154/// resides.
155///
156/// \returns a nested name specifier that refers into the target context, or
157/// NULL if no qualification is needed.
158static NestedNameSpecifier *
159getRequiredQualification(ASTContext &Context,
160 DeclContext *CurContext,
161 DeclContext *TargetContext) {
162 llvm::SmallVector<DeclContext *, 4> TargetParents;
163
164 for (DeclContext *CommonAncestor = TargetContext;
165 CommonAncestor && !CommonAncestor->Encloses(CurContext);
166 CommonAncestor = CommonAncestor->getLookupParent()) {
167 if (CommonAncestor->isTransparentContext() ||
168 CommonAncestor->isFunctionOrMethod())
169 continue;
170
171 TargetParents.push_back(CommonAncestor);
172 }
173
174 NestedNameSpecifier *Result = 0;
175 while (!TargetParents.empty()) {
176 DeclContext *Parent = TargetParents.back();
177 TargetParents.pop_back();
178
179 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
180 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
181 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
182 Result = NestedNameSpecifier::Create(Context, Result,
183 false,
184 Context.getTypeDeclType(TD).getTypePtr());
185 else
186 assert(Parent->isTranslationUnit());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000187 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000188 return Result;
189}
190
191void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
Douglas Gregor8e0a0e42009-09-22 23:31:26 +0000192 assert(!ShadowMaps.empty() && "Must enter into a results scope");
193
Douglas Gregor86d9a522009-09-21 16:56:56 +0000194 if (R.Kind != Result::RK_Declaration) {
195 // For non-declaration results, just add the result.
196 Results.push_back(R);
197 return;
198 }
Douglas Gregorf52cede2009-10-09 22:16:47 +0000199
200 // Skip unnamed entities.
201 if (!R.Declaration->getDeclName())
202 return;
203
Douglas Gregor86d9a522009-09-21 16:56:56 +0000204 // Look through using declarations.
John McCall9488ea12009-11-17 05:59:44 +0000205 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration))
Douglas Gregor0563c262009-09-22 23:15:58 +0000206 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
207 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000208
209 // Handle each declaration in an overload set separately.
210 if (OverloadedFunctionDecl *Ovl
211 = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) {
212 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
213 FEnd = Ovl->function_end();
214 F != FEnd; ++F)
Douglas Gregor456c4a12009-09-21 20:12:40 +0000215 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000216
217 return;
218 }
219
220 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
221 unsigned IDNS = CanonDecl->getIdentifierNamespace();
222
223 // Friend declarations and declarations introduced due to friends are never
224 // added as results.
225 if (isa<FriendDecl>(CanonDecl) ||
226 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
227 return;
228
229 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
230 // __va_list_tag is a freak of nature. Find it and skip it.
231 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
232 return;
233
Douglas Gregorf52cede2009-10-09 22:16:47 +0000234 // Filter out names reserved for the implementation (C99 7.1.3,
235 // C++ [lib.global.names]). Users don't need to see those.
Daniel Dunbare013d682009-10-18 20:26:12 +0000236 //
237 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000238 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000239 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000240 if (Name[0] == '_' &&
241 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
242 return;
243 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000244 }
245
246 // C++ constructors are never found by name lookup.
247 if (isa<CXXConstructorDecl>(CanonDecl))
248 return;
249
250 // Filter out any unwanted results.
251 if (Filter && !(this->*Filter)(R.Declaration))
252 return;
253
254 ShadowMap &SMap = ShadowMaps.back();
255 ShadowMap::iterator I, IEnd;
256 for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
257 I != IEnd; ++I) {
258 NamedDecl *ND = I->second.first;
259 unsigned Index = I->second.second;
260 if (ND->getCanonicalDecl() == CanonDecl) {
261 // This is a redeclaration. Always pick the newer declaration.
262 I->second.first = R.Declaration;
263 Results[Index].Declaration = R.Declaration;
264
265 // Pick the best rank of the two.
266 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
267
268 // We're done.
269 return;
270 }
271 }
272
273 // This is a new declaration in this scope. However, check whether this
274 // declaration name is hidden by a similarly-named declaration in an outer
275 // scope.
276 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
277 --SMEnd;
278 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
279 for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
280 I != IEnd; ++I) {
281 // A tag declaration does not hide a non-tag declaration.
282 if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
283 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
284 Decl::IDNS_ObjCProtocol)))
285 continue;
286
287 // Protocols are in distinct namespaces from everything else.
288 if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
289 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
290 I->second.first->getIdentifierNamespace() != IDNS)
291 continue;
292
293 // The newly-added result is hidden by an entry in the shadow map.
294 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
295 I->second.first)) {
296 // Note that this result was hidden.
297 R.Hidden = true;
Douglas Gregor0563c262009-09-22 23:15:58 +0000298 R.QualifierIsInformative = false;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000299
300 if (!R.Qualifier)
301 R.Qualifier = getRequiredQualification(SemaRef.Context,
302 CurContext,
303 R.Declaration->getDeclContext());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000304 } else {
305 // This result was hidden and cannot be found; don't bother adding
306 // it.
307 return;
308 }
309
310 break;
311 }
312 }
313
314 // Make sure that any given declaration only shows up in the result set once.
315 if (!AllDeclsFound.insert(CanonDecl))
316 return;
317
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000318 // If the filter is for nested-name-specifiers, then this result starts a
319 // nested-name-specifier.
320 if ((Filter == &ResultBuilder::IsNestedNameSpecifier) ||
321 (Filter == &ResultBuilder::IsMember &&
322 isa<CXXRecordDecl>(R.Declaration) &&
323 cast<CXXRecordDecl>(R.Declaration)->isInjectedClassName()))
324 R.StartsNestedNameSpecifier = true;
325
Douglas Gregor0563c262009-09-22 23:15:58 +0000326 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000327 if (R.QualifierIsInformative && !R.Qualifier &&
328 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000329 DeclContext *Ctx = R.Declaration->getDeclContext();
330 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
331 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
332 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
333 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
334 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
335 else
336 R.QualifierIsInformative = false;
337 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000338
Douglas Gregor86d9a522009-09-21 16:56:56 +0000339 // Insert this result into the set of results and into the current shadow
340 // map.
341 SMap.insert(std::make_pair(R.Declaration->getDeclName(),
342 std::make_pair(R.Declaration, Results.size())));
343 Results.push_back(R);
344}
345
346/// \brief Enter into a new scope.
347void ResultBuilder::EnterNewScope() {
348 ShadowMaps.push_back(ShadowMap());
349}
350
351/// \brief Exit from the current scope.
352void ResultBuilder::ExitScope() {
353 ShadowMaps.pop_back();
354}
355
Douglas Gregor791215b2009-09-21 20:51:25 +0000356/// \brief Determines whether this given declaration will be found by
357/// ordinary name lookup.
358bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
359 unsigned IDNS = Decl::IDNS_Ordinary;
360 if (SemaRef.getLangOptions().CPlusPlus)
361 IDNS |= Decl::IDNS_Tag;
362
363 return ND->getIdentifierNamespace() & IDNS;
364}
365
Douglas Gregor86d9a522009-09-21 16:56:56 +0000366/// \brief Determines whether the given declaration is suitable as the
367/// start of a C++ nested-name-specifier, e.g., a class or namespace.
368bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
369 // Allow us to find class templates, too.
370 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
371 ND = ClassTemplate->getTemplatedDecl();
372
373 return SemaRef.isAcceptableNestedNameSpecifier(ND);
374}
375
376/// \brief Determines whether the given declaration is an enumeration.
377bool ResultBuilder::IsEnum(NamedDecl *ND) const {
378 return isa<EnumDecl>(ND);
379}
380
381/// \brief Determines whether the given declaration is a class or struct.
382bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
383 // Allow us to find class templates, too.
384 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
385 ND = ClassTemplate->getTemplatedDecl();
386
387 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
388 return RD->getTagKind() == TagDecl::TK_class ||
389 RD->getTagKind() == TagDecl::TK_struct;
390
391 return false;
392}
393
394/// \brief Determines whether the given declaration is a union.
395bool ResultBuilder::IsUnion(NamedDecl *ND) const {
396 // Allow us to find class templates, too.
397 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
398 ND = ClassTemplate->getTemplatedDecl();
399
400 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
401 return RD->getTagKind() == TagDecl::TK_union;
402
403 return false;
404}
405
406/// \brief Determines whether the given declaration is a namespace.
407bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
408 return isa<NamespaceDecl>(ND);
409}
410
411/// \brief Determines whether the given declaration is a namespace or
412/// namespace alias.
413bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
414 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
415}
416
417/// \brief Brief determines whether the given declaration is a namespace or
418/// namespace alias.
419bool ResultBuilder::IsType(NamedDecl *ND) const {
420 return isa<TypeDecl>(ND);
421}
422
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000423/// \brief Since every declaration found within a class is a member that we
424/// care about, always returns true. This predicate exists mostly to
425/// communicate to the result builder that we are performing a lookup for
426/// member access.
427bool ResultBuilder::IsMember(NamedDecl *ND) const {
428 return true;
429}
430
Douglas Gregor86d9a522009-09-21 16:56:56 +0000431// Find the next outer declaration context corresponding to this scope.
432static DeclContext *findOuterContext(Scope *S) {
433 for (S = S->getParent(); S; S = S->getParent())
434 if (S->getEntity())
435 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
436
437 return 0;
438}
439
440/// \brief Collect the results of searching for members within the given
441/// declaration context.
442///
443/// \param Ctx the declaration context from which we will gather results.
444///
Douglas Gregor0563c262009-09-22 23:15:58 +0000445/// \param Rank the rank given to results in this declaration context.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000446///
447/// \param Visited the set of declaration contexts that have already been
448/// visited. Declaration contexts will only be visited once.
449///
450/// \param Results the result set that will be extended with any results
451/// found within this declaration context (and, for a C++ class, its bases).
452///
Douglas Gregor0563c262009-09-22 23:15:58 +0000453/// \param InBaseClass whether we are in a base class.
454///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000455/// \returns the next higher rank value, after considering all of the
456/// names within this declaration context.
457static unsigned CollectMemberLookupResults(DeclContext *Ctx,
Douglas Gregor0563c262009-09-22 23:15:58 +0000458 unsigned Rank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000459 DeclContext *CurContext,
460 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor0563c262009-09-22 23:15:58 +0000461 ResultBuilder &Results,
462 bool InBaseClass = false) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000463 // Make sure we don't visit the same context twice.
464 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor0563c262009-09-22 23:15:58 +0000465 return Rank;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000466
467 // Enumerate all of the results in this context.
Douglas Gregor0563c262009-09-22 23:15:58 +0000468 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000469 Results.EnterNewScope();
470 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
471 CurCtx = CurCtx->getNextContext()) {
472 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregorff4393c2009-11-09 21:35:27 +0000473 DEnd = CurCtx->decls_end();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000474 D != DEnd; ++D) {
475 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor0563c262009-09-22 23:15:58 +0000476 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregorff4393c2009-11-09 21:35:27 +0000477
478 // Visit transparent contexts inside this context.
479 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
480 if (InnerCtx->isTransparentContext())
481 CollectMemberLookupResults(InnerCtx, Rank, CurContext, Visited,
482 Results, InBaseClass);
483 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000484 }
485 }
486
487 // Traverse the contexts of inherited classes.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000488 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
489 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
Douglas Gregorff4393c2009-11-09 21:35:27 +0000490 BEnd = Record->bases_end();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000491 B != BEnd; ++B) {
492 QualType BaseType = B->getType();
493
494 // Don't look into dependent bases, because name lookup can't look
495 // there anyway.
496 if (BaseType->isDependentType())
497 continue;
498
499 const RecordType *Record = BaseType->getAs<RecordType>();
500 if (!Record)
501 continue;
502
503 // FIXME: It would be nice to be able to determine whether referencing
504 // a particular member would be ambiguous. For example, given
505 //
506 // struct A { int member; };
507 // struct B { int member; };
508 // struct C : A, B { };
509 //
510 // void f(C *c) { c->### }
511 // accessing 'member' would result in an ambiguity. However, code
512 // completion could be smart enough to qualify the member with the
513 // base class, e.g.,
514 //
515 // c->B::member
516 //
517 // or
518 //
519 // c->A::member
520
521 // Collect results from this base class (and its bases).
Douglas Gregor0563c262009-09-22 23:15:58 +0000522 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
523 Results, /*InBaseClass=*/true);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000524 }
525 }
526
527 // FIXME: Look into base classes in Objective-C!
528
529 Results.ExitScope();
Douglas Gregor0563c262009-09-22 23:15:58 +0000530 return Rank + 1;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000531}
532
533/// \brief Collect the results of searching for members within the given
534/// declaration context.
535///
536/// \param Ctx the declaration context from which we will gather results.
537///
538/// \param InitialRank the initial rank given to results in this declaration
539/// context. Larger rank values will be used for, e.g., members found in
540/// base classes.
541///
542/// \param Results the result set that will be extended with any results
543/// found within this declaration context (and, for a C++ class, its bases).
544///
545/// \returns the next higher rank value, after considering all of the
546/// names within this declaration context.
547static unsigned CollectMemberLookupResults(DeclContext *Ctx,
548 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000549 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000550 ResultBuilder &Results) {
551 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000552 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
553 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000554}
555
556/// \brief Collect the results of searching for declarations within the given
557/// scope and its parent scopes.
558///
559/// \param S the scope in which we will start looking for declarations.
560///
561/// \param InitialRank the initial rank given to results in this scope.
562/// Larger rank values will be used for results found in parent scopes.
563///
Douglas Gregor456c4a12009-09-21 20:12:40 +0000564/// \param CurContext the context from which lookup results will be found.
565///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000566/// \param Results the builder object that will receive each result.
567static unsigned CollectLookupResults(Scope *S,
568 TranslationUnitDecl *TranslationUnit,
569 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000570 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000571 ResultBuilder &Results) {
572 if (!S)
573 return InitialRank;
574
575 // FIXME: Using directives!
576
577 unsigned NextRank = InitialRank;
578 Results.EnterNewScope();
579 if (S->getEntity() &&
580 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
581 // Look into this scope's declaration context, along with any of its
582 // parent lookup contexts (e.g., enclosing classes), up to the point
583 // where we hit the context stored in the next outer scope.
584 DeclContext *Ctx = (DeclContext *)S->getEntity();
585 DeclContext *OuterCtx = findOuterContext(S);
586
587 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
588 Ctx = Ctx->getLookupParent()) {
589 if (Ctx->isFunctionOrMethod())
590 continue;
591
Douglas Gregor456c4a12009-09-21 20:12:40 +0000592 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
593 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000594 }
595 } else if (!S->getParent()) {
596 // Look into the translation unit scope. We walk through the translation
597 // unit's declaration context, because the Scope itself won't have all of
598 // the declarations if we loaded a precompiled header.
599 // FIXME: We would like the translation unit's Scope object to point to the
600 // translation unit, so we don't need this special "if" branch. However,
601 // doing so would force the normal C++ name-lookup code to look into the
602 // translation unit decl when the IdentifierInfo chains would suffice.
603 // Once we fix that problem (which is part of a more general "don't look
604 // in DeclContexts unless we have to" optimization), we can eliminate the
605 // TranslationUnit parameter entirely.
606 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000607 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000608 } else {
609 // Walk through the declarations in this Scope.
610 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
611 D != DEnd; ++D) {
612 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
Douglas Gregor456c4a12009-09-21 20:12:40 +0000613 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
614 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000615 }
616
617 NextRank = NextRank + 1;
618 }
619
620 // Lookup names in the parent scope.
621 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000622 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000623 Results.ExitScope();
624
625 return NextRank;
626}
627
628/// \brief Add type specifiers for the current language as keyword results.
629static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
630 ResultBuilder &Results) {
631 typedef CodeCompleteConsumer::Result Result;
632 Results.MaybeAddResult(Result("short", Rank));
633 Results.MaybeAddResult(Result("long", Rank));
634 Results.MaybeAddResult(Result("signed", Rank));
635 Results.MaybeAddResult(Result("unsigned", Rank));
636 Results.MaybeAddResult(Result("void", Rank));
637 Results.MaybeAddResult(Result("char", Rank));
638 Results.MaybeAddResult(Result("int", Rank));
639 Results.MaybeAddResult(Result("float", Rank));
640 Results.MaybeAddResult(Result("double", Rank));
641 Results.MaybeAddResult(Result("enum", Rank));
642 Results.MaybeAddResult(Result("struct", Rank));
643 Results.MaybeAddResult(Result("union", Rank));
644
645 if (LangOpts.C99) {
646 // C99-specific
647 Results.MaybeAddResult(Result("_Complex", Rank));
648 Results.MaybeAddResult(Result("_Imaginary", Rank));
649 Results.MaybeAddResult(Result("_Bool", Rank));
650 }
651
652 if (LangOpts.CPlusPlus) {
653 // C++-specific
654 Results.MaybeAddResult(Result("bool", Rank));
655 Results.MaybeAddResult(Result("class", Rank));
656 Results.MaybeAddResult(Result("typename", Rank));
657 Results.MaybeAddResult(Result("wchar_t", Rank));
658
659 if (LangOpts.CPlusPlus0x) {
660 Results.MaybeAddResult(Result("char16_t", Rank));
661 Results.MaybeAddResult(Result("char32_t", Rank));
662 Results.MaybeAddResult(Result("decltype", Rank));
663 }
664 }
665
666 // GNU extensions
667 if (LangOpts.GNUMode) {
668 // FIXME: Enable when we actually support decimal floating point.
669 // Results.MaybeAddResult(Result("_Decimal32", Rank));
670 // Results.MaybeAddResult(Result("_Decimal64", Rank));
671 // Results.MaybeAddResult(Result("_Decimal128", Rank));
672 Results.MaybeAddResult(Result("typeof", Rank));
673 }
674}
675
676/// \brief Add function parameter chunks to the given code completion string.
677static void AddFunctionParameterChunks(ASTContext &Context,
678 FunctionDecl *Function,
679 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000680 typedef CodeCompletionString::Chunk Chunk;
681
Douglas Gregor86d9a522009-09-21 16:56:56 +0000682 CodeCompletionString *CCStr = Result;
683
684 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
685 ParmVarDecl *Param = Function->getParamDecl(P);
686
687 if (Param->hasDefaultArg()) {
688 // When we see an optional default argument, put that argument and
689 // the remaining default arguments into a new, optional string.
690 CodeCompletionString *Opt = new CodeCompletionString;
691 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
692 CCStr = Opt;
693 }
694
695 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000696 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000697
698 // Format the placeholder string.
699 std::string PlaceholderStr;
700 if (Param->getIdentifier())
701 PlaceholderStr = Param->getIdentifier()->getName();
702
703 Param->getType().getAsStringInternal(PlaceholderStr,
704 Context.PrintingPolicy);
705
706 // Add the placeholder string.
707 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
708 }
Douglas Gregorb3d45252009-09-22 21:42:17 +0000709
710 if (const FunctionProtoType *Proto
711 = Function->getType()->getAs<FunctionProtoType>())
712 if (Proto->isVariadic())
713 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000714}
715
716/// \brief Add template parameter chunks to the given code completion string.
717static void AddTemplateParameterChunks(ASTContext &Context,
718 TemplateDecl *Template,
719 CodeCompletionString *Result,
720 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000721 typedef CodeCompletionString::Chunk Chunk;
722
Douglas Gregor86d9a522009-09-21 16:56:56 +0000723 CodeCompletionString *CCStr = Result;
724 bool FirstParameter = true;
725
726 TemplateParameterList *Params = Template->getTemplateParameters();
727 TemplateParameterList::iterator PEnd = Params->end();
728 if (MaxParameters)
729 PEnd = Params->begin() + MaxParameters;
730 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
731 bool HasDefaultArg = false;
732 std::string PlaceholderStr;
733 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
734 if (TTP->wasDeclaredWithTypename())
735 PlaceholderStr = "typename";
736 else
737 PlaceholderStr = "class";
738
739 if (TTP->getIdentifier()) {
740 PlaceholderStr += ' ';
741 PlaceholderStr += TTP->getIdentifier()->getName();
742 }
743
744 HasDefaultArg = TTP->hasDefaultArgument();
745 } else if (NonTypeTemplateParmDecl *NTTP
746 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
747 if (NTTP->getIdentifier())
748 PlaceholderStr = NTTP->getIdentifier()->getName();
749 NTTP->getType().getAsStringInternal(PlaceholderStr,
750 Context.PrintingPolicy);
751 HasDefaultArg = NTTP->hasDefaultArgument();
752 } else {
753 assert(isa<TemplateTemplateParmDecl>(*P));
754 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
755
756 // Since putting the template argument list into the placeholder would
757 // be very, very long, we just use an abbreviation.
758 PlaceholderStr = "template<...> class";
759 if (TTP->getIdentifier()) {
760 PlaceholderStr += ' ';
761 PlaceholderStr += TTP->getIdentifier()->getName();
762 }
763
764 HasDefaultArg = TTP->hasDefaultArgument();
765 }
766
767 if (HasDefaultArg) {
768 // When we see an optional default argument, put that argument and
769 // the remaining default arguments into a new, optional string.
770 CodeCompletionString *Opt = new CodeCompletionString;
771 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
772 CCStr = Opt;
773 }
774
775 if (FirstParameter)
776 FirstParameter = false;
777 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000778 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000779
780 // Add the placeholder string.
781 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
782 }
783}
784
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000785/// \brief Add a qualifier to the given code-completion string, if the
786/// provided nested-name-specifier is non-NULL.
787void AddQualifierToCompletionString(CodeCompletionString *Result,
788 NestedNameSpecifier *Qualifier,
Douglas Gregor0563c262009-09-22 23:15:58 +0000789 bool QualifierIsInformative,
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000790 ASTContext &Context) {
791 if (!Qualifier)
792 return;
793
794 std::string PrintedNNS;
795 {
796 llvm::raw_string_ostream OS(PrintedNNS);
797 Qualifier->print(OS, Context.PrintingPolicy);
798 }
Douglas Gregor0563c262009-09-22 23:15:58 +0000799 if (QualifierIsInformative)
800 Result->AddInformativeChunk(PrintedNNS.c_str());
801 else
802 Result->AddTextChunk(PrintedNNS.c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000803}
804
Douglas Gregor86d9a522009-09-21 16:56:56 +0000805/// \brief If possible, create a new code completion string for the given
806/// result.
807///
808/// \returns Either a new, heap-allocated code completion string describing
809/// how to use this result, or NULL to indicate that the string or name of the
810/// result is all that is needed.
811CodeCompletionString *
812CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000813 typedef CodeCompletionString::Chunk Chunk;
814
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000815 if (Kind == RK_Keyword)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000816 return 0;
817
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000818 if (Kind == RK_Macro) {
819 MacroInfo *MI = S.PP.getMacroInfo(Macro);
820 if (!MI || !MI->isFunctionLike())
821 return 0;
822
823 // Format a function-like macro with placeholders for the arguments.
824 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000825 Result->AddTypedTextChunk(Macro->getName().str().c_str());
826 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000827 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
828 A != AEnd; ++A) {
829 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000830 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000831
832 if (!MI->isVariadic() || A != AEnd - 1) {
833 // Non-variadic argument.
834 Result->AddPlaceholderChunk((*A)->getName().str().c_str());
835 continue;
836 }
837
838 // Variadic argument; cope with the different between GNU and C99
839 // variadic macros, providing a single placeholder for the rest of the
840 // arguments.
841 if ((*A)->isStr("__VA_ARGS__"))
842 Result->AddPlaceholderChunk("...");
843 else {
844 std::string Arg = (*A)->getName();
845 Arg += "...";
846 Result->AddPlaceholderChunk(Arg.c_str());
847 }
848 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000849 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000850 return Result;
851 }
852
853 assert(Kind == RK_Declaration && "Missed a macro kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000854 NamedDecl *ND = Declaration;
855
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000856 if (StartsNestedNameSpecifier) {
857 CodeCompletionString *Result = new CodeCompletionString;
858 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
859 Result->AddTextChunk("::");
860 return Result;
861 }
862
Douglas Gregor86d9a522009-09-21 16:56:56 +0000863 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
864 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000865 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
866 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000867 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
868 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000869 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000870 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000871 return Result;
872 }
873
874 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
875 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000876 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
877 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000878 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000879 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000880
881 // Figure out which template parameters are deduced (or have default
882 // arguments).
883 llvm::SmallVector<bool, 16> Deduced;
884 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
885 unsigned LastDeducibleArgument;
886 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
887 --LastDeducibleArgument) {
888 if (!Deduced[LastDeducibleArgument - 1]) {
889 // C++0x: Figure out if the template argument has a default. If so,
890 // the user doesn't need to type this argument.
891 // FIXME: We need to abstract template parameters better!
892 bool HasDefaultArg = false;
893 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
894 LastDeducibleArgument - 1);
895 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
896 HasDefaultArg = TTP->hasDefaultArgument();
897 else if (NonTypeTemplateParmDecl *NTTP
898 = dyn_cast<NonTypeTemplateParmDecl>(Param))
899 HasDefaultArg = NTTP->hasDefaultArgument();
900 else {
901 assert(isa<TemplateTemplateParmDecl>(Param));
902 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000903 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000904 }
905
906 if (!HasDefaultArg)
907 break;
908 }
909 }
910
911 if (LastDeducibleArgument) {
912 // Some of the function template arguments cannot be deduced from a
913 // function call, so we introduce an explicit template argument list
914 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000915 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000916 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
917 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000918 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000919 }
920
921 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000922 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000923 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000924 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000925 return Result;
926 }
927
928 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
929 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000930 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
931 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000932 Result->AddTypedTextChunk(Template->getNameAsString().c_str());
933 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000934 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000935 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000936 return Result;
937 }
938
Douglas Gregor9630eb62009-11-17 16:44:22 +0000939 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
940 CodeCompletionString *Result = new CodeCompletionString;
941 Selector Sel = Method->getSelector();
942 if (Sel.isUnarySelector()) {
943 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
944 return Result;
945 }
946
947 Result->AddTypedTextChunk(
948 Sel.getIdentifierInfoForSlot(0)->getName().str() + std::string(":"));
949 unsigned Idx = 0;
950 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
951 PEnd = Method->param_end();
952 P != PEnd; (void)++P, ++Idx) {
953 if (Idx > 0) {
954 std::string Keyword = " ";
955 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
956 Keyword += II->getName().str();
957 Keyword += ":";
958 Result->AddTextChunk(Keyword);
959 }
960
961 std::string Arg;
962 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
963 Arg = "(" + Arg + ")";
964 if (IdentifierInfo *II = (*P)->getIdentifier())
965 Arg += II->getName().str();
966 Result->AddPlaceholderChunk(Arg);
967 }
968
969 return Result;
970 }
971
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000972 if (Qualifier) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000973 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000974 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
975 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000976 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000977 return Result;
978 }
979
Douglas Gregor86d9a522009-09-21 16:56:56 +0000980 return 0;
981}
982
Douglas Gregor86d802e2009-09-23 00:34:09 +0000983CodeCompletionString *
984CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
985 unsigned CurrentArg,
986 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000987 typedef CodeCompletionString::Chunk Chunk;
988
Douglas Gregor86d802e2009-09-23 00:34:09 +0000989 CodeCompletionString *Result = new CodeCompletionString;
990 FunctionDecl *FDecl = getFunction();
991 const FunctionProtoType *Proto
992 = dyn_cast<FunctionProtoType>(getFunctionType());
993 if (!FDecl && !Proto) {
994 // Function without a prototype. Just give the return type and a
995 // highlighted ellipsis.
996 const FunctionType *FT = getFunctionType();
997 Result->AddTextChunk(
998 FT->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000999 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1000 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1001 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001002 return Result;
1003 }
1004
1005 if (FDecl)
1006 Result->AddTextChunk(FDecl->getNameAsString().c_str());
1007 else
1008 Result->AddTextChunk(
1009 Proto->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
1010
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001011 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001012 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
1013 for (unsigned I = 0; I != NumParams; ++I) {
1014 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001015 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001016
1017 std::string ArgString;
1018 QualType ArgType;
1019
1020 if (FDecl) {
1021 ArgString = FDecl->getParamDecl(I)->getNameAsString();
1022 ArgType = FDecl->getParamDecl(I)->getOriginalType();
1023 } else {
1024 ArgType = Proto->getArgType(I);
1025 }
1026
1027 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
1028
1029 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001030 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
1031 ArgString.c_str()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001032 else
1033 Result->AddTextChunk(ArgString.c_str());
1034 }
1035
1036 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001037 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001038 if (CurrentArg < NumParams)
1039 Result->AddTextChunk("...");
1040 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001041 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001042 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001043 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001044
1045 return Result;
1046}
1047
Douglas Gregor86d9a522009-09-21 16:56:56 +00001048namespace {
1049 struct SortCodeCompleteResult {
1050 typedef CodeCompleteConsumer::Result Result;
1051
Douglas Gregor6a684032009-09-28 03:51:44 +00001052 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregor36ecb042009-11-17 23:22:23 +00001053 if (!X.getObjCSelector().isNull() && !Y.getObjCSelector().isNull()) {
1054 // Consider all selector kinds to be equivalent.
1055 } else if (X.getNameKind() != Y.getNameKind())
Douglas Gregor6a684032009-09-28 03:51:44 +00001056 return X.getNameKind() < Y.getNameKind();
1057
1058 return llvm::LowercaseString(X.getAsString())
1059 < llvm::LowercaseString(Y.getAsString());
1060 }
1061
Douglas Gregor86d9a522009-09-21 16:56:56 +00001062 bool operator()(const Result &X, const Result &Y) const {
1063 // Sort first by rank.
1064 if (X.Rank < Y.Rank)
1065 return true;
1066 else if (X.Rank > Y.Rank)
1067 return false;
1068
1069 // Result kinds are ordered by decreasing importance.
1070 if (X.Kind < Y.Kind)
1071 return true;
1072 else if (X.Kind > Y.Kind)
1073 return false;
1074
1075 // Non-hidden names precede hidden names.
1076 if (X.Hidden != Y.Hidden)
1077 return !X.Hidden;
1078
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001079 // Non-nested-name-specifiers precede nested-name-specifiers.
1080 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1081 return !X.StartsNestedNameSpecifier;
1082
Douglas Gregor86d9a522009-09-21 16:56:56 +00001083 // Ordering depends on the kind of result.
1084 switch (X.Kind) {
1085 case Result::RK_Declaration:
1086 // Order based on the declaration names.
Douglas Gregor6a684032009-09-28 03:51:44 +00001087 return isEarlierDeclarationName(X.Declaration->getDeclName(),
1088 Y.Declaration->getDeclName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001089
1090 case Result::RK_Keyword:
Steve Naroff7f511122009-10-08 23:45:10 +00001091 return strcmp(X.Keyword, Y.Keyword) < 0;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001092
1093 case Result::RK_Macro:
1094 return llvm::LowercaseString(X.Macro->getName()) <
1095 llvm::LowercaseString(Y.Macro->getName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001096 }
1097
1098 // Silence GCC warning.
1099 return false;
1100 }
1101 };
1102}
1103
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001104static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1105 ResultBuilder &Results) {
1106 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001107 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1108 MEnd = PP.macro_end();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001109 M != MEnd; ++M)
1110 Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1111 Results.ExitScope();
1112}
1113
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001114static void HandleCodeCompleteResults(Sema *S,
1115 CodeCompleteConsumer *CodeCompleter,
1116 CodeCompleteConsumer::Result *Results,
1117 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00001118 // Sort the results by rank/kind/etc.
1119 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1120
1121 if (CodeCompleter)
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001122 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001123}
1124
Douglas Gregor791215b2009-09-21 20:51:25 +00001125void Sema::CodeCompleteOrdinaryName(Scope *S) {
1126 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001127 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1128 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001129 if (CodeCompleter->includeMacros())
1130 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001131 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00001132}
1133
Douglas Gregor95ac6552009-11-18 01:29:26 +00001134static void AddObjCProperties(ObjCContainerDecl *Container,
1135 DeclContext *CurContext,
1136 ResultBuilder &Results) {
1137 typedef CodeCompleteConsumer::Result Result;
1138
1139 // Add properties in this container.
1140 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
1141 PEnd = Container->prop_end();
1142 P != PEnd;
1143 ++P)
1144 Results.MaybeAddResult(Result(*P, 0), CurContext);
1145
1146 // Add properties in referenced protocols.
1147 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
1148 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
1149 PEnd = Protocol->protocol_end();
1150 P != PEnd; ++P)
1151 AddObjCProperties(*P, CurContext, Results);
1152 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
1153 // Look through categories.
1154 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
1155 Category; Category = Category->getNextClassCategory())
1156 AddObjCProperties(Category, CurContext, Results);
1157
1158 // Look through protocols.
1159 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
1160 E = IFace->protocol_end();
1161 I != E; ++I)
1162 AddObjCProperties(*I, CurContext, Results);
1163
1164 // Look in the superclass.
1165 if (IFace->getSuperClass())
1166 AddObjCProperties(IFace->getSuperClass(), CurContext, Results);
1167 } else if (const ObjCCategoryDecl *Category
1168 = dyn_cast<ObjCCategoryDecl>(Container)) {
1169 // Look through protocols.
1170 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
1171 PEnd = Category->protocol_end();
1172 P != PEnd; ++P)
1173 AddObjCProperties(*P, CurContext, Results);
1174 }
1175}
1176
Douglas Gregor81b747b2009-09-17 21:32:03 +00001177void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1178 SourceLocation OpLoc,
1179 bool IsArrow) {
1180 if (!BaseE || !CodeCompleter)
1181 return;
1182
Douglas Gregor86d9a522009-09-21 16:56:56 +00001183 typedef CodeCompleteConsumer::Result Result;
1184
Douglas Gregor81b747b2009-09-17 21:32:03 +00001185 Expr *Base = static_cast<Expr *>(BaseE);
1186 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001187
1188 if (IsArrow) {
1189 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1190 BaseType = Ptr->getPointeeType();
1191 else if (BaseType->isObjCObjectPointerType())
1192 /*Do nothing*/ ;
1193 else
1194 return;
1195 }
1196
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001197 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001198 unsigned NextRank = 0;
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001199
Douglas Gregor95ac6552009-11-18 01:29:26 +00001200 Results.EnterNewScope();
1201 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
1202 // Access to a C/C++ class, struct, or union.
1203 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1204 Record->getDecl(), Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001205
Douglas Gregor95ac6552009-11-18 01:29:26 +00001206 if (getLangOptions().CPlusPlus) {
1207 if (!Results.empty()) {
1208 // The "template" keyword can follow "->" or "." in the grammar.
1209 // However, we only want to suggest the template keyword if something
1210 // is dependent.
1211 bool IsDependent = BaseType->isDependentType();
1212 if (!IsDependent) {
1213 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1214 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1215 IsDependent = Ctx->isDependentContext();
1216 break;
1217 }
1218 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001219
Douglas Gregor95ac6552009-11-18 01:29:26 +00001220 if (IsDependent)
1221 Results.MaybeAddResult(Result("template", NextRank++));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001222 }
1223
Douglas Gregor95ac6552009-11-18 01:29:26 +00001224 // We could have the start of a nested-name-specifier. Add those
1225 // results as well.
1226 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1227 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
1228 CurContext, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001229 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00001230 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
1231 // Objective-C property reference.
1232
1233 // Add property results based on our interface.
1234 const ObjCObjectPointerType *ObjCPtr
1235 = BaseType->getAsObjCInterfacePointerType();
1236 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
1237 AddObjCProperties(ObjCPtr->getInterfaceDecl(), CurContext, Results);
1238
1239 // Add properties from the protocols in a qualified interface.
1240 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
1241 E = ObjCPtr->qual_end();
1242 I != E; ++I)
1243 AddObjCProperties(*I, CurContext, Results);
1244
1245 // FIXME: We could (should?) also look for "implicit" properties, identified
1246 // only by the presence of nullary and unary selectors.
1247 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
1248 (!IsArrow && BaseType->isObjCInterfaceType())) {
1249 // Objective-C instance variable access.
1250 ObjCInterfaceDecl *Class = 0;
1251 if (const ObjCObjectPointerType *ObjCPtr
1252 = BaseType->getAs<ObjCObjectPointerType>())
1253 Class = ObjCPtr->getInterfaceDecl();
1254 else
1255 Class = BaseType->getAs<ObjCInterfaceType>()->getDecl();
1256
1257 // Add all ivars from this class and its superclasses.
1258 for (; Class; Class = Class->getSuperClass()) {
1259 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
1260 IVarEnd = Class->ivar_end();
1261 IVar != IVarEnd; ++IVar)
1262 Results.MaybeAddResult(Result(*IVar, 0), CurContext);
1263 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001264 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00001265
1266 // FIXME: How do we cope with isa?
1267
1268 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001269
1270 // Add macros
1271 if (CodeCompleter->includeMacros())
1272 AddMacroResults(PP, NextRank, Results);
1273
1274 // Hand off the results found for code completion.
1275 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001276}
1277
Douglas Gregor374929f2009-09-18 15:37:17 +00001278void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1279 if (!CodeCompleter)
1280 return;
1281
Douglas Gregor86d9a522009-09-21 16:56:56 +00001282 typedef CodeCompleteConsumer::Result Result;
1283 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +00001284 switch ((DeclSpec::TST)TagSpec) {
1285 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001286 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +00001287 break;
1288
1289 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001290 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +00001291 break;
1292
1293 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00001294 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001295 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00001296 break;
1297
1298 default:
1299 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1300 return;
1301 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001302
1303 ResultBuilder Results(*this, Filter);
1304 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001305 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001306
1307 if (getLangOptions().CPlusPlus) {
1308 // We could have the start of a nested-name-specifier. Add those
1309 // results as well.
1310 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001311 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1312 NextRank, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001313 }
1314
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001315 if (CodeCompleter->includeMacros())
1316 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001317 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00001318}
1319
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001320void Sema::CodeCompleteCase(Scope *S) {
1321 if (getSwitchStack().empty() || !CodeCompleter)
1322 return;
1323
1324 SwitchStmt *Switch = getSwitchStack().back();
1325 if (!Switch->getCond()->getType()->isEnumeralType())
1326 return;
1327
1328 // Code-complete the cases of a switch statement over an enumeration type
1329 // by providing the list of
1330 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1331
1332 // Determine which enumerators we have already seen in the switch statement.
1333 // FIXME: Ideally, we would also be able to look *past* the code-completion
1334 // token, in case we are code-completing in the middle of the switch and not
1335 // at the end. However, we aren't able to do so at the moment.
1336 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001337 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001338 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1339 SC = SC->getNextSwitchCase()) {
1340 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1341 if (!Case)
1342 continue;
1343
1344 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1345 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1346 if (EnumConstantDecl *Enumerator
1347 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1348 // We look into the AST of the case statement to determine which
1349 // enumerator was named. Alternatively, we could compute the value of
1350 // the integral constant expression, then compare it against the
1351 // values of each enumerator. However, value-based approach would not
1352 // work as well with C++ templates where enumerators declared within a
1353 // template are type- and value-dependent.
1354 EnumeratorsSeen.insert(Enumerator);
1355
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001356 // If this is a qualified-id, keep track of the nested-name-specifier
1357 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001358 //
1359 // switch (TagD.getKind()) {
1360 // case TagDecl::TK_enum:
1361 // break;
1362 // case XXX
1363 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001364 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001365 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1366 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00001367 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001368 }
1369 }
1370
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001371 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1372 // If there are no prior enumerators in C++, check whether we have to
1373 // qualify the names of the enumerators that we suggest, because they
1374 // may not be visible in this scope.
1375 Qualifier = getRequiredQualification(Context, CurContext,
1376 Enum->getDeclContext());
1377
1378 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1379 }
1380
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001381 // Add any enumerators that have not yet been mentioned.
1382 ResultBuilder Results(*this);
1383 Results.EnterNewScope();
1384 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1385 EEnd = Enum->enumerator_end();
1386 E != EEnd; ++E) {
1387 if (EnumeratorsSeen.count(*E))
1388 continue;
1389
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001390 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001391 }
1392 Results.ExitScope();
1393
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001394 if (CodeCompleter->includeMacros())
1395 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001396 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001397}
1398
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001399namespace {
1400 struct IsBetterOverloadCandidate {
1401 Sema &S;
1402
1403 public:
1404 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1405
1406 bool
1407 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1408 return S.isBetterOverloadCandidate(X, Y);
1409 }
1410 };
1411}
1412
1413void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1414 ExprTy **ArgsIn, unsigned NumArgs) {
1415 if (!CodeCompleter)
1416 return;
1417
1418 Expr *Fn = (Expr *)FnIn;
1419 Expr **Args = (Expr **)ArgsIn;
1420
1421 // Ignore type-dependent call expressions entirely.
1422 if (Fn->isTypeDependent() ||
1423 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1424 return;
1425
1426 NamedDecl *Function;
1427 DeclarationName UnqualifiedName;
1428 NestedNameSpecifier *Qualifier;
1429 SourceRange QualifierRange;
1430 bool ArgumentDependentLookup;
1431 bool HasExplicitTemplateArgs;
John McCall833ca992009-10-29 08:12:44 +00001432 const TemplateArgumentLoc *ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001433 unsigned NumExplicitTemplateArgs;
1434
1435 DeconstructCallFunction(Fn,
1436 Function, UnqualifiedName, Qualifier, QualifierRange,
1437 ArgumentDependentLookup, HasExplicitTemplateArgs,
1438 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1439
1440
1441 // FIXME: What if we're calling something that isn't a function declaration?
1442 // FIXME: What if we're calling a pseudo-destructor?
1443 // FIXME: What if we're calling a member function?
1444
1445 // Build an overload candidate set based on the functions we find.
1446 OverloadCandidateSet CandidateSet;
1447 AddOverloadedCallCandidates(Function, UnqualifiedName,
1448 ArgumentDependentLookup, HasExplicitTemplateArgs,
1449 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1450 Args, NumArgs,
1451 CandidateSet,
1452 /*PartialOverloading=*/true);
1453
1454 // Sort the overload candidate set by placing the best overloads first.
1455 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1456 IsBetterOverloadCandidate(*this));
1457
1458 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05944382009-09-23 00:16:58 +00001459 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1460 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlsson90756302009-09-22 17:29:51 +00001461
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001462 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1463 CandEnd = CandidateSet.end();
1464 Cand != CandEnd; ++Cand) {
1465 if (Cand->Viable)
Douglas Gregor05944382009-09-23 00:16:58 +00001466 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001467 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001468 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
Douglas Gregor05944382009-09-23 00:16:58 +00001469 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001470}
1471
Douglas Gregor81b747b2009-09-17 21:32:03 +00001472void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1473 bool EnteringContext) {
1474 if (!SS.getScopeRep() || !CodeCompleter)
1475 return;
1476
Douglas Gregor86d9a522009-09-21 16:56:56 +00001477 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1478 if (!Ctx)
1479 return;
1480
1481 ResultBuilder Results(*this);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001482 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001483
1484 // The "template" keyword can follow "::" in the grammar, but only
1485 // put it into the grammar if the nested-name-specifier is dependent.
1486 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1487 if (!Results.empty() && NNS->isDependent())
1488 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1489
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001490 if (CodeCompleter->includeMacros())
1491 AddMacroResults(PP, NextRank + 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001492 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001493}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001494
1495void Sema::CodeCompleteUsing(Scope *S) {
1496 if (!CodeCompleter)
1497 return;
1498
Douglas Gregor86d9a522009-09-21 16:56:56 +00001499 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001500 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001501
1502 // If we aren't in class scope, we could see the "namespace" keyword.
1503 if (!S->isClassScope())
1504 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1505
1506 // After "using", we can see anything that would start a
1507 // nested-name-specifier.
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001508 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1509 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001510 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001511
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001512 if (CodeCompleter->includeMacros())
1513 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001514 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001515}
1516
1517void Sema::CodeCompleteUsingDirective(Scope *S) {
1518 if (!CodeCompleter)
1519 return;
1520
Douglas Gregor86d9a522009-09-21 16:56:56 +00001521 // After "using namespace", we expect to see a namespace name or namespace
1522 // alias.
1523 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001524 Results.EnterNewScope();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001525 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1526 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001527 Results.ExitScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001528 if (CodeCompleter->includeMacros())
1529 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001530 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001531}
1532
1533void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1534 if (!CodeCompleter)
1535 return;
1536
Douglas Gregor86d9a522009-09-21 16:56:56 +00001537 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1538 DeclContext *Ctx = (DeclContext *)S->getEntity();
1539 if (!S->getParent())
1540 Ctx = Context.getTranslationUnitDecl();
1541
1542 if (Ctx && Ctx->isFileContext()) {
1543 // We only want to see those namespaces that have already been defined
1544 // within this scope, because its likely that the user is creating an
1545 // extended namespace declaration. Keep track of the most recent
1546 // definition of each namespace.
1547 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1548 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1549 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1550 NS != NSEnd; ++NS)
1551 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1552
1553 // Add the most recent definition (or extended definition) of each
1554 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001555 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001556 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1557 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1558 NS != NSEnd; ++NS)
Douglas Gregor456c4a12009-09-21 20:12:40 +00001559 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1560 CurContext);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001561 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001562 }
1563
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001564 if (CodeCompleter->includeMacros())
1565 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001566 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001567}
1568
1569void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1570 if (!CodeCompleter)
1571 return;
1572
Douglas Gregor86d9a522009-09-21 16:56:56 +00001573 // After "namespace", we expect to see a namespace or alias.
1574 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001575 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1576 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001577 if (CodeCompleter->includeMacros())
1578 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001579 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001580}
1581
Douglas Gregored8d3222009-09-18 20:05:18 +00001582void Sema::CodeCompleteOperatorName(Scope *S) {
1583 if (!CodeCompleter)
1584 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001585
1586 typedef CodeCompleteConsumer::Result Result;
1587 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001588 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00001589
Douglas Gregor86d9a522009-09-21 16:56:56 +00001590 // Add the names of overloadable operators.
1591#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1592 if (std::strcmp(Spelling, "?")) \
1593 Results.MaybeAddResult(Result(Spelling, 0));
1594#include "clang/Basic/OperatorKinds.def"
1595
1596 // Add any type names visible from the current scope
1597 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001598 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001599
1600 // Add any type specifiers
1601 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1602
1603 // Add any nested-name-specifiers
1604 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001605 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1606 NextRank + 1, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001607 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001608
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001609 if (CodeCompleter->includeMacros())
1610 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001611 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00001612}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001613
Steve Naroffece8e712009-10-08 21:55:05 +00001614void Sema::CodeCompleteObjCProperty(Scope *S, ObjCDeclSpec &ODS) {
1615 if (!CodeCompleter)
1616 return;
1617 unsigned Attributes = ODS.getPropertyAttributes();
1618
1619 typedef CodeCompleteConsumer::Result Result;
1620 ResultBuilder Results(*this);
1621 Results.EnterNewScope();
1622 if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly))
1623 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
1624 if (!(Attributes & ObjCDeclSpec::DQ_PR_assign))
1625 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
1626 if (!(Attributes & ObjCDeclSpec::DQ_PR_readwrite))
1627 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
1628 if (!(Attributes & ObjCDeclSpec::DQ_PR_retain))
1629 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
1630 if (!(Attributes & ObjCDeclSpec::DQ_PR_copy))
1631 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
1632 if (!(Attributes & ObjCDeclSpec::DQ_PR_nonatomic))
1633 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
1634 if (!(Attributes & ObjCDeclSpec::DQ_PR_setter))
1635 Results.MaybeAddResult(CodeCompleteConsumer::Result("setter", 0));
1636 if (!(Attributes & ObjCDeclSpec::DQ_PR_getter))
1637 Results.MaybeAddResult(CodeCompleteConsumer::Result("getter", 0));
1638 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001639 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00001640}
Steve Naroffc4df6d22009-11-07 02:08:14 +00001641
Douglas Gregor36ecb042009-11-17 23:22:23 +00001642/// \brief Add all of the Objective-C methods in the given Objective-C
1643/// container to the set of results.
1644///
1645/// The container will be a class, protocol, category, or implementation of
1646/// any of the above. This mether will recurse to include methods from
1647/// the superclasses of classes along with their categories, protocols, and
1648/// implementations.
1649///
1650/// \param Container the container in which we'll look to find methods.
1651///
1652/// \param WantInstance whether to add instance methods (only); if false, this
1653/// routine will add factory methods (only).
1654///
1655/// \param CurContext the context in which we're performing the lookup that
1656/// finds methods.
1657///
1658/// \param Results the structure into which we'll add results.
1659static void AddObjCMethods(ObjCContainerDecl *Container,
1660 bool WantInstanceMethods,
1661 DeclContext *CurContext,
1662 ResultBuilder &Results) {
1663 typedef CodeCompleteConsumer::Result Result;
1664 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
1665 MEnd = Container->meth_end();
1666 M != MEnd; ++M) {
1667 if ((*M)->isInstanceMethod() == WantInstanceMethods)
1668 Results.MaybeAddResult(Result(*M, 0), CurContext);
1669 }
1670
1671 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
1672 if (!IFace)
1673 return;
1674
1675 // Add methods in protocols.
1676 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
1677 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1678 E = Protocols.end();
1679 I != E; ++I)
1680 AddObjCMethods(*I, WantInstanceMethods, CurContext, Results);
1681
1682 // Add methods in categories.
1683 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
1684 CatDecl = CatDecl->getNextClassCategory()) {
1685 AddObjCMethods(CatDecl, WantInstanceMethods, CurContext, Results);
1686
1687 // Add a categories protocol methods.
1688 const ObjCList<ObjCProtocolDecl> &Protocols
1689 = CatDecl->getReferencedProtocols();
1690 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1691 E = Protocols.end();
1692 I != E; ++I)
1693 AddObjCMethods(*I, WantInstanceMethods, CurContext, Results);
1694
1695 // Add methods in category implementations.
1696 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
1697 AddObjCMethods(Impl, WantInstanceMethods, CurContext, Results);
1698 }
1699
1700 // Add methods in superclass.
1701 if (IFace->getSuperClass())
1702 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, CurContext,
1703 Results);
1704
1705 // Add methods in our implementation, if any.
1706 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
1707 AddObjCMethods(Impl, WantInstanceMethods, CurContext, Results);
1708}
1709
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001710void Sema::CodeCompleteObjCClassMessage(Scope *S, IdentifierInfo *FName,
1711 SourceLocation FNameLoc) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00001712 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00001713 ObjCInterfaceDecl *CDecl = 0;
1714
Douglas Gregor24a069f2009-11-17 17:59:40 +00001715 if (FName->isStr("super")) {
1716 // We're sending a message to "super".
1717 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
1718 // Figure out which interface we're in.
1719 CDecl = CurMethod->getClassInterface();
1720 if (!CDecl)
1721 return;
1722
1723 // Find the superclass of this class.
1724 CDecl = CDecl->getSuperClass();
1725 if (!CDecl)
1726 return;
1727
1728 if (CurMethod->isInstanceMethod()) {
1729 // We are inside an instance method, which means that the message
1730 // send [super ...] is actually calling an instance method on the
1731 // current object. Build the super expression and handle this like
1732 // an instance method.
1733 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
1734 SuperTy = Context.getObjCObjectPointerType(SuperTy);
1735 OwningExprResult Super
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001736 = Owned(new (Context) ObjCSuperExpr(FNameLoc, SuperTy));
1737 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get());
Douglas Gregor24a069f2009-11-17 17:59:40 +00001738 }
1739
1740 // Okay, we're calling a factory method in our superclass.
1741 }
1742 }
1743
1744 // If the given name refers to an interface type, retrieve the
1745 // corresponding declaration.
1746 if (!CDecl)
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001747 if (TypeTy *Ty = getTypeName(*FName, FNameLoc, S, 0, false)) {
Douglas Gregor24a069f2009-11-17 17:59:40 +00001748 QualType T = GetTypeFromParser(Ty, 0);
1749 if (!T.isNull())
1750 if (const ObjCInterfaceType *Interface = T->getAs<ObjCInterfaceType>())
1751 CDecl = Interface->getDecl();
1752 }
1753
1754 if (!CDecl && FName->isStr("super")) {
1755 // "super" may be the name of a variable, in which case we are
1756 // probably calling an instance method.
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001757 OwningExprResult Super = ActOnDeclarationNameExpr(S, FNameLoc, FName,
Douglas Gregor24a069f2009-11-17 17:59:40 +00001758 false, 0, false);
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001759 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get());
Douglas Gregor24a069f2009-11-17 17:59:40 +00001760 }
1761
Douglas Gregor36ecb042009-11-17 23:22:23 +00001762 // Add all of the factory methods in this Objective-C class, its protocols,
1763 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00001764 ResultBuilder Results(*this);
1765 Results.EnterNewScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00001766 AddObjCMethods(CDecl, false, CurContext, Results);
Steve Naroffc4df6d22009-11-07 02:08:14 +00001767 Results.ExitScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00001768
Steve Naroffc4df6d22009-11-07 02:08:14 +00001769 // This also suppresses remaining diagnostics.
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001770 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00001771}
1772
Douglas Gregor60b01cc2009-11-17 23:31:36 +00001773void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00001774 typedef CodeCompleteConsumer::Result Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00001775
1776 Expr *RecExpr = static_cast<Expr *>(Receiver);
1777 QualType RecType = RecExpr->getType();
1778
Douglas Gregor36ecb042009-11-17 23:22:23 +00001779 // If necessary, apply function/array conversion to the receiver.
1780 // C99 6.7.5.3p[7,8].
1781 DefaultFunctionArrayConversion(RecExpr);
1782 QualType ReceiverType = RecExpr->getType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00001783
Douglas Gregor36ecb042009-11-17 23:22:23 +00001784 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType()) {
1785 // FIXME: We're messaging 'id'. Do we actually want to look up every method
1786 // in the universe?
1787 return;
1788 }
1789
Douglas Gregor36ecb042009-11-17 23:22:23 +00001790 // Build the set of methods we can see.
1791 ResultBuilder Results(*this);
1792 Results.EnterNewScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00001793
Douglas Gregorf74a4192009-11-18 00:06:18 +00001794 // Handle messages to Class. This really isn't a message to an instance
1795 // method, so we treat it the same way we would treat a message send to a
1796 // class method.
1797 if (ReceiverType->isObjCClassType() ||
1798 ReceiverType->isObjCQualifiedClassType()) {
1799 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
1800 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
1801 AddObjCMethods(ClassDecl, false, CurContext, Results);
1802 }
1803 }
1804 // Handle messages to a qualified ID ("id<foo>").
1805 else if (const ObjCObjectPointerType *QualID
1806 = ReceiverType->getAsObjCQualifiedIdType()) {
1807 // Search protocols for instance methods.
1808 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
1809 E = QualID->qual_end();
1810 I != E; ++I)
1811 AddObjCMethods(*I, true, CurContext, Results);
1812 }
1813 // Handle messages to a pointer to interface type.
1814 else if (const ObjCObjectPointerType *IFacePtr
1815 = ReceiverType->getAsObjCInterfacePointerType()) {
1816 // Search the class, its superclasses, etc., for instance methods.
1817 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, CurContext, Results);
1818
1819 // Search protocols for instance methods.
1820 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
1821 E = IFacePtr->qual_end();
1822 I != E; ++I)
1823 AddObjCMethods(*I, true, CurContext, Results);
1824 }
1825
Steve Naroffc4df6d22009-11-07 02:08:14 +00001826 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001827 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00001828}
Douglas Gregor55385fe2009-11-18 04:19:12 +00001829
1830/// \brief Add all of the protocol declarations that we find in the given
1831/// (translation unit) context.
1832static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
1833 ResultBuilder &Results) {
1834 typedef CodeCompleteConsumer::Result Result;
1835
1836 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
1837 DEnd = Ctx->decls_end();
1838 D != DEnd; ++D) {
1839 // Record any protocols we find.
1840 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
1841 Results.MaybeAddResult(Result(Proto, 0), CurContext);
1842
1843 // Record any forward-declared protocols we find.
1844 if (ObjCForwardProtocolDecl *Forward
1845 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
1846 for (ObjCForwardProtocolDecl::protocol_iterator
1847 P = Forward->protocol_begin(),
1848 PEnd = Forward->protocol_end();
1849 P != PEnd; ++P)
1850 Results.MaybeAddResult(Result(*P, 0), CurContext);
1851 }
1852 }
1853}
1854
1855void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
1856 unsigned NumProtocols) {
1857 ResultBuilder Results(*this);
1858 Results.EnterNewScope();
1859
1860 // Tell the result set to ignore all of the protocols we have
1861 // already seen.
1862 for (unsigned I = 0; I != NumProtocols; ++I)
1863 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first))
1864 Results.Ignore(Protocol);
1865
1866 // Add all protocols.
1867 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, Results);
1868
1869 Results.ExitScope();
1870 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1871}