blob: c6323956cc91945c2ad3cebb7fa70b71c5d45300 [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(),
476 DEnd = CurCtx->decls_end();
477 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 Gregor86d9a522009-09-21 16:56:56 +0000480 }
481 }
482
483 // Traverse the contexts of inherited classes.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000484 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
485 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
486 BEnd = Record->bases_end();
487 B != BEnd; ++B) {
488 QualType BaseType = B->getType();
489
490 // Don't look into dependent bases, because name lookup can't look
491 // there anyway.
492 if (BaseType->isDependentType())
493 continue;
494
495 const RecordType *Record = BaseType->getAs<RecordType>();
496 if (!Record)
497 continue;
498
499 // FIXME: It would be nice to be able to determine whether referencing
500 // a particular member would be ambiguous. For example, given
501 //
502 // struct A { int member; };
503 // struct B { int member; };
504 // struct C : A, B { };
505 //
506 // void f(C *c) { c->### }
507 // accessing 'member' would result in an ambiguity. However, code
508 // completion could be smart enough to qualify the member with the
509 // base class, e.g.,
510 //
511 // c->B::member
512 //
513 // or
514 //
515 // c->A::member
516
517 // Collect results from this base class (and its bases).
Douglas Gregor0563c262009-09-22 23:15:58 +0000518 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
519 Results, /*InBaseClass=*/true);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000520 }
521 }
522
523 // FIXME: Look into base classes in Objective-C!
524
525 Results.ExitScope();
Douglas Gregor0563c262009-09-22 23:15:58 +0000526 return Rank + 1;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000527}
528
529/// \brief Collect the results of searching for members within the given
530/// declaration context.
531///
532/// \param Ctx the declaration context from which we will gather results.
533///
534/// \param InitialRank the initial rank given to results in this declaration
535/// context. Larger rank values will be used for, e.g., members found in
536/// base classes.
537///
538/// \param Results the result set that will be extended with any results
539/// found within this declaration context (and, for a C++ class, its bases).
540///
541/// \returns the next higher rank value, after considering all of the
542/// names within this declaration context.
543static unsigned CollectMemberLookupResults(DeclContext *Ctx,
544 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000545 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000546 ResultBuilder &Results) {
547 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000548 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
549 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000550}
551
552/// \brief Collect the results of searching for declarations within the given
553/// scope and its parent scopes.
554///
555/// \param S the scope in which we will start looking for declarations.
556///
557/// \param InitialRank the initial rank given to results in this scope.
558/// Larger rank values will be used for results found in parent scopes.
559///
Douglas Gregor456c4a12009-09-21 20:12:40 +0000560/// \param CurContext the context from which lookup results will be found.
561///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000562/// \param Results the builder object that will receive each result.
563static unsigned CollectLookupResults(Scope *S,
564 TranslationUnitDecl *TranslationUnit,
565 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000566 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000567 ResultBuilder &Results) {
568 if (!S)
569 return InitialRank;
570
571 // FIXME: Using directives!
572
573 unsigned NextRank = InitialRank;
574 Results.EnterNewScope();
575 if (S->getEntity() &&
576 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
577 // Look into this scope's declaration context, along with any of its
578 // parent lookup contexts (e.g., enclosing classes), up to the point
579 // where we hit the context stored in the next outer scope.
580 DeclContext *Ctx = (DeclContext *)S->getEntity();
581 DeclContext *OuterCtx = findOuterContext(S);
582
583 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
584 Ctx = Ctx->getLookupParent()) {
585 if (Ctx->isFunctionOrMethod())
586 continue;
587
Douglas Gregor456c4a12009-09-21 20:12:40 +0000588 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
589 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000590 }
591 } else if (!S->getParent()) {
592 // Look into the translation unit scope. We walk through the translation
593 // unit's declaration context, because the Scope itself won't have all of
594 // the declarations if we loaded a precompiled header.
595 // FIXME: We would like the translation unit's Scope object to point to the
596 // translation unit, so we don't need this special "if" branch. However,
597 // doing so would force the normal C++ name-lookup code to look into the
598 // translation unit decl when the IdentifierInfo chains would suffice.
599 // Once we fix that problem (which is part of a more general "don't look
600 // in DeclContexts unless we have to" optimization), we can eliminate the
601 // TranslationUnit parameter entirely.
602 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000603 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000604 } else {
605 // Walk through the declarations in this Scope.
606 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
607 D != DEnd; ++D) {
608 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
Douglas Gregor456c4a12009-09-21 20:12:40 +0000609 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
610 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000611 }
612
613 NextRank = NextRank + 1;
614 }
615
616 // Lookup names in the parent scope.
617 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000618 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000619 Results.ExitScope();
620
621 return NextRank;
622}
623
624/// \brief Add type specifiers for the current language as keyword results.
625static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
626 ResultBuilder &Results) {
627 typedef CodeCompleteConsumer::Result Result;
628 Results.MaybeAddResult(Result("short", Rank));
629 Results.MaybeAddResult(Result("long", Rank));
630 Results.MaybeAddResult(Result("signed", Rank));
631 Results.MaybeAddResult(Result("unsigned", Rank));
632 Results.MaybeAddResult(Result("void", Rank));
633 Results.MaybeAddResult(Result("char", Rank));
634 Results.MaybeAddResult(Result("int", Rank));
635 Results.MaybeAddResult(Result("float", Rank));
636 Results.MaybeAddResult(Result("double", Rank));
637 Results.MaybeAddResult(Result("enum", Rank));
638 Results.MaybeAddResult(Result("struct", Rank));
639 Results.MaybeAddResult(Result("union", Rank));
640
641 if (LangOpts.C99) {
642 // C99-specific
643 Results.MaybeAddResult(Result("_Complex", Rank));
644 Results.MaybeAddResult(Result("_Imaginary", Rank));
645 Results.MaybeAddResult(Result("_Bool", Rank));
646 }
647
648 if (LangOpts.CPlusPlus) {
649 // C++-specific
650 Results.MaybeAddResult(Result("bool", Rank));
651 Results.MaybeAddResult(Result("class", Rank));
652 Results.MaybeAddResult(Result("typename", Rank));
653 Results.MaybeAddResult(Result("wchar_t", Rank));
654
655 if (LangOpts.CPlusPlus0x) {
656 Results.MaybeAddResult(Result("char16_t", Rank));
657 Results.MaybeAddResult(Result("char32_t", Rank));
658 Results.MaybeAddResult(Result("decltype", Rank));
659 }
660 }
661
662 // GNU extensions
663 if (LangOpts.GNUMode) {
664 // FIXME: Enable when we actually support decimal floating point.
665 // Results.MaybeAddResult(Result("_Decimal32", Rank));
666 // Results.MaybeAddResult(Result("_Decimal64", Rank));
667 // Results.MaybeAddResult(Result("_Decimal128", Rank));
668 Results.MaybeAddResult(Result("typeof", Rank));
669 }
670}
671
672/// \brief Add function parameter chunks to the given code completion string.
673static void AddFunctionParameterChunks(ASTContext &Context,
674 FunctionDecl *Function,
675 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000676 typedef CodeCompletionString::Chunk Chunk;
677
Douglas Gregor86d9a522009-09-21 16:56:56 +0000678 CodeCompletionString *CCStr = Result;
679
680 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
681 ParmVarDecl *Param = Function->getParamDecl(P);
682
683 if (Param->hasDefaultArg()) {
684 // When we see an optional default argument, put that argument and
685 // the remaining default arguments into a new, optional string.
686 CodeCompletionString *Opt = new CodeCompletionString;
687 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
688 CCStr = Opt;
689 }
690
691 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000692 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000693
694 // Format the placeholder string.
695 std::string PlaceholderStr;
696 if (Param->getIdentifier())
697 PlaceholderStr = Param->getIdentifier()->getName();
698
699 Param->getType().getAsStringInternal(PlaceholderStr,
700 Context.PrintingPolicy);
701
702 // Add the placeholder string.
703 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
704 }
Douglas Gregorb3d45252009-09-22 21:42:17 +0000705
706 if (const FunctionProtoType *Proto
707 = Function->getType()->getAs<FunctionProtoType>())
708 if (Proto->isVariadic())
709 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000710}
711
712/// \brief Add template parameter chunks to the given code completion string.
713static void AddTemplateParameterChunks(ASTContext &Context,
714 TemplateDecl *Template,
715 CodeCompletionString *Result,
716 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000717 typedef CodeCompletionString::Chunk Chunk;
718
Douglas Gregor86d9a522009-09-21 16:56:56 +0000719 CodeCompletionString *CCStr = Result;
720 bool FirstParameter = true;
721
722 TemplateParameterList *Params = Template->getTemplateParameters();
723 TemplateParameterList::iterator PEnd = Params->end();
724 if (MaxParameters)
725 PEnd = Params->begin() + MaxParameters;
726 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
727 bool HasDefaultArg = false;
728 std::string PlaceholderStr;
729 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
730 if (TTP->wasDeclaredWithTypename())
731 PlaceholderStr = "typename";
732 else
733 PlaceholderStr = "class";
734
735 if (TTP->getIdentifier()) {
736 PlaceholderStr += ' ';
737 PlaceholderStr += TTP->getIdentifier()->getName();
738 }
739
740 HasDefaultArg = TTP->hasDefaultArgument();
741 } else if (NonTypeTemplateParmDecl *NTTP
742 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
743 if (NTTP->getIdentifier())
744 PlaceholderStr = NTTP->getIdentifier()->getName();
745 NTTP->getType().getAsStringInternal(PlaceholderStr,
746 Context.PrintingPolicy);
747 HasDefaultArg = NTTP->hasDefaultArgument();
748 } else {
749 assert(isa<TemplateTemplateParmDecl>(*P));
750 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
751
752 // Since putting the template argument list into the placeholder would
753 // be very, very long, we just use an abbreviation.
754 PlaceholderStr = "template<...> class";
755 if (TTP->getIdentifier()) {
756 PlaceholderStr += ' ';
757 PlaceholderStr += TTP->getIdentifier()->getName();
758 }
759
760 HasDefaultArg = TTP->hasDefaultArgument();
761 }
762
763 if (HasDefaultArg) {
764 // When we see an optional default argument, put that argument and
765 // the remaining default arguments into a new, optional string.
766 CodeCompletionString *Opt = new CodeCompletionString;
767 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
768 CCStr = Opt;
769 }
770
771 if (FirstParameter)
772 FirstParameter = false;
773 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000774 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000775
776 // Add the placeholder string.
777 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
778 }
779}
780
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000781/// \brief Add a qualifier to the given code-completion string, if the
782/// provided nested-name-specifier is non-NULL.
783void AddQualifierToCompletionString(CodeCompletionString *Result,
784 NestedNameSpecifier *Qualifier,
Douglas Gregor0563c262009-09-22 23:15:58 +0000785 bool QualifierIsInformative,
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000786 ASTContext &Context) {
787 if (!Qualifier)
788 return;
789
790 std::string PrintedNNS;
791 {
792 llvm::raw_string_ostream OS(PrintedNNS);
793 Qualifier->print(OS, Context.PrintingPolicy);
794 }
Douglas Gregor0563c262009-09-22 23:15:58 +0000795 if (QualifierIsInformative)
796 Result->AddInformativeChunk(PrintedNNS.c_str());
797 else
798 Result->AddTextChunk(PrintedNNS.c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000799}
800
Douglas Gregor86d9a522009-09-21 16:56:56 +0000801/// \brief If possible, create a new code completion string for the given
802/// result.
803///
804/// \returns Either a new, heap-allocated code completion string describing
805/// how to use this result, or NULL to indicate that the string or name of the
806/// result is all that is needed.
807CodeCompletionString *
808CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000809 typedef CodeCompletionString::Chunk Chunk;
810
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000811 if (Kind == RK_Keyword)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000812 return 0;
813
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000814 if (Kind == RK_Macro) {
815 MacroInfo *MI = S.PP.getMacroInfo(Macro);
816 if (!MI || !MI->isFunctionLike())
817 return 0;
818
819 // Format a function-like macro with placeholders for the arguments.
820 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000821 Result->AddTypedTextChunk(Macro->getName().str().c_str());
822 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000823 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
824 A != AEnd; ++A) {
825 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000826 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000827
828 if (!MI->isVariadic() || A != AEnd - 1) {
829 // Non-variadic argument.
830 Result->AddPlaceholderChunk((*A)->getName().str().c_str());
831 continue;
832 }
833
834 // Variadic argument; cope with the different between GNU and C99
835 // variadic macros, providing a single placeholder for the rest of the
836 // arguments.
837 if ((*A)->isStr("__VA_ARGS__"))
838 Result->AddPlaceholderChunk("...");
839 else {
840 std::string Arg = (*A)->getName();
841 Arg += "...";
842 Result->AddPlaceholderChunk(Arg.c_str());
843 }
844 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000845 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +0000846 return Result;
847 }
848
849 assert(Kind == RK_Declaration && "Missed a macro kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +0000850 NamedDecl *ND = Declaration;
851
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000852 if (StartsNestedNameSpecifier) {
853 CodeCompletionString *Result = new CodeCompletionString;
854 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
855 Result->AddTextChunk("::");
856 return Result;
857 }
858
Douglas Gregor86d9a522009-09-21 16:56:56 +0000859 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
860 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000861 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
862 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000863 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
864 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000865 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000866 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000867 return Result;
868 }
869
870 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
871 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000872 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
873 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000874 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000875 Result->AddTypedTextChunk(Function->getNameAsString().c_str());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000876
877 // Figure out which template parameters are deduced (or have default
878 // arguments).
879 llvm::SmallVector<bool, 16> Deduced;
880 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
881 unsigned LastDeducibleArgument;
882 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
883 --LastDeducibleArgument) {
884 if (!Deduced[LastDeducibleArgument - 1]) {
885 // C++0x: Figure out if the template argument has a default. If so,
886 // the user doesn't need to type this argument.
887 // FIXME: We need to abstract template parameters better!
888 bool HasDefaultArg = false;
889 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
890 LastDeducibleArgument - 1);
891 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
892 HasDefaultArg = TTP->hasDefaultArgument();
893 else if (NonTypeTemplateParmDecl *NTTP
894 = dyn_cast<NonTypeTemplateParmDecl>(Param))
895 HasDefaultArg = NTTP->hasDefaultArgument();
896 else {
897 assert(isa<TemplateTemplateParmDecl>(Param));
898 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000899 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000900 }
901
902 if (!HasDefaultArg)
903 break;
904 }
905 }
906
907 if (LastDeducibleArgument) {
908 // Some of the function template arguments cannot be deduced from a
909 // function call, so we introduce an explicit template argument list
910 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000911 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000912 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
913 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000914 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000915 }
916
917 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000918 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000919 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000920 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000921 return Result;
922 }
923
924 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
925 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000926 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
927 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000928 Result->AddTypedTextChunk(Template->getNameAsString().c_str());
929 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000930 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000931 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000932 return Result;
933 }
934
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000935 if (Qualifier) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000936 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregor0563c262009-09-22 23:15:58 +0000937 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
938 S.Context);
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000939 Result->AddTypedTextChunk(ND->getNameAsString().c_str());
Douglas Gregorb9d0ef72009-09-21 19:57:38 +0000940 return Result;
941 }
942
Douglas Gregor86d9a522009-09-21 16:56:56 +0000943 return 0;
944}
945
Douglas Gregor86d802e2009-09-23 00:34:09 +0000946CodeCompletionString *
947CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
948 unsigned CurrentArg,
949 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000950 typedef CodeCompletionString::Chunk Chunk;
951
Douglas Gregor86d802e2009-09-23 00:34:09 +0000952 CodeCompletionString *Result = new CodeCompletionString;
953 FunctionDecl *FDecl = getFunction();
954 const FunctionProtoType *Proto
955 = dyn_cast<FunctionProtoType>(getFunctionType());
956 if (!FDecl && !Proto) {
957 // Function without a prototype. Just give the return type and a
958 // highlighted ellipsis.
959 const FunctionType *FT = getFunctionType();
960 Result->AddTextChunk(
961 FT->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000962 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
963 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
964 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +0000965 return Result;
966 }
967
968 if (FDecl)
969 Result->AddTextChunk(FDecl->getNameAsString().c_str());
970 else
971 Result->AddTextChunk(
972 Proto->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
973
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000974 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +0000975 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
976 for (unsigned I = 0; I != NumParams; ++I) {
977 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000978 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +0000979
980 std::string ArgString;
981 QualType ArgType;
982
983 if (FDecl) {
984 ArgString = FDecl->getParamDecl(I)->getNameAsString();
985 ArgType = FDecl->getParamDecl(I)->getOriginalType();
986 } else {
987 ArgType = Proto->getArgType(I);
988 }
989
990 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
991
992 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000993 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
994 ArgString.c_str()));
Douglas Gregor86d802e2009-09-23 00:34:09 +0000995 else
996 Result->AddTextChunk(ArgString.c_str());
997 }
998
999 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001000 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001001 if (CurrentArg < NumParams)
1002 Result->AddTextChunk("...");
1003 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001004 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001005 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001006 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001007
1008 return Result;
1009}
1010
Douglas Gregor86d9a522009-09-21 16:56:56 +00001011namespace {
1012 struct SortCodeCompleteResult {
1013 typedef CodeCompleteConsumer::Result Result;
1014
Douglas Gregor6a684032009-09-28 03:51:44 +00001015 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
1016 if (X.getNameKind() != Y.getNameKind())
1017 return X.getNameKind() < Y.getNameKind();
1018
1019 return llvm::LowercaseString(X.getAsString())
1020 < llvm::LowercaseString(Y.getAsString());
1021 }
1022
Douglas Gregor86d9a522009-09-21 16:56:56 +00001023 bool operator()(const Result &X, const Result &Y) const {
1024 // Sort first by rank.
1025 if (X.Rank < Y.Rank)
1026 return true;
1027 else if (X.Rank > Y.Rank)
1028 return false;
1029
1030 // Result kinds are ordered by decreasing importance.
1031 if (X.Kind < Y.Kind)
1032 return true;
1033 else if (X.Kind > Y.Kind)
1034 return false;
1035
1036 // Non-hidden names precede hidden names.
1037 if (X.Hidden != Y.Hidden)
1038 return !X.Hidden;
1039
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001040 // Non-nested-name-specifiers precede nested-name-specifiers.
1041 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1042 return !X.StartsNestedNameSpecifier;
1043
Douglas Gregor86d9a522009-09-21 16:56:56 +00001044 // Ordering depends on the kind of result.
1045 switch (X.Kind) {
1046 case Result::RK_Declaration:
1047 // Order based on the declaration names.
Douglas Gregor6a684032009-09-28 03:51:44 +00001048 return isEarlierDeclarationName(X.Declaration->getDeclName(),
1049 Y.Declaration->getDeclName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001050
1051 case Result::RK_Keyword:
Steve Naroff7f511122009-10-08 23:45:10 +00001052 return strcmp(X.Keyword, Y.Keyword) < 0;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001053
1054 case Result::RK_Macro:
1055 return llvm::LowercaseString(X.Macro->getName()) <
1056 llvm::LowercaseString(Y.Macro->getName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001057 }
1058
1059 // Silence GCC warning.
1060 return false;
1061 }
1062 };
1063}
1064
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001065static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1066 ResultBuilder &Results) {
1067 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001068 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1069 MEnd = PP.macro_end();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001070 M != MEnd; ++M)
1071 Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1072 Results.ExitScope();
1073}
1074
Douglas Gregor86d9a522009-09-21 16:56:56 +00001075static void HandleCodeCompleteResults(CodeCompleteConsumer *CodeCompleter,
1076 CodeCompleteConsumer::Result *Results,
1077 unsigned NumResults) {
1078 // Sort the results by rank/kind/etc.
1079 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1080
1081 if (CodeCompleter)
1082 CodeCompleter->ProcessCodeCompleteResults(Results, NumResults);
1083}
1084
Douglas Gregor791215b2009-09-21 20:51:25 +00001085void Sema::CodeCompleteOrdinaryName(Scope *S) {
1086 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001087 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1088 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001089 if (CodeCompleter->includeMacros())
1090 AddMacroResults(PP, NextRank, Results);
Douglas Gregor791215b2009-09-21 20:51:25 +00001091 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1092}
1093
Douglas Gregor81b747b2009-09-17 21:32:03 +00001094void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1095 SourceLocation OpLoc,
1096 bool IsArrow) {
1097 if (!BaseE || !CodeCompleter)
1098 return;
1099
Douglas Gregor86d9a522009-09-21 16:56:56 +00001100 typedef CodeCompleteConsumer::Result Result;
1101
Douglas Gregor81b747b2009-09-17 21:32:03 +00001102 Expr *Base = static_cast<Expr *>(BaseE);
1103 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001104
1105 if (IsArrow) {
1106 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1107 BaseType = Ptr->getPointeeType();
1108 else if (BaseType->isObjCObjectPointerType())
1109 /*Do nothing*/ ;
1110 else
1111 return;
1112 }
1113
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001114 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001115 unsigned NextRank = 0;
1116
1117 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor456c4a12009-09-21 20:12:40 +00001118 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1119 Record->getDecl(), Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001120
1121 if (getLangOptions().CPlusPlus) {
1122 if (!Results.empty()) {
1123 // The "template" keyword can follow "->" or "." in the grammar.
1124 // However, we only want to suggest the template keyword if something
1125 // is dependent.
1126 bool IsDependent = BaseType->isDependentType();
1127 if (!IsDependent) {
1128 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1129 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1130 IsDependent = Ctx->isDependentContext();
1131 break;
1132 }
1133 }
1134
1135 if (IsDependent)
1136 Results.MaybeAddResult(Result("template", NextRank++));
1137 }
1138
1139 // We could have the start of a nested-name-specifier. Add those
1140 // results as well.
1141 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1142 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +00001143 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001144 }
1145
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001146 // Add macros
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001147 if (CodeCompleter->includeMacros())
1148 AddMacroResults(PP, NextRank, Results);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001149
Douglas Gregor86d9a522009-09-21 16:56:56 +00001150 // Hand off the results found for code completion.
1151 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1152
1153 // We're done!
1154 return;
1155 }
Douglas Gregor81b747b2009-09-17 21:32:03 +00001156}
1157
Douglas Gregor374929f2009-09-18 15:37:17 +00001158void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1159 if (!CodeCompleter)
1160 return;
1161
Douglas Gregor86d9a522009-09-21 16:56:56 +00001162 typedef CodeCompleteConsumer::Result Result;
1163 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +00001164 switch ((DeclSpec::TST)TagSpec) {
1165 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001166 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +00001167 break;
1168
1169 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001170 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +00001171 break;
1172
1173 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00001174 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00001175 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00001176 break;
1177
1178 default:
1179 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1180 return;
1181 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001182
1183 ResultBuilder Results(*this, Filter);
1184 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001185 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001186
1187 if (getLangOptions().CPlusPlus) {
1188 // We could have the start of a nested-name-specifier. Add those
1189 // results as well.
1190 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001191 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1192 NextRank, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001193 }
1194
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001195 if (CodeCompleter->includeMacros())
1196 AddMacroResults(PP, NextRank, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001197 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00001198}
1199
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001200void Sema::CodeCompleteCase(Scope *S) {
1201 if (getSwitchStack().empty() || !CodeCompleter)
1202 return;
1203
1204 SwitchStmt *Switch = getSwitchStack().back();
1205 if (!Switch->getCond()->getType()->isEnumeralType())
1206 return;
1207
1208 // Code-complete the cases of a switch statement over an enumeration type
1209 // by providing the list of
1210 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1211
1212 // Determine which enumerators we have already seen in the switch statement.
1213 // FIXME: Ideally, we would also be able to look *past* the code-completion
1214 // token, in case we are code-completing in the middle of the switch and not
1215 // at the end. However, we aren't able to do so at the moment.
1216 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001217 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001218 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1219 SC = SC->getNextSwitchCase()) {
1220 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1221 if (!Case)
1222 continue;
1223
1224 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1225 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1226 if (EnumConstantDecl *Enumerator
1227 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1228 // We look into the AST of the case statement to determine which
1229 // enumerator was named. Alternatively, we could compute the value of
1230 // the integral constant expression, then compare it against the
1231 // values of each enumerator. However, value-based approach would not
1232 // work as well with C++ templates where enumerators declared within a
1233 // template are type- and value-dependent.
1234 EnumeratorsSeen.insert(Enumerator);
1235
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001236 // If this is a qualified-id, keep track of the nested-name-specifier
1237 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001238 //
1239 // switch (TagD.getKind()) {
1240 // case TagDecl::TK_enum:
1241 // break;
1242 // case XXX
1243 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001244 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001245 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1246 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00001247 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001248 }
1249 }
1250
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001251 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1252 // If there are no prior enumerators in C++, check whether we have to
1253 // qualify the names of the enumerators that we suggest, because they
1254 // may not be visible in this scope.
1255 Qualifier = getRequiredQualification(Context, CurContext,
1256 Enum->getDeclContext());
1257
1258 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1259 }
1260
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001261 // Add any enumerators that have not yet been mentioned.
1262 ResultBuilder Results(*this);
1263 Results.EnterNewScope();
1264 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1265 EEnd = Enum->enumerator_end();
1266 E != EEnd; ++E) {
1267 if (EnumeratorsSeen.count(*E))
1268 continue;
1269
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001270 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001271 }
1272 Results.ExitScope();
1273
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001274 if (CodeCompleter->includeMacros())
1275 AddMacroResults(PP, 1, Results);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00001276 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1277}
1278
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001279namespace {
1280 struct IsBetterOverloadCandidate {
1281 Sema &S;
1282
1283 public:
1284 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1285
1286 bool
1287 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1288 return S.isBetterOverloadCandidate(X, Y);
1289 }
1290 };
1291}
1292
1293void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1294 ExprTy **ArgsIn, unsigned NumArgs) {
1295 if (!CodeCompleter)
1296 return;
1297
1298 Expr *Fn = (Expr *)FnIn;
1299 Expr **Args = (Expr **)ArgsIn;
1300
1301 // Ignore type-dependent call expressions entirely.
1302 if (Fn->isTypeDependent() ||
1303 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1304 return;
1305
1306 NamedDecl *Function;
1307 DeclarationName UnqualifiedName;
1308 NestedNameSpecifier *Qualifier;
1309 SourceRange QualifierRange;
1310 bool ArgumentDependentLookup;
1311 bool HasExplicitTemplateArgs;
John McCall833ca992009-10-29 08:12:44 +00001312 const TemplateArgumentLoc *ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001313 unsigned NumExplicitTemplateArgs;
1314
1315 DeconstructCallFunction(Fn,
1316 Function, UnqualifiedName, Qualifier, QualifierRange,
1317 ArgumentDependentLookup, HasExplicitTemplateArgs,
1318 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1319
1320
1321 // FIXME: What if we're calling something that isn't a function declaration?
1322 // FIXME: What if we're calling a pseudo-destructor?
1323 // FIXME: What if we're calling a member function?
1324
1325 // Build an overload candidate set based on the functions we find.
1326 OverloadCandidateSet CandidateSet;
1327 AddOverloadedCallCandidates(Function, UnqualifiedName,
1328 ArgumentDependentLookup, HasExplicitTemplateArgs,
1329 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1330 Args, NumArgs,
1331 CandidateSet,
1332 /*PartialOverloading=*/true);
1333
1334 // Sort the overload candidate set by placing the best overloads first.
1335 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1336 IsBetterOverloadCandidate(*this));
1337
1338 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05944382009-09-23 00:16:58 +00001339 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1340 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlsson90756302009-09-22 17:29:51 +00001341
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001342 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1343 CandEnd = CandidateSet.end();
1344 Cand != CandEnd; ++Cand) {
1345 if (Cand->Viable)
Douglas Gregor05944382009-09-23 00:16:58 +00001346 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001347 }
Douglas Gregor05944382009-09-23 00:16:58 +00001348 CodeCompleter->ProcessOverloadCandidates(NumArgs, Results.data(),
1349 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00001350}
1351
Douglas Gregor81b747b2009-09-17 21:32:03 +00001352void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1353 bool EnteringContext) {
1354 if (!SS.getScopeRep() || !CodeCompleter)
1355 return;
1356
Douglas Gregor86d9a522009-09-21 16:56:56 +00001357 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1358 if (!Ctx)
1359 return;
1360
1361 ResultBuilder Results(*this);
Douglas Gregor456c4a12009-09-21 20:12:40 +00001362 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001363
1364 // The "template" keyword can follow "::" in the grammar, but only
1365 // put it into the grammar if the nested-name-specifier is dependent.
1366 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1367 if (!Results.empty() && NNS->isDependent())
1368 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1369
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001370 if (CodeCompleter->includeMacros())
1371 AddMacroResults(PP, NextRank + 1, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001372 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00001373}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001374
1375void Sema::CodeCompleteUsing(Scope *S) {
1376 if (!CodeCompleter)
1377 return;
1378
Douglas Gregor86d9a522009-09-21 16:56:56 +00001379 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001380 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001381
1382 // If we aren't in class scope, we could see the "namespace" keyword.
1383 if (!S->isClassScope())
1384 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1385
1386 // After "using", we can see anything that would start a
1387 // nested-name-specifier.
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001388 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1389 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001390 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001391
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001392 if (CodeCompleter->includeMacros())
1393 AddMacroResults(PP, NextRank, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001394 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001395}
1396
1397void Sema::CodeCompleteUsingDirective(Scope *S) {
1398 if (!CodeCompleter)
1399 return;
1400
Douglas Gregor86d9a522009-09-21 16:56:56 +00001401 // After "using namespace", we expect to see a namespace name or namespace
1402 // alias.
1403 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001404 Results.EnterNewScope();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001405 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1406 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001407 Results.ExitScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001408 if (CodeCompleter->includeMacros())
1409 AddMacroResults(PP, NextRank, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001410 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001411}
1412
1413void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1414 if (!CodeCompleter)
1415 return;
1416
Douglas Gregor86d9a522009-09-21 16:56:56 +00001417 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1418 DeclContext *Ctx = (DeclContext *)S->getEntity();
1419 if (!S->getParent())
1420 Ctx = Context.getTranslationUnitDecl();
1421
1422 if (Ctx && Ctx->isFileContext()) {
1423 // We only want to see those namespaces that have already been defined
1424 // within this scope, because its likely that the user is creating an
1425 // extended namespace declaration. Keep track of the most recent
1426 // definition of each namespace.
1427 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1428 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1429 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1430 NS != NSEnd; ++NS)
1431 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1432
1433 // Add the most recent definition (or extended definition) of each
1434 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001435 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001436 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1437 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1438 NS != NSEnd; ++NS)
Douglas Gregor456c4a12009-09-21 20:12:40 +00001439 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1440 CurContext);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001441 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001442 }
1443
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001444 if (CodeCompleter->includeMacros())
1445 AddMacroResults(PP, 1, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001446 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001447}
1448
1449void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1450 if (!CodeCompleter)
1451 return;
1452
Douglas Gregor86d9a522009-09-21 16:56:56 +00001453 // After "namespace", we expect to see a namespace or alias.
1454 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001455 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1456 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001457 if (CodeCompleter->includeMacros())
1458 AddMacroResults(PP, NextRank, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001459 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001460}
1461
Douglas Gregored8d3222009-09-18 20:05:18 +00001462void Sema::CodeCompleteOperatorName(Scope *S) {
1463 if (!CodeCompleter)
1464 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001465
1466 typedef CodeCompleteConsumer::Result Result;
1467 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001468 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00001469
Douglas Gregor86d9a522009-09-21 16:56:56 +00001470 // Add the names of overloadable operators.
1471#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1472 if (std::strcmp(Spelling, "?")) \
1473 Results.MaybeAddResult(Result(Spelling, 0));
1474#include "clang/Basic/OperatorKinds.def"
1475
1476 // Add any type names visible from the current scope
1477 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00001478 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001479
1480 // Add any type specifiers
1481 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1482
1483 // Add any nested-name-specifiers
1484 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001485 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1486 NextRank + 1, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00001487 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001488
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001489 if (CodeCompleter->includeMacros())
1490 AddMacroResults(PP, NextRank, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001491 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00001492}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00001493
Steve Naroffece8e712009-10-08 21:55:05 +00001494void Sema::CodeCompleteObjCProperty(Scope *S, ObjCDeclSpec &ODS) {
1495 if (!CodeCompleter)
1496 return;
1497 unsigned Attributes = ODS.getPropertyAttributes();
1498
1499 typedef CodeCompleteConsumer::Result Result;
1500 ResultBuilder Results(*this);
1501 Results.EnterNewScope();
1502 if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly))
1503 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
1504 if (!(Attributes & ObjCDeclSpec::DQ_PR_assign))
1505 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
1506 if (!(Attributes & ObjCDeclSpec::DQ_PR_readwrite))
1507 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
1508 if (!(Attributes & ObjCDeclSpec::DQ_PR_retain))
1509 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
1510 if (!(Attributes & ObjCDeclSpec::DQ_PR_copy))
1511 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
1512 if (!(Attributes & ObjCDeclSpec::DQ_PR_nonatomic))
1513 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
1514 if (!(Attributes & ObjCDeclSpec::DQ_PR_setter))
1515 Results.MaybeAddResult(CodeCompleteConsumer::Result("setter", 0));
1516 if (!(Attributes & ObjCDeclSpec::DQ_PR_getter))
1517 Results.MaybeAddResult(CodeCompleteConsumer::Result("getter", 0));
1518 Results.ExitScope();
1519 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1520}
Steve Naroffc4df6d22009-11-07 02:08:14 +00001521
1522void Sema::CodeCompleteObjCFactoryMethod(Scope *S, IdentifierInfo *FName) {
1523 typedef CodeCompleteConsumer::Result Result;
1524 ResultBuilder Results(*this);
1525 Results.EnterNewScope();
1526
1527 ObjCInterfaceDecl *CDecl = getObjCInterfaceDecl(FName);
1528
1529 while (CDecl != NULL) {
1530 for (ObjCInterfaceDecl::classmeth_iterator I = CDecl->classmeth_begin(),
1531 E = CDecl->classmeth_end();
1532 I != E; ++I) {
1533 Results.MaybeAddResult(Result(*I, 0), CurContext);
1534 }
1535 // Add class methods in protocols.
1536 const ObjCList<ObjCProtocolDecl> &Protocols=CDecl->getReferencedProtocols();
1537 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1538 E = Protocols.end(); I != E; ++I) {
1539 for (ObjCProtocolDecl::classmeth_iterator I2 = (*I)->classmeth_begin(),
1540 E2 = (*I)->classmeth_end();
1541 I2 != E2; ++I2) {
1542 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1543 }
1544 }
1545 // Add class methods in categories.
1546 ObjCCategoryDecl *CatDecl = CDecl->getCategoryList();
1547 while (CatDecl) {
1548 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
1549 E = CatDecl->classmeth_end();
1550 I != E; ++I) {
1551 Results.MaybeAddResult(Result(*I, 0), CurContext);
1552 }
1553 // Add a categories protocol methods.
1554 const ObjCList<ObjCProtocolDecl> &Protocols =
1555 CatDecl->getReferencedProtocols();
1556 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1557 E = Protocols.end(); I != E; ++I) {
1558 for (ObjCProtocolDecl::classmeth_iterator I2 = (*I)->classmeth_begin(),
1559 E2 = (*I)->classmeth_end();
1560 I2 != E2; ++I2) {
1561 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1562 }
1563 }
1564 CatDecl = CatDecl->getNextClassCategory();
1565 }
1566 CDecl = CDecl->getSuperClass();
1567 }
1568 Results.ExitScope();
1569 // This also suppresses remaining diagnostics.
1570 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1571}
1572
1573void Sema::CodeCompleteObjCInstanceMethod(Scope *S, ExprTy *Receiver) {
1574 typedef CodeCompleteConsumer::Result Result;
1575 ResultBuilder Results(*this);
1576 Results.EnterNewScope();
1577
1578 Expr *RecExpr = static_cast<Expr *>(Receiver);
1579 QualType RecType = RecExpr->getType();
1580
1581 const ObjCObjectPointerType* OCOPT = RecType->getAs<ObjCObjectPointerType>();
1582
1583 if (!OCOPT)
1584 return;
1585
1586 // FIXME: handle 'id', 'Class', and qualified types.
1587 ObjCInterfaceDecl *CDecl = OCOPT->getInterfaceDecl();
1588
1589 while (CDecl != NULL) {
1590 for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1591 E = CDecl->instmeth_end();
1592 I != E; ++I) {
1593 Results.MaybeAddResult(Result(*I, 0), CurContext);
1594 }
1595 // Add class methods in protocols.
1596 const ObjCList<ObjCProtocolDecl> &Protocols=CDecl->getReferencedProtocols();
1597 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1598 E = Protocols.end(); I != E; ++I) {
1599 for (ObjCProtocolDecl::instmeth_iterator I2 = (*I)->instmeth_begin(),
1600 E2 = (*I)->instmeth_end();
1601 I2 != E2; ++I2) {
1602 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1603 }
1604 }
1605 // Add class methods in categories.
1606 ObjCCategoryDecl *CatDecl = CDecl->getCategoryList();
1607 while (CatDecl) {
1608 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
1609 E = CatDecl->instmeth_end();
1610 I != E; ++I) {
1611 Results.MaybeAddResult(Result(*I, 0), CurContext);
1612 }
1613 // Add a categories protocol methods.
1614 const ObjCList<ObjCProtocolDecl> &Protocols =
1615 CatDecl->getReferencedProtocols();
1616 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1617 E = Protocols.end(); I != E; ++I) {
1618 for (ObjCProtocolDecl::instmeth_iterator I2 = (*I)->instmeth_begin(),
1619 E2 = (*I)->instmeth_end();
1620 I2 != E2; ++I2) {
1621 Results.MaybeAddResult(Result(*I2, 0), CurContext);
1622 }
1623 }
1624 CatDecl = CatDecl->getNextClassCategory();
1625 }
1626 CDecl = CDecl->getSuperClass();
1627 }
1628 Results.ExitScope();
1629 // This also suppresses remaining diagnostics.
1630 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1631}