blob: 79904c9c5329156b5a2407f681e04a55f0c81813 [file] [log] [blame]
Douglas Gregor2436e712009-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 Gregorf2510672009-09-21 19:57:38 +000015#include "clang/AST/ExprCXX.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000016#include "llvm/ADT/SmallPtrSet.h"
17#include <list>
18#include <map>
19#include <vector>
Douglas Gregor2436e712009-09-17 21:32:03 +000020
21using namespace clang;
22
23/// \brief Set the code-completion consumer for semantic analysis.
24void Sema::setCodeCompleteConsumer(CodeCompleteConsumer *CCC) {
25 assert(((CodeCompleter != 0) != (CCC != 0)) &&
26 "Already set or cleared a code-completion consumer?");
27 CodeCompleter = CCC;
28}
29
Douglas Gregor3545ff42009-09-21 16:56:56 +000030namespace {
31 /// \brief A container of code-completion results.
32 class ResultBuilder {
33 public:
34 /// \brief The type of a name-lookup filter, which can be provided to the
35 /// name-lookup routines to specify which declarations should be included in
36 /// the result set (when it returns true) and which declarations should be
37 /// filtered out (returns false).
38 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
39
40 typedef CodeCompleteConsumer::Result Result;
41
42 private:
43 /// \brief The actual results we have found.
44 std::vector<Result> Results;
45
46 /// \brief A record of all of the declarations we have found and placed
47 /// into the result set, used to ensure that no declaration ever gets into
48 /// the result set twice.
49 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
50
51 /// \brief A mapping from declaration names to the declarations that have
52 /// this name within a particular scope and their index within the list of
53 /// results.
54 typedef std::multimap<DeclarationName,
55 std::pair<NamedDecl *, unsigned> > ShadowMap;
56
57 /// \brief The semantic analysis object for which results are being
58 /// produced.
59 Sema &SemaRef;
60
61 /// \brief If non-NULL, a filter function used to remove any code-completion
62 /// results that are not desirable.
63 LookupFilter Filter;
64
65 /// \brief A list of shadow maps, which is used to model name hiding at
66 /// different levels of, e.g., the inheritance hierarchy.
67 std::list<ShadowMap> ShadowMaps;
68
69 public:
70 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
71 : SemaRef(SemaRef), Filter(Filter) { }
72
73 /// \brief Set the filter used for code-completion results.
74 void setFilter(LookupFilter Filter) {
75 this->Filter = Filter;
76 }
77
78 typedef std::vector<Result>::iterator iterator;
79 iterator begin() { return Results.begin(); }
80 iterator end() { return Results.end(); }
81
82 Result *data() { return Results.empty()? 0 : &Results.front(); }
83 unsigned size() const { return Results.size(); }
84 bool empty() const { return Results.empty(); }
85
86 /// \brief Add a new result to this result set (if it isn't already in one
87 /// of the shadow maps), or replace an existing result (for, e.g., a
88 /// redeclaration).
Douglas Gregor2af2f672009-09-21 20:12:40 +000089 ///
90 /// \param R the result to add (if it is unique).
91 ///
92 /// \param R the context in which this result will be named.
93 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor3545ff42009-09-21 16:56:56 +000094
95 /// \brief Enter into a new scope.
96 void EnterNewScope();
97
98 /// \brief Exit from the current scope.
99 void ExitScope();
100
101 /// \name Name lookup predicates
102 ///
103 /// These predicates can be passed to the name lookup functions to filter the
104 /// results of name lookup. All of the predicates have the same type, so that
105 ///
106 //@{
107 bool IsNestedNameSpecifier(NamedDecl *ND) const;
108 bool IsEnum(NamedDecl *ND) const;
109 bool IsClassOrStruct(NamedDecl *ND) const;
110 bool IsUnion(NamedDecl *ND) const;
111 bool IsNamespace(NamedDecl *ND) const;
112 bool IsNamespaceOrAlias(NamedDecl *ND) const;
113 bool IsType(NamedDecl *ND) const;
114 //@}
115 };
116}
117
118/// \brief Determines whether the given hidden result could be found with
119/// some extra work, e.g., by qualifying the name.
120///
121/// \param Hidden the declaration that is hidden by the currenly \p Visible
122/// declaration.
123///
124/// \param Visible the declaration with the same name that is already visible.
125///
126/// \returns true if the hidden result can be found by some mechanism,
127/// false otherwise.
128static bool canHiddenResultBeFound(const LangOptions &LangOpts,
129 NamedDecl *Hidden, NamedDecl *Visible) {
130 // In C, there is no way to refer to a hidden name.
131 if (!LangOpts.CPlusPlus)
132 return false;
133
134 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
135
136 // There is no way to qualify a name declared in a function or method.
137 if (HiddenCtx->isFunctionOrMethod())
138 return false;
139
Douglas Gregor3545ff42009-09-21 16:56:56 +0000140 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
141}
142
Douglas Gregor2af2f672009-09-21 20:12:40 +0000143/// \brief Compute the qualification required to get from the current context
144/// (\p CurContext) to the target context (\p TargetContext).
145///
146/// \param Context the AST context in which the qualification will be used.
147///
148/// \param CurContext the context where an entity is being named, which is
149/// typically based on the current scope.
150///
151/// \param TargetContext the context in which the named entity actually
152/// resides.
153///
154/// \returns a nested name specifier that refers into the target context, or
155/// NULL if no qualification is needed.
156static NestedNameSpecifier *
157getRequiredQualification(ASTContext &Context,
158 DeclContext *CurContext,
159 DeclContext *TargetContext) {
160 llvm::SmallVector<DeclContext *, 4> TargetParents;
161
162 for (DeclContext *CommonAncestor = TargetContext;
163 CommonAncestor && !CommonAncestor->Encloses(CurContext);
164 CommonAncestor = CommonAncestor->getLookupParent()) {
165 if (CommonAncestor->isTransparentContext() ||
166 CommonAncestor->isFunctionOrMethod())
167 continue;
168
169 TargetParents.push_back(CommonAncestor);
170 }
171
172 NestedNameSpecifier *Result = 0;
173 while (!TargetParents.empty()) {
174 DeclContext *Parent = TargetParents.back();
175 TargetParents.pop_back();
176
177 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
178 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
179 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
180 Result = NestedNameSpecifier::Create(Context, Result,
181 false,
182 Context.getTypeDeclType(TD).getTypePtr());
183 else
184 assert(Parent->isTranslationUnit());
185 }
186
187 return Result;
188}
189
190void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000191 if (R.Kind != Result::RK_Declaration) {
192 // For non-declaration results, just add the result.
193 Results.push_back(R);
194 return;
195 }
196
197 // Look through using declarations.
198 if (UsingDecl *Using = dyn_cast<UsingDecl>(R.Declaration))
Douglas Gregor2af2f672009-09-21 20:12:40 +0000199 return MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
200 CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000201
202 // Handle each declaration in an overload set separately.
203 if (OverloadedFunctionDecl *Ovl
204 = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) {
205 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
206 FEnd = Ovl->function_end();
207 F != FEnd; ++F)
Douglas Gregor2af2f672009-09-21 20:12:40 +0000208 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000209
210 return;
211 }
212
213 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
214 unsigned IDNS = CanonDecl->getIdentifierNamespace();
215
216 // Friend declarations and declarations introduced due to friends are never
217 // added as results.
218 if (isa<FriendDecl>(CanonDecl) ||
219 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
220 return;
221
222 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
223 // __va_list_tag is a freak of nature. Find it and skip it.
224 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
225 return;
226
227 // FIXME: Should we filter out other names in the implementation's
228 // namespace, e.g., those containing a __ or that start with _[A-Z]?
229 }
230
231 // C++ constructors are never found by name lookup.
232 if (isa<CXXConstructorDecl>(CanonDecl))
233 return;
234
235 // Filter out any unwanted results.
236 if (Filter && !(this->*Filter)(R.Declaration))
237 return;
238
239 ShadowMap &SMap = ShadowMaps.back();
240 ShadowMap::iterator I, IEnd;
241 for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
242 I != IEnd; ++I) {
243 NamedDecl *ND = I->second.first;
244 unsigned Index = I->second.second;
245 if (ND->getCanonicalDecl() == CanonDecl) {
246 // This is a redeclaration. Always pick the newer declaration.
247 I->second.first = R.Declaration;
248 Results[Index].Declaration = R.Declaration;
249
250 // Pick the best rank of the two.
251 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
252
253 // We're done.
254 return;
255 }
256 }
257
258 // This is a new declaration in this scope. However, check whether this
259 // declaration name is hidden by a similarly-named declaration in an outer
260 // scope.
261 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
262 --SMEnd;
263 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
264 for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
265 I != IEnd; ++I) {
266 // A tag declaration does not hide a non-tag declaration.
267 if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
268 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
269 Decl::IDNS_ObjCProtocol)))
270 continue;
271
272 // Protocols are in distinct namespaces from everything else.
273 if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
274 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
275 I->second.first->getIdentifierNamespace() != IDNS)
276 continue;
277
278 // The newly-added result is hidden by an entry in the shadow map.
279 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
280 I->second.first)) {
281 // Note that this result was hidden.
282 R.Hidden = true;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000283
284 if (!R.Qualifier)
285 R.Qualifier = getRequiredQualification(SemaRef.Context,
286 CurContext,
287 R.Declaration->getDeclContext());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000288 } else {
289 // This result was hidden and cannot be found; don't bother adding
290 // it.
291 return;
292 }
293
294 break;
295 }
296 }
297
298 // Make sure that any given declaration only shows up in the result set once.
299 if (!AllDeclsFound.insert(CanonDecl))
300 return;
301
302 // Insert this result into the set of results and into the current shadow
303 // map.
304 SMap.insert(std::make_pair(R.Declaration->getDeclName(),
305 std::make_pair(R.Declaration, Results.size())));
306 Results.push_back(R);
307}
308
309/// \brief Enter into a new scope.
310void ResultBuilder::EnterNewScope() {
311 ShadowMaps.push_back(ShadowMap());
312}
313
314/// \brief Exit from the current scope.
315void ResultBuilder::ExitScope() {
316 ShadowMaps.pop_back();
317}
318
319/// \brief Determines whether the given declaration is suitable as the
320/// start of a C++ nested-name-specifier, e.g., a class or namespace.
321bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
322 // Allow us to find class templates, too.
323 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
324 ND = ClassTemplate->getTemplatedDecl();
325
326 return SemaRef.isAcceptableNestedNameSpecifier(ND);
327}
328
329/// \brief Determines whether the given declaration is an enumeration.
330bool ResultBuilder::IsEnum(NamedDecl *ND) const {
331 return isa<EnumDecl>(ND);
332}
333
334/// \brief Determines whether the given declaration is a class or struct.
335bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
336 // Allow us to find class templates, too.
337 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
338 ND = ClassTemplate->getTemplatedDecl();
339
340 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
341 return RD->getTagKind() == TagDecl::TK_class ||
342 RD->getTagKind() == TagDecl::TK_struct;
343
344 return false;
345}
346
347/// \brief Determines whether the given declaration is a union.
348bool ResultBuilder::IsUnion(NamedDecl *ND) const {
349 // Allow us to find class templates, too.
350 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
351 ND = ClassTemplate->getTemplatedDecl();
352
353 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
354 return RD->getTagKind() == TagDecl::TK_union;
355
356 return false;
357}
358
359/// \brief Determines whether the given declaration is a namespace.
360bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
361 return isa<NamespaceDecl>(ND);
362}
363
364/// \brief Determines whether the given declaration is a namespace or
365/// namespace alias.
366bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
367 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
368}
369
370/// \brief Brief determines whether the given declaration is a namespace or
371/// namespace alias.
372bool ResultBuilder::IsType(NamedDecl *ND) const {
373 return isa<TypeDecl>(ND);
374}
375
376// Find the next outer declaration context corresponding to this scope.
377static DeclContext *findOuterContext(Scope *S) {
378 for (S = S->getParent(); S; S = S->getParent())
379 if (S->getEntity())
380 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
381
382 return 0;
383}
384
385/// \brief Collect the results of searching for members within the given
386/// declaration context.
387///
388/// \param Ctx the declaration context from which we will gather results.
389///
390/// \param InitialRank the initial rank given to results in this declaration
391/// context. Larger rank values will be used for, e.g., members found in
392/// base classes.
393///
394/// \param Visited the set of declaration contexts that have already been
395/// visited. Declaration contexts will only be visited once.
396///
397/// \param Results the result set that will be extended with any results
398/// found within this declaration context (and, for a C++ class, its bases).
399///
400/// \returns the next higher rank value, after considering all of the
401/// names within this declaration context.
402static unsigned CollectMemberLookupResults(DeclContext *Ctx,
403 unsigned InitialRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000404 DeclContext *CurContext,
405 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor3545ff42009-09-21 16:56:56 +0000406 ResultBuilder &Results) {
407 // Make sure we don't visit the same context twice.
408 if (!Visited.insert(Ctx->getPrimaryContext()))
409 return InitialRank;
410
411 // Enumerate all of the results in this context.
412 Results.EnterNewScope();
413 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
414 CurCtx = CurCtx->getNextContext()) {
415 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
416 DEnd = CurCtx->decls_end();
417 D != DEnd; ++D) {
418 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor2af2f672009-09-21 20:12:40 +0000419 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, InitialRank),
420 CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000421 }
422 }
423
424 // Traverse the contexts of inherited classes.
425 unsigned NextRank = InitialRank;
426 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
427 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
428 BEnd = Record->bases_end();
429 B != BEnd; ++B) {
430 QualType BaseType = B->getType();
431
432 // Don't look into dependent bases, because name lookup can't look
433 // there anyway.
434 if (BaseType->isDependentType())
435 continue;
436
437 const RecordType *Record = BaseType->getAs<RecordType>();
438 if (!Record)
439 continue;
440
441 // FIXME: It would be nice to be able to determine whether referencing
442 // a particular member would be ambiguous. For example, given
443 //
444 // struct A { int member; };
445 // struct B { int member; };
446 // struct C : A, B { };
447 //
448 // void f(C *c) { c->### }
449 // accessing 'member' would result in an ambiguity. However, code
450 // completion could be smart enough to qualify the member with the
451 // base class, e.g.,
452 //
453 // c->B::member
454 //
455 // or
456 //
457 // c->A::member
458
459 // Collect results from this base class (and its bases).
460 NextRank = std::max(NextRank,
461 CollectMemberLookupResults(Record->getDecl(),
462 InitialRank + 1,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000463 CurContext,
Douglas Gregor3545ff42009-09-21 16:56:56 +0000464 Visited,
465 Results));
466 }
467 }
468
469 // FIXME: Look into base classes in Objective-C!
470
471 Results.ExitScope();
472 return NextRank;
473}
474
475/// \brief Collect the results of searching for members within the given
476/// declaration context.
477///
478/// \param Ctx the declaration context from which we will gather results.
479///
480/// \param InitialRank the initial rank given to results in this declaration
481/// context. Larger rank values will be used for, e.g., members found in
482/// base classes.
483///
484/// \param Results the result set that will be extended with any results
485/// found within this declaration context (and, for a C++ class, its bases).
486///
487/// \returns the next higher rank value, after considering all of the
488/// names within this declaration context.
489static unsigned CollectMemberLookupResults(DeclContext *Ctx,
490 unsigned InitialRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000491 DeclContext *CurContext,
Douglas Gregor3545ff42009-09-21 16:56:56 +0000492 ResultBuilder &Results) {
493 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor2af2f672009-09-21 20:12:40 +0000494 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
495 Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000496}
497
498/// \brief Collect the results of searching for declarations within the given
499/// scope and its parent scopes.
500///
501/// \param S the scope in which we will start looking for declarations.
502///
503/// \param InitialRank the initial rank given to results in this scope.
504/// Larger rank values will be used for results found in parent scopes.
505///
Douglas Gregor2af2f672009-09-21 20:12:40 +0000506/// \param CurContext the context from which lookup results will be found.
507///
Douglas Gregor3545ff42009-09-21 16:56:56 +0000508/// \param Results the builder object that will receive each result.
509static unsigned CollectLookupResults(Scope *S,
510 TranslationUnitDecl *TranslationUnit,
511 unsigned InitialRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000512 DeclContext *CurContext,
Douglas Gregor3545ff42009-09-21 16:56:56 +0000513 ResultBuilder &Results) {
514 if (!S)
515 return InitialRank;
516
517 // FIXME: Using directives!
518
519 unsigned NextRank = InitialRank;
520 Results.EnterNewScope();
521 if (S->getEntity() &&
522 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
523 // Look into this scope's declaration context, along with any of its
524 // parent lookup contexts (e.g., enclosing classes), up to the point
525 // where we hit the context stored in the next outer scope.
526 DeclContext *Ctx = (DeclContext *)S->getEntity();
527 DeclContext *OuterCtx = findOuterContext(S);
528
529 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
530 Ctx = Ctx->getLookupParent()) {
531 if (Ctx->isFunctionOrMethod())
532 continue;
533
Douglas Gregor2af2f672009-09-21 20:12:40 +0000534 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
535 Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000536 }
537 } else if (!S->getParent()) {
538 // Look into the translation unit scope. We walk through the translation
539 // unit's declaration context, because the Scope itself won't have all of
540 // the declarations if we loaded a precompiled header.
541 // FIXME: We would like the translation unit's Scope object to point to the
542 // translation unit, so we don't need this special "if" branch. However,
543 // doing so would force the normal C++ name-lookup code to look into the
544 // translation unit decl when the IdentifierInfo chains would suffice.
545 // Once we fix that problem (which is part of a more general "don't look
546 // in DeclContexts unless we have to" optimization), we can eliminate the
547 // TranslationUnit parameter entirely.
548 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000549 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000550 } else {
551 // Walk through the declarations in this Scope.
552 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
553 D != DEnd; ++D) {
554 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
Douglas Gregor2af2f672009-09-21 20:12:40 +0000555 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
556 CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000557 }
558
559 NextRank = NextRank + 1;
560 }
561
562 // Lookup names in the parent scope.
563 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000564 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000565 Results.ExitScope();
566
567 return NextRank;
568}
569
570/// \brief Add type specifiers for the current language as keyword results.
571static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
572 ResultBuilder &Results) {
573 typedef CodeCompleteConsumer::Result Result;
574 Results.MaybeAddResult(Result("short", Rank));
575 Results.MaybeAddResult(Result("long", Rank));
576 Results.MaybeAddResult(Result("signed", Rank));
577 Results.MaybeAddResult(Result("unsigned", Rank));
578 Results.MaybeAddResult(Result("void", Rank));
579 Results.MaybeAddResult(Result("char", Rank));
580 Results.MaybeAddResult(Result("int", Rank));
581 Results.MaybeAddResult(Result("float", Rank));
582 Results.MaybeAddResult(Result("double", Rank));
583 Results.MaybeAddResult(Result("enum", Rank));
584 Results.MaybeAddResult(Result("struct", Rank));
585 Results.MaybeAddResult(Result("union", Rank));
586
587 if (LangOpts.C99) {
588 // C99-specific
589 Results.MaybeAddResult(Result("_Complex", Rank));
590 Results.MaybeAddResult(Result("_Imaginary", Rank));
591 Results.MaybeAddResult(Result("_Bool", Rank));
592 }
593
594 if (LangOpts.CPlusPlus) {
595 // C++-specific
596 Results.MaybeAddResult(Result("bool", Rank));
597 Results.MaybeAddResult(Result("class", Rank));
598 Results.MaybeAddResult(Result("typename", Rank));
599 Results.MaybeAddResult(Result("wchar_t", Rank));
600
601 if (LangOpts.CPlusPlus0x) {
602 Results.MaybeAddResult(Result("char16_t", Rank));
603 Results.MaybeAddResult(Result("char32_t", Rank));
604 Results.MaybeAddResult(Result("decltype", Rank));
605 }
606 }
607
608 // GNU extensions
609 if (LangOpts.GNUMode) {
610 // FIXME: Enable when we actually support decimal floating point.
611 // Results.MaybeAddResult(Result("_Decimal32", Rank));
612 // Results.MaybeAddResult(Result("_Decimal64", Rank));
613 // Results.MaybeAddResult(Result("_Decimal128", Rank));
614 Results.MaybeAddResult(Result("typeof", Rank));
615 }
616}
617
618/// \brief Add function parameter chunks to the given code completion string.
619static void AddFunctionParameterChunks(ASTContext &Context,
620 FunctionDecl *Function,
621 CodeCompletionString *Result) {
622 CodeCompletionString *CCStr = Result;
623
624 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
625 ParmVarDecl *Param = Function->getParamDecl(P);
626
627 if (Param->hasDefaultArg()) {
628 // When we see an optional default argument, put that argument and
629 // the remaining default arguments into a new, optional string.
630 CodeCompletionString *Opt = new CodeCompletionString;
631 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
632 CCStr = Opt;
633 }
634
635 if (P != 0)
636 CCStr->AddTextChunk(", ");
637
638 // Format the placeholder string.
639 std::string PlaceholderStr;
640 if (Param->getIdentifier())
641 PlaceholderStr = Param->getIdentifier()->getName();
642
643 Param->getType().getAsStringInternal(PlaceholderStr,
644 Context.PrintingPolicy);
645
646 // Add the placeholder string.
647 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
648 }
649}
650
651/// \brief Add template parameter chunks to the given code completion string.
652static void AddTemplateParameterChunks(ASTContext &Context,
653 TemplateDecl *Template,
654 CodeCompletionString *Result,
655 unsigned MaxParameters = 0) {
656 CodeCompletionString *CCStr = Result;
657 bool FirstParameter = true;
658
659 TemplateParameterList *Params = Template->getTemplateParameters();
660 TemplateParameterList::iterator PEnd = Params->end();
661 if (MaxParameters)
662 PEnd = Params->begin() + MaxParameters;
663 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
664 bool HasDefaultArg = false;
665 std::string PlaceholderStr;
666 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
667 if (TTP->wasDeclaredWithTypename())
668 PlaceholderStr = "typename";
669 else
670 PlaceholderStr = "class";
671
672 if (TTP->getIdentifier()) {
673 PlaceholderStr += ' ';
674 PlaceholderStr += TTP->getIdentifier()->getName();
675 }
676
677 HasDefaultArg = TTP->hasDefaultArgument();
678 } else if (NonTypeTemplateParmDecl *NTTP
679 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
680 if (NTTP->getIdentifier())
681 PlaceholderStr = NTTP->getIdentifier()->getName();
682 NTTP->getType().getAsStringInternal(PlaceholderStr,
683 Context.PrintingPolicy);
684 HasDefaultArg = NTTP->hasDefaultArgument();
685 } else {
686 assert(isa<TemplateTemplateParmDecl>(*P));
687 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
688
689 // Since putting the template argument list into the placeholder would
690 // be very, very long, we just use an abbreviation.
691 PlaceholderStr = "template<...> class";
692 if (TTP->getIdentifier()) {
693 PlaceholderStr += ' ';
694 PlaceholderStr += TTP->getIdentifier()->getName();
695 }
696
697 HasDefaultArg = TTP->hasDefaultArgument();
698 }
699
700 if (HasDefaultArg) {
701 // When we see an optional default argument, put that argument and
702 // the remaining default arguments into a new, optional string.
703 CodeCompletionString *Opt = new CodeCompletionString;
704 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
705 CCStr = Opt;
706 }
707
708 if (FirstParameter)
709 FirstParameter = false;
710 else
711 CCStr->AddTextChunk(", ");
712
713 // Add the placeholder string.
714 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
715 }
716}
717
Douglas Gregorf2510672009-09-21 19:57:38 +0000718/// \brief Add a qualifier to the given code-completion string, if the
719/// provided nested-name-specifier is non-NULL.
720void AddQualifierToCompletionString(CodeCompletionString *Result,
721 NestedNameSpecifier *Qualifier,
722 ASTContext &Context) {
723 if (!Qualifier)
724 return;
725
726 std::string PrintedNNS;
727 {
728 llvm::raw_string_ostream OS(PrintedNNS);
729 Qualifier->print(OS, Context.PrintingPolicy);
730 }
731 Result->AddTextChunk(PrintedNNS.c_str());
732}
733
Douglas Gregor3545ff42009-09-21 16:56:56 +0000734/// \brief If possible, create a new code completion string for the given
735/// result.
736///
737/// \returns Either a new, heap-allocated code completion string describing
738/// how to use this result, or NULL to indicate that the string or name of the
739/// result is all that is needed.
740CodeCompletionString *
741CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
742 if (Kind != RK_Declaration)
743 return 0;
744
745 NamedDecl *ND = Declaration;
746
747 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
748 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregorf2510672009-09-21 19:57:38 +0000749 AddQualifierToCompletionString(Result, Qualifier, S.Context);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000750 Result->AddTextChunk(Function->getNameAsString().c_str());
751 Result->AddTextChunk("(");
752 AddFunctionParameterChunks(S.Context, Function, Result);
753 Result->AddTextChunk(")");
754 return Result;
755 }
756
757 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
758 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregorf2510672009-09-21 19:57:38 +0000759 AddQualifierToCompletionString(Result, Qualifier, S.Context);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000760 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
761 Result->AddTextChunk(Function->getNameAsString().c_str());
762
763 // Figure out which template parameters are deduced (or have default
764 // arguments).
765 llvm::SmallVector<bool, 16> Deduced;
766 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
767 unsigned LastDeducibleArgument;
768 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
769 --LastDeducibleArgument) {
770 if (!Deduced[LastDeducibleArgument - 1]) {
771 // C++0x: Figure out if the template argument has a default. If so,
772 // the user doesn't need to type this argument.
773 // FIXME: We need to abstract template parameters better!
774 bool HasDefaultArg = false;
775 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
776 LastDeducibleArgument - 1);
777 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
778 HasDefaultArg = TTP->hasDefaultArgument();
779 else if (NonTypeTemplateParmDecl *NTTP
780 = dyn_cast<NonTypeTemplateParmDecl>(Param))
781 HasDefaultArg = NTTP->hasDefaultArgument();
782 else {
783 assert(isa<TemplateTemplateParmDecl>(Param));
784 HasDefaultArg
785 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
786 }
787
788 if (!HasDefaultArg)
789 break;
790 }
791 }
792
793 if (LastDeducibleArgument) {
794 // Some of the function template arguments cannot be deduced from a
795 // function call, so we introduce an explicit template argument list
796 // containing all of the arguments up to the first deducible argument.
797 Result->AddTextChunk("<");
798 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
799 LastDeducibleArgument);
800 Result->AddTextChunk(">");
801 }
802
803 // Add the function parameters
804 Result->AddTextChunk("(");
805 AddFunctionParameterChunks(S.Context, Function, Result);
806 Result->AddTextChunk(")");
807 return Result;
808 }
809
810 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
811 CodeCompletionString *Result = new CodeCompletionString;
Douglas Gregorf2510672009-09-21 19:57:38 +0000812 AddQualifierToCompletionString(Result, Qualifier, S.Context);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000813 Result->AddTextChunk(Template->getNameAsString().c_str());
814 Result->AddTextChunk("<");
815 AddTemplateParameterChunks(S.Context, Template, Result);
816 Result->AddTextChunk(">");
817 return Result;
818 }
819
Douglas Gregorf2510672009-09-21 19:57:38 +0000820 if (Qualifier) {
821 CodeCompletionString *Result = new CodeCompletionString;
822 AddQualifierToCompletionString(Result, Qualifier, S.Context);
823 Result->AddTextChunk(ND->getNameAsString().c_str());
824 return Result;
825 }
826
Douglas Gregor3545ff42009-09-21 16:56:56 +0000827 return 0;
828}
829
830namespace {
831 struct SortCodeCompleteResult {
832 typedef CodeCompleteConsumer::Result Result;
833
834 bool operator()(const Result &X, const Result &Y) const {
835 // Sort first by rank.
836 if (X.Rank < Y.Rank)
837 return true;
838 else if (X.Rank > Y.Rank)
839 return false;
840
841 // Result kinds are ordered by decreasing importance.
842 if (X.Kind < Y.Kind)
843 return true;
844 else if (X.Kind > Y.Kind)
845 return false;
846
847 // Non-hidden names precede hidden names.
848 if (X.Hidden != Y.Hidden)
849 return !X.Hidden;
850
851 // Ordering depends on the kind of result.
852 switch (X.Kind) {
853 case Result::RK_Declaration:
854 // Order based on the declaration names.
855 return X.Declaration->getDeclName() < Y.Declaration->getDeclName();
856
857 case Result::RK_Keyword:
858 return strcmp(X.Keyword, Y.Keyword) == -1;
859 }
860
861 // Silence GCC warning.
862 return false;
863 }
864 };
865}
866
867static void HandleCodeCompleteResults(CodeCompleteConsumer *CodeCompleter,
868 CodeCompleteConsumer::Result *Results,
869 unsigned NumResults) {
870 // Sort the results by rank/kind/etc.
871 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
872
873 if (CodeCompleter)
874 CodeCompleter->ProcessCodeCompleteResults(Results, NumResults);
875}
876
Douglas Gregor2436e712009-09-17 21:32:03 +0000877void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
878 SourceLocation OpLoc,
879 bool IsArrow) {
880 if (!BaseE || !CodeCompleter)
881 return;
882
Douglas Gregor3545ff42009-09-21 16:56:56 +0000883 typedef CodeCompleteConsumer::Result Result;
884
Douglas Gregor2436e712009-09-17 21:32:03 +0000885 Expr *Base = static_cast<Expr *>(BaseE);
886 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +0000887
888 if (IsArrow) {
889 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
890 BaseType = Ptr->getPointeeType();
891 else if (BaseType->isObjCObjectPointerType())
892 /*Do nothing*/ ;
893 else
894 return;
895 }
896
897 ResultBuilder Results(*this);
898 unsigned NextRank = 0;
899
900 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor2af2f672009-09-21 20:12:40 +0000901 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
902 Record->getDecl(), Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000903
904 if (getLangOptions().CPlusPlus) {
905 if (!Results.empty()) {
906 // The "template" keyword can follow "->" or "." in the grammar.
907 // However, we only want to suggest the template keyword if something
908 // is dependent.
909 bool IsDependent = BaseType->isDependentType();
910 if (!IsDependent) {
911 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
912 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
913 IsDependent = Ctx->isDependentContext();
914 break;
915 }
916 }
917
918 if (IsDependent)
919 Results.MaybeAddResult(Result("template", NextRank++));
920 }
921
922 // We could have the start of a nested-name-specifier. Add those
923 // results as well.
924 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
925 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000926 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000927 }
928
929 // Hand off the results found for code completion.
930 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
931
932 // We're done!
933 return;
934 }
Douglas Gregor2436e712009-09-17 21:32:03 +0000935}
936
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000937void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
938 if (!CodeCompleter)
939 return;
940
Douglas Gregor3545ff42009-09-21 16:56:56 +0000941 typedef CodeCompleteConsumer::Result Result;
942 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000943 switch ((DeclSpec::TST)TagSpec) {
944 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +0000945 Filter = &ResultBuilder::IsEnum;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000946 break;
947
948 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +0000949 Filter = &ResultBuilder::IsUnion;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000950 break;
951
952 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000953 case DeclSpec::TST_class:
Douglas Gregor3545ff42009-09-21 16:56:56 +0000954 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000955 break;
956
957 default:
958 assert(false && "Unknown type specifier kind in CodeCompleteTag");
959 return;
960 }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000961
962 ResultBuilder Results(*this, Filter);
963 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor2af2f672009-09-21 20:12:40 +0000964 0, CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000965
966 if (getLangOptions().CPlusPlus) {
967 // We could have the start of a nested-name-specifier. Add those
968 // results as well.
969 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
970 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
Douglas Gregor2af2f672009-09-21 20:12:40 +0000971 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +0000972 }
973
974 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +0000975}
976
Douglas Gregord328d572009-09-21 18:10:23 +0000977void Sema::CodeCompleteCase(Scope *S) {
978 if (getSwitchStack().empty() || !CodeCompleter)
979 return;
980
981 SwitchStmt *Switch = getSwitchStack().back();
982 if (!Switch->getCond()->getType()->isEnumeralType())
983 return;
984
985 // Code-complete the cases of a switch statement over an enumeration type
986 // by providing the list of
987 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
988
989 // Determine which enumerators we have already seen in the switch statement.
990 // FIXME: Ideally, we would also be able to look *past* the code-completion
991 // token, in case we are code-completing in the middle of the switch and not
992 // at the end. However, we aren't able to do so at the moment.
993 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorf2510672009-09-21 19:57:38 +0000994 NestedNameSpecifier *Qualifier = 0;
Douglas Gregord328d572009-09-21 18:10:23 +0000995 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
996 SC = SC->getNextSwitchCase()) {
997 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
998 if (!Case)
999 continue;
1000
1001 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1002 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1003 if (EnumConstantDecl *Enumerator
1004 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1005 // We look into the AST of the case statement to determine which
1006 // enumerator was named. Alternatively, we could compute the value of
1007 // the integral constant expression, then compare it against the
1008 // values of each enumerator. However, value-based approach would not
1009 // work as well with C++ templates where enumerators declared within a
1010 // template are type- and value-dependent.
1011 EnumeratorsSeen.insert(Enumerator);
1012
Douglas Gregorf2510672009-09-21 19:57:38 +00001013 // If this is a qualified-id, keep track of the nested-name-specifier
1014 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00001015 //
1016 // switch (TagD.getKind()) {
1017 // case TagDecl::TK_enum:
1018 // break;
1019 // case XXX
1020 //
Douglas Gregorf2510672009-09-21 19:57:38 +00001021 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00001022 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1023 // TK_struct, and TK_class.
Douglas Gregorf2510672009-09-21 19:57:38 +00001024 if (QualifiedDeclRefExpr *QDRE = dyn_cast<QualifiedDeclRefExpr>(DRE))
1025 Qualifier = QDRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00001026 }
1027 }
1028
Douglas Gregorf2510672009-09-21 19:57:38 +00001029 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1030 // If there are no prior enumerators in C++, check whether we have to
1031 // qualify the names of the enumerators that we suggest, because they
1032 // may not be visible in this scope.
1033 Qualifier = getRequiredQualification(Context, CurContext,
1034 Enum->getDeclContext());
1035
1036 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1037 }
1038
Douglas Gregord328d572009-09-21 18:10:23 +00001039 // Add any enumerators that have not yet been mentioned.
1040 ResultBuilder Results(*this);
1041 Results.EnterNewScope();
1042 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1043 EEnd = Enum->enumerator_end();
1044 E != EEnd; ++E) {
1045 if (EnumeratorsSeen.count(*E))
1046 continue;
1047
Douglas Gregorf2510672009-09-21 19:57:38 +00001048 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregord328d572009-09-21 18:10:23 +00001049 }
1050 Results.ExitScope();
1051
Douglas Gregord328d572009-09-21 18:10:23 +00001052 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1053}
1054
Douglas Gregor2436e712009-09-17 21:32:03 +00001055void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1056 bool EnteringContext) {
1057 if (!SS.getScopeRep() || !CodeCompleter)
1058 return;
1059
Douglas Gregor3545ff42009-09-21 16:56:56 +00001060 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1061 if (!Ctx)
1062 return;
1063
1064 ResultBuilder Results(*this);
Douglas Gregor2af2f672009-09-21 20:12:40 +00001065 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001066
1067 // The "template" keyword can follow "::" in the grammar, but only
1068 // put it into the grammar if the nested-name-specifier is dependent.
1069 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1070 if (!Results.empty() && NNS->isDependent())
1071 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1072
1073 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00001074}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001075
1076void Sema::CodeCompleteUsing(Scope *S) {
1077 if (!CodeCompleter)
1078 return;
1079
Douglas Gregor3545ff42009-09-21 16:56:56 +00001080 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
1081
1082 // If we aren't in class scope, we could see the "namespace" keyword.
1083 if (!S->isClassScope())
1084 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1085
1086 // After "using", we can see anything that would start a
1087 // nested-name-specifier.
Douglas Gregor2af2f672009-09-21 20:12:40 +00001088 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0,
1089 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001090
1091 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001092}
1093
1094void Sema::CodeCompleteUsingDirective(Scope *S) {
1095 if (!CodeCompleter)
1096 return;
1097
Douglas Gregor3545ff42009-09-21 16:56:56 +00001098 // After "using namespace", we expect to see a namespace name or namespace
1099 // alias.
1100 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor2af2f672009-09-21 20:12:40 +00001101 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1102 Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001103 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001104}
1105
1106void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1107 if (!CodeCompleter)
1108 return;
1109
Douglas Gregor3545ff42009-09-21 16:56:56 +00001110 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1111 DeclContext *Ctx = (DeclContext *)S->getEntity();
1112 if (!S->getParent())
1113 Ctx = Context.getTranslationUnitDecl();
1114
1115 if (Ctx && Ctx->isFileContext()) {
1116 // We only want to see those namespaces that have already been defined
1117 // within this scope, because its likely that the user is creating an
1118 // extended namespace declaration. Keep track of the most recent
1119 // definition of each namespace.
1120 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1121 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1122 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1123 NS != NSEnd; ++NS)
1124 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1125
1126 // Add the most recent definition (or extended definition) of each
1127 // namespace to the list of results.
1128 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1129 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1130 NS != NSEnd; ++NS)
Douglas Gregor2af2f672009-09-21 20:12:40 +00001131 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1132 CurContext);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001133 }
1134
1135 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001136}
1137
1138void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1139 if (!CodeCompleter)
1140 return;
1141
Douglas Gregor3545ff42009-09-21 16:56:56 +00001142 // After "namespace", we expect to see a namespace or alias.
1143 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor2af2f672009-09-21 20:12:40 +00001144 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1145 Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001146 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001147}
1148
Douglas Gregorc811ede2009-09-18 20:05:18 +00001149void Sema::CodeCompleteOperatorName(Scope *S) {
1150 if (!CodeCompleter)
1151 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00001152
1153 typedef CodeCompleteConsumer::Result Result;
1154 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregorc811ede2009-09-18 20:05:18 +00001155
Douglas Gregor3545ff42009-09-21 16:56:56 +00001156 // Add the names of overloadable operators.
1157#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1158 if (std::strcmp(Spelling, "?")) \
1159 Results.MaybeAddResult(Result(Spelling, 0));
1160#include "clang/Basic/OperatorKinds.def"
1161
1162 // Add any type names visible from the current scope
1163 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor2af2f672009-09-21 20:12:40 +00001164 0, CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001165
1166 // Add any type specifiers
1167 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1168
1169 // Add any nested-name-specifiers
1170 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1171 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank + 1,
Douglas Gregor2af2f672009-09-21 20:12:40 +00001172 CurContext, Results);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001173
1174 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00001175}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00001176