blob: d54e4c0e03a5308afe57112b0d593097e1468d64 [file] [log] [blame]
Douglas Gregor81b747b2009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
13#include "Sema.h"
14#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000015#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000016#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000017#include "clang/Lex/MacroInfo.h"
18#include "clang/Lex/Preprocessor.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000019#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000020#include "llvm/ADT/StringExtras.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000021#include <list>
22#include <map>
23#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000024
25using namespace clang;
26
Douglas Gregor86d9a522009-09-21 16:56:56 +000027namespace {
28 /// \brief A container of code-completion results.
29 class ResultBuilder {
30 public:
31 /// \brief The type of a name-lookup filter, which can be provided to the
32 /// name-lookup routines to specify which declarations should be included in
33 /// the result set (when it returns true) and which declarations should be
34 /// filtered out (returns false).
35 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
36
37 typedef CodeCompleteConsumer::Result Result;
38
39 private:
40 /// \brief The actual results we have found.
41 std::vector<Result> Results;
42
43 /// \brief A record of all of the declarations we have found and placed
44 /// into the result set, used to ensure that no declaration ever gets into
45 /// the result set twice.
46 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
47
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000048 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
49
50 /// \brief An entry in the shadow map, which is optimized to store
51 /// a single (declaration, index) mapping (the common case) but
52 /// can also store a list of (declaration, index) mappings.
53 class ShadowMapEntry {
54 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
55
56 /// \brief Contains either the solitary NamedDecl * or a vector
57 /// of (declaration, index) pairs.
58 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
59
60 /// \brief When the entry contains a single declaration, this is
61 /// the index associated with that entry.
62 unsigned SingleDeclIndex;
63
64 public:
65 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
66
67 void Add(NamedDecl *ND, unsigned Index) {
68 if (DeclOrVector.isNull()) {
69 // 0 - > 1 elements: just set the single element information.
70 DeclOrVector = ND;
71 SingleDeclIndex = Index;
72 return;
73 }
74
75 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
76 // 1 -> 2 elements: create the vector of results and push in the
77 // existing declaration.
78 DeclIndexPairVector *Vec = new DeclIndexPairVector;
79 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
80 DeclOrVector = Vec;
81 }
82
83 // Add the new element to the end of the vector.
84 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
85 DeclIndexPair(ND, Index));
86 }
87
88 void Destroy() {
89 if (DeclIndexPairVector *Vec
90 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
91 delete Vec;
92 DeclOrVector = ((NamedDecl *)0);
93 }
94 }
95
96 // Iteration.
97 class iterator;
98 iterator begin() const;
99 iterator end() const;
100 };
101
Douglas Gregor86d9a522009-09-21 16:56:56 +0000102 /// \brief A mapping from declaration names to the declarations that have
103 /// this name within a particular scope and their index within the list of
104 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000105 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000106
107 /// \brief The semantic analysis object for which results are being
108 /// produced.
109 Sema &SemaRef;
110
111 /// \brief If non-NULL, a filter function used to remove any code-completion
112 /// results that are not desirable.
113 LookupFilter Filter;
114
115 /// \brief A list of shadow maps, which is used to model name hiding at
116 /// different levels of, e.g., the inheritance hierarchy.
117 std::list<ShadowMap> ShadowMaps;
118
119 public:
120 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
121 : SemaRef(SemaRef), Filter(Filter) { }
122
123 /// \brief Set the filter used for code-completion results.
124 void setFilter(LookupFilter Filter) {
125 this->Filter = Filter;
126 }
127
128 typedef std::vector<Result>::iterator iterator;
129 iterator begin() { return Results.begin(); }
130 iterator end() { return Results.end(); }
131
132 Result *data() { return Results.empty()? 0 : &Results.front(); }
133 unsigned size() const { return Results.size(); }
134 bool empty() const { return Results.empty(); }
135
136 /// \brief Add a new result to this result set (if it isn't already in one
137 /// of the shadow maps), or replace an existing result (for, e.g., a
138 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000139 ///
140 /// \param R the result to add (if it is unique).
141 ///
142 /// \param R the context in which this result will be named.
143 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000144
145 /// \brief Enter into a new scope.
146 void EnterNewScope();
147
148 /// \brief Exit from the current scope.
149 void ExitScope();
150
Douglas Gregor55385fe2009-11-18 04:19:12 +0000151 /// \brief Ignore this declaration, if it is seen again.
152 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
153
Douglas Gregor86d9a522009-09-21 16:56:56 +0000154 /// \name Name lookup predicates
155 ///
156 /// These predicates can be passed to the name lookup functions to filter the
157 /// results of name lookup. All of the predicates have the same type, so that
158 ///
159 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000160 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000161 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000162 bool IsNestedNameSpecifier(NamedDecl *ND) const;
163 bool IsEnum(NamedDecl *ND) const;
164 bool IsClassOrStruct(NamedDecl *ND) const;
165 bool IsUnion(NamedDecl *ND) const;
166 bool IsNamespace(NamedDecl *ND) const;
167 bool IsNamespaceOrAlias(NamedDecl *ND) const;
168 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000169 bool IsMember(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000170 //@}
171 };
172}
173
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000174class ResultBuilder::ShadowMapEntry::iterator {
175 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
176 unsigned SingleDeclIndex;
177
178public:
179 typedef DeclIndexPair value_type;
180 typedef value_type reference;
181 typedef std::ptrdiff_t difference_type;
182 typedef std::input_iterator_tag iterator_category;
183
184 class pointer {
185 DeclIndexPair Value;
186
187 public:
188 pointer(const DeclIndexPair &Value) : Value(Value) { }
189
190 const DeclIndexPair *operator->() const {
191 return &Value;
192 }
193 };
194
195 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
196
197 iterator(NamedDecl *SingleDecl, unsigned Index)
198 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
199
200 iterator(const DeclIndexPair *Iterator)
201 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
202
203 iterator &operator++() {
204 if (DeclOrIterator.is<NamedDecl *>()) {
205 DeclOrIterator = (NamedDecl *)0;
206 SingleDeclIndex = 0;
207 return *this;
208 }
209
210 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
211 ++I;
212 DeclOrIterator = I;
213 return *this;
214 }
215
216 iterator operator++(int) {
217 iterator tmp(*this);
218 ++(*this);
219 return tmp;
220 }
221
222 reference operator*() const {
223 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
224 return reference(ND, SingleDeclIndex);
225
Douglas Gregord490f952009-12-06 21:27:58 +0000226 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000227 }
228
229 pointer operator->() const {
230 return pointer(**this);
231 }
232
233 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000234 return X.DeclOrIterator.getOpaqueValue()
235 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000236 X.SingleDeclIndex == Y.SingleDeclIndex;
237 }
238
239 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000240 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000241 }
242};
243
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000244ResultBuilder::ShadowMapEntry::iterator
245ResultBuilder::ShadowMapEntry::begin() const {
246 if (DeclOrVector.isNull())
247 return iterator();
248
249 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
250 return iterator(ND, SingleDeclIndex);
251
252 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
253}
254
255ResultBuilder::ShadowMapEntry::iterator
256ResultBuilder::ShadowMapEntry::end() const {
257 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
258 return iterator();
259
260 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
261}
262
Douglas Gregor86d9a522009-09-21 16:56:56 +0000263/// \brief Determines whether the given hidden result could be found with
264/// some extra work, e.g., by qualifying the name.
265///
266/// \param Hidden the declaration that is hidden by the currenly \p Visible
267/// declaration.
268///
269/// \param Visible the declaration with the same name that is already visible.
270///
271/// \returns true if the hidden result can be found by some mechanism,
272/// false otherwise.
273static bool canHiddenResultBeFound(const LangOptions &LangOpts,
274 NamedDecl *Hidden, NamedDecl *Visible) {
275 // In C, there is no way to refer to a hidden name.
276 if (!LangOpts.CPlusPlus)
277 return false;
278
279 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
280
281 // There is no way to qualify a name declared in a function or method.
282 if (HiddenCtx->isFunctionOrMethod())
283 return false;
284
Douglas Gregor86d9a522009-09-21 16:56:56 +0000285 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
286}
287
Douglas Gregor456c4a12009-09-21 20:12:40 +0000288/// \brief Compute the qualification required to get from the current context
289/// (\p CurContext) to the target context (\p TargetContext).
290///
291/// \param Context the AST context in which the qualification will be used.
292///
293/// \param CurContext the context where an entity is being named, which is
294/// typically based on the current scope.
295///
296/// \param TargetContext the context in which the named entity actually
297/// resides.
298///
299/// \returns a nested name specifier that refers into the target context, or
300/// NULL if no qualification is needed.
301static NestedNameSpecifier *
302getRequiredQualification(ASTContext &Context,
303 DeclContext *CurContext,
304 DeclContext *TargetContext) {
305 llvm::SmallVector<DeclContext *, 4> TargetParents;
306
307 for (DeclContext *CommonAncestor = TargetContext;
308 CommonAncestor && !CommonAncestor->Encloses(CurContext);
309 CommonAncestor = CommonAncestor->getLookupParent()) {
310 if (CommonAncestor->isTransparentContext() ||
311 CommonAncestor->isFunctionOrMethod())
312 continue;
313
314 TargetParents.push_back(CommonAncestor);
315 }
316
317 NestedNameSpecifier *Result = 0;
318 while (!TargetParents.empty()) {
319 DeclContext *Parent = TargetParents.back();
320 TargetParents.pop_back();
321
322 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
323 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
324 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
325 Result = NestedNameSpecifier::Create(Context, Result,
326 false,
327 Context.getTypeDeclType(TD).getTypePtr());
328 else
329 assert(Parent->isTranslationUnit());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000330 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000331 return Result;
332}
333
334void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
Douglas Gregor8e0a0e42009-09-22 23:31:26 +0000335 assert(!ShadowMaps.empty() && "Must enter into a results scope");
336
Douglas Gregor86d9a522009-09-21 16:56:56 +0000337 if (R.Kind != Result::RK_Declaration) {
338 // For non-declaration results, just add the result.
339 Results.push_back(R);
340 return;
341 }
Douglas Gregorf52cede2009-10-09 22:16:47 +0000342
343 // Skip unnamed entities.
344 if (!R.Declaration->getDeclName())
345 return;
346
Douglas Gregor86d9a522009-09-21 16:56:56 +0000347 // Look through using declarations.
John McCall9488ea12009-11-17 05:59:44 +0000348 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration))
Douglas Gregor0563c262009-09-22 23:15:58 +0000349 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
350 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000351
Douglas Gregor86d9a522009-09-21 16:56:56 +0000352 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
353 unsigned IDNS = CanonDecl->getIdentifierNamespace();
354
355 // Friend declarations and declarations introduced due to friends are never
356 // added as results.
357 if (isa<FriendDecl>(CanonDecl) ||
358 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
359 return;
Douglas Gregore29ffaa2009-12-11 16:18:54 +0000360
Douglas Gregor76282942009-12-11 17:31:05 +0000361 // Class template (partial) specializations are never added as results.
Douglas Gregore29ffaa2009-12-11 16:18:54 +0000362 if (isa<ClassTemplateSpecializationDecl>(CanonDecl) ||
363 isa<ClassTemplatePartialSpecializationDecl>(CanonDecl))
364 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000365
Douglas Gregor76282942009-12-11 17:31:05 +0000366 // Using declarations themselves are never added as results.
367 if (isa<UsingDecl>(CanonDecl))
368 return;
369
Douglas Gregor86d9a522009-09-21 16:56:56 +0000370 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
371 // __va_list_tag is a freak of nature. Find it and skip it.
372 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
373 return;
374
Douglas Gregorf52cede2009-10-09 22:16:47 +0000375 // Filter out names reserved for the implementation (C99 7.1.3,
376 // C++ [lib.global.names]). Users don't need to see those.
Daniel Dunbare013d682009-10-18 20:26:12 +0000377 //
378 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000379 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000380 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000381 if (Name[0] == '_' &&
382 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
383 return;
384 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000385 }
386
387 // C++ constructors are never found by name lookup.
388 if (isa<CXXConstructorDecl>(CanonDecl))
389 return;
390
391 // Filter out any unwanted results.
392 if (Filter && !(this->*Filter)(R.Declaration))
393 return;
394
395 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000396 ShadowMapEntry::iterator I, IEnd;
397 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
398 if (NamePos != SMap.end()) {
399 I = NamePos->second.begin();
400 IEnd = NamePos->second.end();
401 }
402
403 for (; I != IEnd; ++I) {
404 NamedDecl *ND = I->first;
405 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000406 if (ND->getCanonicalDecl() == CanonDecl) {
407 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000408 Results[Index].Declaration = R.Declaration;
409
410 // Pick the best rank of the two.
411 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
412
413 // We're done.
414 return;
415 }
416 }
417
418 // This is a new declaration in this scope. However, check whether this
419 // declaration name is hidden by a similarly-named declaration in an outer
420 // scope.
421 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
422 --SMEnd;
423 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000424 ShadowMapEntry::iterator I, IEnd;
425 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
426 if (NamePos != SM->end()) {
427 I = NamePos->second.begin();
428 IEnd = NamePos->second.end();
429 }
430 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000431 // A tag declaration does not hide a non-tag declaration.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000432 if (I->first->getIdentifierNamespace() == Decl::IDNS_Tag &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000433 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
434 Decl::IDNS_ObjCProtocol)))
435 continue;
436
437 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000438 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000439 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000440 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000441 continue;
442
443 // The newly-added result is hidden by an entry in the shadow map.
444 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000445 I->first)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000446 // Note that this result was hidden.
447 R.Hidden = true;
Douglas Gregor0563c262009-09-22 23:15:58 +0000448 R.QualifierIsInformative = false;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000449
450 if (!R.Qualifier)
451 R.Qualifier = getRequiredQualification(SemaRef.Context,
452 CurContext,
453 R.Declaration->getDeclContext());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000454 } else {
455 // This result was hidden and cannot be found; don't bother adding
456 // it.
457 return;
458 }
459
460 break;
461 }
462 }
463
464 // Make sure that any given declaration only shows up in the result set once.
465 if (!AllDeclsFound.insert(CanonDecl))
466 return;
467
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000468 // If the filter is for nested-name-specifiers, then this result starts a
469 // nested-name-specifier.
470 if ((Filter == &ResultBuilder::IsNestedNameSpecifier) ||
471 (Filter == &ResultBuilder::IsMember &&
472 isa<CXXRecordDecl>(R.Declaration) &&
473 cast<CXXRecordDecl>(R.Declaration)->isInjectedClassName()))
474 R.StartsNestedNameSpecifier = true;
475
Douglas Gregor0563c262009-09-22 23:15:58 +0000476 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000477 if (R.QualifierIsInformative && !R.Qualifier &&
478 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000479 DeclContext *Ctx = R.Declaration->getDeclContext();
480 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
481 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
482 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
483 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
484 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
485 else
486 R.QualifierIsInformative = false;
487 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000488
Douglas Gregor86d9a522009-09-21 16:56:56 +0000489 // Insert this result into the set of results and into the current shadow
490 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000491 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000492 Results.push_back(R);
493}
494
495/// \brief Enter into a new scope.
496void ResultBuilder::EnterNewScope() {
497 ShadowMaps.push_back(ShadowMap());
498}
499
500/// \brief Exit from the current scope.
501void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000502 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
503 EEnd = ShadowMaps.back().end();
504 E != EEnd;
505 ++E)
506 E->second.Destroy();
507
Douglas Gregor86d9a522009-09-21 16:56:56 +0000508 ShadowMaps.pop_back();
509}
510
Douglas Gregor791215b2009-09-21 20:51:25 +0000511/// \brief Determines whether this given declaration will be found by
512/// ordinary name lookup.
513bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
514 unsigned IDNS = Decl::IDNS_Ordinary;
515 if (SemaRef.getLangOptions().CPlusPlus)
516 IDNS |= Decl::IDNS_Tag;
517
518 return ND->getIdentifierNamespace() & IDNS;
519}
520
Douglas Gregor01dfea02010-01-10 23:08:15 +0000521/// \brief Determines whether this given declaration will be found by
522/// ordinary name lookup.
523bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
524 unsigned IDNS = Decl::IDNS_Ordinary;
525 if (SemaRef.getLangOptions().CPlusPlus)
526 IDNS |= Decl::IDNS_Tag;
527
528 return (ND->getIdentifierNamespace() & IDNS) &&
529 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND);
530}
531
Douglas Gregor86d9a522009-09-21 16:56:56 +0000532/// \brief Determines whether the given declaration is suitable as the
533/// start of a C++ nested-name-specifier, e.g., a class or namespace.
534bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
535 // Allow us to find class templates, too.
536 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
537 ND = ClassTemplate->getTemplatedDecl();
538
539 return SemaRef.isAcceptableNestedNameSpecifier(ND);
540}
541
542/// \brief Determines whether the given declaration is an enumeration.
543bool ResultBuilder::IsEnum(NamedDecl *ND) const {
544 return isa<EnumDecl>(ND);
545}
546
547/// \brief Determines whether the given declaration is a class or struct.
548bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
549 // Allow us to find class templates, too.
550 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
551 ND = ClassTemplate->getTemplatedDecl();
552
553 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
554 return RD->getTagKind() == TagDecl::TK_class ||
555 RD->getTagKind() == TagDecl::TK_struct;
556
557 return false;
558}
559
560/// \brief Determines whether the given declaration is a union.
561bool ResultBuilder::IsUnion(NamedDecl *ND) const {
562 // Allow us to find class templates, too.
563 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
564 ND = ClassTemplate->getTemplatedDecl();
565
566 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
567 return RD->getTagKind() == TagDecl::TK_union;
568
569 return false;
570}
571
572/// \brief Determines whether the given declaration is a namespace.
573bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
574 return isa<NamespaceDecl>(ND);
575}
576
577/// \brief Determines whether the given declaration is a namespace or
578/// namespace alias.
579bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
580 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
581}
582
Douglas Gregor76282942009-12-11 17:31:05 +0000583/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000584bool ResultBuilder::IsType(NamedDecl *ND) const {
585 return isa<TypeDecl>(ND);
586}
587
Douglas Gregor76282942009-12-11 17:31:05 +0000588/// \brief Determines which members of a class should be visible via
589/// "." or "->". Only value declarations, nested name specifiers, and
590/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000591bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +0000592 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
593 ND = Using->getTargetDecl();
594
Douglas Gregorce821962009-12-11 18:14:22 +0000595 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
596 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000597}
598
Douglas Gregor86d9a522009-09-21 16:56:56 +0000599// Find the next outer declaration context corresponding to this scope.
600static DeclContext *findOuterContext(Scope *S) {
601 for (S = S->getParent(); S; S = S->getParent())
602 if (S->getEntity())
603 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
604
605 return 0;
606}
607
608/// \brief Collect the results of searching for members within the given
609/// declaration context.
610///
611/// \param Ctx the declaration context from which we will gather results.
612///
Douglas Gregor0563c262009-09-22 23:15:58 +0000613/// \param Rank the rank given to results in this declaration context.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000614///
615/// \param Visited the set of declaration contexts that have already been
616/// visited. Declaration contexts will only be visited once.
617///
618/// \param Results the result set that will be extended with any results
619/// found within this declaration context (and, for a C++ class, its bases).
620///
Douglas Gregor0563c262009-09-22 23:15:58 +0000621/// \param InBaseClass whether we are in a base class.
622///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000623/// \returns the next higher rank value, after considering all of the
624/// names within this declaration context.
625static unsigned CollectMemberLookupResults(DeclContext *Ctx,
Douglas Gregor0563c262009-09-22 23:15:58 +0000626 unsigned Rank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000627 DeclContext *CurContext,
628 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
Douglas Gregor0563c262009-09-22 23:15:58 +0000629 ResultBuilder &Results,
630 bool InBaseClass = false) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000631 // Make sure we don't visit the same context twice.
632 if (!Visited.insert(Ctx->getPrimaryContext()))
Douglas Gregor0563c262009-09-22 23:15:58 +0000633 return Rank;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000634
635 // Enumerate all of the results in this context.
Douglas Gregor0563c262009-09-22 23:15:58 +0000636 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000637 Results.EnterNewScope();
638 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
639 CurCtx = CurCtx->getNextContext()) {
640 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
Douglas Gregorff4393c2009-11-09 21:35:27 +0000641 DEnd = CurCtx->decls_end();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000642 D != DEnd; ++D) {
643 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor0563c262009-09-22 23:15:58 +0000644 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
Douglas Gregorff4393c2009-11-09 21:35:27 +0000645
646 // Visit transparent contexts inside this context.
647 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
648 if (InnerCtx->isTransparentContext())
649 CollectMemberLookupResults(InnerCtx, Rank, CurContext, Visited,
650 Results, InBaseClass);
651 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000652 }
653 }
654
655 // Traverse the contexts of inherited classes.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000656 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
657 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
Douglas Gregorff4393c2009-11-09 21:35:27 +0000658 BEnd = Record->bases_end();
Douglas Gregor86d9a522009-09-21 16:56:56 +0000659 B != BEnd; ++B) {
660 QualType BaseType = B->getType();
661
662 // Don't look into dependent bases, because name lookup can't look
663 // there anyway.
664 if (BaseType->isDependentType())
665 continue;
666
667 const RecordType *Record = BaseType->getAs<RecordType>();
668 if (!Record)
669 continue;
670
671 // FIXME: It would be nice to be able to determine whether referencing
672 // a particular member would be ambiguous. For example, given
673 //
674 // struct A { int member; };
675 // struct B { int member; };
676 // struct C : A, B { };
677 //
678 // void f(C *c) { c->### }
679 // accessing 'member' would result in an ambiguity. However, code
680 // completion could be smart enough to qualify the member with the
681 // base class, e.g.,
682 //
683 // c->B::member
684 //
685 // or
686 //
687 // c->A::member
688
689 // Collect results from this base class (and its bases).
Douglas Gregor0563c262009-09-22 23:15:58 +0000690 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
691 Results, /*InBaseClass=*/true);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000692 }
693 }
694
695 // FIXME: Look into base classes in Objective-C!
696
697 Results.ExitScope();
Douglas Gregor0563c262009-09-22 23:15:58 +0000698 return Rank + 1;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000699}
700
701/// \brief Collect the results of searching for members within the given
702/// declaration context.
703///
704/// \param Ctx the declaration context from which we will gather results.
705///
706/// \param InitialRank the initial rank given to results in this declaration
707/// context. Larger rank values will be used for, e.g., members found in
708/// base classes.
709///
710/// \param Results the result set that will be extended with any results
711/// found within this declaration context (and, for a C++ class, its bases).
712///
713/// \returns the next higher rank value, after considering all of the
714/// names within this declaration context.
715static unsigned CollectMemberLookupResults(DeclContext *Ctx,
716 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000717 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000718 ResultBuilder &Results) {
719 llvm::SmallPtrSet<DeclContext *, 16> Visited;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000720 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
721 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000722}
723
724/// \brief Collect the results of searching for declarations within the given
725/// scope and its parent scopes.
726///
727/// \param S the scope in which we will start looking for declarations.
728///
729/// \param InitialRank the initial rank given to results in this scope.
730/// Larger rank values will be used for results found in parent scopes.
731///
Douglas Gregor456c4a12009-09-21 20:12:40 +0000732/// \param CurContext the context from which lookup results will be found.
733///
Douglas Gregor86d9a522009-09-21 16:56:56 +0000734/// \param Results the builder object that will receive each result.
735static unsigned CollectLookupResults(Scope *S,
736 TranslationUnitDecl *TranslationUnit,
737 unsigned InitialRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000738 DeclContext *CurContext,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000739 ResultBuilder &Results) {
740 if (!S)
741 return InitialRank;
742
743 // FIXME: Using directives!
744
745 unsigned NextRank = InitialRank;
746 Results.EnterNewScope();
747 if (S->getEntity() &&
748 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
749 // Look into this scope's declaration context, along with any of its
750 // parent lookup contexts (e.g., enclosing classes), up to the point
751 // where we hit the context stored in the next outer scope.
752 DeclContext *Ctx = (DeclContext *)S->getEntity();
753 DeclContext *OuterCtx = findOuterContext(S);
754
755 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
756 Ctx = Ctx->getLookupParent()) {
757 if (Ctx->isFunctionOrMethod())
758 continue;
759
Douglas Gregor456c4a12009-09-21 20:12:40 +0000760 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
761 Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000762 }
763 } else if (!S->getParent()) {
764 // Look into the translation unit scope. We walk through the translation
765 // unit's declaration context, because the Scope itself won't have all of
766 // the declarations if we loaded a precompiled header.
767 // FIXME: We would like the translation unit's Scope object to point to the
768 // translation unit, so we don't need this special "if" branch. However,
769 // doing so would force the normal C++ name-lookup code to look into the
770 // translation unit decl when the IdentifierInfo chains would suffice.
771 // Once we fix that problem (which is part of a more general "don't look
772 // in DeclContexts unless we have to" optimization), we can eliminate the
773 // TranslationUnit parameter entirely.
774 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000775 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000776 } else {
777 // Walk through the declarations in this Scope.
778 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
779 D != DEnd; ++D) {
780 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
Douglas Gregor456c4a12009-09-21 20:12:40 +0000781 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
782 CurContext);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000783 }
784
785 NextRank = NextRank + 1;
786 }
787
788 // Lookup names in the parent scope.
789 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
Douglas Gregor456c4a12009-09-21 20:12:40 +0000790 CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000791 Results.ExitScope();
792
793 return NextRank;
794}
795
796/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregor9a0c85e2009-12-07 09:51:25 +0000797static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000798 ResultBuilder &Results) {
799 typedef CodeCompleteConsumer::Result Result;
800 Results.MaybeAddResult(Result("short", Rank));
801 Results.MaybeAddResult(Result("long", Rank));
802 Results.MaybeAddResult(Result("signed", Rank));
803 Results.MaybeAddResult(Result("unsigned", Rank));
804 Results.MaybeAddResult(Result("void", Rank));
805 Results.MaybeAddResult(Result("char", Rank));
806 Results.MaybeAddResult(Result("int", Rank));
807 Results.MaybeAddResult(Result("float", Rank));
808 Results.MaybeAddResult(Result("double", Rank));
809 Results.MaybeAddResult(Result("enum", Rank));
810 Results.MaybeAddResult(Result("struct", Rank));
811 Results.MaybeAddResult(Result("union", Rank));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000812 Results.MaybeAddResult(Result("const", Rank));
813 Results.MaybeAddResult(Result("volatile", Rank));
814
Douglas Gregor86d9a522009-09-21 16:56:56 +0000815 if (LangOpts.C99) {
816 // C99-specific
817 Results.MaybeAddResult(Result("_Complex", Rank));
818 Results.MaybeAddResult(Result("_Imaginary", Rank));
819 Results.MaybeAddResult(Result("_Bool", Rank));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000820 Results.MaybeAddResult(Result("restrict", Rank));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000821 }
822
823 if (LangOpts.CPlusPlus) {
824 // C++-specific
825 Results.MaybeAddResult(Result("bool", Rank));
826 Results.MaybeAddResult(Result("class", Rank));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000827 Results.MaybeAddResult(Result("wchar_t", Rank));
828
Douglas Gregor01dfea02010-01-10 23:08:15 +0000829 // typename qualified-id
830 CodeCompletionString *Pattern = new CodeCompletionString;
831 Pattern->AddTypedTextChunk("typename");
832 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
833 Pattern->AddPlaceholderChunk("qualified-id");
834 Results.MaybeAddResult(Result(Pattern, Rank));
835
Douglas Gregor86d9a522009-09-21 16:56:56 +0000836 if (LangOpts.CPlusPlus0x) {
Douglas Gregor01dfea02010-01-10 23:08:15 +0000837 Results.MaybeAddResult(Result("auto", Rank));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000838 Results.MaybeAddResult(Result("char16_t", Rank));
839 Results.MaybeAddResult(Result("char32_t", Rank));
840 Results.MaybeAddResult(Result("decltype", Rank));
841 }
842 }
843
844 // GNU extensions
845 if (LangOpts.GNUMode) {
846 // FIXME: Enable when we actually support decimal floating point.
847 // Results.MaybeAddResult(Result("_Decimal32", Rank));
848 // Results.MaybeAddResult(Result("_Decimal64", Rank));
849 // Results.MaybeAddResult(Result("_Decimal128", Rank));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000850
851 CodeCompletionString *Pattern = new CodeCompletionString;
852 Pattern->AddTypedTextChunk("typeof");
853 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
854 Pattern->AddPlaceholderChunk("expression-or-type");
855 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
856 Results.MaybeAddResult(Result(Pattern, Rank));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000857 }
858}
859
Douglas Gregor01dfea02010-01-10 23:08:15 +0000860static void AddStorageSpecifiers(Action::CodeCompletionContext CCC,
861 const LangOptions &LangOpts,
862 unsigned Rank,
863 ResultBuilder &Results) {
864 typedef CodeCompleteConsumer::Result Result;
865 // Note: we don't suggest either "auto" or "register", because both
866 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
867 // in C++0x as a type specifier.
868 Results.MaybeAddResult(Result("extern", Rank));
869 Results.MaybeAddResult(Result("static", Rank));
870}
871
872static void AddFunctionSpecifiers(Action::CodeCompletionContext CCC,
873 const LangOptions &LangOpts,
874 unsigned Rank,
875 ResultBuilder &Results) {
876 typedef CodeCompleteConsumer::Result Result;
877 switch (CCC) {
878 case Action::CCC_Class:
879 case Action::CCC_MemberTemplate:
880 if (LangOpts.CPlusPlus) {
881 Results.MaybeAddResult(Result("explicit", Rank));
882 Results.MaybeAddResult(Result("friend", Rank));
883 Results.MaybeAddResult(Result("mutable", Rank));
884 Results.MaybeAddResult(Result("virtual", Rank));
885 }
886 // Fall through
887
888 case Action::CCC_Namespace:
889 case Action::CCC_Template:
890 if (LangOpts.CPlusPlus || LangOpts.C99)
891 Results.MaybeAddResult(Result("inline", Rank));
892 break;
893
894 case Action::CCC_Expression:
895 case Action::CCC_Statement:
896 case Action::CCC_ForInit:
897 case Action::CCC_Condition:
898 break;
899 }
900}
901
902/// \brief Add language constructs that show up for "ordinary" names.
903static void AddOrdinaryNameResults(Action::CodeCompletionContext CCC,
904 Scope *S,
905 Sema &SemaRef,
906 unsigned Rank,
907 ResultBuilder &Results) {
908 typedef CodeCompleteConsumer::Result Result;
909 switch (CCC) {
910 case Action::CCC_Namespace:
911 if (SemaRef.getLangOptions().CPlusPlus) {
912 // namespace <identifier> { }
913 CodeCompletionString *Pattern = new CodeCompletionString;
914 Pattern->AddTypedTextChunk("namespace");
915 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
916 Pattern->AddPlaceholderChunk("identifier");
917 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
918 Pattern->AddPlaceholderChunk("declarations");
919 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
920 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
921 Results.MaybeAddResult(Result(Pattern, Rank));
922
923 // namespace identifier = identifier ;
924 Pattern = new CodeCompletionString;
925 Pattern->AddTypedTextChunk("namespace");
926 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
927 Pattern->AddPlaceholderChunk("identifier");
928 Pattern->AddChunk(CodeCompletionString::CK_Equal);
929 Pattern->AddPlaceholderChunk("identifier");
930 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
931 Results.MaybeAddResult(Result(Pattern, Rank));
932
933 // Using directives
934 Pattern = new CodeCompletionString;
935 Pattern->AddTypedTextChunk("using");
936 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
937 Pattern->AddTextChunk("namespace");
938 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
939 Pattern->AddPlaceholderChunk("identifier");
940 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
941 Results.MaybeAddResult(Result(Pattern, Rank));
942
943 // asm(string-literal)
944 Pattern = new CodeCompletionString;
945 Pattern->AddTypedTextChunk("asm");
946 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
947 Pattern->AddPlaceholderChunk("string-literal");
948 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
949 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
950 Results.MaybeAddResult(Result(Pattern, Rank));
951
952 // Explicit template instantiation
953 Pattern = new CodeCompletionString;
954 Pattern->AddTypedTextChunk("template");
955 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
956 Pattern->AddPlaceholderChunk("declaration");
957 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
958 Results.MaybeAddResult(Result(Pattern, Rank));
959 }
960 // Fall through
961
962 case Action::CCC_Class:
963 Results.MaybeAddResult(Result("typedef", Rank));
964 if (SemaRef.getLangOptions().CPlusPlus) {
965 // Using declaration
966 CodeCompletionString *Pattern = new CodeCompletionString;
967 Pattern->AddTypedTextChunk("using");
968 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
969 Pattern->AddPlaceholderChunk("qualified-id");
970 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
971 Results.MaybeAddResult(Result(Pattern, Rank));
972
973 // using typename qualified-id; (only in a dependent context)
974 if (SemaRef.CurContext->isDependentContext()) {
975 Pattern = new CodeCompletionString;
976 Pattern->AddTypedTextChunk("using");
977 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
978 Pattern->AddTextChunk("typename");
979 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
980 Pattern->AddPlaceholderChunk("qualified-id");
981 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
982 Results.MaybeAddResult(Result(Pattern, Rank));
983 }
984
985 if (CCC == Action::CCC_Class) {
986 // public:
987 Pattern = new CodeCompletionString;
988 Pattern->AddTypedTextChunk("public");
989 Pattern->AddChunk(CodeCompletionString::CK_Colon);
990 Results.MaybeAddResult(Result(Pattern, Rank));
991
992 // protected:
993 Pattern = new CodeCompletionString;
994 Pattern->AddTypedTextChunk("protected");
995 Pattern->AddChunk(CodeCompletionString::CK_Colon);
996 Results.MaybeAddResult(Result(Pattern, Rank));
997
998 // private:
999 Pattern = new CodeCompletionString;
1000 Pattern->AddTypedTextChunk("private");
1001 Pattern->AddChunk(CodeCompletionString::CK_Colon);
1002 Results.MaybeAddResult(Result(Pattern, Rank));
1003 }
1004 }
1005 // Fall through
1006
1007 case Action::CCC_Template:
1008 case Action::CCC_MemberTemplate:
1009 if (SemaRef.getLangOptions().CPlusPlus) {
1010 // template < parameters >
1011 CodeCompletionString *Pattern = new CodeCompletionString;
1012 Pattern->AddTypedTextChunk("template");
1013 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1014 Pattern->AddPlaceholderChunk("parameters");
1015 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1016 Results.MaybeAddResult(Result(Pattern, Rank));
1017 }
1018
1019 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Rank, Results);
1020 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Rank, Results);
1021 break;
1022
1023 case Action::CCC_Statement: {
1024 Results.MaybeAddResult(Result("typedef", Rank));
1025
1026 CodeCompletionString *Pattern = 0;
1027 if (SemaRef.getLangOptions().CPlusPlus) {
1028 Pattern = new CodeCompletionString;
1029 Pattern->AddTypedTextChunk("try");
1030 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1031 Pattern->AddPlaceholderChunk("statements");
1032 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1033 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1034 Pattern->AddTextChunk("catch");
1035 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1036 Pattern->AddPlaceholderChunk("declaration");
1037 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1038 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1039 Pattern->AddPlaceholderChunk("statements");
1040 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1041 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1042 Results.MaybeAddResult(Result(Pattern, Rank));
1043 }
1044
1045 // if (condition) { statements }
1046 Pattern = new CodeCompletionString;
1047 Pattern->AddTypedTextChunk("if");
1048 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1049 if (SemaRef.getLangOptions().CPlusPlus)
1050 Pattern->AddPlaceholderChunk("condition");
1051 else
1052 Pattern->AddPlaceholderChunk("expression");
1053 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1054 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1055 Pattern->AddPlaceholderChunk("statements");
1056 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1057 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1058 Results.MaybeAddResult(Result(Pattern, Rank));
1059
1060 // switch (condition) { }
1061 Pattern = new CodeCompletionString;
1062 Pattern->AddTypedTextChunk("switch");
1063 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1064 if (SemaRef.getLangOptions().CPlusPlus)
1065 Pattern->AddPlaceholderChunk("condition");
1066 else
1067 Pattern->AddPlaceholderChunk("expression");
1068 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1069 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1070 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1071 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1072 Results.MaybeAddResult(Result(Pattern, Rank));
1073
1074 // Switch-specific statements.
1075 if (!SemaRef.getSwitchStack().empty()) {
1076 // case expression:
1077 Pattern = new CodeCompletionString;
1078 Pattern->AddTypedTextChunk("case");
1079 Pattern->AddPlaceholderChunk("expression");
1080 Pattern->AddChunk(CodeCompletionString::CK_Colon);
1081 Results.MaybeAddResult(Result(Pattern, Rank));
1082
1083 // default:
1084 Pattern = new CodeCompletionString;
1085 Pattern->AddTypedTextChunk("default");
1086 Pattern->AddChunk(CodeCompletionString::CK_Colon);
1087 Results.MaybeAddResult(Result(Pattern, Rank));
1088 }
1089
1090 /// while (condition) { statements }
1091 Pattern = new CodeCompletionString;
1092 Pattern->AddTypedTextChunk("while");
1093 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1094 if (SemaRef.getLangOptions().CPlusPlus)
1095 Pattern->AddPlaceholderChunk("condition");
1096 else
1097 Pattern->AddPlaceholderChunk("expression");
1098 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1099 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1100 Pattern->AddPlaceholderChunk("statements");
1101 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1102 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1103 Results.MaybeAddResult(Result(Pattern, Rank));
1104
1105 // do { statements } while ( expression );
1106 Pattern = new CodeCompletionString;
1107 Pattern->AddTypedTextChunk("do");
1108 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1109 Pattern->AddPlaceholderChunk("statements");
1110 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1111 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1112 Pattern->AddTextChunk("while");
1113 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1114 Pattern->AddPlaceholderChunk("expression");
1115 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1116 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1117 Results.MaybeAddResult(Result(Pattern, Rank));
1118
1119 // for ( for-init-statement ; condition ; expression ) { statements }
1120 Pattern = new CodeCompletionString;
1121 Pattern->AddTypedTextChunk("for");
1122 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1123 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1124 Pattern->AddPlaceholderChunk("init-statement");
1125 else
1126 Pattern->AddPlaceholderChunk("init-expression");
1127 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1128 Pattern->AddPlaceholderChunk("condition");
1129 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1130 Pattern->AddPlaceholderChunk("inc-expression");
1131 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1132 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1133 Pattern->AddPlaceholderChunk("statements");
1134 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1135 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1136 Results.MaybeAddResult(Result(Pattern, Rank));
1137
1138 if (S->getContinueParent()) {
1139 // continue ;
1140 Pattern = new CodeCompletionString;
1141 Pattern->AddTypedTextChunk("continue");
1142 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1143 Results.MaybeAddResult(Result(Pattern, Rank));
1144 }
1145
1146 if (S->getBreakParent()) {
1147 // break ;
1148 Pattern = new CodeCompletionString;
1149 Pattern->AddTypedTextChunk("break");
1150 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1151 Results.MaybeAddResult(Result(Pattern, Rank));
1152 }
1153
1154 // "return expression ;" or "return ;", depending on whether we
1155 // know the function is void or not.
1156 bool isVoid = false;
1157 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1158 isVoid = Function->getResultType()->isVoidType();
1159 else if (ObjCMethodDecl *Method
1160 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1161 isVoid = Method->getResultType()->isVoidType();
1162 else if (SemaRef.CurBlock && !SemaRef.CurBlock->ReturnType.isNull())
1163 isVoid = SemaRef.CurBlock->ReturnType->isVoidType();
1164 Pattern = new CodeCompletionString;
1165 Pattern->AddTypedTextChunk("return");
1166 if (!isVoid)
1167 Pattern->AddPlaceholderChunk("expression");
1168 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1169 Results.MaybeAddResult(Result(Pattern, Rank));
1170
1171 // goto identifier ;
1172 Pattern = new CodeCompletionString;
1173 Pattern->AddTypedTextChunk("goto");
1174 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1175 Pattern->AddPlaceholderChunk("identifier");
1176 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1177 Results.MaybeAddResult(Result(Pattern, Rank));
1178
1179 // Using directives
1180 Pattern = new CodeCompletionString;
1181 Pattern->AddTypedTextChunk("using");
1182 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1183 Pattern->AddTextChunk("namespace");
1184 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1185 Pattern->AddPlaceholderChunk("identifier");
1186 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1187 Results.MaybeAddResult(Result(Pattern, Rank));
1188 }
1189
1190 // Fall through (for statement expressions).
1191 case Action::CCC_ForInit:
1192 case Action::CCC_Condition:
1193 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Rank, Results);
1194 // Fall through: conditions and statements can have expressions.
1195
1196 case Action::CCC_Expression: {
1197 CodeCompletionString *Pattern = 0;
1198 if (SemaRef.getLangOptions().CPlusPlus) {
1199 // 'this', if we're in a non-static member function.
1200 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1201 if (!Method->isStatic())
1202 Results.MaybeAddResult(Result("this", Rank));
1203
1204 // true, false
1205 Results.MaybeAddResult(Result("true", Rank));
1206 Results.MaybeAddResult(Result("false", Rank));
1207
1208 // dynamic_cast < type-id > ( expression )
1209 Pattern = new CodeCompletionString;
1210 Pattern->AddTypedTextChunk("dynamic_cast");
1211 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1212 Pattern->AddPlaceholderChunk("type-id");
1213 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1214 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1215 Pattern->AddPlaceholderChunk("expression");
1216 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1217 Results.MaybeAddResult(Result(Pattern, Rank));
1218
1219 // static_cast < type-id > ( expression )
1220 Pattern = new CodeCompletionString;
1221 Pattern->AddTypedTextChunk("static_cast");
1222 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1223 Pattern->AddPlaceholderChunk("type-id");
1224 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1225 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1226 Pattern->AddPlaceholderChunk("expression");
1227 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1228 Results.MaybeAddResult(Result(Pattern, Rank));
1229
1230 // reinterpret_cast < type-id > ( expression )
1231 Pattern = new CodeCompletionString;
1232 Pattern->AddTypedTextChunk("reinterpret_cast");
1233 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1234 Pattern->AddPlaceholderChunk("type-id");
1235 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1236 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1237 Pattern->AddPlaceholderChunk("expression");
1238 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1239 Results.MaybeAddResult(Result(Pattern, Rank));
1240
1241 // const_cast < type-id > ( expression )
1242 Pattern = new CodeCompletionString;
1243 Pattern->AddTypedTextChunk("const_cast");
1244 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1245 Pattern->AddPlaceholderChunk("type-id");
1246 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1247 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1248 Pattern->AddPlaceholderChunk("expression");
1249 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1250 Results.MaybeAddResult(Result(Pattern, Rank));
1251
1252 // typeid ( expression-or-type )
1253 Pattern = new CodeCompletionString;
1254 Pattern->AddTypedTextChunk("typeid");
1255 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1256 Pattern->AddPlaceholderChunk("expression-or-type");
1257 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1258 Results.MaybeAddResult(Result(Pattern, Rank));
1259
1260 // new T ( ... )
1261 Pattern = new CodeCompletionString;
1262 Pattern->AddTypedTextChunk("new");
1263 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1264 Pattern->AddPlaceholderChunk("type-id");
1265 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1266 Pattern->AddPlaceholderChunk("expressions");
1267 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1268 Results.MaybeAddResult(Result(Pattern, Rank));
1269
1270 // new T [ ] ( ... )
1271 Pattern = new CodeCompletionString;
1272 Pattern->AddTypedTextChunk("new");
1273 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1274 Pattern->AddPlaceholderChunk("type-id");
1275 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1276 Pattern->AddPlaceholderChunk("size");
1277 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1278 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1279 Pattern->AddPlaceholderChunk("expressions");
1280 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1281 Results.MaybeAddResult(Result(Pattern, Rank));
1282
1283 // delete expression
1284 Pattern = new CodeCompletionString;
1285 Pattern->AddTypedTextChunk("delete");
1286 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1287 Pattern->AddPlaceholderChunk("expression");
1288 Results.MaybeAddResult(Result(Pattern, Rank));
1289
1290 // delete [] expression
1291 Pattern = new CodeCompletionString;
1292 Pattern->AddTypedTextChunk("delete");
1293 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1294 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1295 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1296 Pattern->AddPlaceholderChunk("expression");
1297 Results.MaybeAddResult(Result(Pattern, Rank));
1298
1299 // throw expression
1300 Pattern = new CodeCompletionString;
1301 Pattern->AddTypedTextChunk("throw");
1302 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1303 Pattern->AddPlaceholderChunk("expression");
1304 Results.MaybeAddResult(Result(Pattern, Rank));
1305 }
1306
1307 if (SemaRef.getLangOptions().ObjC1) {
1308 // Add "super", if we're in an Objective-C class with a superclass.
1309 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
1310 if (Method->getClassInterface()->getSuperClass())
1311 Results.MaybeAddResult(Result("super", Rank));
1312 }
1313
1314 // sizeof expression
1315 Pattern = new CodeCompletionString;
1316 Pattern->AddTypedTextChunk("sizeof");
1317 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1318 Pattern->AddPlaceholderChunk("expression-or-type");
1319 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1320 Results.MaybeAddResult(Result(Pattern, Rank));
1321 break;
1322 }
1323 }
1324
1325 AddTypeSpecifierResults(SemaRef.getLangOptions(), Rank, Results);
1326
1327 if (SemaRef.getLangOptions().CPlusPlus)
1328 Results.MaybeAddResult(Result("operator", Rank));
1329}
1330
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001331/// \brief If the given declaration has an associated type, add it as a result
1332/// type chunk.
1333static void AddResultTypeChunk(ASTContext &Context,
1334 NamedDecl *ND,
1335 CodeCompletionString *Result) {
1336 if (!ND)
1337 return;
1338
1339 // Determine the type of the declaration (if it has a type).
1340 QualType T;
1341 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1342 T = Function->getResultType();
1343 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1344 T = Method->getResultType();
1345 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1346 T = FunTmpl->getTemplatedDecl()->getResultType();
1347 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1348 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1349 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1350 /* Do nothing: ignore unresolved using declarations*/
1351 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1352 T = Value->getType();
1353 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1354 T = Property->getType();
1355
1356 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1357 return;
1358
1359 std::string TypeStr;
1360 T.getAsStringInternal(TypeStr, Context.PrintingPolicy);
1361 Result->AddResultTypeChunk(TypeStr);
1362}
1363
Douglas Gregor86d9a522009-09-21 16:56:56 +00001364/// \brief Add function parameter chunks to the given code completion string.
1365static void AddFunctionParameterChunks(ASTContext &Context,
1366 FunctionDecl *Function,
1367 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001368 typedef CodeCompletionString::Chunk Chunk;
1369
Douglas Gregor86d9a522009-09-21 16:56:56 +00001370 CodeCompletionString *CCStr = Result;
1371
1372 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1373 ParmVarDecl *Param = Function->getParamDecl(P);
1374
1375 if (Param->hasDefaultArg()) {
1376 // When we see an optional default argument, put that argument and
1377 // the remaining default arguments into a new, optional string.
1378 CodeCompletionString *Opt = new CodeCompletionString;
1379 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1380 CCStr = Opt;
1381 }
1382
1383 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001384 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001385
1386 // Format the placeholder string.
1387 std::string PlaceholderStr;
1388 if (Param->getIdentifier())
1389 PlaceholderStr = Param->getIdentifier()->getName();
1390
1391 Param->getType().getAsStringInternal(PlaceholderStr,
1392 Context.PrintingPolicy);
1393
1394 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001395 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001396 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00001397
1398 if (const FunctionProtoType *Proto
1399 = Function->getType()->getAs<FunctionProtoType>())
1400 if (Proto->isVariadic())
1401 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-09-21 16:56:56 +00001402}
1403
1404/// \brief Add template parameter chunks to the given code completion string.
1405static void AddTemplateParameterChunks(ASTContext &Context,
1406 TemplateDecl *Template,
1407 CodeCompletionString *Result,
1408 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001409 typedef CodeCompletionString::Chunk Chunk;
1410
Douglas Gregor86d9a522009-09-21 16:56:56 +00001411 CodeCompletionString *CCStr = Result;
1412 bool FirstParameter = true;
1413
1414 TemplateParameterList *Params = Template->getTemplateParameters();
1415 TemplateParameterList::iterator PEnd = Params->end();
1416 if (MaxParameters)
1417 PEnd = Params->begin() + MaxParameters;
1418 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1419 bool HasDefaultArg = false;
1420 std::string PlaceholderStr;
1421 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1422 if (TTP->wasDeclaredWithTypename())
1423 PlaceholderStr = "typename";
1424 else
1425 PlaceholderStr = "class";
1426
1427 if (TTP->getIdentifier()) {
1428 PlaceholderStr += ' ';
1429 PlaceholderStr += TTP->getIdentifier()->getName();
1430 }
1431
1432 HasDefaultArg = TTP->hasDefaultArgument();
1433 } else if (NonTypeTemplateParmDecl *NTTP
1434 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1435 if (NTTP->getIdentifier())
1436 PlaceholderStr = NTTP->getIdentifier()->getName();
1437 NTTP->getType().getAsStringInternal(PlaceholderStr,
1438 Context.PrintingPolicy);
1439 HasDefaultArg = NTTP->hasDefaultArgument();
1440 } else {
1441 assert(isa<TemplateTemplateParmDecl>(*P));
1442 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1443
1444 // Since putting the template argument list into the placeholder would
1445 // be very, very long, we just use an abbreviation.
1446 PlaceholderStr = "template<...> class";
1447 if (TTP->getIdentifier()) {
1448 PlaceholderStr += ' ';
1449 PlaceholderStr += TTP->getIdentifier()->getName();
1450 }
1451
1452 HasDefaultArg = TTP->hasDefaultArgument();
1453 }
1454
1455 if (HasDefaultArg) {
1456 // When we see an optional default argument, put that argument and
1457 // the remaining default arguments into a new, optional string.
1458 CodeCompletionString *Opt = new CodeCompletionString;
1459 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1460 CCStr = Opt;
1461 }
1462
1463 if (FirstParameter)
1464 FirstParameter = false;
1465 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001466 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001467
1468 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001469 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001470 }
1471}
1472
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001473/// \brief Add a qualifier to the given code-completion string, if the
1474/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00001475static void
1476AddQualifierToCompletionString(CodeCompletionString *Result,
1477 NestedNameSpecifier *Qualifier,
1478 bool QualifierIsInformative,
1479 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001480 if (!Qualifier)
1481 return;
1482
1483 std::string PrintedNNS;
1484 {
1485 llvm::raw_string_ostream OS(PrintedNNS);
1486 Qualifier->print(OS, Context.PrintingPolicy);
1487 }
Douglas Gregor0563c262009-09-22 23:15:58 +00001488 if (QualifierIsInformative)
Benjamin Kramer660cc182009-11-29 20:18:50 +00001489 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor0563c262009-09-22 23:15:58 +00001490 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00001491 Result->AddTextChunk(PrintedNNS);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001492}
1493
Douglas Gregora61a8792009-12-11 18:44:16 +00001494static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1495 FunctionDecl *Function) {
1496 const FunctionProtoType *Proto
1497 = Function->getType()->getAs<FunctionProtoType>();
1498 if (!Proto || !Proto->getTypeQuals())
1499 return;
1500
1501 std::string QualsStr;
1502 if (Proto->getTypeQuals() & Qualifiers::Const)
1503 QualsStr += " const";
1504 if (Proto->getTypeQuals() & Qualifiers::Volatile)
1505 QualsStr += " volatile";
1506 if (Proto->getTypeQuals() & Qualifiers::Restrict)
1507 QualsStr += " restrict";
1508 Result->AddInformativeChunk(QualsStr);
1509}
1510
Douglas Gregor86d9a522009-09-21 16:56:56 +00001511/// \brief If possible, create a new code completion string for the given
1512/// result.
1513///
1514/// \returns Either a new, heap-allocated code completion string describing
1515/// how to use this result, or NULL to indicate that the string or name of the
1516/// result is all that is needed.
1517CodeCompletionString *
1518CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001519 typedef CodeCompletionString::Chunk Chunk;
1520
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001521 if (Kind == RK_Pattern)
1522 return Pattern->Clone();
1523
1524 CodeCompletionString *Result = new CodeCompletionString;
1525
1526 if (Kind == RK_Keyword) {
1527 Result->AddTypedTextChunk(Keyword);
1528 return Result;
1529 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001530
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001531 if (Kind == RK_Macro) {
1532 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001533 assert(MI && "Not a macro?");
1534
1535 Result->AddTypedTextChunk(Macro->getName());
1536
1537 if (!MI->isFunctionLike())
1538 return Result;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001539
1540 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001541 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001542 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
1543 A != AEnd; ++A) {
1544 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001545 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001546
1547 if (!MI->isVariadic() || A != AEnd - 1) {
1548 // Non-variadic argument.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001549 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001550 continue;
1551 }
1552
1553 // Variadic argument; cope with the different between GNU and C99
1554 // variadic macros, providing a single placeholder for the rest of the
1555 // arguments.
1556 if ((*A)->isStr("__VA_ARGS__"))
1557 Result->AddPlaceholderChunk("...");
1558 else {
1559 std::string Arg = (*A)->getName();
1560 Arg += "...";
Benjamin Kramer660cc182009-11-29 20:18:50 +00001561 Result->AddPlaceholderChunk(Arg);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001562 }
1563 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001564 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001565 return Result;
1566 }
1567
1568 assert(Kind == RK_Declaration && "Missed a macro kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00001569 NamedDecl *ND = Declaration;
1570
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001571 if (StartsNestedNameSpecifier) {
Benjamin Kramer660cc182009-11-29 20:18:50 +00001572 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001573 Result->AddTextChunk("::");
1574 return Result;
1575 }
1576
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001577 AddResultTypeChunk(S.Context, ND, Result);
1578
Douglas Gregor86d9a522009-09-21 16:56:56 +00001579 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001580 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1581 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00001582 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001583 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001584 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001585 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00001586 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001587 return Result;
1588 }
1589
1590 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001591 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1592 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001593 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramer660cc182009-11-29 20:18:50 +00001594 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001595
1596 // Figure out which template parameters are deduced (or have default
1597 // arguments).
1598 llvm::SmallVector<bool, 16> Deduced;
1599 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
1600 unsigned LastDeducibleArgument;
1601 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
1602 --LastDeducibleArgument) {
1603 if (!Deduced[LastDeducibleArgument - 1]) {
1604 // C++0x: Figure out if the template argument has a default. If so,
1605 // the user doesn't need to type this argument.
1606 // FIXME: We need to abstract template parameters better!
1607 bool HasDefaultArg = false;
1608 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
1609 LastDeducibleArgument - 1);
1610 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1611 HasDefaultArg = TTP->hasDefaultArgument();
1612 else if (NonTypeTemplateParmDecl *NTTP
1613 = dyn_cast<NonTypeTemplateParmDecl>(Param))
1614 HasDefaultArg = NTTP->hasDefaultArgument();
1615 else {
1616 assert(isa<TemplateTemplateParmDecl>(Param));
1617 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001618 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001619 }
1620
1621 if (!HasDefaultArg)
1622 break;
1623 }
1624 }
1625
1626 if (LastDeducibleArgument) {
1627 // Some of the function template arguments cannot be deduced from a
1628 // function call, so we introduce an explicit template argument list
1629 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001630 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001631 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
1632 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001633 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001634 }
1635
1636 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001637 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001638 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001639 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00001640 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001641 return Result;
1642 }
1643
1644 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001645 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1646 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00001647 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001648 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001649 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001650 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001651 return Result;
1652 }
1653
Douglas Gregor9630eb62009-11-17 16:44:22 +00001654 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00001655 Selector Sel = Method->getSelector();
1656 if (Sel.isUnarySelector()) {
1657 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
1658 return Result;
1659 }
1660
Douglas Gregord3c68542009-11-19 01:08:35 +00001661 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
1662 SelName += ':';
1663 if (StartParameter == 0)
1664 Result->AddTypedTextChunk(SelName);
1665 else {
1666 Result->AddInformativeChunk(SelName);
1667
1668 // If there is only one parameter, and we're past it, add an empty
1669 // typed-text chunk since there is nothing to type.
1670 if (Method->param_size() == 1)
1671 Result->AddTypedTextChunk("");
1672 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00001673 unsigned Idx = 0;
1674 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
1675 PEnd = Method->param_end();
1676 P != PEnd; (void)++P, ++Idx) {
1677 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00001678 std::string Keyword;
1679 if (Idx > StartParameter)
Douglas Gregor834389b2010-01-12 06:38:28 +00001680 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001681 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
1682 Keyword += II->getName().str();
1683 Keyword += ":";
Douglas Gregor4ad96852009-11-19 07:41:15 +00001684 if (Idx < StartParameter || AllParametersAreInformative) {
Douglas Gregord3c68542009-11-19 01:08:35 +00001685 Result->AddInformativeChunk(Keyword);
1686 } else if (Idx == StartParameter)
1687 Result->AddTypedTextChunk(Keyword);
1688 else
1689 Result->AddTextChunk(Keyword);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001690 }
Douglas Gregord3c68542009-11-19 01:08:35 +00001691
1692 // If we're before the starting parameter, skip the placeholder.
1693 if (Idx < StartParameter)
1694 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00001695
1696 std::string Arg;
1697 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
1698 Arg = "(" + Arg + ")";
1699 if (IdentifierInfo *II = (*P)->getIdentifier())
1700 Arg += II->getName().str();
Douglas Gregor4ad96852009-11-19 07:41:15 +00001701 if (AllParametersAreInformative)
1702 Result->AddInformativeChunk(Arg);
1703 else
1704 Result->AddPlaceholderChunk(Arg);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001705 }
1706
Douglas Gregor2a17af02009-12-23 00:21:46 +00001707 if (Method->isVariadic()) {
1708 if (AllParametersAreInformative)
1709 Result->AddInformativeChunk(", ...");
1710 else
1711 Result->AddPlaceholderChunk(", ...");
1712 }
1713
Douglas Gregor9630eb62009-11-17 16:44:22 +00001714 return Result;
1715 }
1716
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001717 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00001718 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1719 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001720
1721 Result->AddTypedTextChunk(ND->getNameAsString());
1722 return Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001723}
1724
Douglas Gregor86d802e2009-09-23 00:34:09 +00001725CodeCompletionString *
1726CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
1727 unsigned CurrentArg,
1728 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001729 typedef CodeCompletionString::Chunk Chunk;
1730
Douglas Gregor86d802e2009-09-23 00:34:09 +00001731 CodeCompletionString *Result = new CodeCompletionString;
1732 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001733 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00001734 const FunctionProtoType *Proto
1735 = dyn_cast<FunctionProtoType>(getFunctionType());
1736 if (!FDecl && !Proto) {
1737 // Function without a prototype. Just give the return type and a
1738 // highlighted ellipsis.
1739 const FunctionType *FT = getFunctionType();
1740 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00001741 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001742 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1743 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1744 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001745 return Result;
1746 }
1747
1748 if (FDecl)
Benjamin Kramer660cc182009-11-29 20:18:50 +00001749 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregor86d802e2009-09-23 00:34:09 +00001750 else
1751 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00001752 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001753
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001754 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001755 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
1756 for (unsigned I = 0; I != NumParams; ++I) {
1757 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001758 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001759
1760 std::string ArgString;
1761 QualType ArgType;
1762
1763 if (FDecl) {
1764 ArgString = FDecl->getParamDecl(I)->getNameAsString();
1765 ArgType = FDecl->getParamDecl(I)->getOriginalType();
1766 } else {
1767 ArgType = Proto->getArgType(I);
1768 }
1769
1770 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
1771
1772 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001773 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramer660cc182009-11-29 20:18:50 +00001774 ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001775 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00001776 Result->AddTextChunk(ArgString);
Douglas Gregor86d802e2009-09-23 00:34:09 +00001777 }
1778
1779 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001780 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001781 if (CurrentArg < NumParams)
1782 Result->AddTextChunk("...");
1783 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001784 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001785 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001786 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001787
1788 return Result;
1789}
1790
Douglas Gregor86d9a522009-09-21 16:56:56 +00001791namespace {
1792 struct SortCodeCompleteResult {
1793 typedef CodeCompleteConsumer::Result Result;
1794
Douglas Gregor6a684032009-09-28 03:51:44 +00001795 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregor2b0cc122009-12-05 09:08:56 +00001796 Selector XSel = X.getObjCSelector();
1797 Selector YSel = Y.getObjCSelector();
1798 if (!XSel.isNull() && !YSel.isNull()) {
1799 // We are comparing two selectors.
1800 unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
1801 if (N == 0)
1802 ++N;
1803 for (unsigned I = 0; I != N; ++I) {
1804 IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
1805 IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
1806 if (!XId || !YId)
1807 return XId && !YId;
1808
1809 switch (XId->getName().compare_lower(YId->getName())) {
1810 case -1: return true;
1811 case 1: return false;
1812 default: break;
1813 }
1814 }
1815
1816 return XSel.getNumArgs() < YSel.getNumArgs();
1817 }
1818
1819 // For non-selectors, order by kind.
1820 if (X.getNameKind() != Y.getNameKind())
Douglas Gregor6a684032009-09-28 03:51:44 +00001821 return X.getNameKind() < Y.getNameKind();
1822
Douglas Gregor2b0cc122009-12-05 09:08:56 +00001823 // Order identifiers by comparison of their lowercased names.
1824 if (IdentifierInfo *XId = X.getAsIdentifierInfo())
1825 return XId->getName().compare_lower(
1826 Y.getAsIdentifierInfo()->getName()) < 0;
1827
1828 // Order overloaded operators by the order in which they appear
1829 // in our list of operators.
1830 if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
1831 return XOp < Y.getCXXOverloadedOperator();
1832
1833 // Order C++0x user-defined literal operators lexically by their
1834 // lowercased suffixes.
1835 if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
1836 return XLit->getName().compare_lower(
1837 Y.getCXXLiteralIdentifier()->getName()) < 0;
1838
1839 // The only stable ordering we have is to turn the name into a
1840 // string and then compare the lower-case strings. This is
1841 // inefficient, but thankfully does not happen too often.
Benjamin Kramer0e7049f2009-12-05 10:22:15 +00001842 return llvm::StringRef(X.getAsString()).compare_lower(
1843 Y.getAsString()) < 0;
Douglas Gregor6a684032009-09-28 03:51:44 +00001844 }
1845
Douglas Gregor86d9a522009-09-21 16:56:56 +00001846 bool operator()(const Result &X, const Result &Y) const {
1847 // Sort first by rank.
1848 if (X.Rank < Y.Rank)
1849 return true;
1850 else if (X.Rank > Y.Rank)
1851 return false;
1852
Douglas Gregor54f01612009-11-19 00:01:57 +00001853 // We use a special ordering for keywords and patterns, based on the
1854 // typed text.
1855 if ((X.Kind == Result::RK_Keyword || X.Kind == Result::RK_Pattern) &&
1856 (Y.Kind == Result::RK_Keyword || Y.Kind == Result::RK_Pattern)) {
1857 const char *XStr = (X.Kind == Result::RK_Keyword)? X.Keyword
1858 : X.Pattern->getTypedText();
1859 const char *YStr = (Y.Kind == Result::RK_Keyword)? Y.Keyword
1860 : Y.Pattern->getTypedText();
Benjamin Kramerf42d4882009-12-05 10:07:04 +00001861 return llvm::StringRef(XStr).compare_lower(YStr) < 0;
Douglas Gregor54f01612009-11-19 00:01:57 +00001862 }
1863
Douglas Gregor86d9a522009-09-21 16:56:56 +00001864 // Result kinds are ordered by decreasing importance.
1865 if (X.Kind < Y.Kind)
1866 return true;
1867 else if (X.Kind > Y.Kind)
1868 return false;
1869
1870 // Non-hidden names precede hidden names.
1871 if (X.Hidden != Y.Hidden)
1872 return !X.Hidden;
1873
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001874 // Non-nested-name-specifiers precede nested-name-specifiers.
1875 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1876 return !X.StartsNestedNameSpecifier;
1877
Douglas Gregor86d9a522009-09-21 16:56:56 +00001878 // Ordering depends on the kind of result.
1879 switch (X.Kind) {
1880 case Result::RK_Declaration:
1881 // Order based on the declaration names.
Douglas Gregor6a684032009-09-28 03:51:44 +00001882 return isEarlierDeclarationName(X.Declaration->getDeclName(),
1883 Y.Declaration->getDeclName());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001884
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001885 case Result::RK_Macro:
Douglas Gregor2b0cc122009-12-05 09:08:56 +00001886 return X.Macro->getName().compare_lower(Y.Macro->getName()) < 0;
Douglas Gregor54f01612009-11-19 00:01:57 +00001887
1888 case Result::RK_Keyword:
1889 case Result::RK_Pattern:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001890 llvm_unreachable("Result kinds handled above");
Douglas Gregor54f01612009-11-19 00:01:57 +00001891 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001892 }
1893
1894 // Silence GCC warning.
1895 return false;
1896 }
1897 };
1898}
1899
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001900static void AddMacroResults(Preprocessor &PP, unsigned Rank,
1901 ResultBuilder &Results) {
1902 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001903 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1904 MEnd = PP.macro_end();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001905 M != MEnd; ++M)
1906 Results.MaybeAddResult(CodeCompleteConsumer::Result(M->first, Rank));
1907 Results.ExitScope();
1908}
1909
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001910static void HandleCodeCompleteResults(Sema *S,
1911 CodeCompleteConsumer *CodeCompleter,
1912 CodeCompleteConsumer::Result *Results,
1913 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00001914 // Sort the results by rank/kind/etc.
1915 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1916
1917 if (CodeCompleter)
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001918 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00001919
1920 for (unsigned I = 0; I != NumResults; ++I)
1921 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001922}
1923
Douglas Gregor01dfea02010-01-10 23:08:15 +00001924void Sema::CodeCompleteOrdinaryName(Scope *S,
1925 CodeCompletionContext CompletionContext) {
Douglas Gregor2a7925c2009-12-07 09:54:55 +00001926 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001927 ResultBuilder Results(*this);
1928
1929 // Determine how to filter results, e.g., so that the names of
1930 // values (functions, enumerators, function templates, etc.) are
1931 // only allowed where we can have an expression.
1932 switch (CompletionContext) {
1933 case CCC_Namespace:
1934 case CCC_Class:
1935 case CCC_Template:
1936 case CCC_MemberTemplate:
1937 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
1938 break;
1939
1940 case CCC_Expression:
1941 case CCC_Statement:
1942 case CCC_ForInit:
1943 case CCC_Condition:
1944 Results.setFilter(&ResultBuilder::IsOrdinaryName);
1945 break;
1946 }
1947
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001948 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1949 0, CurContext, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00001950
1951 Results.EnterNewScope();
Douglas Gregor01dfea02010-01-10 23:08:15 +00001952 AddOrdinaryNameResults(CompletionContext, S, *this, NextRank, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00001953 Results.ExitScope();
1954
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001955 if (CodeCompleter->includeMacros())
1956 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001957 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00001958}
1959
Douglas Gregor95ac6552009-11-18 01:29:26 +00001960static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00001961 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00001962 DeclContext *CurContext,
1963 ResultBuilder &Results) {
1964 typedef CodeCompleteConsumer::Result Result;
1965
1966 // Add properties in this container.
1967 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
1968 PEnd = Container->prop_end();
1969 P != PEnd;
1970 ++P)
1971 Results.MaybeAddResult(Result(*P, 0), CurContext);
1972
1973 // Add properties in referenced protocols.
1974 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
1975 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
1976 PEnd = Protocol->protocol_end();
1977 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00001978 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001979 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00001980 if (AllowCategories) {
1981 // Look through categories.
1982 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
1983 Category; Category = Category->getNextClassCategory())
1984 AddObjCProperties(Category, AllowCategories, CurContext, Results);
1985 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00001986
1987 // Look through protocols.
1988 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
1989 E = IFace->protocol_end();
1990 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00001991 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001992
1993 // Look in the superclass.
1994 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00001995 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
1996 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001997 } else if (const ObjCCategoryDecl *Category
1998 = dyn_cast<ObjCCategoryDecl>(Container)) {
1999 // Look through protocols.
2000 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
2001 PEnd = Category->protocol_end();
2002 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002003 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002004 }
2005}
2006
Douglas Gregor81b747b2009-09-17 21:32:03 +00002007void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2008 SourceLocation OpLoc,
2009 bool IsArrow) {
2010 if (!BaseE || !CodeCompleter)
2011 return;
2012
Douglas Gregor86d9a522009-09-21 16:56:56 +00002013 typedef CodeCompleteConsumer::Result Result;
2014
Douglas Gregor81b747b2009-09-17 21:32:03 +00002015 Expr *Base = static_cast<Expr *>(BaseE);
2016 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002017
2018 if (IsArrow) {
2019 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2020 BaseType = Ptr->getPointeeType();
2021 else if (BaseType->isObjCObjectPointerType())
2022 /*Do nothing*/ ;
2023 else
2024 return;
2025 }
2026
Douglas Gregoreb5758b2009-09-23 22:26:46 +00002027 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002028 unsigned NextRank = 0;
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002029
Douglas Gregor95ac6552009-11-18 01:29:26 +00002030 Results.EnterNewScope();
2031 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
2032 // Access to a C/C++ class, struct, or union.
2033 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
2034 Record->getDecl(), Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002035
Douglas Gregor95ac6552009-11-18 01:29:26 +00002036 if (getLangOptions().CPlusPlus) {
2037 if (!Results.empty()) {
2038 // The "template" keyword can follow "->" or "." in the grammar.
2039 // However, we only want to suggest the template keyword if something
2040 // is dependent.
2041 bool IsDependent = BaseType->isDependentType();
2042 if (!IsDependent) {
2043 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2044 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2045 IsDependent = Ctx->isDependentContext();
2046 break;
2047 }
2048 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002049
Douglas Gregor95ac6552009-11-18 01:29:26 +00002050 if (IsDependent)
2051 Results.MaybeAddResult(Result("template", NextRank++));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002052 }
2053
Douglas Gregor95ac6552009-11-18 01:29:26 +00002054 // We could have the start of a nested-name-specifier. Add those
2055 // results as well.
Douglas Gregor76282942009-12-11 17:31:05 +00002056 // FIXME: We should really walk base classes to produce
2057 // nested-name-specifiers so that we produce more-precise results.
Douglas Gregor95ac6552009-11-18 01:29:26 +00002058 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
2059 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
2060 CurContext, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002061 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002062 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2063 // Objective-C property reference.
2064
2065 // Add property results based on our interface.
2066 const ObjCObjectPointerType *ObjCPtr
2067 = BaseType->getAsObjCInterfacePointerType();
2068 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00002069 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002070
2071 // Add properties from the protocols in a qualified interface.
2072 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2073 E = ObjCPtr->qual_end();
2074 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002075 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002076 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2077 (!IsArrow && BaseType->isObjCInterfaceType())) {
2078 // Objective-C instance variable access.
2079 ObjCInterfaceDecl *Class = 0;
2080 if (const ObjCObjectPointerType *ObjCPtr
2081 = BaseType->getAs<ObjCObjectPointerType>())
2082 Class = ObjCPtr->getInterfaceDecl();
2083 else
2084 Class = BaseType->getAs<ObjCInterfaceType>()->getDecl();
2085
2086 // Add all ivars from this class and its superclasses.
2087 for (; Class; Class = Class->getSuperClass()) {
2088 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
2089 IVarEnd = Class->ivar_end();
2090 IVar != IVarEnd; ++IVar)
2091 Results.MaybeAddResult(Result(*IVar, 0), CurContext);
2092 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002093 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002094
2095 // FIXME: How do we cope with isa?
2096
2097 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002098
2099 // Add macros
2100 if (CodeCompleter->includeMacros())
2101 AddMacroResults(PP, NextRank, Results);
2102
2103 // Hand off the results found for code completion.
2104 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002105}
2106
Douglas Gregor374929f2009-09-18 15:37:17 +00002107void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2108 if (!CodeCompleter)
2109 return;
2110
Douglas Gregor86d9a522009-09-21 16:56:56 +00002111 typedef CodeCompleteConsumer::Result Result;
2112 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +00002113 switch ((DeclSpec::TST)TagSpec) {
2114 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002115 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +00002116 break;
2117
2118 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002119 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +00002120 break;
2121
2122 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00002123 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002124 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00002125 break;
2126
2127 default:
2128 assert(false && "Unknown type specifier kind in CodeCompleteTag");
2129 return;
2130 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002131
2132 ResultBuilder Results(*this, Filter);
2133 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00002134 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002135
2136 if (getLangOptions().CPlusPlus) {
2137 // We could have the start of a nested-name-specifier. Add those
2138 // results as well.
2139 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002140 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
2141 NextRank, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002142 }
2143
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002144 if (CodeCompleter->includeMacros())
2145 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002146 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00002147}
2148
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002149void Sema::CodeCompleteCase(Scope *S) {
2150 if (getSwitchStack().empty() || !CodeCompleter)
2151 return;
2152
2153 SwitchStmt *Switch = getSwitchStack().back();
2154 if (!Switch->getCond()->getType()->isEnumeralType())
2155 return;
2156
2157 // Code-complete the cases of a switch statement over an enumeration type
2158 // by providing the list of
2159 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2160
2161 // Determine which enumerators we have already seen in the switch statement.
2162 // FIXME: Ideally, we would also be able to look *past* the code-completion
2163 // token, in case we are code-completing in the middle of the switch and not
2164 // at the end. However, we aren't able to do so at the moment.
2165 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002166 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002167 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2168 SC = SC->getNextSwitchCase()) {
2169 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2170 if (!Case)
2171 continue;
2172
2173 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2174 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2175 if (EnumConstantDecl *Enumerator
2176 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2177 // We look into the AST of the case statement to determine which
2178 // enumerator was named. Alternatively, we could compute the value of
2179 // the integral constant expression, then compare it against the
2180 // values of each enumerator. However, value-based approach would not
2181 // work as well with C++ templates where enumerators declared within a
2182 // template are type- and value-dependent.
2183 EnumeratorsSeen.insert(Enumerator);
2184
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002185 // If this is a qualified-id, keep track of the nested-name-specifier
2186 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002187 //
2188 // switch (TagD.getKind()) {
2189 // case TagDecl::TK_enum:
2190 // break;
2191 // case XXX
2192 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002193 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002194 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2195 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002196 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002197 }
2198 }
2199
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002200 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2201 // If there are no prior enumerators in C++, check whether we have to
2202 // qualify the names of the enumerators that we suggest, because they
2203 // may not be visible in this scope.
2204 Qualifier = getRequiredQualification(Context, CurContext,
2205 Enum->getDeclContext());
2206
2207 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2208 }
2209
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002210 // Add any enumerators that have not yet been mentioned.
2211 ResultBuilder Results(*this);
2212 Results.EnterNewScope();
2213 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2214 EEnd = Enum->enumerator_end();
2215 E != EEnd; ++E) {
2216 if (EnumeratorsSeen.count(*E))
2217 continue;
2218
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002219 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002220 }
2221 Results.ExitScope();
2222
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002223 if (CodeCompleter->includeMacros())
2224 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002225 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002226}
2227
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002228namespace {
2229 struct IsBetterOverloadCandidate {
2230 Sema &S;
2231
2232 public:
2233 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
2234
2235 bool
2236 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
2237 return S.isBetterOverloadCandidate(X, Y);
2238 }
2239 };
2240}
2241
2242void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2243 ExprTy **ArgsIn, unsigned NumArgs) {
2244 if (!CodeCompleter)
2245 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002246
2247 // When we're code-completing for a call, we fall back to ordinary
2248 // name code-completion whenever we can't produce specific
2249 // results. We may want to revisit this strategy in the future,
2250 // e.g., by merging the two kinds of results.
2251
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002252 Expr *Fn = (Expr *)FnIn;
2253 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002254
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002255 // Ignore type-dependent call expressions entirely.
2256 if (Fn->isTypeDependent() ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00002257 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00002258 CodeCompleteOrdinaryName(S, CCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002259 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002260 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002261
John McCall3b4294e2009-12-16 12:17:52 +00002262 // Build an overload candidate set based on the functions we find.
2263 OverloadCandidateSet CandidateSet;
2264
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002265 // FIXME: What if we're calling something that isn't a function declaration?
2266 // FIXME: What if we're calling a pseudo-destructor?
2267 // FIXME: What if we're calling a member function?
2268
John McCall3b4294e2009-12-16 12:17:52 +00002269 Expr *NakedFn = Fn->IgnoreParenCasts();
2270 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
2271 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
2272 /*PartialOverloading=*/ true);
2273 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
2274 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
2275 if (FDecl)
2276 AddOverloadCandidate(FDecl, Args, NumArgs, CandidateSet,
2277 false, false, /*PartialOverloading*/ true);
2278 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002279
2280 // Sort the overload candidate set by placing the best overloads first.
2281 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
2282 IsBetterOverloadCandidate(*this));
2283
2284 // Add the remaining viable overload candidates as code-completion reslults.
Douglas Gregor05944382009-09-23 00:16:58 +00002285 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
2286 llvm::SmallVector<ResultCandidate, 8> Results;
Anders Carlsson90756302009-09-22 17:29:51 +00002287
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002288 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2289 CandEnd = CandidateSet.end();
2290 Cand != CandEnd; ++Cand) {
2291 if (Cand->Viable)
Douglas Gregor05944382009-09-23 00:16:58 +00002292 Results.push_back(ResultCandidate(Cand->Function));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002293 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00002294
2295 if (Results.empty())
Douglas Gregor01dfea02010-01-10 23:08:15 +00002296 CodeCompleteOrdinaryName(S, CCC_Expression);
Douglas Gregoref96eac2009-12-11 19:06:04 +00002297 else
2298 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
2299 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002300}
2301
Douglas Gregor81b747b2009-09-17 21:32:03 +00002302void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
2303 bool EnteringContext) {
2304 if (!SS.getScopeRep() || !CodeCompleter)
2305 return;
2306
Douglas Gregor86d9a522009-09-21 16:56:56 +00002307 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
2308 if (!Ctx)
2309 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00002310
2311 // Try to instantiate any non-dependent declaration contexts before
2312 // we look in them.
2313 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS))
2314 return;
2315
Douglas Gregor86d9a522009-09-21 16:56:56 +00002316 ResultBuilder Results(*this);
Douglas Gregor456c4a12009-09-21 20:12:40 +00002317 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002318
2319 // The "template" keyword can follow "::" in the grammar, but only
2320 // put it into the grammar if the nested-name-specifier is dependent.
2321 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
2322 if (!Results.empty() && NNS->isDependent())
2323 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
2324
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002325 if (CodeCompleter->includeMacros())
2326 AddMacroResults(PP, NextRank + 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002327 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002328}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002329
2330void Sema::CodeCompleteUsing(Scope *S) {
2331 if (!CodeCompleter)
2332 return;
2333
Douglas Gregor86d9a522009-09-21 16:56:56 +00002334 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002335 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002336
2337 // If we aren't in class scope, we could see the "namespace" keyword.
2338 if (!S->isClassScope())
2339 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
2340
2341 // After "using", we can see anything that would start a
2342 // nested-name-specifier.
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002343 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
2344 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002345 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002346
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002347 if (CodeCompleter->includeMacros())
2348 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002349 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002350}
2351
2352void Sema::CodeCompleteUsingDirective(Scope *S) {
2353 if (!CodeCompleter)
2354 return;
2355
Douglas Gregor86d9a522009-09-21 16:56:56 +00002356 // After "using namespace", we expect to see a namespace name or namespace
2357 // alias.
2358 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002359 Results.EnterNewScope();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002360 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
2361 0, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002362 Results.ExitScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002363 if (CodeCompleter->includeMacros())
2364 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002365 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002366}
2367
2368void Sema::CodeCompleteNamespaceDecl(Scope *S) {
2369 if (!CodeCompleter)
2370 return;
2371
Douglas Gregor86d9a522009-09-21 16:56:56 +00002372 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
2373 DeclContext *Ctx = (DeclContext *)S->getEntity();
2374 if (!S->getParent())
2375 Ctx = Context.getTranslationUnitDecl();
2376
2377 if (Ctx && Ctx->isFileContext()) {
2378 // We only want to see those namespaces that have already been defined
2379 // within this scope, because its likely that the user is creating an
2380 // extended namespace declaration. Keep track of the most recent
2381 // definition of each namespace.
2382 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
2383 for (DeclContext::specific_decl_iterator<NamespaceDecl>
2384 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
2385 NS != NSEnd; ++NS)
2386 OrigToLatest[NS->getOriginalNamespace()] = *NS;
2387
2388 // Add the most recent definition (or extended definition) of each
2389 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002390 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002391 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
2392 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
2393 NS != NSEnd; ++NS)
Douglas Gregor456c4a12009-09-21 20:12:40 +00002394 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
2395 CurContext);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002396 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002397 }
2398
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002399 if (CodeCompleter->includeMacros())
2400 AddMacroResults(PP, 1, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002401 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002402}
2403
2404void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
2405 if (!CodeCompleter)
2406 return;
2407
Douglas Gregor86d9a522009-09-21 16:56:56 +00002408 // After "namespace", we expect to see a namespace or alias.
2409 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002410 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
2411 0, CurContext, Results);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002412 if (CodeCompleter->includeMacros())
2413 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002414 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002415}
2416
Douglas Gregored8d3222009-09-18 20:05:18 +00002417void Sema::CodeCompleteOperatorName(Scope *S) {
2418 if (!CodeCompleter)
2419 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002420
2421 typedef CodeCompleteConsumer::Result Result;
2422 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002423 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00002424
Douglas Gregor86d9a522009-09-21 16:56:56 +00002425 // Add the names of overloadable operators.
2426#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2427 if (std::strcmp(Spelling, "?")) \
2428 Results.MaybeAddResult(Result(Spelling, 0));
2429#include "clang/Basic/OperatorKinds.def"
2430
2431 // Add any type names visible from the current scope
2432 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
Douglas Gregor456c4a12009-09-21 20:12:40 +00002433 0, CurContext, Results);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002434
2435 // Add any type specifiers
2436 AddTypeSpecifierResults(getLangOptions(), 0, Results);
2437
2438 // Add any nested-name-specifiers
2439 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002440 NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
2441 NextRank + 1, CurContext, Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002442 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002443
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002444 if (CodeCompleter->includeMacros())
2445 AddMacroResults(PP, NextRank, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002446 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00002447}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002448
Douglas Gregorc464ae82009-12-07 09:27:33 +00002449void Sema::CodeCompleteObjCAtDirective(Scope *S, DeclPtrTy ObjCImpDecl,
2450 bool InInterface) {
2451 typedef CodeCompleteConsumer::Result Result;
2452 ResultBuilder Results(*this);
2453 Results.EnterNewScope();
2454 if (ObjCImpDecl) {
2455 // Since we have an implementation, we can end it.
2456 Results.MaybeAddResult(Result("end", 0));
2457
2458 CodeCompletionString *Pattern = 0;
2459 Decl *ImpDecl = ObjCImpDecl.getAs<Decl>();
2460 if (isa<ObjCImplementationDecl>(ImpDecl) ||
2461 isa<ObjCCategoryImplDecl>(ImpDecl)) {
2462 // @dynamic
2463 Pattern = new CodeCompletionString;
2464 Pattern->AddTypedTextChunk("dynamic");
Douglas Gregor834389b2010-01-12 06:38:28 +00002465 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc464ae82009-12-07 09:27:33 +00002466 Pattern->AddPlaceholderChunk("property");
2467 Results.MaybeAddResult(Result(Pattern, 0));
2468
2469 // @synthesize
2470 Pattern = new CodeCompletionString;
2471 Pattern->AddTypedTextChunk("synthesize");
Douglas Gregor834389b2010-01-12 06:38:28 +00002472 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc464ae82009-12-07 09:27:33 +00002473 Pattern->AddPlaceholderChunk("property");
2474 Results.MaybeAddResult(Result(Pattern, 0));
2475 }
2476 } else if (InInterface) {
2477 // Since we have an interface or protocol, we can end it.
2478 Results.MaybeAddResult(Result("end", 0));
2479
Douglas Gregor01dfea02010-01-10 23:08:15 +00002480 if (getLangOptions().ObjC2) {
Douglas Gregorc464ae82009-12-07 09:27:33 +00002481 // @property
2482 Results.MaybeAddResult(Result("property", 0));
2483 }
2484
2485 // @required
2486 Results.MaybeAddResult(Result("required", 0));
2487
2488 // @optional
2489 Results.MaybeAddResult(Result("optional", 0));
2490 } else {
2491 CodeCompletionString *Pattern = 0;
2492
2493 // @class name ;
2494 Pattern = new CodeCompletionString;
2495 Pattern->AddTypedTextChunk("class");
Douglas Gregor834389b2010-01-12 06:38:28 +00002496 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc464ae82009-12-07 09:27:33 +00002497 Pattern->AddPlaceholderChunk("identifier");
Douglas Gregor834389b2010-01-12 06:38:28 +00002498 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregorc464ae82009-12-07 09:27:33 +00002499 Results.MaybeAddResult(Result(Pattern, 0));
2500
2501 // @interface name
2502 // FIXME: Could introduce the whole pattern, including superclasses and
2503 // such.
2504 Pattern = new CodeCompletionString;
2505 Pattern->AddTypedTextChunk("interface");
Douglas Gregor834389b2010-01-12 06:38:28 +00002506 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2507
Douglas Gregorc464ae82009-12-07 09:27:33 +00002508 Pattern->AddPlaceholderChunk("class");
2509 Results.MaybeAddResult(Result(Pattern, 0));
2510
2511 // @protocol name
2512 Pattern = new CodeCompletionString;
2513 Pattern->AddTypedTextChunk("protocol");
Douglas Gregor834389b2010-01-12 06:38:28 +00002514 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2515
Douglas Gregorc464ae82009-12-07 09:27:33 +00002516 Pattern->AddPlaceholderChunk("protocol");
2517 Results.MaybeAddResult(Result(Pattern, 0));
2518
2519 // @implementation name
2520 Pattern = new CodeCompletionString;
2521 Pattern->AddTypedTextChunk("implementation");
Douglas Gregor834389b2010-01-12 06:38:28 +00002522 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2523
Douglas Gregorc464ae82009-12-07 09:27:33 +00002524 Pattern->AddPlaceholderChunk("class");
2525 Results.MaybeAddResult(Result(Pattern, 0));
2526
2527 // @compatibility_alias name
2528 Pattern = new CodeCompletionString;
2529 Pattern->AddTypedTextChunk("compatibility_alias");
Douglas Gregor834389b2010-01-12 06:38:28 +00002530 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2531
Douglas Gregorc464ae82009-12-07 09:27:33 +00002532 Pattern->AddPlaceholderChunk("alias");
Douglas Gregor834389b2010-01-12 06:38:28 +00002533 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2534
Douglas Gregorc464ae82009-12-07 09:27:33 +00002535 Pattern->AddPlaceholderChunk("class");
2536 Results.MaybeAddResult(Result(Pattern, 0));
2537 }
2538 Results.ExitScope();
2539 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2540}
2541
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002542static void AddObjCExpressionResults(unsigned Rank, ResultBuilder &Results) {
2543 typedef CodeCompleteConsumer::Result Result;
2544 CodeCompletionString *Pattern = 0;
2545
2546 // @encode ( type-name )
2547 Pattern = new CodeCompletionString;
2548 Pattern->AddTypedTextChunk("encode");
2549 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2550 Pattern->AddPlaceholderChunk("type-name");
2551 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2552 Results.MaybeAddResult(Result(Pattern, Rank));
2553
2554 // @protocol ( protocol-name )
2555 Pattern = new CodeCompletionString;
2556 Pattern->AddTypedTextChunk("protocol");
2557 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2558 Pattern->AddPlaceholderChunk("protocol-name");
2559 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2560 Results.MaybeAddResult(Result(Pattern, Rank));
2561
2562 // @selector ( selector )
2563 Pattern = new CodeCompletionString;
2564 Pattern->AddTypedTextChunk("selector");
2565 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2566 Pattern->AddPlaceholderChunk("selector");
2567 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2568 Results.MaybeAddResult(Result(Pattern, Rank));
2569}
2570
2571void Sema::CodeCompleteObjCAtStatement(Scope *S) {
2572 typedef CodeCompleteConsumer::Result Result;
2573 ResultBuilder Results(*this);
2574 Results.EnterNewScope();
2575
2576 CodeCompletionString *Pattern = 0;
2577
2578 // @try { statements } @catch ( declaration ) { statements } @finally
2579 // { statements }
2580 Pattern = new CodeCompletionString;
2581 Pattern->AddTypedTextChunk("try");
2582 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2583 Pattern->AddPlaceholderChunk("statements");
2584 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2585 Pattern->AddTextChunk("@catch");
2586 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2587 Pattern->AddPlaceholderChunk("parameter");
2588 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2589 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2590 Pattern->AddPlaceholderChunk("statements");
2591 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2592 Pattern->AddTextChunk("@finally");
2593 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2594 Pattern->AddPlaceholderChunk("statements");
2595 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2596 Results.MaybeAddResult(Result(Pattern, 0));
2597
2598 // @throw
2599 Pattern = new CodeCompletionString;
2600 Pattern->AddTypedTextChunk("throw");
Douglas Gregor834389b2010-01-12 06:38:28 +00002601 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2602
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002603 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor834389b2010-01-12 06:38:28 +00002604 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
2605 Results.MaybeAddResult(Result(Pattern, 0));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002606
2607 // @synchronized ( expression ) { statements }
2608 Pattern = new CodeCompletionString;
2609 Pattern->AddTypedTextChunk("synchronized");
Douglas Gregor834389b2010-01-12 06:38:28 +00002610 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2611
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002612 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2613 Pattern->AddPlaceholderChunk("expression");
2614 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2615 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2616 Pattern->AddPlaceholderChunk("statements");
2617 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2618 Results.MaybeAddResult(Result(Pattern, 0)); // FIXME: add ';' chunk
2619
2620 AddObjCExpressionResults(0, Results);
2621 Results.ExitScope();
2622 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2623}
2624
2625void Sema::CodeCompleteObjCAtExpression(Scope *S) {
2626 ResultBuilder Results(*this);
2627 Results.EnterNewScope();
2628 AddObjCExpressionResults(0, Results);
2629 Results.ExitScope();
2630 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2631}
2632
Douglas Gregor988358f2009-11-19 00:14:45 +00002633/// \brief Determine whether the addition of the given flag to an Objective-C
2634/// property's attributes will cause a conflict.
2635static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
2636 // Check if we've already added this flag.
2637 if (Attributes & NewFlag)
2638 return true;
2639
2640 Attributes |= NewFlag;
2641
2642 // Check for collisions with "readonly".
2643 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
2644 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
2645 ObjCDeclSpec::DQ_PR_assign |
2646 ObjCDeclSpec::DQ_PR_copy |
2647 ObjCDeclSpec::DQ_PR_retain)))
2648 return true;
2649
2650 // Check for more than one of { assign, copy, retain }.
2651 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
2652 ObjCDeclSpec::DQ_PR_copy |
2653 ObjCDeclSpec::DQ_PR_retain);
2654 if (AssignCopyRetMask &&
2655 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
2656 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
2657 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
2658 return true;
2659
2660 return false;
2661}
2662
Douglas Gregora93b1082009-11-18 23:08:07 +00002663void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00002664 if (!CodeCompleter)
2665 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00002666
Steve Naroffece8e712009-10-08 21:55:05 +00002667 unsigned Attributes = ODS.getPropertyAttributes();
2668
2669 typedef CodeCompleteConsumer::Result Result;
2670 ResultBuilder Results(*this);
2671 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00002672 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
Steve Naroffece8e712009-10-08 21:55:05 +00002673 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00002674 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
Steve Naroffece8e712009-10-08 21:55:05 +00002675 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00002676 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
Steve Naroffece8e712009-10-08 21:55:05 +00002677 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00002678 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
Steve Naroffece8e712009-10-08 21:55:05 +00002679 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00002680 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
Steve Naroffece8e712009-10-08 21:55:05 +00002681 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00002682 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
Steve Naroffece8e712009-10-08 21:55:05 +00002683 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
Douglas Gregor988358f2009-11-19 00:14:45 +00002684 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00002685 CodeCompletionString *Setter = new CodeCompletionString;
2686 Setter->AddTypedTextChunk("setter");
2687 Setter->AddTextChunk(" = ");
2688 Setter->AddPlaceholderChunk("method");
2689 Results.MaybeAddResult(CodeCompleteConsumer::Result(Setter, 0));
2690 }
Douglas Gregor988358f2009-11-19 00:14:45 +00002691 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00002692 CodeCompletionString *Getter = new CodeCompletionString;
2693 Getter->AddTypedTextChunk("getter");
2694 Getter->AddTextChunk(" = ");
2695 Getter->AddPlaceholderChunk("method");
2696 Results.MaybeAddResult(CodeCompleteConsumer::Result(Getter, 0));
2697 }
Steve Naroffece8e712009-10-08 21:55:05 +00002698 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002699 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00002700}
Steve Naroffc4df6d22009-11-07 02:08:14 +00002701
Douglas Gregor4ad96852009-11-19 07:41:15 +00002702/// \brief Descripts the kind of Objective-C method that we want to find
2703/// via code completion.
2704enum ObjCMethodKind {
2705 MK_Any, //< Any kind of method, provided it means other specified criteria.
2706 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
2707 MK_OneArgSelector //< One-argument selector.
2708};
2709
2710static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
2711 ObjCMethodKind WantKind,
2712 IdentifierInfo **SelIdents,
2713 unsigned NumSelIdents) {
2714 Selector Sel = Method->getSelector();
2715 if (NumSelIdents > Sel.getNumArgs())
2716 return false;
2717
2718 switch (WantKind) {
2719 case MK_Any: break;
2720 case MK_ZeroArgSelector: return Sel.isUnarySelector();
2721 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
2722 }
2723
2724 for (unsigned I = 0; I != NumSelIdents; ++I)
2725 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
2726 return false;
2727
2728 return true;
2729}
2730
Douglas Gregor36ecb042009-11-17 23:22:23 +00002731/// \brief Add all of the Objective-C methods in the given Objective-C
2732/// container to the set of results.
2733///
2734/// The container will be a class, protocol, category, or implementation of
2735/// any of the above. This mether will recurse to include methods from
2736/// the superclasses of classes along with their categories, protocols, and
2737/// implementations.
2738///
2739/// \param Container the container in which we'll look to find methods.
2740///
2741/// \param WantInstance whether to add instance methods (only); if false, this
2742/// routine will add factory methods (only).
2743///
2744/// \param CurContext the context in which we're performing the lookup that
2745/// finds methods.
2746///
2747/// \param Results the structure into which we'll add results.
2748static void AddObjCMethods(ObjCContainerDecl *Container,
2749 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00002750 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00002751 IdentifierInfo **SelIdents,
2752 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00002753 DeclContext *CurContext,
2754 ResultBuilder &Results) {
2755 typedef CodeCompleteConsumer::Result Result;
2756 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
2757 MEnd = Container->meth_end();
2758 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002759 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
2760 // Check whether the selector identifiers we've been given are a
2761 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00002762 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00002763 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00002764
Douglas Gregord3c68542009-11-19 01:08:35 +00002765 Result R = Result(*M, 0);
2766 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00002767 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregord3c68542009-11-19 01:08:35 +00002768 Results.MaybeAddResult(R, CurContext);
2769 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00002770 }
2771
2772 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
2773 if (!IFace)
2774 return;
2775
2776 // Add methods in protocols.
2777 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
2778 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
2779 E = Protocols.end();
2780 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002781 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord3c68542009-11-19 01:08:35 +00002782 CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00002783
2784 // Add methods in categories.
2785 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
2786 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00002787 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
2788 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00002789
2790 // Add a categories protocol methods.
2791 const ObjCList<ObjCProtocolDecl> &Protocols
2792 = CatDecl->getReferencedProtocols();
2793 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
2794 E = Protocols.end();
2795 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002796 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
2797 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00002798
2799 // Add methods in category implementations.
2800 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00002801 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
2802 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00002803 }
2804
2805 // Add methods in superclass.
2806 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00002807 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
2808 SelIdents, NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00002809
2810 // Add methods in our implementation, if any.
2811 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00002812 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
2813 NumSelIdents, CurContext, Results);
2814}
2815
2816
2817void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
2818 DeclPtrTy *Methods,
2819 unsigned NumMethods) {
2820 typedef CodeCompleteConsumer::Result Result;
2821
2822 // Try to find the interface where getters might live.
2823 ObjCInterfaceDecl *Class
2824 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
2825 if (!Class) {
2826 if (ObjCCategoryDecl *Category
2827 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
2828 Class = Category->getClassInterface();
2829
2830 if (!Class)
2831 return;
2832 }
2833
2834 // Find all of the potential getters.
2835 ResultBuilder Results(*this);
2836 Results.EnterNewScope();
2837
2838 // FIXME: We need to do this because Objective-C methods don't get
2839 // pushed into DeclContexts early enough. Argh!
2840 for (unsigned I = 0; I != NumMethods; ++I) {
2841 if (ObjCMethodDecl *Method
2842 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
2843 if (Method->isInstanceMethod() &&
2844 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
2845 Result R = Result(Method, 0);
2846 R.AllParametersAreInformative = true;
2847 Results.MaybeAddResult(R, CurContext);
2848 }
2849 }
2850
2851 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
2852 Results.ExitScope();
2853 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
2854}
2855
2856void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
2857 DeclPtrTy *Methods,
2858 unsigned NumMethods) {
2859 typedef CodeCompleteConsumer::Result Result;
2860
2861 // Try to find the interface where setters might live.
2862 ObjCInterfaceDecl *Class
2863 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
2864 if (!Class) {
2865 if (ObjCCategoryDecl *Category
2866 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
2867 Class = Category->getClassInterface();
2868
2869 if (!Class)
2870 return;
2871 }
2872
2873 // Find all of the potential getters.
2874 ResultBuilder Results(*this);
2875 Results.EnterNewScope();
2876
2877 // FIXME: We need to do this because Objective-C methods don't get
2878 // pushed into DeclContexts early enough. Argh!
2879 for (unsigned I = 0; I != NumMethods; ++I) {
2880 if (ObjCMethodDecl *Method
2881 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
2882 if (Method->isInstanceMethod() &&
2883 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
2884 Result R = Result(Method, 0);
2885 R.AllParametersAreInformative = true;
2886 Results.MaybeAddResult(R, CurContext);
2887 }
2888 }
2889
2890 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
2891
2892 Results.ExitScope();
2893 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00002894}
2895
Douglas Gregor60b01cc2009-11-17 23:31:36 +00002896void Sema::CodeCompleteObjCClassMessage(Scope *S, IdentifierInfo *FName,
Douglas Gregord3c68542009-11-19 01:08:35 +00002897 SourceLocation FNameLoc,
2898 IdentifierInfo **SelIdents,
2899 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00002900 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00002901 ObjCInterfaceDecl *CDecl = 0;
2902
Douglas Gregor24a069f2009-11-17 17:59:40 +00002903 if (FName->isStr("super")) {
2904 // We're sending a message to "super".
2905 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
2906 // Figure out which interface we're in.
2907 CDecl = CurMethod->getClassInterface();
2908 if (!CDecl)
2909 return;
2910
2911 // Find the superclass of this class.
2912 CDecl = CDecl->getSuperClass();
2913 if (!CDecl)
2914 return;
2915
2916 if (CurMethod->isInstanceMethod()) {
2917 // We are inside an instance method, which means that the message
2918 // send [super ...] is actually calling an instance method on the
2919 // current object. Build the super expression and handle this like
2920 // an instance method.
2921 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
2922 SuperTy = Context.getObjCObjectPointerType(SuperTy);
2923 OwningExprResult Super
Douglas Gregor60b01cc2009-11-17 23:31:36 +00002924 = Owned(new (Context) ObjCSuperExpr(FNameLoc, SuperTy));
Douglas Gregord3c68542009-11-19 01:08:35 +00002925 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
2926 SelIdents, NumSelIdents);
Douglas Gregor24a069f2009-11-17 17:59:40 +00002927 }
2928
2929 // Okay, we're calling a factory method in our superclass.
2930 }
2931 }
2932
2933 // If the given name refers to an interface type, retrieve the
2934 // corresponding declaration.
2935 if (!CDecl)
Douglas Gregor60b01cc2009-11-17 23:31:36 +00002936 if (TypeTy *Ty = getTypeName(*FName, FNameLoc, S, 0, false)) {
Douglas Gregor24a069f2009-11-17 17:59:40 +00002937 QualType T = GetTypeFromParser(Ty, 0);
2938 if (!T.isNull())
2939 if (const ObjCInterfaceType *Interface = T->getAs<ObjCInterfaceType>())
2940 CDecl = Interface->getDecl();
2941 }
2942
2943 if (!CDecl && FName->isStr("super")) {
2944 // "super" may be the name of a variable, in which case we are
2945 // probably calling an instance method.
John McCallf7a1a742009-11-24 19:00:30 +00002946 CXXScopeSpec SS;
2947 UnqualifiedId id;
2948 id.setIdentifier(FName, FNameLoc);
2949 OwningExprResult Super = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregord3c68542009-11-19 01:08:35 +00002950 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
2951 SelIdents, NumSelIdents);
Douglas Gregor24a069f2009-11-17 17:59:40 +00002952 }
2953
Douglas Gregor36ecb042009-11-17 23:22:23 +00002954 // Add all of the factory methods in this Objective-C class, its protocols,
2955 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00002956 ResultBuilder Results(*this);
2957 Results.EnterNewScope();
Douglas Gregor4ad96852009-11-19 07:41:15 +00002958 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
2959 Results);
Steve Naroffc4df6d22009-11-07 02:08:14 +00002960 Results.ExitScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00002961
Steve Naroffc4df6d22009-11-07 02:08:14 +00002962 // This also suppresses remaining diagnostics.
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002963 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00002964}
2965
Douglas Gregord3c68542009-11-19 01:08:35 +00002966void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
2967 IdentifierInfo **SelIdents,
2968 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00002969 typedef CodeCompleteConsumer::Result Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00002970
2971 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00002972
Douglas Gregor36ecb042009-11-17 23:22:23 +00002973 // If necessary, apply function/array conversion to the receiver.
2974 // C99 6.7.5.3p[7,8].
2975 DefaultFunctionArrayConversion(RecExpr);
2976 QualType ReceiverType = RecExpr->getType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00002977
Douglas Gregor36ecb042009-11-17 23:22:23 +00002978 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType()) {
2979 // FIXME: We're messaging 'id'. Do we actually want to look up every method
2980 // in the universe?
2981 return;
2982 }
2983
Douglas Gregor36ecb042009-11-17 23:22:23 +00002984 // Build the set of methods we can see.
2985 ResultBuilder Results(*this);
2986 Results.EnterNewScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00002987
Douglas Gregorf74a4192009-11-18 00:06:18 +00002988 // Handle messages to Class. This really isn't a message to an instance
2989 // method, so we treat it the same way we would treat a message send to a
2990 // class method.
2991 if (ReceiverType->isObjCClassType() ||
2992 ReceiverType->isObjCQualifiedClassType()) {
2993 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
2994 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00002995 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
2996 CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00002997 }
2998 }
2999 // Handle messages to a qualified ID ("id<foo>").
3000 else if (const ObjCObjectPointerType *QualID
3001 = ReceiverType->getAsObjCQualifiedIdType()) {
3002 // Search protocols for instance methods.
3003 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
3004 E = QualID->qual_end();
3005 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003006 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3007 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003008 }
3009 // Handle messages to a pointer to interface type.
3010 else if (const ObjCObjectPointerType *IFacePtr
3011 = ReceiverType->getAsObjCInterfacePointerType()) {
3012 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00003013 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
3014 NumSelIdents, CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003015
3016 // Search protocols for instance methods.
3017 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
3018 E = IFacePtr->qual_end();
3019 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003020 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3021 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003022 }
3023
Steve Naroffc4df6d22009-11-07 02:08:14 +00003024 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003025 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00003026}
Douglas Gregor55385fe2009-11-18 04:19:12 +00003027
3028/// \brief Add all of the protocol declarations that we find in the given
3029/// (translation unit) context.
3030static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00003031 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00003032 ResultBuilder &Results) {
3033 typedef CodeCompleteConsumer::Result Result;
3034
3035 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3036 DEnd = Ctx->decls_end();
3037 D != DEnd; ++D) {
3038 // Record any protocols we find.
3039 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00003040 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
3041 Results.MaybeAddResult(Result(Proto, 0), CurContext);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003042
3043 // Record any forward-declared protocols we find.
3044 if (ObjCForwardProtocolDecl *Forward
3045 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
3046 for (ObjCForwardProtocolDecl::protocol_iterator
3047 P = Forward->protocol_begin(),
3048 PEnd = Forward->protocol_end();
3049 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00003050 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
3051 Results.MaybeAddResult(Result(*P, 0), CurContext);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003052 }
3053 }
3054}
3055
3056void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
3057 unsigned NumProtocols) {
3058 ResultBuilder Results(*this);
3059 Results.EnterNewScope();
3060
3061 // Tell the result set to ignore all of the protocols we have
3062 // already seen.
3063 for (unsigned I = 0; I != NumProtocols; ++I)
3064 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first))
3065 Results.Ignore(Protocol);
3066
3067 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00003068 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
3069 Results);
3070
3071 Results.ExitScope();
3072 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3073}
3074
3075void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
3076 ResultBuilder Results(*this);
3077 Results.EnterNewScope();
3078
3079 // Add all protocols.
3080 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
3081 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003082
3083 Results.ExitScope();
3084 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3085}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003086
3087/// \brief Add all of the Objective-C interface declarations that we find in
3088/// the given (translation unit) context.
3089static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
3090 bool OnlyForwardDeclarations,
3091 bool OnlyUnimplemented,
3092 ResultBuilder &Results) {
3093 typedef CodeCompleteConsumer::Result Result;
3094
3095 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3096 DEnd = Ctx->decls_end();
3097 D != DEnd; ++D) {
3098 // Record any interfaces we find.
3099 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
3100 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
3101 (!OnlyUnimplemented || !Class->getImplementation()))
3102 Results.MaybeAddResult(Result(Class, 0), CurContext);
3103
3104 // Record any forward-declared interfaces we find.
3105 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
3106 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
3107 C != CEnd; ++C)
3108 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
3109 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
3110 Results.MaybeAddResult(Result(C->getInterface(), 0), CurContext);
3111 }
3112 }
3113}
3114
3115void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
3116 ResultBuilder Results(*this);
3117 Results.EnterNewScope();
3118
3119 // Add all classes.
3120 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
3121 false, Results);
3122
3123 Results.ExitScope();
3124 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3125}
3126
3127void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName) {
3128 ResultBuilder Results(*this);
3129 Results.EnterNewScope();
3130
3131 // Make sure that we ignore the class we're currently defining.
3132 NamedDecl *CurClass
3133 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003134 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003135 Results.Ignore(CurClass);
3136
3137 // Add all classes.
3138 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3139 false, Results);
3140
3141 Results.ExitScope();
3142 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3143}
3144
3145void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
3146 ResultBuilder Results(*this);
3147 Results.EnterNewScope();
3148
3149 // Add all unimplemented classes.
3150 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3151 true, Results);
3152
3153 Results.ExitScope();
3154 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3155}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003156
3157void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
3158 IdentifierInfo *ClassName) {
3159 typedef CodeCompleteConsumer::Result Result;
3160
3161 ResultBuilder Results(*this);
3162
3163 // Ignore any categories we find that have already been implemented by this
3164 // interface.
3165 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3166 NamedDecl *CurClass
3167 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
3168 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
3169 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3170 Category = Category->getNextClassCategory())
3171 CategoryNames.insert(Category->getIdentifier());
3172
3173 // Add all of the categories we know about.
3174 Results.EnterNewScope();
3175 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3176 for (DeclContext::decl_iterator D = TU->decls_begin(),
3177 DEnd = TU->decls_end();
3178 D != DEnd; ++D)
3179 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
3180 if (CategoryNames.insert(Category->getIdentifier()))
3181 Results.MaybeAddResult(Result(Category, 0), CurContext);
3182 Results.ExitScope();
3183
3184 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3185}
3186
3187void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
3188 IdentifierInfo *ClassName) {
3189 typedef CodeCompleteConsumer::Result Result;
3190
3191 // Find the corresponding interface. If we couldn't find the interface, the
3192 // program itself is ill-formed. However, we'll try to be helpful still by
3193 // providing the list of all of the categories we know about.
3194 NamedDecl *CurClass
3195 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
3196 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
3197 if (!Class)
3198 return CodeCompleteObjCInterfaceCategory(S, ClassName);
3199
3200 ResultBuilder Results(*this);
3201
3202 // Add all of the categories that have have corresponding interface
3203 // declarations in this class and any of its superclasses, except for
3204 // already-implemented categories in the class itself.
3205 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3206 Results.EnterNewScope();
3207 bool IgnoreImplemented = true;
3208 while (Class) {
3209 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3210 Category = Category->getNextClassCategory())
3211 if ((!IgnoreImplemented || !Category->getImplementation()) &&
3212 CategoryNames.insert(Category->getIdentifier()))
3213 Results.MaybeAddResult(Result(Category, 0), CurContext);
3214
3215 Class = Class->getSuperClass();
3216 IgnoreImplemented = false;
3217 }
3218 Results.ExitScope();
3219
3220 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3221}
Douglas Gregor322328b2009-11-18 22:32:06 +00003222
Douglas Gregor424b2a52009-11-18 22:56:13 +00003223void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
Douglas Gregor322328b2009-11-18 22:32:06 +00003224 typedef CodeCompleteConsumer::Result Result;
3225 ResultBuilder Results(*this);
3226
3227 // Figure out where this @synthesize lives.
3228 ObjCContainerDecl *Container
3229 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3230 if (!Container ||
3231 (!isa<ObjCImplementationDecl>(Container) &&
3232 !isa<ObjCCategoryImplDecl>(Container)))
3233 return;
3234
3235 // Ignore any properties that have already been implemented.
3236 for (DeclContext::decl_iterator D = Container->decls_begin(),
3237 DEnd = Container->decls_end();
3238 D != DEnd; ++D)
3239 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
3240 Results.Ignore(PropertyImpl->getPropertyDecl());
3241
3242 // Add any properties that we find.
3243 Results.EnterNewScope();
3244 if (ObjCImplementationDecl *ClassImpl
3245 = dyn_cast<ObjCImplementationDecl>(Container))
3246 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
3247 Results);
3248 else
3249 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
3250 false, CurContext, Results);
3251 Results.ExitScope();
3252
3253 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3254}
3255
3256void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
3257 IdentifierInfo *PropertyName,
3258 DeclPtrTy ObjCImpDecl) {
3259 typedef CodeCompleteConsumer::Result Result;
3260 ResultBuilder Results(*this);
3261
3262 // Figure out where this @synthesize lives.
3263 ObjCContainerDecl *Container
3264 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3265 if (!Container ||
3266 (!isa<ObjCImplementationDecl>(Container) &&
3267 !isa<ObjCCategoryImplDecl>(Container)))
3268 return;
3269
3270 // Figure out which interface we're looking into.
3271 ObjCInterfaceDecl *Class = 0;
3272 if (ObjCImplementationDecl *ClassImpl
3273 = dyn_cast<ObjCImplementationDecl>(Container))
3274 Class = ClassImpl->getClassInterface();
3275 else
3276 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
3277 ->getClassInterface();
3278
3279 // Add all of the instance variables in this class and its superclasses.
3280 Results.EnterNewScope();
3281 for(; Class; Class = Class->getSuperClass()) {
3282 // FIXME: We could screen the type of each ivar for compatibility with
3283 // the property, but is that being too paternal?
3284 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
3285 IVarEnd = Class->ivar_end();
3286 IVar != IVarEnd; ++IVar)
3287 Results.MaybeAddResult(Result(*IVar, 0), CurContext);
3288 }
3289 Results.ExitScope();
3290
3291 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3292}