blob: 70af446bff2fd41b154e6e0031154416479d712c [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
98 /// \name Name lookup predicates
99 ///
100 /// These predicates can be passed to the name lookup functions to filter the
101 /// results of name lookup. All of the predicates have the same type, so that
102 ///
103 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000104 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000105 bool IsNestedNameSpecifier(NamedDecl *ND) const;
106 bool IsEnum(NamedDecl *ND) const;
107 bool IsClassOrStruct(NamedDecl *ND) const;
108 bool IsUnion(NamedDecl *ND) const;
109 bool IsNamespace(NamedDecl *ND) const;
110 bool IsNamespaceOrAlias(NamedDecl *ND) const;
111 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000112 bool IsMember(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000113 //@}
114 };
115}
116
117/// \brief Determines whether the given hidden result could be found with
118/// some extra work, e.g., by qualifying the name.
119///
120/// \param Hidden the declaration that is hidden by the currenly \p Visible
121/// declaration.
122///
123/// \param Visible the declaration with the same name that is already visible.
124///
125/// \returns true if the hidden result can be found by some mechanism,
126/// false otherwise.
127static bool canHiddenResultBeFound(const LangOptions &LangOpts,
128 NamedDecl *Hidden, NamedDecl *Visible) {
129 // In C, there is no way to refer to a hidden name.
130 if (!LangOpts.CPlusPlus)
131 return false;
132
133 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
134
135 // There is no way to qualify a name declared in a function or method.
136 if (HiddenCtx->isFunctionOrMethod())
137 return false;
138
Douglas Gregor86d9a522009-09-21 16:56:56 +0000139 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
140}
141
Douglas Gregor456c4a12009-09-21 20:12:40 +0000142/// \brief Compute the qualification required to get from the current context
143/// (\p CurContext) to the target context (\p TargetContext).
144///
145/// \param Context the AST context in which the qualification will be used.
146///
147/// \param CurContext the context where an entity is being named, which is
148/// typically based on the current scope.
149///
150/// \param TargetContext the context in which the named entity actually
151/// resides.
152///
153/// \returns a nested name specifier that refers into the target context, or
154/// NULL if no qualification is needed.
155static NestedNameSpecifier *
156getRequiredQualification(ASTContext &Context,
157 DeclContext *CurContext,
158 DeclContext *TargetContext) {
159 llvm::SmallVector<DeclContext *, 4> TargetParents;
160
161 for (DeclContext *CommonAncestor = TargetContext;
162 CommonAncestor && !CommonAncestor->Encloses(CurContext);
163 CommonAncestor = CommonAncestor->getLookupParent()) {
164 if (CommonAncestor->isTransparentContext() ||
165 CommonAncestor->isFunctionOrMethod())
166 continue;
167
168 TargetParents.push_back(CommonAncestor);
169 }
170
171 NestedNameSpecifier *Result = 0;
172 while (!TargetParents.empty()) {
173 DeclContext *Parent = TargetParents.back();
174 TargetParents.pop_back();
175
176 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
177 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
178 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
179 Result = NestedNameSpecifier::Create(Context, Result,
180 false,
181 Context.getTypeDeclType(TD).getTypePtr());
182 else
183 assert(Parent->isTranslationUnit());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000184 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000185 return Result;
186}
187
188void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
Douglas Gregor8e0a0e42009-09-22 23:31:26 +0000189 assert(!ShadowMaps.empty() && "Must enter into a results scope");
190
Douglas Gregor86d9a522009-09-21 16:56:56 +0000191 if (R.Kind != Result::RK_Declaration) {
192 // For non-declaration results, just add the result.
193 Results.push_back(R);
194 return;
195 }
Douglas Gregorf52cede2009-10-09 22:16:47 +0000196
197 // Skip unnamed entities.
198 if (!R.Declaration->getDeclName())
199 return;
200
Douglas Gregor86d9a522009-09-21 16:56:56 +0000201 // Look through using declarations.
John McCall9488ea12009-11-17 05:59:44 +0000202 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration))
Douglas Gregor0563c262009-09-22 23:15:58 +0000203 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
204 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000205
206 // Handle each declaration in an overload set separately.
207 if (OverloadedFunctionDecl *Ovl
208 = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) {
209 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
210 FEnd = Ovl->function_end();
211 F != FEnd; ++F)
Douglas Gregor456c4a12009-09-21 20:12:40 +0000212 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000213
214 return;
215 }
216
217 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
218 unsigned IDNS = CanonDecl->getIdentifierNamespace();
219
220 // Friend declarations and declarations introduced due to friends are never
221 // added as results.
222 if (isa<FriendDecl>(CanonDecl) ||
223 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
224 return;
225
226 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
227 // __va_list_tag is a freak of nature. Find it and skip it.
228 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
229 return;
230
Douglas Gregorf52cede2009-10-09 22:16:47 +0000231 // Filter out names reserved for the implementation (C99 7.1.3,
232 // C++ [lib.global.names]). Users don't need to see those.
Daniel Dunbare013d682009-10-18 20:26:12 +0000233 //
234 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000235 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000236 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000237 if (Name[0] == '_' &&
238 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
239 return;
240 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000241 }
242
243 // C++ constructors are never found by name lookup.
244 if (isa<CXXConstructorDecl>(CanonDecl))
245 return;
246
247 // Filter out any unwanted results.
248 if (Filter && !(this->*Filter)(R.Declaration))
249 return;
250
251 ShadowMap &SMap = ShadowMaps.back();
252 ShadowMap::iterator I, IEnd;
253 for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
254 I != IEnd; ++I) {
255 NamedDecl *ND = I->second.first;
256 unsigned Index = I->second.second;
257 if (ND->getCanonicalDecl() == CanonDecl) {
258 // This is a redeclaration. Always pick the newer declaration.
259 I->second.first = R.Declaration;
260 Results[Index].Declaration = R.Declaration;
261
262 // Pick the best rank of the two.
263 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
264
265 // We're done.
266 return;
267 }
268 }
269
270 // This is a new declaration in this scope. However, check whether this
271 // declaration name is hidden by a similarly-named declaration in an outer
272 // scope.
273 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
274 --SMEnd;
275 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
276 for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
277 I != IEnd; ++I) {
278 // A tag declaration does not hide a non-tag declaration.
279 if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
280 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
281 Decl::IDNS_ObjCProtocol)))
282 continue;
283
284 // Protocols are in distinct namespaces from everything else.
285 if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
286 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
287 I->second.first->getIdentifierNamespace() != IDNS)
288 continue;
289
290 // The newly-added result is hidden by an entry in the shadow map.
291 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
292 I->second.first)) {
293 // Note that this result was hidden.
294 R.Hidden = true;
Douglas Gregor0563c262009-09-22 23:15:58 +0000295 R.QualifierIsInformative = false;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000296
297 if (!R.Qualifier)
298 R.Qualifier = getRequiredQualification(SemaRef.Context,
299 CurContext,
300 R.Declaration->getDeclContext());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000301 } else {
302 // This result was hidden and cannot be found; don't bother adding
303 // it.
304 return;
305 }
306
307 break;
308 }
309 }
310
311 // Make sure that any given declaration only shows up in the result set once.
312 if (!AllDeclsFound.insert(CanonDecl))
313 return;
314
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000315 // If the filter is for nested-name-specifiers, then this result starts a
316 // nested-name-specifier.
317 if ((Filter == &ResultBuilder::IsNestedNameSpecifier) ||
318 (Filter == &ResultBuilder::IsMember &&
319 isa<CXXRecordDecl>(R.Declaration) &&
320 cast<CXXRecordDecl>(R.Declaration)->isInjectedClassName()))
321 R.StartsNestedNameSpecifier = true;
322
Douglas Gregor0563c262009-09-22 23:15:58 +0000323 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000324 if (R.QualifierIsInformative && !R.Qualifier &&
325 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000326 DeclContext *Ctx = R.Declaration->getDeclContext();
327 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
328 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
329 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
330 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
331 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
332 else
333 R.QualifierIsInformative = false;
334 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000335
Douglas Gregor86d9a522009-09-21 16:56:56 +0000336 // Insert this result into the set of results and into the current shadow
337 // map.
338 SMap.insert(std::make_pair(R.Declaration->getDeclName(),
339 std::make_pair(R.Declaration, Results.size())));
340 Results.push_back(R);
341}
342
343/// \brief Enter into a new scope.
344void ResultBuilder::EnterNewScope() {
345 ShadowMaps.push_back(ShadowMap());
346}
347
348/// \brief Exit from the current scope.
349void ResultBuilder::ExitScope() {
350 ShadowMaps.pop_back();
351}
352
Douglas Gregor791215b2009-09-21 20:51:25 +0000353/// \brief Determines whether this given declaration will be found by
354/// ordinary name lookup.
355bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
356 unsigned IDNS = Decl::IDNS_Ordinary;
357 if (SemaRef.getLangOptions().CPlusPlus)
358 IDNS |= Decl::IDNS_Tag;
359
360 return ND->getIdentifierNamespace() & IDNS;
361}
362
Douglas Gregor86d9a522009-09-21 16:56:56 +0000363/// \brief Determines whether the given declaration is suitable as the
364/// start of a C++ nested-name-specifier, e.g., a class or namespace.
365bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
366 // Allow us to find class templates, too.
367 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
368 ND = ClassTemplate->getTemplatedDecl();
369
370 return SemaRef.isAcceptableNestedNameSpecifier(ND);
371}
372
373/// \brief Determines whether the given declaration is an enumeration.
374bool ResultBuilder::IsEnum(NamedDecl *ND) const {
375 return isa<EnumDecl>(ND);
376}
377
378/// \brief Determines whether the given declaration is a class or struct.
379bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
380 // Allow us to find class templates, too.
381 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
382 ND = ClassTemplate->getTemplatedDecl();
383
384 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
385 return RD->getTagKind() == TagDecl::TK_class ||
386 RD->getTagKind() == TagDecl::TK_struct;
387
388 return false;
389}
390
391/// \brief Determines whether the given declaration is a union.
392bool ResultBuilder::IsUnion(NamedDecl *ND) const {
393 // Allow us to find class templates, too.
394 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
395 ND = ClassTemplate->getTemplatedDecl();
396
397 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
398 return RD->getTagKind() == TagDecl::TK_union;
399
400 return false;
401}
402
403/// \brief Determines whether the given declaration is a namespace.
404bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
405 return isa<NamespaceDecl>(ND);
406}
407
408/// \brief Determines whether the given declaration is a namespace or
409/// namespace alias.
410bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
411 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
412}
413
414/// \brief Brief determines whether the given declaration is a namespace or
415/// namespace alias.
416bool ResultBuilder::IsType(NamedDecl *ND) const {
417 return isa<TypeDecl>(ND);
418}
419
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000420/// \brief Since every declaration found within a class is a member that we
421/// care about, always returns true. This predicate exists mostly to
422/// communicate to the result builder that we are performing a lookup for
423/// member access.
424bool ResultBuilder::IsMember(NamedDecl *ND) const {
425 return true;
426}
427
Douglas Gregor86d9a522009-09-21 16:56:56 +0000428// Find the next outer declaration context corresponding to this scope.
429static DeclContext *findOuterContext(Scope *S) {
430 for (S = S->getParent(); S; S = S->getParent())
431 if (S->getEntity())
432 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
433
434 return 0;
435}
436
437/// \brief Collect the results of searching for members within the given
438/// declaration context.
439///
440/// \param Ctx the declaration context from which we will gather results.
441///
Douglas Gregor0563c262009-09-22 23:15:58 +0000442/// \param Rank the rank given to results in this declaration context.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000443///
444/// \param Visited the set of declaration contexts that have already been
445/// visited. Declaration contexts will only be visited once.
446///
447/// \param Results the result set that will be extended with any results
448/// found within this declaration context (and, for a C++ class, its bases).
449///
Douglas Gregor0563c262009-09-22 23:15:58 +0000450/// \param InBaseClass whether we are in a base class.
451///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000452/// \returns the next higher rank value, after considering all of the
453/// names within this declaration context.
454static unsigned CollectMemberLookupResults(DeclContext *Ctx,
Douglas Gregor0563c262009-09-22 23:15:58 +0000455 unsigned Rank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000456 DeclContext *CurContext,
457 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor0563c262009-09-22 23:15:58 +0000458 ResultBuilder &Results,
459 bool InBaseClass = false) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000460 // Make sure we don't visit the same context twice.
461 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor0563c262009-09-22 23:15:58 +0000462 return Rank;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000463
464 // Enumerate all of the results in this context.
Douglas Gregor0563c262009-09-22 23:15:58 +0000465 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000466 Results.EnterNewScope();
467 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
468 CurCtx = CurCtx->getNextContext()) {
469 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregorff4393c2009-11-09 21:35:27 +0000470 DEnd = CurCtx->decls_end();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000471 D != DEnd; ++D) {
472 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor0563c262009-09-22 23:15:58 +0000473 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregorff4393c2009-11-09 21:35:27 +0000474
475 // Visit transparent contexts inside this context.
476 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
477 if (InnerCtx->isTransparentContext())
478 CollectMemberLookupResults(InnerCtx, Rank, CurContext, Visited,
479 Results, InBaseClass);
480 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000481 }
482 }
483
484 // Traverse the contexts of inherited classes.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000485 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
486 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
Douglas Gregorff4393c2009-11-09 21:35:27 +0000487 BEnd = Record->bases_end();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000488 B != BEnd; ++B) {
489 QualType BaseType = B->getType();
490
491 // Don't look into dependent bases, because name lookup can't look
492 // there anyway.
493 if (BaseType->isDependentType())
494 continue;
495
496 const RecordType *Record = BaseType->getAs<RecordType>();
497 if (!Record)
498 continue;
499
500 // FIXME: It would be nice to be able to determine whether referencing
501 // a particular member would be ambiguous. For example, given
502 //
503 // struct A { int member; };
504 // struct B { int member; };
505 // struct C : A, B { };
506 //
507 // void f(C *c) { c->### }
508 // accessing 'member' would result in an ambiguity. However, code
509 // completion could be smart enough to qualify the member with the
510 // base class, e.g.,
511 //
512 // c->B::member
513 //
514 // or
515 //
516 // c->A::member
517
518 // Collect results from this base class (and its bases).
Douglas Gregor0563c262009-09-22 23:15:58 +0000519 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
520 Results, /*InBaseClass=*/true);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000521 }
522 }
523
524 // FIXME: Look into base classes in Objective-C!
525
526 Results.ExitScope();
Douglas Gregor0563c262009-09-22 23:15:58 +0000527 return Rank + 1;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000528}
529
530/// \brief Collect the results of searching for members within the given
531/// declaration context.
532///
533/// \param Ctx the declaration context from which we will gather results.
534///
535/// \param InitialRank the initial rank given to results in this declaration
536/// context. Larger rank values will be used for, e.g., members found in
537/// base classes.
538///
539/// \param Results the result set that will be extended with any results
540/// found within this declaration context (and, for a C++ class, its bases).
541///
542/// \returns the next higher rank value, after considering all of the
543/// names within this declaration context.
544static unsigned CollectMemberLookupResults(DeclContext *Ctx,
545 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000546 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000547 ResultBuilder &Results) {
548 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000549 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
550 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000551}
552
553/// \brief Collect the results of searching for declarations within the given
554/// scope and its parent scopes.
555///
556/// \param S the scope in which we will start looking for declarations.
557///
558/// \param InitialRank the initial rank given to results in this scope.
559/// Larger rank values will be used for results found in parent scopes.
560///
Douglas Gregor456c4a12009-09-21 20:12:40 +0000561/// \param CurContext the context from which lookup results will be found.
562///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000563/// \param Results the builder object that will receive each result.
564static unsigned CollectLookupResults(Scope *S,
565 TranslationUnitDecl *TranslationUnit,
566 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000567 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000568 ResultBuilder &Results) {
569 if (!S)
570 return InitialRank;
571
572 // FIXME: Using directives!
573
574 unsigned NextRank = InitialRank;
575 Results.EnterNewScope();
576 if (S->getEntity() &&
577 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
578 // Look into this scope's declaration context, along with any of its
579 // parent lookup contexts (e.g., enclosing classes), up to the point
580 // where we hit the context stored in the next outer scope.
581 DeclContext *Ctx = (DeclContext *)S->getEntity();
582 DeclContext *OuterCtx = findOuterContext(S);
583
584 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
585 Ctx = Ctx->getLookupParent()) {
586 if (Ctx->isFunctionOrMethod())
587 continue;
588
Douglas Gregor456c4a12009-09-21 20:12:40 +0000589 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
590 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000591 }
592 } else if (!S->getParent()) {
593 // Look into the translation unit scope. We walk through the translation
594 // unit's declaration context, because the Scope itself won't have all of
595 // the declarations if we loaded a precompiled header.
596 // FIXME: We would like the translation unit's Scope object to point to the
597 // translation unit, so we don't need this special "if" branch. However,
598 // doing so would force the normal C++ name-lookup code to look into the
599 // translation unit decl when the IdentifierInfo chains would suffice.
600 // Once we fix that problem (which is part of a more general "don't look
601 // in DeclContexts unless we have to" optimization), we can eliminate the
602 // TranslationUnit parameter entirely.
603 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000604 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000605 } else {
606 // Walk through the declarations in this Scope.
607 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
608 D != DEnd; ++D) {
609 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
Douglas Gregor456c4a12009-09-21 20:12:40 +0000610 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
611 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000612 }
613
614 NextRank = NextRank + 1;
615 }
616
617 // Lookup names in the parent scope.
618 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000619 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000620 Results.ExitScope();
621
622 return NextRank;
623}
624
625/// \brief Add type specifiers for the current language as keyword results.
626static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
627 ResultBuilder &Results) {
628 typedef CodeCompleteConsumer::Result Result;
629 Results.MaybeAddResult(Result("short", Rank));
630 Results.MaybeAddResult(Result("long", Rank));
631 Results.MaybeAddResult(Result("signed", Rank));
632 Results.MaybeAddResult(Result("unsigned", Rank));
633 Results.MaybeAddResult(Result("void", Rank));
634 Results.MaybeAddResult(Result("char", Rank));
635 Results.MaybeAddResult(Result("int", Rank));
636 Results.MaybeAddResult(Result("float", Rank));
637 Results.MaybeAddResult(Result("double", Rank));
638 Results.MaybeAddResult(Result("enum", Rank));
639 Results.MaybeAddResult(Result("struct", Rank));
640 Results.MaybeAddResult(Result("union", Rank));
641
642 if (LangOpts.C99) {
643 // C99-specific
644 Results.MaybeAddResult(Result("_Complex", Rank));
645 Results.MaybeAddResult(Result("_Imaginary", Rank));
646 Results.MaybeAddResult(Result("_Bool", Rank));
647 }
648
649 if (LangOpts.CPlusPlus) {
650 // C++-specific
651 Results.MaybeAddResult(Result("bool", Rank));
652 Results.MaybeAddResult(Result("class", Rank));
653 Results.MaybeAddResult(Result("typename", Rank));
654 Results.MaybeAddResult(Result("wchar_t", Rank));
655
656 if (LangOpts.CPlusPlus0x) {
657 Results.MaybeAddResult(Result("char16_t", Rank));
658 Results.MaybeAddResult(Result("char32_t", Rank));
659 Results.MaybeAddResult(Result("decltype", Rank));
660 }
661 }
662
663 // GNU extensions
664 if (LangOpts.GNUMode) {
665 // FIXME: Enable when we actually support decimal floating point.
666 // Results.MaybeAddResult(Result("_Decimal32", Rank));
667 // Results.MaybeAddResult(Result("_Decimal64", Rank));
668 // Results.MaybeAddResult(Result("_Decimal128", Rank));
669 Results.MaybeAddResult(Result("typeof", Rank));
670 }
671}
672
673/// \brief Add function parameter chunks to the given code completion string.
674static void AddFunctionParameterChunks(ASTContext &Context,
675 FunctionDecl *Function,
676 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000677 typedef CodeCompletionString::Chunk Chunk;
678
Douglas Gregor86d9a522009-09-21 16:56:56 +0000679 CodeCompletionString *CCStr = Result;
680
681 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
682 ParmVarDecl *Param = Function->getParamDecl(P);
683
684 if (Param->hasDefaultArg()) {
685 // When we see an optional default argument, put that argument and
686 // the remaining default arguments into a new, optional string.
687 CodeCompletionString *Opt = new CodeCompletionString;
688 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
689 CCStr = Opt;
690 }
691
692 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000693 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000694
695 // Format the placeholder string.
696 std::string PlaceholderStr;
697 if (Param->getIdentifier())
698 PlaceholderStr = Param->getIdentifier()->getName();
699
700 Param->getType().getAsStringInternal(PlaceholderStr,
701 Context.PrintingPolicy);
702
703 // Add the placeholder string.
704 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
705 }
Douglas Gregorb3d45252009-09-22 21:42:17 +0000706
707 if (const FunctionProtoType *Proto
708 = Function->getType()->getAs<FunctionProtoType>())
709 if (Proto->isVariadic())
710 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000711}
712
713/// \brief Add template parameter chunks to the given code completion string.
714static void AddTemplateParameterChunks(ASTContext &Context,
715 TemplateDecl *Template,
716 CodeCompletionString *Result,
717 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000718 typedef CodeCompletionString::Chunk Chunk;
719
Douglas Gregor86d9a522009-09-21 16:56:56 +0000720 CodeCompletionString *CCStr = Result;
721 bool FirstParameter = true;
722
723 TemplateParameterList *Params = Template->getTemplateParameters();
724 TemplateParameterList::iterator PEnd = Params->end();
725 if (MaxParameters)
726 PEnd = Params->begin() + MaxParameters;
727 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
728 bool HasDefaultArg = false;
729 std::string PlaceholderStr;
730 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
731 if (TTP->wasDeclaredWithTypename())
732 PlaceholderStr = "typename";
733 else
734 PlaceholderStr = "class";
735
736 if (TTP->getIdentifier()) {
737 PlaceholderStr += ' ';
738 PlaceholderStr += TTP->getIdentifier()->getName();
739 }
740
741 HasDefaultArg = TTP->hasDefaultArgument();
742 } else if (NonTypeTemplateParmDecl *NTTP
743 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
744 if (NTTP->getIdentifier())
745 PlaceholderStr = NTTP->getIdentifier()->getName();
746 NTTP->getType().getAsStringInternal(PlaceholderStr,
747 Context.PrintingPolicy);
748 HasDefaultArg = NTTP->hasDefaultArgument();
749 } else {
750 assert(isa<TemplateTemplateParmDecl>(*P));
751 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
752
753 // Since putting the template argument list into the placeholder would
754 // be very, very long, we just use an abbreviation.
755 PlaceholderStr = "template<...> class";
756 if (TTP->getIdentifier()) {
757 PlaceholderStr += ' ';
758 PlaceholderStr += TTP->getIdentifier()->getName();
759 }
760
761 HasDefaultArg = TTP->hasDefaultArgument();
762 }
763
764 if (HasDefaultArg) {
765 // When we see an optional default argument, put that argument and
766 // the remaining default arguments into a new, optional string.
767 CodeCompletionString *Opt = new CodeCompletionString;
768 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
769 CCStr = Opt;
770 }
771
772 if (FirstParameter)
773 FirstParameter = false;
774 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000775 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000776
777 // Add the placeholder string.
778 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
779 }
780}
781
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000782/// \brief Add a qualifier to the given code-completion string, if the
783/// provided nested-name-specifier is non-NULL.
784void AddQualifierToCompletionString(CodeCompletionString *Result,
785 NestedNameSpecifier *Qualifier,
Douglas Gregor0563c262009-09-22 23:15:58 +0000786 bool QualifierIsInformative,
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000787 ASTContext &Context) {
788 if (!Qualifier)
789 return;
790
791 std::string PrintedNNS;
792 {
793 llvm::raw_string_ostream OS(PrintedNNS);
794 Qualifier->print(OS, Context.PrintingPolicy);
795 }
Douglas Gregor0563c262009-09-22 23:15:58 +0000796 if (QualifierIsInformative)
797 Result->AddInformativeChunk(PrintedNNS.c_str());
798 else
799 Result->AddTextChunk(PrintedNNS.c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000800}
801
Douglas Gregor86d9a522009-09-21 16:56:56 +0000802/// \brief If possible, create a new code completion string for the given
803/// result.
804///
805/// \returns Either a new, heap-allocated code completion string describing
806/// how to use this result, or NULL to indicate that the string or name of the
807/// result is all that is needed.
808CodeCompletionString *
809CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000810 typedef CodeCompletionString::Chunk Chunk;
811
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000812 if (Kind == RK_Keyword)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000813 return 0;
814
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000815 if (Kind == RK_Macro) {
816 MacroInfo *MI = S.PP.getMacroInfo(Macro);
817 if (!MI || !MI->isFunctionLike())
818 return 0;
819
820 // Format a function-like macro with placeholders for the arguments.
821 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000822 Result->AddTypedTextChunk(Macro->getName().str().c_str());
823 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000824 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
825 A != AEnd; ++A) {
826 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000827 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000828
829 if (!MI->isVariadic() || A != AEnd - 1) {
830 // Non-variadic argument.
831 Result->AddPlaceholderChunk((*A)->getName().str().c_str());
832 continue;
833 }
834
835 // Variadic argument; cope with the different between GNU and C99
836 // variadic macros, providing a single placeholder for the rest of the
837 // arguments.
838 if ((*A)->isStr("__VA_ARGS__"))
839 Result->AddPlaceholderChunk("...");
840 else {
841 std::string Arg = (*A)->getName();
842 Arg += "...";
843 Result->AddPlaceholderChunk(Arg.c_str());
844 }
845 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000846 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000847 return Result;
848 }
849
850 assert(Kind == RK_Declaration && "Missed a macro kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000851 NamedDecl *ND = Declaration;
852
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000853 if (StartsNestedNameSpecifier) {
854 CodeCompletionString *Result = new CodeCompletionString;
855 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
856 Result->AddTextChunk("::");
857 return Result;
858 }
859
Douglas Gregor86d9a522009-09-21 16:56:56 +0000860 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
861 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000862 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
863 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000864 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
865 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000866 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000867 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000868 return Result;
869 }
870
871 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
872 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000873 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
874 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000875 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000876 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000877
878 // Figure out which template parameters are deduced (or have default
879 // arguments).
880 llvm::SmallVector<bool, 16> Deduced;
881 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
882 unsigned LastDeducibleArgument;
883 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
884 --LastDeducibleArgument) {
885 if (!Deduced[LastDeducibleArgument - 1]) {
886 // C++0x: Figure out if the template argument has a default. If so,
887 // the user doesn't need to type this argument.
888 // FIXME: We need to abstract template parameters better!
889 bool HasDefaultArg = false;
890 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
891 LastDeducibleArgument - 1);
892 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
893 HasDefaultArg = TTP->hasDefaultArgument();
894 else if (NonTypeTemplateParmDecl *NTTP
895 = dyn_cast<NonTypeTemplateParmDecl>(Param))
896 HasDefaultArg = NTTP->hasDefaultArgument();
897 else {
898 assert(isa<TemplateTemplateParmDecl>(Param));
899 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000900 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000901 }
902
903 if (!HasDefaultArg)
904 break;
905 }
906 }
907
908 if (LastDeducibleArgument) {
909 // Some of the function template arguments cannot be deduced from a
910 // function call, so we introduce an explicit template argument list
911 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000912 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000913 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
914 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000915 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000916 }
917
918 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000919 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000920 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000921 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000922 return Result;
923 }
924
925 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
926 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000927 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
928 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000929 Result->AddTypedTextChunk(Template->getNameAsString().c_str());
930 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000931 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000932 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000933 return Result;
934 }
935
Douglas Gregor9630eb62009-11-17 16:44:22 +0000936 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
937 CodeCompletionString *Result = new CodeCompletionString;
938 Selector Sel = Method->getSelector();
939 if (Sel.isUnarySelector()) {
940 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
941 return Result;
942 }
943
944 Result->AddTypedTextChunk(
945 Sel.getIdentifierInfoForSlot(0)->getName().str() + std::string(":"));
946 unsigned Idx = 0;
947 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
948 PEnd = Method->param_end();
949 P != PEnd; (void)++P, ++Idx) {
950 if (Idx > 0) {
951 std::string Keyword = " ";
952 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
953 Keyword += II->getName().str();
954 Keyword += ":";
955 Result->AddTextChunk(Keyword);
956 }
957
958 std::string Arg;
959 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
960 Arg = "(" + Arg + ")";
961 if (IdentifierInfo *II = (*P)->getIdentifier())
962 Arg += II->getName().str();
963 Result->AddPlaceholderChunk(Arg);
964 }
965
966 return Result;
967 }
968
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000969 if (Qualifier) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000970 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000971 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
972 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000973 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000974 return Result;
975 }
976
Douglas Gregor86d9a522009-09-21 16:56:56 +0000977 return 0;
978}
979
Douglas Gregor86d802e2009-09-23 00:34:09 +0000980CodeCompletionString *
981CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
982 unsigned CurrentArg,
983 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000984 typedef CodeCompletionString::Chunk Chunk;
985
Douglas Gregor86d802e2009-09-23 00:34:09 +0000986 CodeCompletionString *Result = new CodeCompletionString;
987 FunctionDecl *FDecl = getFunction();
988 const FunctionProtoType *Proto
989 = dyn_cast<FunctionProtoType>(getFunctionType());
990 if (!FDecl && !Proto) {
991 // Function without a prototype. Just give the return type and a
992 // highlighted ellipsis.
993 const FunctionType *FT = getFunctionType();
994 Result->AddTextChunk(
995 FT->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000996 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
997 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
998 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +0000999 return Result;
1000 }
1001
1002 if (FDecl)
1003 Result->AddTextChunk(FDecl->getNameAsString().c_str());
1004 else
1005 Result->AddTextChunk(
1006 Proto->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
1007
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001008 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001009 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
1010 for (unsigned I = 0; I != NumParams; ++I) {
1011 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001012 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001013
1014 std::string ArgString;
1015 QualType ArgType;
1016
1017 if (FDecl) {
1018 ArgString = FDecl->getParamDecl(I)->getNameAsString();
1019 ArgType = FDecl->getParamDecl(I)->getOriginalType();
1020 } else {
1021 ArgType = Proto->getArgType(I);
1022 }
1023
1024 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
1025
1026 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001027 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
1028 ArgString.c_str()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001029 else
1030 Result->AddTextChunk(ArgString.c_str());
1031 }
1032
1033 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001034 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001035 if (CurrentArg < NumParams)
1036 Result->AddTextChunk("...");
1037 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001038 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001039 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001040 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001041
1042 return Result;
1043}
1044
Douglas Gregor86d9a522009-09-21 16:56:56 +00001045namespace {
1046 struct SortCodeCompleteResult {
1047 typedef CodeCompleteConsumer::Result Result;
1048
Douglas Gregor6a684032009-09-28 03:51:44 +00001049 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregor36ecb042009-11-17 23:22:23 +00001050 if (!X.getObjCSelector().isNull() && !Y.getObjCSelector().isNull()) {
1051 // Consider all selector kinds to be equivalent.
1052 } else if (X.getNameKind() != Y.getNameKind())
Douglas Gregor6a684032009-09-28 03:51:44 +00001053 return X.getNameKind() < Y.getNameKind();
1054
1055 return llvm::LowercaseString(X.getAsString())
1056 < llvm::LowercaseString(Y.getAsString());
1057 }
1058
Douglas Gregor86d9a522009-09-21 16:56:56 +00001059 bool operator()(const Result &X, const Result &Y) const {
1060 // Sort first by rank.
1061 if (X.Rank < Y.Rank)
1062 return true;
1063 else if (X.Rank > Y.Rank)
1064 return false;
1065
1066 // Result kinds are ordered by decreasing importance.
1067 if (X.Kind < Y.Kind)
1068 return true;
1069 else if (X.Kind > Y.Kind)
1070 return false;
1071
1072 // Non-hidden names precede hidden names.
1073 if (X.Hidden != Y.Hidden)
1074 return !X.Hidden;
1075
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001076 // Non-nested-name-specifiers precede nested-name-specifiers.
1077 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1078 return !X.StartsNestedNameSpecifier;
1079
Douglas Gregor86d9a522009-09-21 16:56:56 +00001080 // Ordering depends on the kind of result.
1081 switch (X.Kind) {
1082 case Result::RK_Declaration:
1083 // Order based on the declaration names.
Douglas Gregor6a684032009-09-28 03:51:44 +00001084 return isEarlierDeclarationName(X.Declaration->getDeclName(),
1085 Y.Declaration->getDeclName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001086
1087 case Result::RK_Keyword:
Steve Naroff7f511122009-10-08 23:45:10 +00001088 return strcmp(X.Keyword, Y.Keyword) < 0;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001089
1090 case Result::RK_Macro:
1091 return llvm::LowercaseString(X.Macro->getName()) <
1092 llvm::LowercaseString(Y.Macro->getName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001093 }
1094
1095 // Silence GCC warning.
1096 return false;
1097 }
1098 };
1099}
1100
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001101static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1102 ResultBuilder &Results) {
1103 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001104 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1105 MEnd = PP.macro_end();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001106 M != MEnd; ++M)
1107 Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1108 Results.ExitScope();
1109}
1110
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001111static void HandleCodeCompleteResults(Sema *S,
1112 CodeCompleteConsumer *CodeCompleter,
1113 CodeCompleteConsumer::Result *Results,
1114 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00001115 // Sort the results by rank/kind/etc.
1116 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1117
1118 if (CodeCompleter)
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001119 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001120}
1121
Douglas Gregor791215b2009-09-21 20:51:25 +00001122void Sema::CodeCompleteOrdinaryName(Scope *S) {
1123 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001124 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1125 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001126 if (CodeCompleter->includeMacros())
1127 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001128 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00001129}
1130
Douglas Gregor81b747b2009-09-17 21:32:03 +00001131void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1132 SourceLocation OpLoc,
1133 bool IsArrow) {
1134 if (!BaseE || !CodeCompleter)
1135 return;
1136
Douglas Gregor86d9a522009-09-21 16:56:56 +00001137 typedef CodeCompleteConsumer::Result Result;
1138
Douglas Gregor81b747b2009-09-17 21:32:03 +00001139 Expr *Base = static_cast<Expr *>(BaseE);
1140 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001141
1142 if (IsArrow) {
1143 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1144 BaseType = Ptr->getPointeeType();
1145 else if (BaseType->isObjCObjectPointerType())
1146 /*Do nothing*/ ;
1147 else
1148 return;
1149 }
1150
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001151 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001152 unsigned NextRank = 0;
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001153
1154 // If this isn't a record type, we are done.
1155 const RecordType *Record = BaseType->getAs<RecordType>();
1156 if (!Record)
Douglas Gregor86d9a522009-09-21 16:56:56 +00001157 return;
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001158
1159 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1160 Record->getDecl(), Results);
1161
1162 if (getLangOptions().CPlusPlus) {
1163 if (!Results.empty()) {
1164 // The "template" keyword can follow "->" or "." in the grammar.
1165 // However, we only want to suggest the template keyword if something
1166 // is dependent.
1167 bool IsDependent = BaseType->isDependentType();
1168 if (!IsDependent) {
1169 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1170 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1171 IsDependent = Ctx->isDependentContext();
1172 break;
1173 }
1174 }
1175
1176 if (IsDependent)
1177 Results.MaybeAddResult(Result("template", NextRank++));
1178 }
1179
1180 // We could have the start of a nested-name-specifier. Add those
1181 // results as well.
1182 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1183 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
1184 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001185 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001186
1187 // Add macros
1188 if (CodeCompleter->includeMacros())
1189 AddMacroResults(PP, NextRank, Results);
1190
1191 // Hand off the results found for code completion.
1192 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001193}
1194
Douglas Gregor374929f2009-09-18 15:37:17 +00001195void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1196 if (!CodeCompleter)
1197 return;
1198
Douglas Gregor86d9a522009-09-21 16:56:56 +00001199 typedef CodeCompleteConsumer::Result Result;
1200 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +00001201 switch ((DeclSpec::TST)TagSpec) {
1202 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001203 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +00001204 break;
1205
1206 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001207 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +00001208 break;
1209
1210 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00001211 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001212 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00001213 break;
1214
1215 default:
1216 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1217 return;
1218 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001219
1220 ResultBuilder Results(*this, Filter);
1221 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001222 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001223
1224 if (getLangOptions().CPlusPlus) {
1225 // We could have the start of a nested-name-specifier. Add those
1226 // results as well.
1227 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001228 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1229 NextRank, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001230 }
1231
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001232 if (CodeCompleter->includeMacros())
1233 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001234 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00001235}
1236
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001237void Sema::CodeCompleteCase(Scope *S) {
1238 if (getSwitchStack().empty() || !CodeCompleter)
1239 return;
1240
1241 SwitchStmt *Switch = getSwitchStack().back();
1242 if (!Switch->getCond()->getType()->isEnumeralType())
1243 return;
1244
1245 // Code-complete the cases of a switch statement over an enumeration type
1246 // by providing the list of
1247 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1248
1249 // Determine which enumerators we have already seen in the switch statement.
1250 // FIXME: Ideally, we would also be able to look *past* the code-completion
1251 // token, in case we are code-completing in the middle of the switch and not
1252 // at the end. However, we aren't able to do so at the moment.
1253 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001254 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001255 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1256 SC = SC->getNextSwitchCase()) {
1257 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1258 if (!Case)
1259 continue;
1260
1261 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1262 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1263 if (EnumConstantDecl *Enumerator
1264 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1265 // We look into the AST of the case statement to determine which
1266 // enumerator was named. Alternatively, we could compute the value of
1267 // the integral constant expression, then compare it against the
1268 // values of each enumerator. However, value-based approach would not
1269 // work as well with C++ templates where enumerators declared within a
1270 // template are type- and value-dependent.
1271 EnumeratorsSeen.insert(Enumerator);
1272
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001273 // If this is a qualified-id, keep track of the nested-name-specifier
1274 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001275 //
1276 // switch (TagD.getKind()) {
1277 // case TagDecl::TK_enum:
1278 // break;
1279 // case XXX
1280 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001281 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001282 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1283 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00001284 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001285 }
1286 }
1287
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001288 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1289 // If there are no prior enumerators in C++, check whether we have to
1290 // qualify the names of the enumerators that we suggest, because they
1291 // may not be visible in this scope.
1292 Qualifier = getRequiredQualification(Context, CurContext,
1293 Enum->getDeclContext());
1294
1295 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1296 }
1297
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001298 // Add any enumerators that have not yet been mentioned.
1299 ResultBuilder Results(*this);
1300 Results.EnterNewScope();
1301 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1302 EEnd = Enum->enumerator_end();
1303 E != EEnd; ++E) {
1304 if (EnumeratorsSeen.count(*E))
1305 continue;
1306
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001307 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001308 }
1309 Results.ExitScope();
1310
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001311 if (CodeCompleter->includeMacros())
1312 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001313 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001314}
1315
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001316namespace {
1317 struct IsBetterOverloadCandidate {
1318 Sema &S;
1319
1320 public:
1321 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1322
1323 bool
1324 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1325 return S.isBetterOverloadCandidate(X, Y);
1326 }
1327 };
1328}
1329
1330void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1331 ExprTy **ArgsIn, unsigned NumArgs) {
1332 if (!CodeCompleter)
1333 return;
1334
1335 Expr *Fn = (Expr *)FnIn;
1336 Expr **Args = (Expr **)ArgsIn;
1337
1338 // Ignore type-dependent call expressions entirely.
1339 if (Fn->isTypeDependent() ||
1340 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1341 return;
1342
1343 NamedDecl *Function;
1344 DeclarationName UnqualifiedName;
1345 NestedNameSpecifier *Qualifier;
1346 SourceRange QualifierRange;
1347 bool ArgumentDependentLookup;
1348 bool HasExplicitTemplateArgs;
John McCall833ca992009-10-29 08:12:44 +00001349 const TemplateArgumentLoc *ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001350 unsigned NumExplicitTemplateArgs;
1351
1352 DeconstructCallFunction(Fn,
1353 Function, UnqualifiedName, Qualifier, QualifierRange,
1354 ArgumentDependentLookup, HasExplicitTemplateArgs,
1355 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1356
1357
1358 // FIXME: What if we're calling something that isn't a function declaration?
1359 // FIXME: What if we're calling a pseudo-destructor?
1360 // FIXME: What if we're calling a member function?
1361
1362 // Build an overload candidate set based on the functions we find.
1363 OverloadCandidateSet CandidateSet;
1364 AddOverloadedCallCandidates(Function, UnqualifiedName,
1365 ArgumentDependentLookup, HasExplicitTemplateArgs,
1366 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1367 Args, NumArgs,
1368 CandidateSet,
1369 /*PartialOverloading=*/true);
1370
1371 // Sort the overload candidate set by placing the best overloads first.
1372 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1373 IsBetterOverloadCandidate(*this));
1374
1375 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05944382009-09-23 00:16:58 +00001376 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1377 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlsson90756302009-09-22 17:29:51 +00001378
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001379 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1380 CandEnd = CandidateSet.end();
1381 Cand != CandEnd; ++Cand) {
1382 if (Cand->Viable)
Douglas Gregor05944382009-09-23 00:16:58 +00001383 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001384 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001385 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
Douglas Gregor05944382009-09-23 00:16:58 +00001386 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001387}
1388
Douglas Gregor81b747b2009-09-17 21:32:03 +00001389void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1390 bool EnteringContext) {
1391 if (!SS.getScopeRep() || !CodeCompleter)
1392 return;
1393
Douglas Gregor86d9a522009-09-21 16:56:56 +00001394 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1395 if (!Ctx)
1396 return;
1397
1398 ResultBuilder Results(*this);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001399 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001400
1401 // The "template" keyword can follow "::" in the grammar, but only
1402 // put it into the grammar if the nested-name-specifier is dependent.
1403 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1404 if (!Results.empty() && NNS->isDependent())
1405 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1406
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001407 if (CodeCompleter->includeMacros())
1408 AddMacroResults(PP, NextRank + 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001409 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001410}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001411
1412void Sema::CodeCompleteUsing(Scope *S) {
1413 if (!CodeCompleter)
1414 return;
1415
Douglas Gregor86d9a522009-09-21 16:56:56 +00001416 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001417 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001418
1419 // If we aren't in class scope, we could see the "namespace" keyword.
1420 if (!S->isClassScope())
1421 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1422
1423 // After "using", we can see anything that would start a
1424 // nested-name-specifier.
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001425 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1426 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001427 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001428
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001429 if (CodeCompleter->includeMacros())
1430 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001431 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001432}
1433
1434void Sema::CodeCompleteUsingDirective(Scope *S) {
1435 if (!CodeCompleter)
1436 return;
1437
Douglas Gregor86d9a522009-09-21 16:56:56 +00001438 // After "using namespace", we expect to see a namespace name or namespace
1439 // alias.
1440 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001441 Results.EnterNewScope();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001442 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1443 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001444 Results.ExitScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001445 if (CodeCompleter->includeMacros())
1446 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001447 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001448}
1449
1450void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1451 if (!CodeCompleter)
1452 return;
1453
Douglas Gregor86d9a522009-09-21 16:56:56 +00001454 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1455 DeclContext *Ctx = (DeclContext *)S->getEntity();
1456 if (!S->getParent())
1457 Ctx = Context.getTranslationUnitDecl();
1458
1459 if (Ctx && Ctx->isFileContext()) {
1460 // We only want to see those namespaces that have already been defined
1461 // within this scope, because its likely that the user is creating an
1462 // extended namespace declaration. Keep track of the most recent
1463 // definition of each namespace.
1464 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1465 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1466 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1467 NS != NSEnd; ++NS)
1468 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1469
1470 // Add the most recent definition (or extended definition) of each
1471 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001472 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001473 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1474 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1475 NS != NSEnd; ++NS)
Douglas Gregor456c4a12009-09-21 20:12:40 +00001476 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1477 CurContext);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001478 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001479 }
1480
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001481 if (CodeCompleter->includeMacros())
1482 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001483 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001484}
1485
1486void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1487 if (!CodeCompleter)
1488 return;
1489
Douglas Gregor86d9a522009-09-21 16:56:56 +00001490 // After "namespace", we expect to see a namespace or alias.
1491 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001492 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1493 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001494 if (CodeCompleter->includeMacros())
1495 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001496 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001497}
1498
Douglas Gregored8d3222009-09-18 20:05:18 +00001499void Sema::CodeCompleteOperatorName(Scope *S) {
1500 if (!CodeCompleter)
1501 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001502
1503 typedef CodeCompleteConsumer::Result Result;
1504 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001505 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00001506
Douglas Gregor86d9a522009-09-21 16:56:56 +00001507 // Add the names of overloadable operators.
1508#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1509 if (std::strcmp(Spelling, "?")) \
1510 Results.MaybeAddResult(Result(Spelling, 0));
1511#include "clang/Basic/OperatorKinds.def"
1512
1513 // Add any type names visible from the current scope
1514 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001515 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001516
1517 // Add any type specifiers
1518 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1519
1520 // Add any nested-name-specifiers
1521 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001522 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1523 NextRank + 1, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001524 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001525
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001526 if (CodeCompleter->includeMacros())
1527 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001528 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00001529}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001530
Steve Naroffece8e712009-10-08 21:55:05 +00001531void Sema::CodeCompleteObjCProperty(Scope *S, ObjCDeclSpec &ODS) {
1532 if (!CodeCompleter)
1533 return;
1534 unsigned Attributes = ODS.getPropertyAttributes();
1535
1536 typedef CodeCompleteConsumer::Result Result;
1537 ResultBuilder Results(*this);
1538 Results.EnterNewScope();
1539 if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly))
1540 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
1541 if (!(Attributes & ObjCDeclSpec::DQ_PR_assign))
1542 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
1543 if (!(Attributes & ObjCDeclSpec::DQ_PR_readwrite))
1544 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
1545 if (!(Attributes & ObjCDeclSpec::DQ_PR_retain))
1546 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
1547 if (!(Attributes & ObjCDeclSpec::DQ_PR_copy))
1548 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
1549 if (!(Attributes & ObjCDeclSpec::DQ_PR_nonatomic))
1550 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
1551 if (!(Attributes & ObjCDeclSpec::DQ_PR_setter))
1552 Results.MaybeAddResult(CodeCompleteConsumer::Result("setter", 0));
1553 if (!(Attributes & ObjCDeclSpec::DQ_PR_getter))
1554 Results.MaybeAddResult(CodeCompleteConsumer::Result("getter", 0));
1555 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001556 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00001557}
Steve Naroffc4df6d22009-11-07 02:08:14 +00001558
Douglas Gregor36ecb042009-11-17 23:22:23 +00001559/// \brief Add all of the Objective-C methods in the given Objective-C
1560/// container to the set of results.
1561///
1562/// The container will be a class, protocol, category, or implementation of
1563/// any of the above. This mether will recurse to include methods from
1564/// the superclasses of classes along with their categories, protocols, and
1565/// implementations.
1566///
1567/// \param Container the container in which we'll look to find methods.
1568///
1569/// \param WantInstance whether to add instance methods (only); if false, this
1570/// routine will add factory methods (only).
1571///
1572/// \param CurContext the context in which we're performing the lookup that
1573/// finds methods.
1574///
1575/// \param Results the structure into which we'll add results.
1576static void AddObjCMethods(ObjCContainerDecl *Container,
1577 bool WantInstanceMethods,
1578 DeclContext *CurContext,
1579 ResultBuilder &Results) {
1580 typedef CodeCompleteConsumer::Result Result;
1581 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
1582 MEnd = Container->meth_end();
1583 M != MEnd; ++M) {
1584 if ((*M)->isInstanceMethod() == WantInstanceMethods)
1585 Results.MaybeAddResult(Result(*M, 0), CurContext);
1586 }
1587
1588 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
1589 if (!IFace)
1590 return;
1591
1592 // Add methods in protocols.
1593 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
1594 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1595 E = Protocols.end();
1596 I != E; ++I)
1597 AddObjCMethods(*I, WantInstanceMethods, CurContext, Results);
1598
1599 // Add methods in categories.
1600 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
1601 CatDecl = CatDecl->getNextClassCategory()) {
1602 AddObjCMethods(CatDecl, WantInstanceMethods, CurContext, Results);
1603
1604 // Add a categories protocol methods.
1605 const ObjCList<ObjCProtocolDecl> &Protocols
1606 = CatDecl->getReferencedProtocols();
1607 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1608 E = Protocols.end();
1609 I != E; ++I)
1610 AddObjCMethods(*I, WantInstanceMethods, CurContext, Results);
1611
1612 // Add methods in category implementations.
1613 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
1614 AddObjCMethods(Impl, WantInstanceMethods, CurContext, Results);
1615 }
1616
1617 // Add methods in superclass.
1618 if (IFace->getSuperClass())
1619 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, CurContext,
1620 Results);
1621
1622 // Add methods in our implementation, if any.
1623 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
1624 AddObjCMethods(Impl, WantInstanceMethods, CurContext, Results);
1625}
1626
Steve Naroffc4df6d22009-11-07 02:08:14 +00001627void Sema::CodeCompleteObjCFactoryMethod(Scope *S, IdentifierInfo *FName) {
1628 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00001629 ObjCInterfaceDecl *CDecl = 0;
1630
1631 // FIXME: Pass this in!
1632 SourceLocation NameLoc;
1633
1634 if (FName->isStr("super")) {
1635 // We're sending a message to "super".
1636 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
1637 // Figure out which interface we're in.
1638 CDecl = CurMethod->getClassInterface();
1639 if (!CDecl)
1640 return;
1641
1642 // Find the superclass of this class.
1643 CDecl = CDecl->getSuperClass();
1644 if (!CDecl)
1645 return;
1646
1647 if (CurMethod->isInstanceMethod()) {
1648 // We are inside an instance method, which means that the message
1649 // send [super ...] is actually calling an instance method on the
1650 // current object. Build the super expression and handle this like
1651 // an instance method.
1652 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
1653 SuperTy = Context.getObjCObjectPointerType(SuperTy);
1654 OwningExprResult Super
1655 = Owned(new (Context) ObjCSuperExpr(NameLoc, SuperTy));
1656 return CodeCompleteObjCInstanceMethod(S, (Expr *)Super.get());
1657 }
1658
1659 // Okay, we're calling a factory method in our superclass.
1660 }
1661 }
1662
1663 // If the given name refers to an interface type, retrieve the
1664 // corresponding declaration.
1665 if (!CDecl)
1666 if (TypeTy *Ty = getTypeName(*FName, NameLoc, S, 0, false)) {
1667 QualType T = GetTypeFromParser(Ty, 0);
1668 if (!T.isNull())
1669 if (const ObjCInterfaceType *Interface = T->getAs<ObjCInterfaceType>())
1670 CDecl = Interface->getDecl();
1671 }
1672
1673 if (!CDecl && FName->isStr("super")) {
1674 // "super" may be the name of a variable, in which case we are
1675 // probably calling an instance method.
1676 OwningExprResult Super = ActOnDeclarationNameExpr(S, NameLoc, FName,
1677 false, 0, false);
1678 return CodeCompleteObjCInstanceMethod(S, (Expr *)Super.get());
1679 }
1680
Douglas Gregor36ecb042009-11-17 23:22:23 +00001681 // Add all of the factory methods in this Objective-C class, its protocols,
1682 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00001683 ResultBuilder Results(*this);
1684 Results.EnterNewScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00001685 AddObjCMethods(CDecl, false, CurContext, Results);
Steve Naroffc4df6d22009-11-07 02:08:14 +00001686 Results.ExitScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00001687
Steve Naroffc4df6d22009-11-07 02:08:14 +00001688 // This also suppresses remaining diagnostics.
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001689 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00001690}
1691
1692void Sema::CodeCompleteObjCInstanceMethod(Scope *S, ExprTy *Receiver) {
1693 typedef CodeCompleteConsumer::Result Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00001694
1695 Expr *RecExpr = static_cast<Expr *>(Receiver);
1696 QualType RecType = RecExpr->getType();
1697
Douglas Gregor36ecb042009-11-17 23:22:23 +00001698 // If necessary, apply function/array conversion to the receiver.
1699 // C99 6.7.5.3p[7,8].
1700 DefaultFunctionArrayConversion(RecExpr);
1701 QualType ReceiverType = RecExpr->getType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00001702
Douglas Gregor36ecb042009-11-17 23:22:23 +00001703 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType()) {
1704 // FIXME: We're messaging 'id'. Do we actually want to look up every method
1705 // in the universe?
1706 return;
1707 }
1708
1709 const ObjCObjectPointerType* OCOPT
1710 = ReceiverType->getAs<ObjCObjectPointerType>();
Steve Naroffc4df6d22009-11-07 02:08:14 +00001711 if (!OCOPT)
1712 return;
1713
1714 // FIXME: handle 'id', 'Class', and qualified types.
Douglas Gregor36ecb042009-11-17 23:22:23 +00001715
1716 // Build the set of methods we can see.
1717 ResultBuilder Results(*this);
1718 Results.EnterNewScope();
Steve Naroffc4df6d22009-11-07 02:08:14 +00001719
Douglas Gregor36ecb042009-11-17 23:22:23 +00001720 ObjCInterfaceDecl *CDecl = OCOPT->getInterfaceDecl();
1721 if (!CDecl)
1722 return;
1723
1724 AddObjCMethods(CDecl, true, CurContext, Results);
Steve Naroffc4df6d22009-11-07 02:08:14 +00001725 Results.ExitScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00001726
Steve Naroffc4df6d22009-11-07 02:08:14 +00001727 // This also suppresses remaining diagnostics.
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001728 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00001729}