blob: 072dfe9b73ad7d30cc16d9de11e8c902e2b2049e [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 Gregor3f7c7f42009-10-30 16:50:04 +000016#include "clang/Lex/MacroInfo.h"
17#include "clang/Lex/Preprocessor.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000018#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000019#include "llvm/ADT/StringExtras.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000020#include <list>
21#include <map>
22#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000023
24using namespace clang;
25
26/// \brief Set the code-completion consumer for semantic analysis.
27void Sema::setCodeCompleteConsumer(CodeCompleteConsumer *CCC) {
28 assert(((CodeCompleter != 0) != (CCC != 0)) &&
29 "Already set or cleared a code-completion consumer?");
30 CodeCompleter = CCC;
31}
32
Douglas Gregor86d9a522009-09-21 16:56:56 +000033namespace {
34 /// \brief A container of code-completion results.
35 class ResultBuilder {
36 public:
37 /// \brief The type of a name-lookup filter, which can be provided to the
38 /// name-lookup routines to specify which declarations should be included in
39 /// the result set (when it returns true) and which declarations should be
40 /// filtered out (returns false).
41 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
42
43 typedef CodeCompleteConsumer::Result Result;
44
45 private:
46 /// \brief The actual results we have found.
47 std::vector<Result> Results;
48
49 /// \brief A record of all of the declarations we have found and placed
50 /// into the result set, used to ensure that no declaration ever gets into
51 /// the result set twice.
52 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
53
54 /// \brief A mapping from declaration names to the declarations that have
55 /// this name within a particular scope and their index within the list of
56 /// results.
57 typedef std::multimap<DeclarationName,
58 std::pair<NamedDecl *, unsigned> > ShadowMap;
59
60 /// \brief The semantic analysis object for which results are being
61 /// produced.
62 Sema &SemaRef;
63
64 /// \brief If non-NULL, a filter function used to remove any code-completion
65 /// results that are not desirable.
66 LookupFilter Filter;
67
68 /// \brief A list of shadow maps, which is used to model name hiding at
69 /// different levels of, e.g., the inheritance hierarchy.
70 std::list<ShadowMap> ShadowMaps;
71
72 public:
73 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
74 : SemaRef(SemaRef), Filter(Filter) { }
75
76 /// \brief Set the filter used for code-completion results.
77 void setFilter(LookupFilter Filter) {
78 this->Filter = Filter;
79 }
80
81 typedef std::vector<Result>::iterator iterator;
82 iterator begin() { return Results.begin(); }
83 iterator end() { return Results.end(); }
84
85 Result *data() { return Results.empty()? 0 : &Results.front(); }
86 unsigned size() const { return Results.size(); }
87 bool empty() const { return Results.empty(); }
88
89 /// \brief Add a new result to this result set (if it isn't already in one
90 /// of the shadow maps), or replace an existing result (for, e.g., a
91 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +000092 ///
93 /// \param R the result to add (if it is unique).
94 ///
95 /// \param R the context in which this result will be named.
96 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +000097
98 /// \brief Enter into a new scope.
99 void EnterNewScope();
100
101 /// \brief Exit from the current scope.
102 void ExitScope();
103
104 /// \name Name lookup predicates
105 ///
106 /// These predicates can be passed to the name lookup functions to filter the
107 /// results of name lookup. All of the predicates have the same type, so that
108 ///
109 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000110 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000111 bool IsNestedNameSpecifier(NamedDecl *ND) const;
112 bool IsEnum(NamedDecl *ND) const;
113 bool IsClassOrStruct(NamedDecl *ND) const;
114 bool IsUnion(NamedDecl *ND) const;
115 bool IsNamespace(NamedDecl *ND) const;
116 bool IsNamespaceOrAlias(NamedDecl *ND) const;
117 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000118 bool IsMember(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000119 //@}
120 };
121}
122
123/// \brief Determines whether the given hidden result could be found with
124/// some extra work, e.g., by qualifying the name.
125///
126/// \param Hidden the declaration that is hidden by the currenly \p Visible
127/// declaration.
128///
129/// \param Visible the declaration with the same name that is already visible.
130///
131/// \returns true if the hidden result can be found by some mechanism,
132/// false otherwise.
133static bool canHiddenResultBeFound(const LangOptions &LangOpts,
134 NamedDecl *Hidden, NamedDecl *Visible) {
135 // In C, there is no way to refer to a hidden name.
136 if (!LangOpts.CPlusPlus)
137 return false;
138
139 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
140
141 // There is no way to qualify a name declared in a function or method.
142 if (HiddenCtx->isFunctionOrMethod())
143 return false;
144
Douglas Gregor86d9a522009-09-21 16:56:56 +0000145 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
146}
147
Douglas Gregor456c4a12009-09-21 20:12:40 +0000148/// \brief Compute the qualification required to get from the current context
149/// (\p CurContext) to the target context (\p TargetContext).
150///
151/// \param Context the AST context in which the qualification will be used.
152///
153/// \param CurContext the context where an entity is being named, which is
154/// typically based on the current scope.
155///
156/// \param TargetContext the context in which the named entity actually
157/// resides.
158///
159/// \returns a nested name specifier that refers into the target context, or
160/// NULL if no qualification is needed.
161static NestedNameSpecifier *
162getRequiredQualification(ASTContext &Context,
163 DeclContext *CurContext,
164 DeclContext *TargetContext) {
165 llvm::SmallVector<DeclContext *, 4> TargetParents;
166
167 for (DeclContext *CommonAncestor = TargetContext;
168 CommonAncestor && !CommonAncestor->Encloses(CurContext);
169 CommonAncestor = CommonAncestor->getLookupParent()) {
170 if (CommonAncestor->isTransparentContext() ||
171 CommonAncestor->isFunctionOrMethod())
172 continue;
173
174 TargetParents.push_back(CommonAncestor);
175 }
176
177 NestedNameSpecifier *Result = 0;
178 while (!TargetParents.empty()) {
179 DeclContext *Parent = TargetParents.back();
180 TargetParents.pop_back();
181
182 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
183 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
184 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
185 Result = NestedNameSpecifier::Create(Context, Result,
186 false,
187 Context.getTypeDeclType(TD).getTypePtr());
188 else
189 assert(Parent->isTranslationUnit());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000190 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000191 return Result;
192}
193
194void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
Douglas Gregor8e0a0e42009-09-22 23:31:26 +0000195 assert(!ShadowMaps.empty() && "Must enter into a results scope");
196
Douglas Gregor86d9a522009-09-21 16:56:56 +0000197 if (R.Kind != Result::RK_Declaration) {
198 // For non-declaration results, just add the result.
199 Results.push_back(R);
200 return;
201 }
Douglas Gregorf52cede2009-10-09 22:16:47 +0000202
203 // Skip unnamed entities.
204 if (!R.Declaration->getDeclName())
205 return;
206
Douglas Gregor86d9a522009-09-21 16:56:56 +0000207 // Look through using declarations.
208 if (UsingDecl *Using = dyn_cast<UsingDecl>(R.Declaration))
Douglas Gregor0563c262009-09-22 23:15:58 +0000209 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
210 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000211
212 // Handle each declaration in an overload set separately.
213 if (OverloadedFunctionDecl *Ovl
214 = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) {
215 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
216 FEnd = Ovl->function_end();
217 F != FEnd; ++F)
Douglas Gregor456c4a12009-09-21 20:12:40 +0000218 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000219
220 return;
221 }
222
223 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
224 unsigned IDNS = CanonDecl->getIdentifierNamespace();
225
226 // Friend declarations and declarations introduced due to friends are never
227 // added as results.
228 if (isa<FriendDecl>(CanonDecl) ||
229 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
230 return;
231
232 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
233 // __va_list_tag is a freak of nature. Find it and skip it.
234 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
235 return;
236
Douglas Gregorf52cede2009-10-09 22:16:47 +0000237 // Filter out names reserved for the implementation (C99 7.1.3,
238 // C++ [lib.global.names]). Users don't need to see those.
Daniel Dunbare013d682009-10-18 20:26:12 +0000239 //
240 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000241 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000242 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000243 if (Name[0] == '_' &&
244 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
245 return;
246 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000247 }
248
249 // C++ constructors are never found by name lookup.
250 if (isa<CXXConstructorDecl>(CanonDecl))
251 return;
252
253 // Filter out any unwanted results.
254 if (Filter && !(this->*Filter)(R.Declaration))
255 return;
256
257 ShadowMap &SMap = ShadowMaps.back();
258 ShadowMap::iterator I, IEnd;
259 for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
260 I != IEnd; ++I) {
261 NamedDecl *ND = I->second.first;
262 unsigned Index = I->second.second;
263 if (ND->getCanonicalDecl() == CanonDecl) {
264 // This is a redeclaration. Always pick the newer declaration.
265 I->second.first = R.Declaration;
266 Results[Index].Declaration = R.Declaration;
267
268 // Pick the best rank of the two.
269 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
270
271 // We're done.
272 return;
273 }
274 }
275
276 // This is a new declaration in this scope. However, check whether this
277 // declaration name is hidden by a similarly-named declaration in an outer
278 // scope.
279 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
280 --SMEnd;
281 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
282 for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
283 I != IEnd; ++I) {
284 // A tag declaration does not hide a non-tag declaration.
285 if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
286 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
287 Decl::IDNS_ObjCProtocol)))
288 continue;
289
290 // Protocols are in distinct namespaces from everything else.
291 if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
292 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
293 I->second.first->getIdentifierNamespace() != IDNS)
294 continue;
295
296 // The newly-added result is hidden by an entry in the shadow map.
297 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
298 I->second.first)) {
299 // Note that this result was hidden.
300 R.Hidden = true;
Douglas Gregor0563c262009-09-22 23:15:58 +0000301 R.QualifierIsInformative = false;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000302
303 if (!R.Qualifier)
304 R.Qualifier = getRequiredQualification(SemaRef.Context,
305 CurContext,
306 R.Declaration->getDeclContext());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000307 } else {
308 // This result was hidden and cannot be found; don't bother adding
309 // it.
310 return;
311 }
312
313 break;
314 }
315 }
316
317 // Make sure that any given declaration only shows up in the result set once.
318 if (!AllDeclsFound.insert(CanonDecl))
319 return;
320
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000321 // If the filter is for nested-name-specifiers, then this result starts a
322 // nested-name-specifier.
323 if ((Filter == &ResultBuilder::IsNestedNameSpecifier) ||
324 (Filter == &ResultBuilder::IsMember &&
325 isa<CXXRecordDecl>(R.Declaration) &&
326 cast<CXXRecordDecl>(R.Declaration)->isInjectedClassName()))
327 R.StartsNestedNameSpecifier = true;
328
Douglas Gregor0563c262009-09-22 23:15:58 +0000329 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000330 if (R.QualifierIsInformative && !R.Qualifier &&
331 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000332 DeclContext *Ctx = R.Declaration->getDeclContext();
333 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
334 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
335 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
336 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
337 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
338 else
339 R.QualifierIsInformative = false;
340 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000341
Douglas Gregor86d9a522009-09-21 16:56:56 +0000342 // Insert this result into the set of results and into the current shadow
343 // map.
344 SMap.insert(std::make_pair(R.Declaration->getDeclName(),
345 std::make_pair(R.Declaration, Results.size())));
346 Results.push_back(R);
347}
348
349/// \brief Enter into a new scope.
350void ResultBuilder::EnterNewScope() {
351 ShadowMaps.push_back(ShadowMap());
352}
353
354/// \brief Exit from the current scope.
355void ResultBuilder::ExitScope() {
356 ShadowMaps.pop_back();
357}
358
Douglas Gregor791215b2009-09-21 20:51:25 +0000359/// \brief Determines whether this given declaration will be found by
360/// ordinary name lookup.
361bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
362 unsigned IDNS = Decl::IDNS_Ordinary;
363 if (SemaRef.getLangOptions().CPlusPlus)
364 IDNS |= Decl::IDNS_Tag;
365
366 return ND->getIdentifierNamespace() & IDNS;
367}
368
Douglas Gregor86d9a522009-09-21 16:56:56 +0000369/// \brief Determines whether the given declaration is suitable as the
370/// start of a C++ nested-name-specifier, e.g., a class or namespace.
371bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
372 // Allow us to find class templates, too.
373 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
374 ND = ClassTemplate->getTemplatedDecl();
375
376 return SemaRef.isAcceptableNestedNameSpecifier(ND);
377}
378
379/// \brief Determines whether the given declaration is an enumeration.
380bool ResultBuilder::IsEnum(NamedDecl *ND) const {
381 return isa<EnumDecl>(ND);
382}
383
384/// \brief Determines whether the given declaration is a class or struct.
385bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
386 // Allow us to find class templates, too.
387 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
388 ND = ClassTemplate->getTemplatedDecl();
389
390 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
391 return RD->getTagKind() == TagDecl::TK_class ||
392 RD->getTagKind() == TagDecl::TK_struct;
393
394 return false;
395}
396
397/// \brief Determines whether the given declaration is a union.
398bool ResultBuilder::IsUnion(NamedDecl *ND) const {
399 // Allow us to find class templates, too.
400 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
401 ND = ClassTemplate->getTemplatedDecl();
402
403 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
404 return RD->getTagKind() == TagDecl::TK_union;
405
406 return false;
407}
408
409/// \brief Determines whether the given declaration is a namespace.
410bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
411 return isa<NamespaceDecl>(ND);
412}
413
414/// \brief Determines whether the given declaration is a namespace or
415/// namespace alias.
416bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
417 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
418}
419
420/// \brief Brief determines whether the given declaration is a namespace or
421/// namespace alias.
422bool ResultBuilder::IsType(NamedDecl *ND) const {
423 return isa<TypeDecl>(ND);
424}
425
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000426/// \brief Since every declaration found within a class is a member that we
427/// care about, always returns true. This predicate exists mostly to
428/// communicate to the result builder that we are performing a lookup for
429/// member access.
430bool ResultBuilder::IsMember(NamedDecl *ND) const {
431 return true;
432}
433
Douglas Gregor86d9a522009-09-21 16:56:56 +0000434// Find the next outer declaration context corresponding to this scope.
435static DeclContext *findOuterContext(Scope *S) {
436 for (S = S->getParent(); S; S = S->getParent())
437 if (S->getEntity())
438 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
439
440 return 0;
441}
442
443/// \brief Collect the results of searching for members within the given
444/// declaration context.
445///
446/// \param Ctx the declaration context from which we will gather results.
447///
Douglas Gregor0563c262009-09-22 23:15:58 +0000448/// \param Rank the rank given to results in this declaration context.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000449///
450/// \param Visited the set of declaration contexts that have already been
451/// visited. Declaration contexts will only be visited once.
452///
453/// \param Results the result set that will be extended with any results
454/// found within this declaration context (and, for a C++ class, its bases).
455///
Douglas Gregor0563c262009-09-22 23:15:58 +0000456/// \param InBaseClass whether we are in a base class.
457///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000458/// \returns the next higher rank value, after considering all of the
459/// names within this declaration context.
460static unsigned CollectMemberLookupResults(DeclContext *Ctx,
Douglas Gregor0563c262009-09-22 23:15:58 +0000461 unsigned Rank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000462 DeclContext *CurContext,
463 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor0563c262009-09-22 23:15:58 +0000464 ResultBuilder &Results,
465 bool InBaseClass = false) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000466 // Make sure we don't visit the same context twice.
467 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor0563c262009-09-22 23:15:58 +0000468 return Rank;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000469
470 // Enumerate all of the results in this context.
Douglas Gregor0563c262009-09-22 23:15:58 +0000471 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000472 Results.EnterNewScope();
473 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
474 CurCtx = CurCtx->getNextContext()) {
475 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregorff4393c2009-11-09 21:35:27 +0000476 DEnd = CurCtx->decls_end();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000477 D != DEnd; ++D) {
478 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor0563c262009-09-22 23:15:58 +0000479 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregorff4393c2009-11-09 21:35:27 +0000480
481 // Visit transparent contexts inside this context.
482 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
483 if (InnerCtx->isTransparentContext())
484 CollectMemberLookupResults(InnerCtx, Rank, CurContext, Visited,
485 Results, InBaseClass);
486 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000487 }
488 }
489
490 // Traverse the contexts of inherited classes.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000491 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
492 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
Douglas Gregorff4393c2009-11-09 21:35:27 +0000493 BEnd = Record->bases_end();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000494 B != BEnd; ++B) {
495 QualType BaseType = B->getType();
496
497 // Don't look into dependent bases, because name lookup can't look
498 // there anyway.
499 if (BaseType->isDependentType())
500 continue;
501
502 const RecordType *Record = BaseType->getAs<RecordType>();
503 if (!Record)
504 continue;
505
506 // FIXME: It would be nice to be able to determine whether referencing
507 // a particular member would be ambiguous. For example, given
508 //
509 // struct A { int member; };
510 // struct B { int member; };
511 // struct C : A, B { };
512 //
513 // void f(C *c) { c->### }
514 // accessing 'member' would result in an ambiguity. However, code
515 // completion could be smart enough to qualify the member with the
516 // base class, e.g.,
517 //
518 // c->B::member
519 //
520 // or
521 //
522 // c->A::member
523
524 // Collect results from this base class (and its bases).
Douglas Gregor0563c262009-09-22 23:15:58 +0000525 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
526 Results, /*InBaseClass=*/true);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000527 }
528 }
529
530 // FIXME: Look into base classes in Objective-C!
531
532 Results.ExitScope();
Douglas Gregor0563c262009-09-22 23:15:58 +0000533 return Rank + 1;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000534}
535
536/// \brief Collect the results of searching for members within the given
537/// declaration context.
538///
539/// \param Ctx the declaration context from which we will gather results.
540///
541/// \param InitialRank the initial rank given to results in this declaration
542/// context. Larger rank values will be used for, e.g., members found in
543/// base classes.
544///
545/// \param Results the result set that will be extended with any results
546/// found within this declaration context (and, for a C++ class, its bases).
547///
548/// \returns the next higher rank value, after considering all of the
549/// names within this declaration context.
550static unsigned CollectMemberLookupResults(DeclContext *Ctx,
551 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000552 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000553 ResultBuilder &Results) {
554 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000555 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
556 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000557}
558
559/// \brief Collect the results of searching for declarations within the given
560/// scope and its parent scopes.
561///
562/// \param S the scope in which we will start looking for declarations.
563///
564/// \param InitialRank the initial rank given to results in this scope.
565/// Larger rank values will be used for results found in parent scopes.
566///
Douglas Gregor456c4a12009-09-21 20:12:40 +0000567/// \param CurContext the context from which lookup results will be found.
568///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000569/// \param Results the builder object that will receive each result.
570static unsigned CollectLookupResults(Scope *S,
571 TranslationUnitDecl *TranslationUnit,
572 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000573 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000574 ResultBuilder &Results) {
575 if (!S)
576 return InitialRank;
577
578 // FIXME: Using directives!
579
580 unsigned NextRank = InitialRank;
581 Results.EnterNewScope();
582 if (S->getEntity() &&
583 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
584 // Look into this scope's declaration context, along with any of its
585 // parent lookup contexts (e.g., enclosing classes), up to the point
586 // where we hit the context stored in the next outer scope.
587 DeclContext *Ctx = (DeclContext *)S->getEntity();
588 DeclContext *OuterCtx = findOuterContext(S);
589
590 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
591 Ctx = Ctx->getLookupParent()) {
592 if (Ctx->isFunctionOrMethod())
593 continue;
594
Douglas Gregor456c4a12009-09-21 20:12:40 +0000595 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
596 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000597 }
598 } else if (!S->getParent()) {
599 // Look into the translation unit scope. We walk through the translation
600 // unit's declaration context, because the Scope itself won't have all of
601 // the declarations if we loaded a precompiled header.
602 // FIXME: We would like the translation unit's Scope object to point to the
603 // translation unit, so we don't need this special "if" branch. However,
604 // doing so would force the normal C++ name-lookup code to look into the
605 // translation unit decl when the IdentifierInfo chains would suffice.
606 // Once we fix that problem (which is part of a more general "don't look
607 // in DeclContexts unless we have to" optimization), we can eliminate the
608 // TranslationUnit parameter entirely.
609 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000610 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000611 } else {
612 // Walk through the declarations in this Scope.
613 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
614 D != DEnd; ++D) {
615 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
Douglas Gregor456c4a12009-09-21 20:12:40 +0000616 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
617 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000618 }
619
620 NextRank = NextRank + 1;
621 }
622
623 // Lookup names in the parent scope.
624 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000625 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000626 Results.ExitScope();
627
628 return NextRank;
629}
630
631/// \brief Add type specifiers for the current language as keyword results.
632static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
633 ResultBuilder &Results) {
634 typedef CodeCompleteConsumer::Result Result;
635 Results.MaybeAddResult(Result("short", Rank));
636 Results.MaybeAddResult(Result("long", Rank));
637 Results.MaybeAddResult(Result("signed", Rank));
638 Results.MaybeAddResult(Result("unsigned", Rank));
639 Results.MaybeAddResult(Result("void", Rank));
640 Results.MaybeAddResult(Result("char", Rank));
641 Results.MaybeAddResult(Result("int", Rank));
642 Results.MaybeAddResult(Result("float", Rank));
643 Results.MaybeAddResult(Result("double", Rank));
644 Results.MaybeAddResult(Result("enum", Rank));
645 Results.MaybeAddResult(Result("struct", Rank));
646 Results.MaybeAddResult(Result("union", Rank));
647
648 if (LangOpts.C99) {
649 // C99-specific
650 Results.MaybeAddResult(Result("_Complex", Rank));
651 Results.MaybeAddResult(Result("_Imaginary", Rank));
652 Results.MaybeAddResult(Result("_Bool", Rank));
653 }
654
655 if (LangOpts.CPlusPlus) {
656 // C++-specific
657 Results.MaybeAddResult(Result("bool", Rank));
658 Results.MaybeAddResult(Result("class", Rank));
659 Results.MaybeAddResult(Result("typename", Rank));
660 Results.MaybeAddResult(Result("wchar_t", Rank));
661
662 if (LangOpts.CPlusPlus0x) {
663 Results.MaybeAddResult(Result("char16_t", Rank));
664 Results.MaybeAddResult(Result("char32_t", Rank));
665 Results.MaybeAddResult(Result("decltype", Rank));
666 }
667 }
668
669 // GNU extensions
670 if (LangOpts.GNUMode) {
671 // FIXME: Enable when we actually support decimal floating point.
672 // Results.MaybeAddResult(Result("_Decimal32", Rank));
673 // Results.MaybeAddResult(Result("_Decimal64", Rank));
674 // Results.MaybeAddResult(Result("_Decimal128", Rank));
675 Results.MaybeAddResult(Result("typeof", Rank));
676 }
677}
678
679/// \brief Add function parameter chunks to the given code completion string.
680static void AddFunctionParameterChunks(ASTContext &Context,
681 FunctionDecl *Function,
682 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000683 typedef CodeCompletionString::Chunk Chunk;
684
Douglas Gregor86d9a522009-09-21 16:56:56 +0000685 CodeCompletionString *CCStr = Result;
686
687 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
688 ParmVarDecl *Param = Function->getParamDecl(P);
689
690 if (Param->hasDefaultArg()) {
691 // When we see an optional default argument, put that argument and
692 // the remaining default arguments into a new, optional string.
693 CodeCompletionString *Opt = new CodeCompletionString;
694 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
695 CCStr = Opt;
696 }
697
698 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000699 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000700
701 // Format the placeholder string.
702 std::string PlaceholderStr;
703 if (Param->getIdentifier())
704 PlaceholderStr = Param->getIdentifier()->getName();
705
706 Param->getType().getAsStringInternal(PlaceholderStr,
707 Context.PrintingPolicy);
708
709 // Add the placeholder string.
710 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
711 }
Douglas Gregorb3d45252009-09-22 21:42:17 +0000712
713 if (const FunctionProtoType *Proto
714 = Function->getType()->getAs<FunctionProtoType>())
715 if (Proto->isVariadic())
716 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000717}
718
719/// \brief Add template parameter chunks to the given code completion string.
720static void AddTemplateParameterChunks(ASTContext &Context,
721 TemplateDecl *Template,
722 CodeCompletionString *Result,
723 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000724 typedef CodeCompletionString::Chunk Chunk;
725
Douglas Gregor86d9a522009-09-21 16:56:56 +0000726 CodeCompletionString *CCStr = Result;
727 bool FirstParameter = true;
728
729 TemplateParameterList *Params = Template->getTemplateParameters();
730 TemplateParameterList::iterator PEnd = Params->end();
731 if (MaxParameters)
732 PEnd = Params->begin() + MaxParameters;
733 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
734 bool HasDefaultArg = false;
735 std::string PlaceholderStr;
736 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
737 if (TTP->wasDeclaredWithTypename())
738 PlaceholderStr = "typename";
739 else
740 PlaceholderStr = "class";
741
742 if (TTP->getIdentifier()) {
743 PlaceholderStr += ' ';
744 PlaceholderStr += TTP->getIdentifier()->getName();
745 }
746
747 HasDefaultArg = TTP->hasDefaultArgument();
748 } else if (NonTypeTemplateParmDecl *NTTP
749 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
750 if (NTTP->getIdentifier())
751 PlaceholderStr = NTTP->getIdentifier()->getName();
752 NTTP->getType().getAsStringInternal(PlaceholderStr,
753 Context.PrintingPolicy);
754 HasDefaultArg = NTTP->hasDefaultArgument();
755 } else {
756 assert(isa<TemplateTemplateParmDecl>(*P));
757 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
758
759 // Since putting the template argument list into the placeholder would
760 // be very, very long, we just use an abbreviation.
761 PlaceholderStr = "template<...> class";
762 if (TTP->getIdentifier()) {
763 PlaceholderStr += ' ';
764 PlaceholderStr += TTP->getIdentifier()->getName();
765 }
766
767 HasDefaultArg = TTP->hasDefaultArgument();
768 }
769
770 if (HasDefaultArg) {
771 // When we see an optional default argument, put that argument and
772 // the remaining default arguments into a new, optional string.
773 CodeCompletionString *Opt = new CodeCompletionString;
774 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
775 CCStr = Opt;
776 }
777
778 if (FirstParameter)
779 FirstParameter = false;
780 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000781 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000782
783 // Add the placeholder string.
784 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
785 }
786}
787
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000788/// \brief Add a qualifier to the given code-completion string, if the
789/// provided nested-name-specifier is non-NULL.
790void AddQualifierToCompletionString(CodeCompletionString *Result,
791 NestedNameSpecifier *Qualifier,
Douglas Gregor0563c262009-09-22 23:15:58 +0000792 bool QualifierIsInformative,
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000793 ASTContext &Context) {
794 if (!Qualifier)
795 return;
796
797 std::string PrintedNNS;
798 {
799 llvm::raw_string_ostream OS(PrintedNNS);
800 Qualifier->print(OS, Context.PrintingPolicy);
801 }
Douglas Gregor0563c262009-09-22 23:15:58 +0000802 if (QualifierIsInformative)
803 Result->AddInformativeChunk(PrintedNNS.c_str());
804 else
805 Result->AddTextChunk(PrintedNNS.c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000806}
807
Douglas Gregor86d9a522009-09-21 16:56:56 +0000808/// \brief If possible, create a new code completion string for the given
809/// result.
810///
811/// \returns Either a new, heap-allocated code completion string describing
812/// how to use this result, or NULL to indicate that the string or name of the
813/// result is all that is needed.
814CodeCompletionString *
815CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000816 typedef CodeCompletionString::Chunk Chunk;
817
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000818 if (Kind == RK_Keyword)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000819 return 0;
820
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000821 if (Kind == RK_Macro) {
822 MacroInfo *MI = S.PP.getMacroInfo(Macro);
823 if (!MI || !MI->isFunctionLike())
824 return 0;
825
826 // Format a function-like macro with placeholders for the arguments.
827 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000828 Result->AddTypedTextChunk(Macro->getName().str().c_str());
829 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000830 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
831 A != AEnd; ++A) {
832 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000833 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000834
835 if (!MI->isVariadic() || A != AEnd - 1) {
836 // Non-variadic argument.
837 Result->AddPlaceholderChunk((*A)->getName().str().c_str());
838 continue;
839 }
840
841 // Variadic argument; cope with the different between GNU and C99
842 // variadic macros, providing a single placeholder for the rest of the
843 // arguments.
844 if ((*A)->isStr("__VA_ARGS__"))
845 Result->AddPlaceholderChunk("...");
846 else {
847 std::string Arg = (*A)->getName();
848 Arg += "...";
849 Result->AddPlaceholderChunk(Arg.c_str());
850 }
851 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000852 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000853 return Result;
854 }
855
856 assert(Kind == RK_Declaration && "Missed a macro kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000857 NamedDecl *ND = Declaration;
858
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000859 if (StartsNestedNameSpecifier) {
860 CodeCompletionString *Result = new CodeCompletionString;
861 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
862 Result->AddTextChunk("::");
863 return Result;
864 }
865
Douglas Gregor86d9a522009-09-21 16:56:56 +0000866 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
867 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000868 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
869 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000870 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
871 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000872 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000873 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000874 return Result;
875 }
876
877 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
878 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000879 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
880 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000881 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000882 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000883
884 // Figure out which template parameters are deduced (or have default
885 // arguments).
886 llvm::SmallVector<bool, 16> Deduced;
887 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
888 unsigned LastDeducibleArgument;
889 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
890 --LastDeducibleArgument) {
891 if (!Deduced[LastDeducibleArgument - 1]) {
892 // C++0x: Figure out if the template argument has a default. If so,
893 // the user doesn't need to type this argument.
894 // FIXME: We need to abstract template parameters better!
895 bool HasDefaultArg = false;
896 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
897 LastDeducibleArgument - 1);
898 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
899 HasDefaultArg = TTP->hasDefaultArgument();
900 else if (NonTypeTemplateParmDecl *NTTP
901 = dyn_cast<NonTypeTemplateParmDecl>(Param))
902 HasDefaultArg = NTTP->hasDefaultArgument();
903 else {
904 assert(isa<TemplateTemplateParmDecl>(Param));
905 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000906 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000907 }
908
909 if (!HasDefaultArg)
910 break;
911 }
912 }
913
914 if (LastDeducibleArgument) {
915 // Some of the function template arguments cannot be deduced from a
916 // function call, so we introduce an explicit template argument list
917 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000918 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000919 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
920 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000921 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000922 }
923
924 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000925 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000926 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000927 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000928 return Result;
929 }
930
931 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
932 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000933 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
934 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000935 Result->AddTypedTextChunk(Template->getNameAsString().c_str());
936 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000937 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000938 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000939 return Result;
940 }
941
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000942 if (Qualifier) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000943 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000944 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
945 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000946 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000947 return Result;
948 }
949
Douglas Gregor86d9a522009-09-21 16:56:56 +0000950 return 0;
951}
952
Douglas Gregor86d802e2009-09-23 00:34:09 +0000953CodeCompletionString *
954CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
955 unsigned CurrentArg,
956 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000957 typedef CodeCompletionString::Chunk Chunk;
958
Douglas Gregor86d802e2009-09-23 00:34:09 +0000959 CodeCompletionString *Result = new CodeCompletionString;
960 FunctionDecl *FDecl = getFunction();
961 const FunctionProtoType *Proto
962 = dyn_cast<FunctionProtoType>(getFunctionType());
963 if (!FDecl && !Proto) {
964 // Function without a prototype. Just give the return type and a
965 // highlighted ellipsis.
966 const FunctionType *FT = getFunctionType();
967 Result->AddTextChunk(
968 FT->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000969 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
970 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
971 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +0000972 return Result;
973 }
974
975 if (FDecl)
976 Result->AddTextChunk(FDecl->getNameAsString().c_str());
977 else
978 Result->AddTextChunk(
979 Proto->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
980
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000981 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +0000982 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
983 for (unsigned I = 0; I != NumParams; ++I) {
984 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000985 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +0000986
987 std::string ArgString;
988 QualType ArgType;
989
990 if (FDecl) {
991 ArgString = FDecl->getParamDecl(I)->getNameAsString();
992 ArgType = FDecl->getParamDecl(I)->getOriginalType();
993 } else {
994 ArgType = Proto->getArgType(I);
995 }
996
997 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
998
999 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001000 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
1001 ArgString.c_str()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001002 else
1003 Result->AddTextChunk(ArgString.c_str());
1004 }
1005
1006 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001007 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001008 if (CurrentArg < NumParams)
1009 Result->AddTextChunk("...");
1010 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001011 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001012 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001013 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001014
1015 return Result;
1016}
1017
Douglas Gregor86d9a522009-09-21 16:56:56 +00001018namespace {
1019 struct SortCodeCompleteResult {
1020 typedef CodeCompleteConsumer::Result Result;
1021
Douglas Gregor6a684032009-09-28 03:51:44 +00001022 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
1023 if (X.getNameKind() != Y.getNameKind())
1024 return X.getNameKind() < Y.getNameKind();
1025
1026 return llvm::LowercaseString(X.getAsString())
1027 < llvm::LowercaseString(Y.getAsString());
1028 }
1029
Douglas Gregor86d9a522009-09-21 16:56:56 +00001030 bool operator()(const Result &X, const Result &Y) const {
1031 // Sort first by rank.
1032 if (X.Rank < Y.Rank)
1033 return true;
1034 else if (X.Rank > Y.Rank)
1035 return false;
1036
1037 // Result kinds are ordered by decreasing importance.
1038 if (X.Kind < Y.Kind)
1039 return true;
1040 else if (X.Kind > Y.Kind)
1041 return false;
1042
1043 // Non-hidden names precede hidden names.
1044 if (X.Hidden != Y.Hidden)
1045 return !X.Hidden;
1046
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001047 // Non-nested-name-specifiers precede nested-name-specifiers.
1048 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1049 return !X.StartsNestedNameSpecifier;
1050
Douglas Gregor86d9a522009-09-21 16:56:56 +00001051 // Ordering depends on the kind of result.
1052 switch (X.Kind) {
1053 case Result::RK_Declaration:
1054 // Order based on the declaration names.
Douglas Gregor6a684032009-09-28 03:51:44 +00001055 return isEarlierDeclarationName(X.Declaration->getDeclName(),
1056 Y.Declaration->getDeclName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001057
1058 case Result::RK_Keyword:
Steve Naroff7f511122009-10-08 23:45:10 +00001059 return strcmp(X.Keyword, Y.Keyword) < 0;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001060
1061 case Result::RK_Macro:
1062 return llvm::LowercaseString(X.Macro->getName()) <
1063 llvm::LowercaseString(Y.Macro->getName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001064 }
1065
1066 // Silence GCC warning.
1067 return false;
1068 }
1069 };
1070}
1071
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001072static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1073 ResultBuilder &Results) {
1074 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001075 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1076 MEnd = PP.macro_end();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001077 M != MEnd; ++M)
1078 Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1079 Results.ExitScope();
1080}
1081
Douglas Gregor86d9a522009-09-21 16:56:56 +00001082static void HandleCodeCompleteResults(CodeCompleteConsumer *CodeCompleter,
1083 CodeCompleteConsumer::Result *Results,
1084 unsigned NumResults) {
1085 // Sort the results by rank/kind/etc.
1086 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1087
1088 if (CodeCompleter)
1089 CodeCompleter->ProcessCodeCompleteResults(Results, NumResults);
1090}
1091
Douglas Gregor791215b2009-09-21 20:51:25 +00001092void Sema::CodeCompleteOrdinaryName(Scope *S) {
1093 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001094 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1095 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001096 if (CodeCompleter->includeMacros())
1097 AddMacroResults(PP, NextRank, Results);
Douglas Gregor791215b2009-09-21 20:51:25 +00001098 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1099}
1100
Douglas Gregor81b747b2009-09-17 21:32:03 +00001101void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1102 SourceLocation OpLoc,
1103 bool IsArrow) {
1104 if (!BaseE || !CodeCompleter)
1105 return;
1106
Douglas Gregor86d9a522009-09-21 16:56:56 +00001107 typedef CodeCompleteConsumer::Result Result;
1108
Douglas Gregor81b747b2009-09-17 21:32:03 +00001109 Expr *Base = static_cast<Expr *>(BaseE);
1110 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001111
1112 if (IsArrow) {
1113 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1114 BaseType = Ptr->getPointeeType();
1115 else if (BaseType->isObjCObjectPointerType())
1116 /*Do nothing*/ ;
1117 else
1118 return;
1119 }
1120
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001121 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001122 unsigned NextRank = 0;
1123
1124 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor456c4a12009-09-21 20:12:40 +00001125 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1126 Record->getDecl(), Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001127
1128 if (getLangOptions().CPlusPlus) {
1129 if (!Results.empty()) {
1130 // The "template" keyword can follow "->" or "." in the grammar.
1131 // However, we only want to suggest the template keyword if something
1132 // is dependent.
1133 bool IsDependent = BaseType->isDependentType();
1134 if (!IsDependent) {
1135 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1136 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1137 IsDependent = Ctx->isDependentContext();
1138 break;
1139 }
1140 }
1141
1142 if (IsDependent)
1143 Results.MaybeAddResult(Result("template", NextRank++));
1144 }
1145
1146 // We could have the start of a nested-name-specifier. Add those
1147 // results as well.
1148 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1149 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +00001150 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001151 }
1152
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001153 // Add macros
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001154 if (CodeCompleter->includeMacros())
1155 AddMacroResults(PP, NextRank, Results);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001156
Douglas Gregor86d9a522009-09-21 16:56:56 +00001157 // Hand off the results found for code completion.
1158 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1159
1160 // We're done!
1161 return;
1162 }
Douglas Gregor81b747b2009-09-17 21:32:03 +00001163}
1164
Douglas Gregor374929f2009-09-18 15:37:17 +00001165void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1166 if (!CodeCompleter)
1167 return;
1168
Douglas Gregor86d9a522009-09-21 16:56:56 +00001169 typedef CodeCompleteConsumer::Result Result;
1170 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +00001171 switch ((DeclSpec::TST)TagSpec) {
1172 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001173 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +00001174 break;
1175
1176 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001177 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +00001178 break;
1179
1180 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00001181 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001182 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00001183 break;
1184
1185 default:
1186 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1187 return;
1188 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001189
1190 ResultBuilder Results(*this, Filter);
1191 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001192 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001193
1194 if (getLangOptions().CPlusPlus) {
1195 // We could have the start of a nested-name-specifier. Add those
1196 // results as well.
1197 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001198 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1199 NextRank, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001200 }
1201
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001202 if (CodeCompleter->includeMacros())
1203 AddMacroResults(PP, NextRank, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001204 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00001205}
1206
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001207void Sema::CodeCompleteCase(Scope *S) {
1208 if (getSwitchStack().empty() || !CodeCompleter)
1209 return;
1210
1211 SwitchStmt *Switch = getSwitchStack().back();
1212 if (!Switch->getCond()->getType()->isEnumeralType())
1213 return;
1214
1215 // Code-complete the cases of a switch statement over an enumeration type
1216 // by providing the list of
1217 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1218
1219 // Determine which enumerators we have already seen in the switch statement.
1220 // FIXME: Ideally, we would also be able to look *past* the code-completion
1221 // token, in case we are code-completing in the middle of the switch and not
1222 // at the end. However, we aren't able to do so at the moment.
1223 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001224 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001225 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1226 SC = SC->getNextSwitchCase()) {
1227 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1228 if (!Case)
1229 continue;
1230
1231 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1232 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1233 if (EnumConstantDecl *Enumerator
1234 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1235 // We look into the AST of the case statement to determine which
1236 // enumerator was named. Alternatively, we could compute the value of
1237 // the integral constant expression, then compare it against the
1238 // values of each enumerator. However, value-based approach would not
1239 // work as well with C++ templates where enumerators declared within a
1240 // template are type- and value-dependent.
1241 EnumeratorsSeen.insert(Enumerator);
1242
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001243 // If this is a qualified-id, keep track of the nested-name-specifier
1244 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001245 //
1246 // switch (TagD.getKind()) {
1247 // case TagDecl::TK_enum:
1248 // break;
1249 // case XXX
1250 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001251 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001252 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1253 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00001254 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001255 }
1256 }
1257
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001258 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1259 // If there are no prior enumerators in C++, check whether we have to
1260 // qualify the names of the enumerators that we suggest, because they
1261 // may not be visible in this scope.
1262 Qualifier = getRequiredQualification(Context, CurContext,
1263 Enum->getDeclContext());
1264
1265 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1266 }
1267
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001268 // Add any enumerators that have not yet been mentioned.
1269 ResultBuilder Results(*this);
1270 Results.EnterNewScope();
1271 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1272 EEnd = Enum->enumerator_end();
1273 E != EEnd; ++E) {
1274 if (EnumeratorsSeen.count(*E))
1275 continue;
1276
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001277 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001278 }
1279 Results.ExitScope();
1280
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001281 if (CodeCompleter->includeMacros())
1282 AddMacroResults(PP, 1, Results);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001283 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1284}
1285
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001286namespace {
1287 struct IsBetterOverloadCandidate {
1288 Sema &S;
1289
1290 public:
1291 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1292
1293 bool
1294 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1295 return S.isBetterOverloadCandidate(X, Y);
1296 }
1297 };
1298}
1299
1300void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1301 ExprTy **ArgsIn, unsigned NumArgs) {
1302 if (!CodeCompleter)
1303 return;
1304
1305 Expr *Fn = (Expr *)FnIn;
1306 Expr **Args = (Expr **)ArgsIn;
1307
1308 // Ignore type-dependent call expressions entirely.
1309 if (Fn->isTypeDependent() ||
1310 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1311 return;
1312
1313 NamedDecl *Function;
1314 DeclarationName UnqualifiedName;
1315 NestedNameSpecifier *Qualifier;
1316 SourceRange QualifierRange;
1317 bool ArgumentDependentLookup;
1318 bool HasExplicitTemplateArgs;
John McCall833ca992009-10-29 08:12:44 +00001319 const TemplateArgumentLoc *ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001320 unsigned NumExplicitTemplateArgs;
1321
1322 DeconstructCallFunction(Fn,
1323 Function, UnqualifiedName, Qualifier, QualifierRange,
1324 ArgumentDependentLookup, HasExplicitTemplateArgs,
1325 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1326
1327
1328 // FIXME: What if we're calling something that isn't a function declaration?
1329 // FIXME: What if we're calling a pseudo-destructor?
1330 // FIXME: What if we're calling a member function?
1331
1332 // Build an overload candidate set based on the functions we find.
1333 OverloadCandidateSet CandidateSet;
1334 AddOverloadedCallCandidates(Function, UnqualifiedName,
1335 ArgumentDependentLookup, HasExplicitTemplateArgs,
1336 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1337 Args, NumArgs,
1338 CandidateSet,
1339 /*PartialOverloading=*/true);
1340
1341 // Sort the overload candidate set by placing the best overloads first.
1342 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1343 IsBetterOverloadCandidate(*this));
1344
1345 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05944382009-09-23 00:16:58 +00001346 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1347 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlsson90756302009-09-22 17:29:51 +00001348
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001349 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1350 CandEnd = CandidateSet.end();
1351 Cand != CandEnd; ++Cand) {
1352 if (Cand->Viable)
Douglas Gregor05944382009-09-23 00:16:58 +00001353 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001354 }
Douglas Gregor05944382009-09-23 00:16:58 +00001355 CodeCompleter->ProcessOverloadCandidates(NumArgs, Results.data(),
1356 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001357}
1358
Douglas Gregor81b747b2009-09-17 21:32:03 +00001359void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1360 bool EnteringContext) {
1361 if (!SS.getScopeRep() || !CodeCompleter)
1362 return;
1363
Douglas Gregor86d9a522009-09-21 16:56:56 +00001364 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1365 if (!Ctx)
1366 return;
1367
1368 ResultBuilder Results(*this);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001369 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001370
1371 // The "template" keyword can follow "::" in the grammar, but only
1372 // put it into the grammar if the nested-name-specifier is dependent.
1373 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1374 if (!Results.empty() && NNS->isDependent())
1375 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1376
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001377 if (CodeCompleter->includeMacros())
1378 AddMacroResults(PP, NextRank + 1, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001379 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001380}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001381
1382void Sema::CodeCompleteUsing(Scope *S) {
1383 if (!CodeCompleter)
1384 return;
1385
Douglas Gregor86d9a522009-09-21 16:56:56 +00001386 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001387 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001388
1389 // If we aren't in class scope, we could see the "namespace" keyword.
1390 if (!S->isClassScope())
1391 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1392
1393 // After "using", we can see anything that would start a
1394 // nested-name-specifier.
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001395 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1396 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001397 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001398
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001399 if (CodeCompleter->includeMacros())
1400 AddMacroResults(PP, NextRank, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001401 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001402}
1403
1404void Sema::CodeCompleteUsingDirective(Scope *S) {
1405 if (!CodeCompleter)
1406 return;
1407
Douglas Gregor86d9a522009-09-21 16:56:56 +00001408 // After "using namespace", we expect to see a namespace name or namespace
1409 // alias.
1410 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001411 Results.EnterNewScope();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001412 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1413 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001414 Results.ExitScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001415 if (CodeCompleter->includeMacros())
1416 AddMacroResults(PP, NextRank, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001417 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001418}
1419
1420void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1421 if (!CodeCompleter)
1422 return;
1423
Douglas Gregor86d9a522009-09-21 16:56:56 +00001424 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1425 DeclContext *Ctx = (DeclContext *)S->getEntity();
1426 if (!S->getParent())
1427 Ctx = Context.getTranslationUnitDecl();
1428
1429 if (Ctx && Ctx->isFileContext()) {
1430 // We only want to see those namespaces that have already been defined
1431 // within this scope, because its likely that the user is creating an
1432 // extended namespace declaration. Keep track of the most recent
1433 // definition of each namespace.
1434 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1435 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1436 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1437 NS != NSEnd; ++NS)
1438 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1439
1440 // Add the most recent definition (or extended definition) of each
1441 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001442 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001443 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1444 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1445 NS != NSEnd; ++NS)
Douglas Gregor456c4a12009-09-21 20:12:40 +00001446 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1447 CurContext);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001448 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001449 }
1450
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001451 if (CodeCompleter->includeMacros())
1452 AddMacroResults(PP, 1, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001453 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001454}
1455
1456void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1457 if (!CodeCompleter)
1458 return;
1459
Douglas Gregor86d9a522009-09-21 16:56:56 +00001460 // After "namespace", we expect to see a namespace or alias.
1461 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001462 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1463 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001464 if (CodeCompleter->includeMacros())
1465 AddMacroResults(PP, NextRank, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001466 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001467}
1468
Douglas Gregored8d3222009-09-18 20:05:18 +00001469void Sema::CodeCompleteOperatorName(Scope *S) {
1470 if (!CodeCompleter)
1471 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001472
1473 typedef CodeCompleteConsumer::Result Result;
1474 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001475 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00001476
Douglas Gregor86d9a522009-09-21 16:56:56 +00001477 // Add the names of overloadable operators.
1478#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1479 if (std::strcmp(Spelling, "?")) \
1480 Results.MaybeAddResult(Result(Spelling, 0));
1481#include "clang/Basic/OperatorKinds.def"
1482
1483 // Add any type names visible from the current scope
1484 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001485 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001486
1487 // Add any type specifiers
1488 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1489
1490 // Add any nested-name-specifiers
1491 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001492 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1493 NextRank + 1, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001494 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001495
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001496 if (CodeCompleter->includeMacros())
1497 AddMacroResults(PP, NextRank, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001498 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00001499}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001500
Steve Naroffece8e712009-10-08 21:55:05 +00001501void Sema::CodeCompleteObjCProperty(Scope *S, ObjCDeclSpec &ODS) {
1502 if (!CodeCompleter)
1503 return;
1504 unsigned Attributes = ODS.getPropertyAttributes();
1505
1506 typedef CodeCompleteConsumer::Result Result;
1507 ResultBuilder Results(*this);
1508 Results.EnterNewScope();
1509 if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly))
1510 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
1511 if (!(Attributes & ObjCDeclSpec::DQ_PR_assign))
1512 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
1513 if (!(Attributes & ObjCDeclSpec::DQ_PR_readwrite))
1514 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
1515 if (!(Attributes & ObjCDeclSpec::DQ_PR_retain))
1516 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
1517 if (!(Attributes & ObjCDeclSpec::DQ_PR_copy))
1518 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
1519 if (!(Attributes & ObjCDeclSpec::DQ_PR_nonatomic))
1520 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
1521 if (!(Attributes & ObjCDeclSpec::DQ_PR_setter))
1522 Results.MaybeAddResult(CodeCompleteConsumer::Result("setter", 0));
1523 if (!(Attributes & ObjCDeclSpec::DQ_PR_getter))
1524 Results.MaybeAddResult(CodeCompleteConsumer::Result("getter", 0));
1525 Results.ExitScope();
1526 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1527}
Steve Naroffc4df6d22009-11-07 02:08:14 +00001528
1529void Sema::CodeCompleteObjCFactoryMethod(Scope *S, IdentifierInfo *FName) {
1530 typedef CodeCompleteConsumer::Result Result;
1531 ResultBuilder Results(*this);
1532 Results.EnterNewScope();
1533
1534 ObjCInterfaceDecl *CDecl = getObjCInterfaceDecl(FName);
1535
1536 while (CDecl != NULL) {
1537 for (ObjCInterfaceDecl::classmeth_iterator I = CDecl->classmeth_begin(),
1538 E = CDecl->classmeth_end();
1539 I != E; ++I) {
1540 Results.MaybeAddResult(Result(*I, 0), CurContext);
1541 }
1542 // Add class methods in protocols.
1543 const ObjCList<ObjCProtocolDecl> &Protocols=CDecl->getReferencedProtocols();
1544 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1545 E = Protocols.end(); I != E; ++I) {
1546 for (ObjCProtocolDecl::classmeth_iterator I2 = (*I)->classmeth_begin(),
1547 E2 = (*I)->classmeth_end();
1548 I2 != E2; ++I2) {
1549 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1550 }
1551 }
1552 // Add class methods in categories.
1553 ObjCCategoryDecl *CatDecl = CDecl->getCategoryList();
1554 while (CatDecl) {
1555 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
1556 E = CatDecl->classmeth_end();
1557 I != E; ++I) {
1558 Results.MaybeAddResult(Result(*I, 0), CurContext);
1559 }
1560 // Add a categories protocol methods.
1561 const ObjCList<ObjCProtocolDecl> &Protocols =
1562 CatDecl->getReferencedProtocols();
1563 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1564 E = Protocols.end(); I != E; ++I) {
1565 for (ObjCProtocolDecl::classmeth_iterator I2 = (*I)->classmeth_begin(),
1566 E2 = (*I)->classmeth_end();
1567 I2 != E2; ++I2) {
1568 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1569 }
1570 }
1571 CatDecl = CatDecl->getNextClassCategory();
1572 }
1573 CDecl = CDecl->getSuperClass();
1574 }
1575 Results.ExitScope();
1576 // This also suppresses remaining diagnostics.
1577 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1578}
1579
1580void Sema::CodeCompleteObjCInstanceMethod(Scope *S, ExprTy *Receiver) {
1581 typedef CodeCompleteConsumer::Result Result;
1582 ResultBuilder Results(*this);
1583 Results.EnterNewScope();
1584
1585 Expr *RecExpr = static_cast<Expr *>(Receiver);
1586 QualType RecType = RecExpr->getType();
1587
1588 const ObjCObjectPointerType* OCOPT = RecType->getAs<ObjCObjectPointerType>();
1589
1590 if (!OCOPT)
1591 return;
1592
1593 // FIXME: handle 'id', 'Class', and qualified types.
1594 ObjCInterfaceDecl *CDecl = OCOPT->getInterfaceDecl();
1595
1596 while (CDecl != NULL) {
1597 for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1598 E = CDecl->instmeth_end();
1599 I != E; ++I) {
1600 Results.MaybeAddResult(Result(*I, 0), CurContext);
1601 }
1602 // Add class methods in protocols.
1603 const ObjCList<ObjCProtocolDecl> &Protocols=CDecl->getReferencedProtocols();
1604 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1605 E = Protocols.end(); I != E; ++I) {
1606 for (ObjCProtocolDecl::instmeth_iterator I2 = (*I)->instmeth_begin(),
1607 E2 = (*I)->instmeth_end();
1608 I2 != E2; ++I2) {
1609 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1610 }
1611 }
1612 // Add class methods in categories.
1613 ObjCCategoryDecl *CatDecl = CDecl->getCategoryList();
1614 while (CatDecl) {
1615 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
1616 E = CatDecl->instmeth_end();
1617 I != E; ++I) {
1618 Results.MaybeAddResult(Result(*I, 0), CurContext);
1619 }
1620 // Add a categories protocol methods.
1621 const ObjCList<ObjCProtocolDecl> &Protocols =
1622 CatDecl->getReferencedProtocols();
1623 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1624 E = Protocols.end(); I != E; ++I) {
1625 for (ObjCProtocolDecl::instmeth_iterator I2 = (*I)->instmeth_begin(),
1626 E2 = (*I)->instmeth_end();
1627 I2 != E2; ++I2) {
1628 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1629 }
1630 }
1631 CatDecl = CatDecl->getNextClassCategory();
1632 }
1633 CDecl = CDecl->getSuperClass();
1634 }
1635 Results.ExitScope();
1636 // This also suppresses remaining diagnostics.
1637 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1638}