blob: 7eeb491391633ac1d59cc0a22253996c93f727a2 [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"
Douglas Gregor1ca6ae82010-01-14 01:09:38 +000014#include "Lookup.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000015#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000017#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000018#include "clang/Lex/MacroInfo.h"
19#include "clang/Lex/Preprocessor.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000020#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000021#include "llvm/ADT/StringExtras.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000022#include <list>
23#include <map>
24#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000025
26using namespace clang;
27
Douglas Gregor86d9a522009-09-21 16:56:56 +000028namespace {
29 /// \brief A container of code-completion results.
30 class ResultBuilder {
31 public:
32 /// \brief The type of a name-lookup filter, which can be provided to the
33 /// name-lookup routines to specify which declarations should be included in
34 /// the result set (when it returns true) and which declarations should be
35 /// filtered out (returns false).
36 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
37
38 typedef CodeCompleteConsumer::Result Result;
39
40 private:
41 /// \brief The actual results we have found.
42 std::vector<Result> Results;
43
44 /// \brief A record of all of the declarations we have found and placed
45 /// into the result set, used to ensure that no declaration ever gets into
46 /// the result set twice.
47 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
48
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000049 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
50
51 /// \brief An entry in the shadow map, which is optimized to store
52 /// a single (declaration, index) mapping (the common case) but
53 /// can also store a list of (declaration, index) mappings.
54 class ShadowMapEntry {
55 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
56
57 /// \brief Contains either the solitary NamedDecl * or a vector
58 /// of (declaration, index) pairs.
59 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
60
61 /// \brief When the entry contains a single declaration, this is
62 /// the index associated with that entry.
63 unsigned SingleDeclIndex;
64
65 public:
66 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
67
68 void Add(NamedDecl *ND, unsigned Index) {
69 if (DeclOrVector.isNull()) {
70 // 0 - > 1 elements: just set the single element information.
71 DeclOrVector = ND;
72 SingleDeclIndex = Index;
73 return;
74 }
75
76 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
77 // 1 -> 2 elements: create the vector of results and push in the
78 // existing declaration.
79 DeclIndexPairVector *Vec = new DeclIndexPairVector;
80 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
81 DeclOrVector = Vec;
82 }
83
84 // Add the new element to the end of the vector.
85 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
86 DeclIndexPair(ND, Index));
87 }
88
89 void Destroy() {
90 if (DeclIndexPairVector *Vec
91 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
92 delete Vec;
93 DeclOrVector = ((NamedDecl *)0);
94 }
95 }
96
97 // Iteration.
98 class iterator;
99 iterator begin() const;
100 iterator end() const;
101 };
102
Douglas Gregor86d9a522009-09-21 16:56:56 +0000103 /// \brief A mapping from declaration names to the declarations that have
104 /// this name within a particular scope and their index within the list of
105 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000106 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000107
108 /// \brief The semantic analysis object for which results are being
109 /// produced.
110 Sema &SemaRef;
111
112 /// \brief If non-NULL, a filter function used to remove any code-completion
113 /// results that are not desirable.
114 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000115
116 /// \brief Whether we should allow declarations as
117 /// nested-name-specifiers that would otherwise be filtered out.
118 bool AllowNestedNameSpecifiers;
119
Douglas Gregor86d9a522009-09-21 16:56:56 +0000120 /// \brief A list of shadow maps, which is used to model name hiding at
121 /// different levels of, e.g., the inheritance hierarchy.
122 std::list<ShadowMap> ShadowMaps;
123
124 public:
125 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
Douglas Gregor45bcd432010-01-14 03:21:49 +0000126 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false) { }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000127
128 /// \brief Set the filter used for code-completion results.
129 void setFilter(LookupFilter Filter) {
130 this->Filter = Filter;
131 }
132
133 typedef std::vector<Result>::iterator iterator;
134 iterator begin() { return Results.begin(); }
135 iterator end() { return Results.end(); }
136
137 Result *data() { return Results.empty()? 0 : &Results.front(); }
138 unsigned size() const { return Results.size(); }
139 bool empty() const { return Results.empty(); }
140
Douglas Gregor45bcd432010-01-14 03:21:49 +0000141 /// \brief Specify whether nested-name-specifiers are allowed.
142 void allowNestedNameSpecifiers(bool Allow = true) {
143 AllowNestedNameSpecifiers = Allow;
144 }
145
Douglas Gregore495b7f2010-01-14 00:20:49 +0000146 /// \brief Determine whether the given declaration is at all interesting
147 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000148 ///
149 /// \param ND the declaration that we are inspecting.
150 ///
151 /// \param AsNestedNameSpecifier will be set true if this declaration is
152 /// only interesting when it is a nested-name-specifier.
153 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000154
155 /// \brief Check whether the result is hidden by the Hiding declaration.
156 ///
157 /// \returns true if the result is hidden and cannot be found, false if
158 /// the hidden result could still be found. When false, \p R may be
159 /// modified to describe how the result can be found (e.g., via extra
160 /// qualification).
161 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
162 NamedDecl *Hiding);
163
Douglas Gregor86d9a522009-09-21 16:56:56 +0000164 /// \brief Add a new result to this result set (if it isn't already in one
165 /// of the shadow maps), or replace an existing result (for, e.g., a
166 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000167 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000168 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000169 ///
170 /// \param R the context in which this result will be named.
171 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000172
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000173 /// \brief Add a new result to this result set, where we already know
174 /// the hiding declation (if any).
175 ///
176 /// \param R the result to add (if it is unique).
177 ///
178 /// \param CurContext the context in which this result will be named.
179 ///
180 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000181 ///
182 /// \param InBaseClass whether the result was found in a base
183 /// class of the searched context.
184 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
185 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000186
Douglas Gregora4477812010-01-14 16:01:26 +0000187 /// \brief Add a new non-declaration result to this result set.
188 void AddResult(Result R);
189
Douglas Gregor86d9a522009-09-21 16:56:56 +0000190 /// \brief Enter into a new scope.
191 void EnterNewScope();
192
193 /// \brief Exit from the current scope.
194 void ExitScope();
195
Douglas Gregor55385fe2009-11-18 04:19:12 +0000196 /// \brief Ignore this declaration, if it is seen again.
197 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
198
Douglas Gregor86d9a522009-09-21 16:56:56 +0000199 /// \name Name lookup predicates
200 ///
201 /// These predicates can be passed to the name lookup functions to filter the
202 /// results of name lookup. All of the predicates have the same type, so that
203 ///
204 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000205 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000206 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000207 bool IsNestedNameSpecifier(NamedDecl *ND) const;
208 bool IsEnum(NamedDecl *ND) const;
209 bool IsClassOrStruct(NamedDecl *ND) const;
210 bool IsUnion(NamedDecl *ND) const;
211 bool IsNamespace(NamedDecl *ND) const;
212 bool IsNamespaceOrAlias(NamedDecl *ND) const;
213 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000214 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000215 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000216 //@}
217 };
218}
219
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000220class ResultBuilder::ShadowMapEntry::iterator {
221 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
222 unsigned SingleDeclIndex;
223
224public:
225 typedef DeclIndexPair value_type;
226 typedef value_type reference;
227 typedef std::ptrdiff_t difference_type;
228 typedef std::input_iterator_tag iterator_category;
229
230 class pointer {
231 DeclIndexPair Value;
232
233 public:
234 pointer(const DeclIndexPair &Value) : Value(Value) { }
235
236 const DeclIndexPair *operator->() const {
237 return &Value;
238 }
239 };
240
241 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
242
243 iterator(NamedDecl *SingleDecl, unsigned Index)
244 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
245
246 iterator(const DeclIndexPair *Iterator)
247 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
248
249 iterator &operator++() {
250 if (DeclOrIterator.is<NamedDecl *>()) {
251 DeclOrIterator = (NamedDecl *)0;
252 SingleDeclIndex = 0;
253 return *this;
254 }
255
256 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
257 ++I;
258 DeclOrIterator = I;
259 return *this;
260 }
261
262 iterator operator++(int) {
263 iterator tmp(*this);
264 ++(*this);
265 return tmp;
266 }
267
268 reference operator*() const {
269 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
270 return reference(ND, SingleDeclIndex);
271
Douglas Gregord490f952009-12-06 21:27:58 +0000272 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000273 }
274
275 pointer operator->() const {
276 return pointer(**this);
277 }
278
279 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000280 return X.DeclOrIterator.getOpaqueValue()
281 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000282 X.SingleDeclIndex == Y.SingleDeclIndex;
283 }
284
285 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000286 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000287 }
288};
289
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000290ResultBuilder::ShadowMapEntry::iterator
291ResultBuilder::ShadowMapEntry::begin() const {
292 if (DeclOrVector.isNull())
293 return iterator();
294
295 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
296 return iterator(ND, SingleDeclIndex);
297
298 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
299}
300
301ResultBuilder::ShadowMapEntry::iterator
302ResultBuilder::ShadowMapEntry::end() const {
303 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
304 return iterator();
305
306 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
307}
308
Douglas Gregor456c4a12009-09-21 20:12:40 +0000309/// \brief Compute the qualification required to get from the current context
310/// (\p CurContext) to the target context (\p TargetContext).
311///
312/// \param Context the AST context in which the qualification will be used.
313///
314/// \param CurContext the context where an entity is being named, which is
315/// typically based on the current scope.
316///
317/// \param TargetContext the context in which the named entity actually
318/// resides.
319///
320/// \returns a nested name specifier that refers into the target context, or
321/// NULL if no qualification is needed.
322static NestedNameSpecifier *
323getRequiredQualification(ASTContext &Context,
324 DeclContext *CurContext,
325 DeclContext *TargetContext) {
326 llvm::SmallVector<DeclContext *, 4> TargetParents;
327
328 for (DeclContext *CommonAncestor = TargetContext;
329 CommonAncestor && !CommonAncestor->Encloses(CurContext);
330 CommonAncestor = CommonAncestor->getLookupParent()) {
331 if (CommonAncestor->isTransparentContext() ||
332 CommonAncestor->isFunctionOrMethod())
333 continue;
334
335 TargetParents.push_back(CommonAncestor);
336 }
337
338 NestedNameSpecifier *Result = 0;
339 while (!TargetParents.empty()) {
340 DeclContext *Parent = TargetParents.back();
341 TargetParents.pop_back();
342
343 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
344 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
345 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
346 Result = NestedNameSpecifier::Create(Context, Result,
347 false,
348 Context.getTypeDeclType(TD).getTypePtr());
349 else
350 assert(Parent->isTranslationUnit());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000351 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000352 return Result;
353}
354
Douglas Gregor45bcd432010-01-14 03:21:49 +0000355bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
356 bool &AsNestedNameSpecifier) const {
357 AsNestedNameSpecifier = false;
358
Douglas Gregore495b7f2010-01-14 00:20:49 +0000359 ND = ND->getUnderlyingDecl();
360 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000361
362 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000363 if (!ND->getDeclName())
364 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000365
366 // Friend declarations and declarations introduced due to friends are never
367 // added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000368 if (isa<FriendDecl>(ND) ||
Douglas Gregor86d9a522009-09-21 16:56:56 +0000369 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000370 return false;
371
Douglas Gregor76282942009-12-11 17:31:05 +0000372 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000373 if (isa<ClassTemplateSpecializationDecl>(ND) ||
374 isa<ClassTemplatePartialSpecializationDecl>(ND))
375 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000376
Douglas Gregor76282942009-12-11 17:31:05 +0000377 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000378 if (isa<UsingDecl>(ND))
379 return false;
380
381 // Some declarations have reserved names that we don't want to ever show.
382 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000383 // __va_list_tag is a freak of nature. Find it and skip it.
384 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000385 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000386
Douglas Gregorf52cede2009-10-09 22:16:47 +0000387 // Filter out names reserved for the implementation (C99 7.1.3,
388 // C++ [lib.global.names]). Users don't need to see those.
Daniel Dunbare013d682009-10-18 20:26:12 +0000389 //
390 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000391 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000392 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000393 if (Name[0] == '_' &&
394 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000395 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000396 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000397 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000398
Douglas Gregor86d9a522009-09-21 16:56:56 +0000399 // C++ constructors are never found by name lookup.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000400 if (isa<CXXConstructorDecl>(ND))
401 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000402
403 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000404 if (Filter && !(this->*Filter)(ND)) {
405 // Check whether it is interesting as a nested-name-specifier.
406 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
407 IsNestedNameSpecifier(ND) &&
408 (Filter != &ResultBuilder::IsMember ||
409 (isa<CXXRecordDecl>(ND) &&
410 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
411 AsNestedNameSpecifier = true;
412 return true;
413 }
414
Douglas Gregore495b7f2010-01-14 00:20:49 +0000415 return false;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000416 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000417
Douglas Gregore495b7f2010-01-14 00:20:49 +0000418 // ... then it must be interesting!
419 return true;
420}
421
Douglas Gregor6660d842010-01-14 00:41:07 +0000422bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
423 NamedDecl *Hiding) {
424 // In C, there is no way to refer to a hidden name.
425 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
426 // name if we introduce the tag type.
427 if (!SemaRef.getLangOptions().CPlusPlus)
428 return true;
429
430 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext();
431
432 // There is no way to qualify a name declared in a function or method.
433 if (HiddenCtx->isFunctionOrMethod())
434 return true;
435
436 if (HiddenCtx == Hiding->getDeclContext()->getLookupContext())
437 return true;
438
439 // We can refer to the result with the appropriate qualification. Do it.
440 R.Hidden = true;
441 R.QualifierIsInformative = false;
442
443 if (!R.Qualifier)
444 R.Qualifier = getRequiredQualification(SemaRef.Context,
445 CurContext,
446 R.Declaration->getDeclContext());
447 return false;
448}
449
Douglas Gregore495b7f2010-01-14 00:20:49 +0000450void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
451 assert(!ShadowMaps.empty() && "Must enter into a results scope");
452
453 if (R.Kind != Result::RK_Declaration) {
454 // For non-declaration results, just add the result.
455 Results.push_back(R);
456 return;
457 }
458
459 // Look through using declarations.
460 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
461 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
462 return;
463 }
464
465 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
466 unsigned IDNS = CanonDecl->getIdentifierNamespace();
467
Douglas Gregor45bcd432010-01-14 03:21:49 +0000468 bool AsNestedNameSpecifier = false;
469 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000470 return;
471
Douglas Gregor86d9a522009-09-21 16:56:56 +0000472 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000473 ShadowMapEntry::iterator I, IEnd;
474 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
475 if (NamePos != SMap.end()) {
476 I = NamePos->second.begin();
477 IEnd = NamePos->second.end();
478 }
479
480 for (; I != IEnd; ++I) {
481 NamedDecl *ND = I->first;
482 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000483 if (ND->getCanonicalDecl() == CanonDecl) {
484 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000485 Results[Index].Declaration = R.Declaration;
486
Douglas Gregor86d9a522009-09-21 16:56:56 +0000487 // We're done.
488 return;
489 }
490 }
491
492 // This is a new declaration in this scope. However, check whether this
493 // declaration name is hidden by a similarly-named declaration in an outer
494 // scope.
495 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
496 --SMEnd;
497 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000498 ShadowMapEntry::iterator I, IEnd;
499 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
500 if (NamePos != SM->end()) {
501 I = NamePos->second.begin();
502 IEnd = NamePos->second.end();
503 }
504 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000505 // A tag declaration does not hide a non-tag declaration.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000506 if (I->first->getIdentifierNamespace() == Decl::IDNS_Tag &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000507 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
508 Decl::IDNS_ObjCProtocol)))
509 continue;
510
511 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000512 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000513 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000514 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000515 continue;
516
517 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000518 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000519 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000520
521 break;
522 }
523 }
524
525 // Make sure that any given declaration only shows up in the result set once.
526 if (!AllDeclsFound.insert(CanonDecl))
527 return;
528
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000529 // If the filter is for nested-name-specifiers, then this result starts a
530 // nested-name-specifier.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000531 if (AsNestedNameSpecifier)
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000532 R.StartsNestedNameSpecifier = true;
533
Douglas Gregor0563c262009-09-22 23:15:58 +0000534 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000535 if (R.QualifierIsInformative && !R.Qualifier &&
536 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000537 DeclContext *Ctx = R.Declaration->getDeclContext();
538 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
539 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
540 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
541 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
542 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
543 else
544 R.QualifierIsInformative = false;
545 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000546
Douglas Gregor86d9a522009-09-21 16:56:56 +0000547 // Insert this result into the set of results and into the current shadow
548 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000549 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000550 Results.push_back(R);
551}
552
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000553void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000554 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000555 if (R.Kind != Result::RK_Declaration) {
556 // For non-declaration results, just add the result.
557 Results.push_back(R);
558 return;
559 }
560
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000561 // Look through using declarations.
562 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
563 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
564 return;
565 }
566
Douglas Gregor45bcd432010-01-14 03:21:49 +0000567 bool AsNestedNameSpecifier = false;
568 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000569 return;
570
571 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
572 return;
573
574 // Make sure that any given declaration only shows up in the result set once.
575 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
576 return;
577
578 // If the filter is for nested-name-specifiers, then this result starts a
579 // nested-name-specifier.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000580 if (AsNestedNameSpecifier)
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000581 R.StartsNestedNameSpecifier = true;
Douglas Gregor0cc84042010-01-14 15:47:35 +0000582 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
583 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
584 ->getLookupContext()))
585 R.QualifierIsInformative = true;
586
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000587 // If this result is supposed to have an informative qualifier, add one.
588 if (R.QualifierIsInformative && !R.Qualifier &&
589 !R.StartsNestedNameSpecifier) {
590 DeclContext *Ctx = R.Declaration->getDeclContext();
591 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
592 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
593 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
594 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000595 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000596 else
597 R.QualifierIsInformative = false;
598 }
599
600 // Insert this result into the set of results.
601 Results.push_back(R);
602}
603
Douglas Gregora4477812010-01-14 16:01:26 +0000604void ResultBuilder::AddResult(Result R) {
605 assert(R.Kind != Result::RK_Declaration &&
606 "Declaration results need more context");
607 Results.push_back(R);
608}
609
Douglas Gregor86d9a522009-09-21 16:56:56 +0000610/// \brief Enter into a new scope.
611void ResultBuilder::EnterNewScope() {
612 ShadowMaps.push_back(ShadowMap());
613}
614
615/// \brief Exit from the current scope.
616void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000617 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
618 EEnd = ShadowMaps.back().end();
619 E != EEnd;
620 ++E)
621 E->second.Destroy();
622
Douglas Gregor86d9a522009-09-21 16:56:56 +0000623 ShadowMaps.pop_back();
624}
625
Douglas Gregor791215b2009-09-21 20:51:25 +0000626/// \brief Determines whether this given declaration will be found by
627/// ordinary name lookup.
628bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
629 unsigned IDNS = Decl::IDNS_Ordinary;
630 if (SemaRef.getLangOptions().CPlusPlus)
631 IDNS |= Decl::IDNS_Tag;
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000632 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
633 return true;
634
Douglas Gregor791215b2009-09-21 20:51:25 +0000635 return ND->getIdentifierNamespace() & IDNS;
636}
637
Douglas Gregor01dfea02010-01-10 23:08:15 +0000638/// \brief Determines whether this given declaration will be found by
639/// ordinary name lookup.
640bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
641 unsigned IDNS = Decl::IDNS_Ordinary;
642 if (SemaRef.getLangOptions().CPlusPlus)
643 IDNS |= Decl::IDNS_Tag;
644
645 return (ND->getIdentifierNamespace() & IDNS) &&
646 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND);
647}
648
Douglas Gregor86d9a522009-09-21 16:56:56 +0000649/// \brief Determines whether the given declaration is suitable as the
650/// start of a C++ nested-name-specifier, e.g., a class or namespace.
651bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
652 // Allow us to find class templates, too.
653 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
654 ND = ClassTemplate->getTemplatedDecl();
655
656 return SemaRef.isAcceptableNestedNameSpecifier(ND);
657}
658
659/// \brief Determines whether the given declaration is an enumeration.
660bool ResultBuilder::IsEnum(NamedDecl *ND) const {
661 return isa<EnumDecl>(ND);
662}
663
664/// \brief Determines whether the given declaration is a class or struct.
665bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
666 // Allow us to find class templates, too.
667 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
668 ND = ClassTemplate->getTemplatedDecl();
669
670 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
671 return RD->getTagKind() == TagDecl::TK_class ||
672 RD->getTagKind() == TagDecl::TK_struct;
673
674 return false;
675}
676
677/// \brief Determines whether the given declaration is a union.
678bool ResultBuilder::IsUnion(NamedDecl *ND) const {
679 // Allow us to find class templates, too.
680 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
681 ND = ClassTemplate->getTemplatedDecl();
682
683 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
684 return RD->getTagKind() == TagDecl::TK_union;
685
686 return false;
687}
688
689/// \brief Determines whether the given declaration is a namespace.
690bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
691 return isa<NamespaceDecl>(ND);
692}
693
694/// \brief Determines whether the given declaration is a namespace or
695/// namespace alias.
696bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
697 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
698}
699
Douglas Gregor76282942009-12-11 17:31:05 +0000700/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000701bool ResultBuilder::IsType(NamedDecl *ND) const {
702 return isa<TypeDecl>(ND);
703}
704
Douglas Gregor76282942009-12-11 17:31:05 +0000705/// \brief Determines which members of a class should be visible via
706/// "." or "->". Only value declarations, nested name specifiers, and
707/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000708bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +0000709 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
710 ND = Using->getTargetDecl();
711
Douglas Gregorce821962009-12-11 18:14:22 +0000712 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
713 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000714}
715
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000716/// \rief Determines whether the given declaration is an Objective-C
717/// instance variable.
718bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
719 return isa<ObjCIvarDecl>(ND);
720}
721
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000722namespace {
723 /// \brief Visible declaration consumer that adds a code-completion result
724 /// for each visible declaration.
725 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
726 ResultBuilder &Results;
727 DeclContext *CurContext;
728
729 public:
730 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
731 : Results(Results), CurContext(CurContext) { }
732
Douglas Gregor0cc84042010-01-14 15:47:35 +0000733 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
734 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000735 }
736 };
737}
738
Douglas Gregor86d9a522009-09-21 16:56:56 +0000739/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +0000740static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000741 ResultBuilder &Results) {
742 typedef CodeCompleteConsumer::Result Result;
Douglas Gregora4477812010-01-14 16:01:26 +0000743 Results.AddResult(Result("short"));
744 Results.AddResult(Result("long"));
745 Results.AddResult(Result("signed"));
746 Results.AddResult(Result("unsigned"));
747 Results.AddResult(Result("void"));
748 Results.AddResult(Result("char"));
749 Results.AddResult(Result("int"));
750 Results.AddResult(Result("float"));
751 Results.AddResult(Result("double"));
752 Results.AddResult(Result("enum"));
753 Results.AddResult(Result("struct"));
754 Results.AddResult(Result("union"));
755 Results.AddResult(Result("const"));
756 Results.AddResult(Result("volatile"));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000757
Douglas Gregor86d9a522009-09-21 16:56:56 +0000758 if (LangOpts.C99) {
759 // C99-specific
Douglas Gregora4477812010-01-14 16:01:26 +0000760 Results.AddResult(Result("_Complex"));
761 Results.AddResult(Result("_Imaginary"));
762 Results.AddResult(Result("_Bool"));
763 Results.AddResult(Result("restrict"));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000764 }
765
766 if (LangOpts.CPlusPlus) {
767 // C++-specific
Douglas Gregora4477812010-01-14 16:01:26 +0000768 Results.AddResult(Result("bool"));
769 Results.AddResult(Result("class"));
770 Results.AddResult(Result("wchar_t"));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000771
Douglas Gregor01dfea02010-01-10 23:08:15 +0000772 // typename qualified-id
773 CodeCompletionString *Pattern = new CodeCompletionString;
774 Pattern->AddTypedTextChunk("typename");
775 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
776 Pattern->AddPlaceholderChunk("qualified-id");
Douglas Gregora4477812010-01-14 16:01:26 +0000777 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000778
Douglas Gregor86d9a522009-09-21 16:56:56 +0000779 if (LangOpts.CPlusPlus0x) {
Douglas Gregora4477812010-01-14 16:01:26 +0000780 Results.AddResult(Result("auto"));
781 Results.AddResult(Result("char16_t"));
782 Results.AddResult(Result("char32_t"));
783 Results.AddResult(Result("decltype"));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000784 }
785 }
786
787 // GNU extensions
788 if (LangOpts.GNUMode) {
789 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +0000790 // Results.AddResult(Result("_Decimal32"));
791 // Results.AddResult(Result("_Decimal64"));
792 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000793
794 CodeCompletionString *Pattern = new CodeCompletionString;
795 Pattern->AddTypedTextChunk("typeof");
796 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
797 Pattern->AddPlaceholderChunk("expression-or-type");
798 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +0000799 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000800 }
801}
802
Douglas Gregor01dfea02010-01-10 23:08:15 +0000803static void AddStorageSpecifiers(Action::CodeCompletionContext CCC,
804 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +0000805 ResultBuilder &Results) {
806 typedef CodeCompleteConsumer::Result Result;
807 // Note: we don't suggest either "auto" or "register", because both
808 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
809 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +0000810 Results.AddResult(Result("extern"));
811 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000812}
813
814static void AddFunctionSpecifiers(Action::CodeCompletionContext CCC,
815 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +0000816 ResultBuilder &Results) {
817 typedef CodeCompleteConsumer::Result Result;
818 switch (CCC) {
819 case Action::CCC_Class:
820 case Action::CCC_MemberTemplate:
821 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +0000822 Results.AddResult(Result("explicit"));
823 Results.AddResult(Result("friend"));
824 Results.AddResult(Result("mutable"));
825 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000826 }
827 // Fall through
828
Douglas Gregorb6ac2452010-01-13 21:24:21 +0000829 case Action::CCC_ObjCInterface:
830 case Action::CCC_ObjCImplementation:
Douglas Gregor01dfea02010-01-10 23:08:15 +0000831 case Action::CCC_Namespace:
832 case Action::CCC_Template:
833 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +0000834 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000835 break;
836
Douglas Gregorc38c3e12010-01-13 21:54:15 +0000837 case Action::CCC_ObjCInstanceVariableList:
Douglas Gregor01dfea02010-01-10 23:08:15 +0000838 case Action::CCC_Expression:
839 case Action::CCC_Statement:
840 case Action::CCC_ForInit:
841 case Action::CCC_Condition:
842 break;
843 }
844}
845
Douglas Gregorbca403c2010-01-13 23:51:12 +0000846static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
847static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
848static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +0000849 ResultBuilder &Results,
850 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +0000851static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +0000852 ResultBuilder &Results,
853 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +0000854static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +0000855 ResultBuilder &Results,
856 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +0000857static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +0000858
Douglas Gregor01dfea02010-01-10 23:08:15 +0000859/// \brief Add language constructs that show up for "ordinary" names.
860static void AddOrdinaryNameResults(Action::CodeCompletionContext CCC,
861 Scope *S,
862 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +0000863 ResultBuilder &Results) {
864 typedef CodeCompleteConsumer::Result Result;
865 switch (CCC) {
866 case Action::CCC_Namespace:
867 if (SemaRef.getLangOptions().CPlusPlus) {
868 // namespace <identifier> { }
869 CodeCompletionString *Pattern = new CodeCompletionString;
870 Pattern->AddTypedTextChunk("namespace");
871 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
872 Pattern->AddPlaceholderChunk("identifier");
873 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
874 Pattern->AddPlaceholderChunk("declarations");
875 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
876 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +0000877 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000878
879 // namespace identifier = identifier ;
880 Pattern = new CodeCompletionString;
881 Pattern->AddTypedTextChunk("namespace");
882 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
883 Pattern->AddPlaceholderChunk("identifier");
884 Pattern->AddChunk(CodeCompletionString::CK_Equal);
885 Pattern->AddPlaceholderChunk("identifier");
886 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +0000887 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000888
889 // Using directives
890 Pattern = new CodeCompletionString;
891 Pattern->AddTypedTextChunk("using");
892 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
893 Pattern->AddTextChunk("namespace");
894 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
895 Pattern->AddPlaceholderChunk("identifier");
896 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +0000897 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000898
899 // asm(string-literal)
900 Pattern = new CodeCompletionString;
901 Pattern->AddTypedTextChunk("asm");
902 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
903 Pattern->AddPlaceholderChunk("string-literal");
904 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
905 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +0000906 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000907
908 // Explicit template instantiation
909 Pattern = new CodeCompletionString;
910 Pattern->AddTypedTextChunk("template");
911 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
912 Pattern->AddPlaceholderChunk("declaration");
913 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +0000914 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000915 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +0000916
917 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +0000918 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +0000919
Douglas Gregor01dfea02010-01-10 23:08:15 +0000920 // Fall through
921
922 case Action::CCC_Class:
Douglas Gregora4477812010-01-14 16:01:26 +0000923 Results.AddResult(Result("typedef"));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000924 if (SemaRef.getLangOptions().CPlusPlus) {
925 // Using declaration
926 CodeCompletionString *Pattern = new CodeCompletionString;
927 Pattern->AddTypedTextChunk("using");
928 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
929 Pattern->AddPlaceholderChunk("qualified-id");
930 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +0000931 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000932
933 // using typename qualified-id; (only in a dependent context)
934 if (SemaRef.CurContext->isDependentContext()) {
935 Pattern = new CodeCompletionString;
936 Pattern->AddTypedTextChunk("using");
937 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
938 Pattern->AddTextChunk("typename");
939 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
940 Pattern->AddPlaceholderChunk("qualified-id");
941 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +0000942 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000943 }
944
945 if (CCC == Action::CCC_Class) {
946 // public:
947 Pattern = new CodeCompletionString;
948 Pattern->AddTypedTextChunk("public");
949 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +0000950 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000951
952 // protected:
953 Pattern = new CodeCompletionString;
954 Pattern->AddTypedTextChunk("protected");
955 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +0000956 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000957
958 // private:
959 Pattern = new CodeCompletionString;
960 Pattern->AddTypedTextChunk("private");
961 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +0000962 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000963 }
964 }
965 // Fall through
966
967 case Action::CCC_Template:
968 case Action::CCC_MemberTemplate:
969 if (SemaRef.getLangOptions().CPlusPlus) {
970 // template < parameters >
971 CodeCompletionString *Pattern = new CodeCompletionString;
972 Pattern->AddTypedTextChunk("template");
973 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
974 Pattern->AddPlaceholderChunk("parameters");
975 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregora4477812010-01-14 16:01:26 +0000976 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000977 }
978
Douglas Gregorbca403c2010-01-13 23:51:12 +0000979 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
980 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +0000981 break;
982
Douglas Gregorb6ac2452010-01-13 21:24:21 +0000983 case Action::CCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +0000984 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
985 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
986 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +0000987 break;
988
989 case Action::CCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +0000990 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
991 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
992 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +0000993 break;
994
Douglas Gregorc38c3e12010-01-13 21:54:15 +0000995 case Action::CCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +0000996 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +0000997 break;
998
Douglas Gregor01dfea02010-01-10 23:08:15 +0000999 case Action::CCC_Statement: {
Douglas Gregora4477812010-01-14 16:01:26 +00001000 Results.AddResult(Result("typedef"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001001
1002 CodeCompletionString *Pattern = 0;
1003 if (SemaRef.getLangOptions().CPlusPlus) {
1004 Pattern = new CodeCompletionString;
1005 Pattern->AddTypedTextChunk("try");
1006 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1007 Pattern->AddPlaceholderChunk("statements");
1008 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1009 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1010 Pattern->AddTextChunk("catch");
1011 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1012 Pattern->AddPlaceholderChunk("declaration");
1013 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1014 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1015 Pattern->AddPlaceholderChunk("statements");
1016 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1017 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001018 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001019 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001020 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001021 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001022
Douglas Gregor01dfea02010-01-10 23:08:15 +00001023 // if (condition) { statements }
1024 Pattern = new CodeCompletionString;
1025 Pattern->AddTypedTextChunk("if");
1026 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1027 if (SemaRef.getLangOptions().CPlusPlus)
1028 Pattern->AddPlaceholderChunk("condition");
1029 else
1030 Pattern->AddPlaceholderChunk("expression");
1031 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1032 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1033 Pattern->AddPlaceholderChunk("statements");
1034 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1035 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001036 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001037
1038 // switch (condition) { }
1039 Pattern = new CodeCompletionString;
1040 Pattern->AddTypedTextChunk("switch");
1041 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1042 if (SemaRef.getLangOptions().CPlusPlus)
1043 Pattern->AddPlaceholderChunk("condition");
1044 else
1045 Pattern->AddPlaceholderChunk("expression");
1046 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1047 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1048 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1049 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001050 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001051
1052 // Switch-specific statements.
1053 if (!SemaRef.getSwitchStack().empty()) {
1054 // case expression:
1055 Pattern = new CodeCompletionString;
1056 Pattern->AddTypedTextChunk("case");
1057 Pattern->AddPlaceholderChunk("expression");
1058 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001059 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001060
1061 // default:
1062 Pattern = new CodeCompletionString;
1063 Pattern->AddTypedTextChunk("default");
1064 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001065 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001066 }
1067
1068 /// while (condition) { statements }
1069 Pattern = new CodeCompletionString;
1070 Pattern->AddTypedTextChunk("while");
1071 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1072 if (SemaRef.getLangOptions().CPlusPlus)
1073 Pattern->AddPlaceholderChunk("condition");
1074 else
1075 Pattern->AddPlaceholderChunk("expression");
1076 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1077 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1078 Pattern->AddPlaceholderChunk("statements");
1079 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1080 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001081 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001082
1083 // do { statements } while ( expression );
1084 Pattern = new CodeCompletionString;
1085 Pattern->AddTypedTextChunk("do");
1086 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1087 Pattern->AddPlaceholderChunk("statements");
1088 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1089 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1090 Pattern->AddTextChunk("while");
1091 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1092 Pattern->AddPlaceholderChunk("expression");
1093 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1094 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +00001095 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001096
1097 // for ( for-init-statement ; condition ; expression ) { statements }
1098 Pattern = new CodeCompletionString;
1099 Pattern->AddTypedTextChunk("for");
1100 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1101 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1102 Pattern->AddPlaceholderChunk("init-statement");
1103 else
1104 Pattern->AddPlaceholderChunk("init-expression");
1105 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1106 Pattern->AddPlaceholderChunk("condition");
1107 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1108 Pattern->AddPlaceholderChunk("inc-expression");
1109 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1110 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1111 Pattern->AddPlaceholderChunk("statements");
1112 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1113 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001114 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001115
1116 if (S->getContinueParent()) {
1117 // continue ;
1118 Pattern = new CodeCompletionString;
1119 Pattern->AddTypedTextChunk("continue");
1120 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +00001121 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001122 }
1123
1124 if (S->getBreakParent()) {
1125 // break ;
1126 Pattern = new CodeCompletionString;
1127 Pattern->AddTypedTextChunk("break");
1128 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +00001129 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001130 }
1131
1132 // "return expression ;" or "return ;", depending on whether we
1133 // know the function is void or not.
1134 bool isVoid = false;
1135 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1136 isVoid = Function->getResultType()->isVoidType();
1137 else if (ObjCMethodDecl *Method
1138 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1139 isVoid = Method->getResultType()->isVoidType();
1140 else if (SemaRef.CurBlock && !SemaRef.CurBlock->ReturnType.isNull())
1141 isVoid = SemaRef.CurBlock->ReturnType->isVoidType();
1142 Pattern = new CodeCompletionString;
1143 Pattern->AddTypedTextChunk("return");
1144 if (!isVoid)
1145 Pattern->AddPlaceholderChunk("expression");
1146 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +00001147 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001148
1149 // goto identifier ;
1150 Pattern = new CodeCompletionString;
1151 Pattern->AddTypedTextChunk("goto");
1152 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1153 Pattern->AddPlaceholderChunk("identifier");
1154 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +00001155 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001156
1157 // Using directives
1158 Pattern = new CodeCompletionString;
1159 Pattern->AddTypedTextChunk("using");
1160 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1161 Pattern->AddTextChunk("namespace");
1162 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1163 Pattern->AddPlaceholderChunk("identifier");
1164 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +00001165 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001166 }
1167
1168 // Fall through (for statement expressions).
1169 case Action::CCC_ForInit:
1170 case Action::CCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001171 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001172 // Fall through: conditions and statements can have expressions.
1173
1174 case Action::CCC_Expression: {
1175 CodeCompletionString *Pattern = 0;
1176 if (SemaRef.getLangOptions().CPlusPlus) {
1177 // 'this', if we're in a non-static member function.
1178 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1179 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001180 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001181
1182 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001183 Results.AddResult(Result("true"));
1184 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001185
1186 // dynamic_cast < type-id > ( expression )
1187 Pattern = new CodeCompletionString;
1188 Pattern->AddTypedTextChunk("dynamic_cast");
1189 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1190 Pattern->AddPlaceholderChunk("type-id");
1191 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1192 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1193 Pattern->AddPlaceholderChunk("expression");
1194 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001195 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001196
1197 // static_cast < type-id > ( expression )
1198 Pattern = new CodeCompletionString;
1199 Pattern->AddTypedTextChunk("static_cast");
1200 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1201 Pattern->AddPlaceholderChunk("type-id");
1202 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1203 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1204 Pattern->AddPlaceholderChunk("expression");
1205 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001206 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001207
1208 // reinterpret_cast < type-id > ( expression )
1209 Pattern = new CodeCompletionString;
1210 Pattern->AddTypedTextChunk("reinterpret_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);
Douglas Gregora4477812010-01-14 16:01:26 +00001217 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001218
1219 // const_cast < type-id > ( expression )
1220 Pattern = new CodeCompletionString;
1221 Pattern->AddTypedTextChunk("const_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);
Douglas Gregora4477812010-01-14 16:01:26 +00001228 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001229
1230 // typeid ( expression-or-type )
1231 Pattern = new CodeCompletionString;
1232 Pattern->AddTypedTextChunk("typeid");
1233 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1234 Pattern->AddPlaceholderChunk("expression-or-type");
1235 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001236 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001237
1238 // new T ( ... )
1239 Pattern = new CodeCompletionString;
1240 Pattern->AddTypedTextChunk("new");
1241 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1242 Pattern->AddPlaceholderChunk("type-id");
1243 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1244 Pattern->AddPlaceholderChunk("expressions");
1245 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001246 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001247
1248 // new T [ ] ( ... )
1249 Pattern = new CodeCompletionString;
1250 Pattern->AddTypedTextChunk("new");
1251 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1252 Pattern->AddPlaceholderChunk("type-id");
1253 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1254 Pattern->AddPlaceholderChunk("size");
1255 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1256 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1257 Pattern->AddPlaceholderChunk("expressions");
1258 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001259 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001260
1261 // delete expression
1262 Pattern = new CodeCompletionString;
1263 Pattern->AddTypedTextChunk("delete");
1264 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1265 Pattern->AddPlaceholderChunk("expression");
Douglas Gregora4477812010-01-14 16:01:26 +00001266 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001267
1268 // delete [] expression
1269 Pattern = new CodeCompletionString;
1270 Pattern->AddTypedTextChunk("delete");
1271 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1272 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1273 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1274 Pattern->AddPlaceholderChunk("expression");
Douglas Gregora4477812010-01-14 16:01:26 +00001275 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001276
1277 // throw expression
1278 Pattern = new CodeCompletionString;
1279 Pattern->AddTypedTextChunk("throw");
1280 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1281 Pattern->AddPlaceholderChunk("expression");
Douglas Gregora4477812010-01-14 16:01:26 +00001282 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001283 }
1284
1285 if (SemaRef.getLangOptions().ObjC1) {
1286 // Add "super", if we're in an Objective-C class with a superclass.
1287 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
1288 if (Method->getClassInterface()->getSuperClass())
Douglas Gregora4477812010-01-14 16:01:26 +00001289 Results.AddResult(Result("super"));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001290
Douglas Gregorbca403c2010-01-13 23:51:12 +00001291 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001292 }
1293
1294 // sizeof expression
1295 Pattern = new CodeCompletionString;
1296 Pattern->AddTypedTextChunk("sizeof");
1297 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1298 Pattern->AddPlaceholderChunk("expression-or-type");
1299 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001300 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001301 break;
1302 }
1303 }
1304
Douglas Gregorbca403c2010-01-13 23:51:12 +00001305 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001306
1307 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregora4477812010-01-14 16:01:26 +00001308 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001309}
1310
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001311/// \brief If the given declaration has an associated type, add it as a result
1312/// type chunk.
1313static void AddResultTypeChunk(ASTContext &Context,
1314 NamedDecl *ND,
1315 CodeCompletionString *Result) {
1316 if (!ND)
1317 return;
1318
1319 // Determine the type of the declaration (if it has a type).
1320 QualType T;
1321 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1322 T = Function->getResultType();
1323 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1324 T = Method->getResultType();
1325 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1326 T = FunTmpl->getTemplatedDecl()->getResultType();
1327 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1328 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1329 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1330 /* Do nothing: ignore unresolved using declarations*/
1331 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1332 T = Value->getType();
1333 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1334 T = Property->getType();
1335
1336 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1337 return;
1338
1339 std::string TypeStr;
1340 T.getAsStringInternal(TypeStr, Context.PrintingPolicy);
1341 Result->AddResultTypeChunk(TypeStr);
1342}
1343
Douglas Gregor86d9a522009-09-21 16:56:56 +00001344/// \brief Add function parameter chunks to the given code completion string.
1345static void AddFunctionParameterChunks(ASTContext &Context,
1346 FunctionDecl *Function,
1347 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001348 typedef CodeCompletionString::Chunk Chunk;
1349
Douglas Gregor86d9a522009-09-21 16:56:56 +00001350 CodeCompletionString *CCStr = Result;
1351
1352 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1353 ParmVarDecl *Param = Function->getParamDecl(P);
1354
1355 if (Param->hasDefaultArg()) {
1356 // When we see an optional default argument, put that argument and
1357 // the remaining default arguments into a new, optional string.
1358 CodeCompletionString *Opt = new CodeCompletionString;
1359 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1360 CCStr = Opt;
1361 }
1362
1363 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001364 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001365
1366 // Format the placeholder string.
1367 std::string PlaceholderStr;
1368 if (Param->getIdentifier())
1369 PlaceholderStr = Param->getIdentifier()->getName();
1370
1371 Param->getType().getAsStringInternal(PlaceholderStr,
1372 Context.PrintingPolicy);
1373
1374 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001375 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001376 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00001377
1378 if (const FunctionProtoType *Proto
1379 = Function->getType()->getAs<FunctionProtoType>())
1380 if (Proto->isVariadic())
1381 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-09-21 16:56:56 +00001382}
1383
1384/// \brief Add template parameter chunks to the given code completion string.
1385static void AddTemplateParameterChunks(ASTContext &Context,
1386 TemplateDecl *Template,
1387 CodeCompletionString *Result,
1388 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001389 typedef CodeCompletionString::Chunk Chunk;
1390
Douglas Gregor86d9a522009-09-21 16:56:56 +00001391 CodeCompletionString *CCStr = Result;
1392 bool FirstParameter = true;
1393
1394 TemplateParameterList *Params = Template->getTemplateParameters();
1395 TemplateParameterList::iterator PEnd = Params->end();
1396 if (MaxParameters)
1397 PEnd = Params->begin() + MaxParameters;
1398 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1399 bool HasDefaultArg = false;
1400 std::string PlaceholderStr;
1401 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1402 if (TTP->wasDeclaredWithTypename())
1403 PlaceholderStr = "typename";
1404 else
1405 PlaceholderStr = "class";
1406
1407 if (TTP->getIdentifier()) {
1408 PlaceholderStr += ' ';
1409 PlaceholderStr += TTP->getIdentifier()->getName();
1410 }
1411
1412 HasDefaultArg = TTP->hasDefaultArgument();
1413 } else if (NonTypeTemplateParmDecl *NTTP
1414 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1415 if (NTTP->getIdentifier())
1416 PlaceholderStr = NTTP->getIdentifier()->getName();
1417 NTTP->getType().getAsStringInternal(PlaceholderStr,
1418 Context.PrintingPolicy);
1419 HasDefaultArg = NTTP->hasDefaultArgument();
1420 } else {
1421 assert(isa<TemplateTemplateParmDecl>(*P));
1422 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1423
1424 // Since putting the template argument list into the placeholder would
1425 // be very, very long, we just use an abbreviation.
1426 PlaceholderStr = "template<...> class";
1427 if (TTP->getIdentifier()) {
1428 PlaceholderStr += ' ';
1429 PlaceholderStr += TTP->getIdentifier()->getName();
1430 }
1431
1432 HasDefaultArg = TTP->hasDefaultArgument();
1433 }
1434
1435 if (HasDefaultArg) {
1436 // When we see an optional default argument, put that argument and
1437 // the remaining default arguments into a new, optional string.
1438 CodeCompletionString *Opt = new CodeCompletionString;
1439 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1440 CCStr = Opt;
1441 }
1442
1443 if (FirstParameter)
1444 FirstParameter = false;
1445 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001446 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001447
1448 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001449 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001450 }
1451}
1452
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001453/// \brief Add a qualifier to the given code-completion string, if the
1454/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00001455static void
1456AddQualifierToCompletionString(CodeCompletionString *Result,
1457 NestedNameSpecifier *Qualifier,
1458 bool QualifierIsInformative,
1459 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001460 if (!Qualifier)
1461 return;
1462
1463 std::string PrintedNNS;
1464 {
1465 llvm::raw_string_ostream OS(PrintedNNS);
1466 Qualifier->print(OS, Context.PrintingPolicy);
1467 }
Douglas Gregor0563c262009-09-22 23:15:58 +00001468 if (QualifierIsInformative)
Benjamin Kramer660cc182009-11-29 20:18:50 +00001469 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor0563c262009-09-22 23:15:58 +00001470 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00001471 Result->AddTextChunk(PrintedNNS);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001472}
1473
Douglas Gregora61a8792009-12-11 18:44:16 +00001474static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1475 FunctionDecl *Function) {
1476 const FunctionProtoType *Proto
1477 = Function->getType()->getAs<FunctionProtoType>();
1478 if (!Proto || !Proto->getTypeQuals())
1479 return;
1480
1481 std::string QualsStr;
1482 if (Proto->getTypeQuals() & Qualifiers::Const)
1483 QualsStr += " const";
1484 if (Proto->getTypeQuals() & Qualifiers::Volatile)
1485 QualsStr += " volatile";
1486 if (Proto->getTypeQuals() & Qualifiers::Restrict)
1487 QualsStr += " restrict";
1488 Result->AddInformativeChunk(QualsStr);
1489}
1490
Douglas Gregor86d9a522009-09-21 16:56:56 +00001491/// \brief If possible, create a new code completion string for the given
1492/// result.
1493///
1494/// \returns Either a new, heap-allocated code completion string describing
1495/// how to use this result, or NULL to indicate that the string or name of the
1496/// result is all that is needed.
1497CodeCompletionString *
1498CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001499 typedef CodeCompletionString::Chunk Chunk;
1500
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001501 if (Kind == RK_Pattern)
1502 return Pattern->Clone();
1503
1504 CodeCompletionString *Result = new CodeCompletionString;
1505
1506 if (Kind == RK_Keyword) {
1507 Result->AddTypedTextChunk(Keyword);
1508 return Result;
1509 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001510
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001511 if (Kind == RK_Macro) {
1512 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001513 assert(MI && "Not a macro?");
1514
1515 Result->AddTypedTextChunk(Macro->getName());
1516
1517 if (!MI->isFunctionLike())
1518 return Result;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001519
1520 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001521 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001522 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
1523 A != AEnd; ++A) {
1524 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001525 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001526
1527 if (!MI->isVariadic() || A != AEnd - 1) {
1528 // Non-variadic argument.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001529 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001530 continue;
1531 }
1532
1533 // Variadic argument; cope with the different between GNU and C99
1534 // variadic macros, providing a single placeholder for the rest of the
1535 // arguments.
1536 if ((*A)->isStr("__VA_ARGS__"))
1537 Result->AddPlaceholderChunk("...");
1538 else {
1539 std::string Arg = (*A)->getName();
1540 Arg += "...";
Benjamin Kramer660cc182009-11-29 20:18:50 +00001541 Result->AddPlaceholderChunk(Arg);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001542 }
1543 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001544 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001545 return Result;
1546 }
1547
1548 assert(Kind == RK_Declaration && "Missed a macro kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00001549 NamedDecl *ND = Declaration;
1550
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001551 if (StartsNestedNameSpecifier) {
Benjamin Kramer660cc182009-11-29 20:18:50 +00001552 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001553 Result->AddTextChunk("::");
1554 return Result;
1555 }
1556
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001557 AddResultTypeChunk(S.Context, ND, Result);
1558
Douglas Gregor86d9a522009-09-21 16:56:56 +00001559 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001560 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1561 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00001562 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001563 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001564 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001565 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00001566 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001567 return Result;
1568 }
1569
1570 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001571 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1572 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001573 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramer660cc182009-11-29 20:18:50 +00001574 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001575
1576 // Figure out which template parameters are deduced (or have default
1577 // arguments).
1578 llvm::SmallVector<bool, 16> Deduced;
1579 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
1580 unsigned LastDeducibleArgument;
1581 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
1582 --LastDeducibleArgument) {
1583 if (!Deduced[LastDeducibleArgument - 1]) {
1584 // C++0x: Figure out if the template argument has a default. If so,
1585 // the user doesn't need to type this argument.
1586 // FIXME: We need to abstract template parameters better!
1587 bool HasDefaultArg = false;
1588 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
1589 LastDeducibleArgument - 1);
1590 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1591 HasDefaultArg = TTP->hasDefaultArgument();
1592 else if (NonTypeTemplateParmDecl *NTTP
1593 = dyn_cast<NonTypeTemplateParmDecl>(Param))
1594 HasDefaultArg = NTTP->hasDefaultArgument();
1595 else {
1596 assert(isa<TemplateTemplateParmDecl>(Param));
1597 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001598 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001599 }
1600
1601 if (!HasDefaultArg)
1602 break;
1603 }
1604 }
1605
1606 if (LastDeducibleArgument) {
1607 // Some of the function template arguments cannot be deduced from a
1608 // function call, so we introduce an explicit template argument list
1609 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001610 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001611 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
1612 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001613 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001614 }
1615
1616 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001617 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001618 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001619 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00001620 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001621 return Result;
1622 }
1623
1624 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001625 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1626 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00001627 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001628 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001629 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001630 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001631 return Result;
1632 }
1633
Douglas Gregor9630eb62009-11-17 16:44:22 +00001634 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00001635 Selector Sel = Method->getSelector();
1636 if (Sel.isUnarySelector()) {
1637 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
1638 return Result;
1639 }
1640
Douglas Gregord3c68542009-11-19 01:08:35 +00001641 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
1642 SelName += ':';
1643 if (StartParameter == 0)
1644 Result->AddTypedTextChunk(SelName);
1645 else {
1646 Result->AddInformativeChunk(SelName);
1647
1648 // If there is only one parameter, and we're past it, add an empty
1649 // typed-text chunk since there is nothing to type.
1650 if (Method->param_size() == 1)
1651 Result->AddTypedTextChunk("");
1652 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00001653 unsigned Idx = 0;
1654 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
1655 PEnd = Method->param_end();
1656 P != PEnd; (void)++P, ++Idx) {
1657 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00001658 std::string Keyword;
1659 if (Idx > StartParameter)
Douglas Gregor834389b2010-01-12 06:38:28 +00001660 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001661 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
1662 Keyword += II->getName().str();
1663 Keyword += ":";
Douglas Gregor4ad96852009-11-19 07:41:15 +00001664 if (Idx < StartParameter || AllParametersAreInformative) {
Douglas Gregord3c68542009-11-19 01:08:35 +00001665 Result->AddInformativeChunk(Keyword);
1666 } else if (Idx == StartParameter)
1667 Result->AddTypedTextChunk(Keyword);
1668 else
1669 Result->AddTextChunk(Keyword);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001670 }
Douglas Gregord3c68542009-11-19 01:08:35 +00001671
1672 // If we're before the starting parameter, skip the placeholder.
1673 if (Idx < StartParameter)
1674 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00001675
1676 std::string Arg;
1677 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
1678 Arg = "(" + Arg + ")";
1679 if (IdentifierInfo *II = (*P)->getIdentifier())
1680 Arg += II->getName().str();
Douglas Gregor4ad96852009-11-19 07:41:15 +00001681 if (AllParametersAreInformative)
1682 Result->AddInformativeChunk(Arg);
1683 else
1684 Result->AddPlaceholderChunk(Arg);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001685 }
1686
Douglas Gregor2a17af02009-12-23 00:21:46 +00001687 if (Method->isVariadic()) {
1688 if (AllParametersAreInformative)
1689 Result->AddInformativeChunk(", ...");
1690 else
1691 Result->AddPlaceholderChunk(", ...");
1692 }
1693
Douglas Gregor9630eb62009-11-17 16:44:22 +00001694 return Result;
1695 }
1696
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001697 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00001698 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1699 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001700
1701 Result->AddTypedTextChunk(ND->getNameAsString());
1702 return Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001703}
1704
Douglas Gregor86d802e2009-09-23 00:34:09 +00001705CodeCompletionString *
1706CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
1707 unsigned CurrentArg,
1708 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001709 typedef CodeCompletionString::Chunk Chunk;
1710
Douglas Gregor86d802e2009-09-23 00:34:09 +00001711 CodeCompletionString *Result = new CodeCompletionString;
1712 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001713 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00001714 const FunctionProtoType *Proto
1715 = dyn_cast<FunctionProtoType>(getFunctionType());
1716 if (!FDecl && !Proto) {
1717 // Function without a prototype. Just give the return type and a
1718 // highlighted ellipsis.
1719 const FunctionType *FT = getFunctionType();
1720 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00001721 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001722 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1723 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1724 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001725 return Result;
1726 }
1727
1728 if (FDecl)
Benjamin Kramer660cc182009-11-29 20:18:50 +00001729 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregor86d802e2009-09-23 00:34:09 +00001730 else
1731 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00001732 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001733
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001734 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001735 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
1736 for (unsigned I = 0; I != NumParams; ++I) {
1737 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001738 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001739
1740 std::string ArgString;
1741 QualType ArgType;
1742
1743 if (FDecl) {
1744 ArgString = FDecl->getParamDecl(I)->getNameAsString();
1745 ArgType = FDecl->getParamDecl(I)->getOriginalType();
1746 } else {
1747 ArgType = Proto->getArgType(I);
1748 }
1749
1750 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
1751
1752 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001753 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramer660cc182009-11-29 20:18:50 +00001754 ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001755 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00001756 Result->AddTextChunk(ArgString);
Douglas Gregor86d802e2009-09-23 00:34:09 +00001757 }
1758
1759 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001760 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001761 if (CurrentArg < NumParams)
1762 Result->AddTextChunk("...");
1763 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001764 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001765 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001766 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00001767
1768 return Result;
1769}
1770
Douglas Gregor86d9a522009-09-21 16:56:56 +00001771namespace {
1772 struct SortCodeCompleteResult {
1773 typedef CodeCompleteConsumer::Result Result;
1774
Douglas Gregor6a684032009-09-28 03:51:44 +00001775 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregor2b0cc122009-12-05 09:08:56 +00001776 Selector XSel = X.getObjCSelector();
1777 Selector YSel = Y.getObjCSelector();
1778 if (!XSel.isNull() && !YSel.isNull()) {
1779 // We are comparing two selectors.
1780 unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
1781 if (N == 0)
1782 ++N;
1783 for (unsigned I = 0; I != N; ++I) {
1784 IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
1785 IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
1786 if (!XId || !YId)
1787 return XId && !YId;
1788
1789 switch (XId->getName().compare_lower(YId->getName())) {
1790 case -1: return true;
1791 case 1: return false;
1792 default: break;
1793 }
1794 }
1795
1796 return XSel.getNumArgs() < YSel.getNumArgs();
1797 }
1798
1799 // For non-selectors, order by kind.
1800 if (X.getNameKind() != Y.getNameKind())
Douglas Gregor6a684032009-09-28 03:51:44 +00001801 return X.getNameKind() < Y.getNameKind();
1802
Douglas Gregor2b0cc122009-12-05 09:08:56 +00001803 // Order identifiers by comparison of their lowercased names.
1804 if (IdentifierInfo *XId = X.getAsIdentifierInfo())
1805 return XId->getName().compare_lower(
1806 Y.getAsIdentifierInfo()->getName()) < 0;
1807
1808 // Order overloaded operators by the order in which they appear
1809 // in our list of operators.
1810 if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
1811 return XOp < Y.getCXXOverloadedOperator();
1812
1813 // Order C++0x user-defined literal operators lexically by their
1814 // lowercased suffixes.
1815 if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
1816 return XLit->getName().compare_lower(
1817 Y.getCXXLiteralIdentifier()->getName()) < 0;
1818
1819 // The only stable ordering we have is to turn the name into a
1820 // string and then compare the lower-case strings. This is
1821 // inefficient, but thankfully does not happen too often.
Benjamin Kramer0e7049f2009-12-05 10:22:15 +00001822 return llvm::StringRef(X.getAsString()).compare_lower(
1823 Y.getAsString()) < 0;
Douglas Gregor6a684032009-09-28 03:51:44 +00001824 }
1825
Douglas Gregorab0b4f12010-01-13 23:24:38 +00001826 /// \brief Retrieve the name that should be used to order a result.
1827 ///
1828 /// If the name needs to be constructed as a string, that string will be
1829 /// saved into Saved and the returned StringRef will refer to it.
1830 static llvm::StringRef getOrderedName(const Result &R,
1831 std::string &Saved) {
1832 switch (R.Kind) {
1833 case Result::RK_Keyword:
1834 return R.Keyword;
1835
1836 case Result::RK_Pattern:
1837 return R.Pattern->getTypedText();
1838
1839 case Result::RK_Macro:
1840 return R.Macro->getName();
1841
1842 case Result::RK_Declaration:
1843 // Handle declarations below.
1844 break;
Douglas Gregor54f01612009-11-19 00:01:57 +00001845 }
Douglas Gregorab0b4f12010-01-13 23:24:38 +00001846
1847 DeclarationName Name = R.Declaration->getDeclName();
Douglas Gregor54f01612009-11-19 00:01:57 +00001848
Douglas Gregorab0b4f12010-01-13 23:24:38 +00001849 // If the name is a simple identifier (by far the common case), or a
1850 // zero-argument selector, just return a reference to that identifier.
1851 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
1852 return Id->getName();
1853 if (Name.isObjCZeroArgSelector())
1854 if (IdentifierInfo *Id
1855 = Name.getObjCSelector().getIdentifierInfoForSlot(0))
1856 return Id->getName();
1857
1858 Saved = Name.getAsString();
1859 return Saved;
1860 }
1861
1862 bool operator()(const Result &X, const Result &Y) const {
1863 std::string XSaved, YSaved;
1864 llvm::StringRef XStr = getOrderedName(X, XSaved);
1865 llvm::StringRef YStr = getOrderedName(Y, YSaved);
1866 int cmp = XStr.compare_lower(YStr);
1867 if (cmp)
1868 return cmp < 0;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001869
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 return false;
1879 }
1880 };
1881}
1882
Douglas Gregorbca403c2010-01-13 23:51:12 +00001883static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001884 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001885 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1886 MEnd = PP.macro_end();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001887 M != MEnd; ++M)
Douglas Gregora4477812010-01-14 16:01:26 +00001888 Results.AddResult(M->first);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001889 Results.ExitScope();
1890}
1891
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001892static void HandleCodeCompleteResults(Sema *S,
1893 CodeCompleteConsumer *CodeCompleter,
1894 CodeCompleteConsumer::Result *Results,
1895 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00001896 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1897
1898 if (CodeCompleter)
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001899 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00001900
1901 for (unsigned I = 0; I != NumResults; ++I)
1902 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001903}
1904
Douglas Gregor01dfea02010-01-10 23:08:15 +00001905void Sema::CodeCompleteOrdinaryName(Scope *S,
1906 CodeCompletionContext CompletionContext) {
Douglas Gregor2a7925c2009-12-07 09:54:55 +00001907 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001908 ResultBuilder Results(*this);
1909
1910 // Determine how to filter results, e.g., so that the names of
1911 // values (functions, enumerators, function templates, etc.) are
1912 // only allowed where we can have an expression.
1913 switch (CompletionContext) {
1914 case CCC_Namespace:
1915 case CCC_Class:
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001916 case CCC_ObjCInterface:
1917 case CCC_ObjCImplementation:
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001918 case CCC_ObjCInstanceVariableList:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001919 case CCC_Template:
1920 case CCC_MemberTemplate:
1921 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
1922 break;
1923
1924 case CCC_Expression:
1925 case CCC_Statement:
1926 case CCC_ForInit:
1927 case CCC_Condition:
1928 Results.setFilter(&ResultBuilder::IsOrdinaryName);
1929 break;
1930 }
1931
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001932 CodeCompletionDeclConsumer Consumer(Results, CurContext);
1933 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00001934
1935 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00001936 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00001937 Results.ExitScope();
1938
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001939 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00001940 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00001941 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00001942}
1943
Douglas Gregor95ac6552009-11-18 01:29:26 +00001944static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00001945 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00001946 DeclContext *CurContext,
1947 ResultBuilder &Results) {
1948 typedef CodeCompleteConsumer::Result Result;
1949
1950 // Add properties in this container.
1951 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
1952 PEnd = Container->prop_end();
1953 P != PEnd;
1954 ++P)
1955 Results.MaybeAddResult(Result(*P, 0), CurContext);
1956
1957 // Add properties in referenced protocols.
1958 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
1959 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
1960 PEnd = Protocol->protocol_end();
1961 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00001962 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001963 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00001964 if (AllowCategories) {
1965 // Look through categories.
1966 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
1967 Category; Category = Category->getNextClassCategory())
1968 AddObjCProperties(Category, AllowCategories, CurContext, Results);
1969 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00001970
1971 // Look through protocols.
1972 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
1973 E = IFace->protocol_end();
1974 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00001975 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001976
1977 // Look in the superclass.
1978 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00001979 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
1980 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001981 } else if (const ObjCCategoryDecl *Category
1982 = dyn_cast<ObjCCategoryDecl>(Container)) {
1983 // Look through protocols.
1984 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
1985 PEnd = Category->protocol_end();
1986 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00001987 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00001988 }
1989}
1990
Douglas Gregor81b747b2009-09-17 21:32:03 +00001991void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1992 SourceLocation OpLoc,
1993 bool IsArrow) {
1994 if (!BaseE || !CodeCompleter)
1995 return;
1996
Douglas Gregor86d9a522009-09-21 16:56:56 +00001997 typedef CodeCompleteConsumer::Result Result;
1998
Douglas Gregor81b747b2009-09-17 21:32:03 +00001999 Expr *Base = static_cast<Expr *>(BaseE);
2000 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002001
2002 if (IsArrow) {
2003 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2004 BaseType = Ptr->getPointeeType();
2005 else if (BaseType->isObjCObjectPointerType())
2006 /*Do nothing*/ ;
2007 else
2008 return;
2009 }
2010
Douglas Gregoreb5758b2009-09-23 22:26:46 +00002011 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002012 Results.EnterNewScope();
2013 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
2014 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00002015 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00002016 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2017 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002018
Douglas Gregor95ac6552009-11-18 01:29:26 +00002019 if (getLangOptions().CPlusPlus) {
2020 if (!Results.empty()) {
2021 // The "template" keyword can follow "->" or "." in the grammar.
2022 // However, we only want to suggest the template keyword if something
2023 // is dependent.
2024 bool IsDependent = BaseType->isDependentType();
2025 if (!IsDependent) {
2026 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2027 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2028 IsDependent = Ctx->isDependentContext();
2029 break;
2030 }
2031 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002032
Douglas Gregor95ac6552009-11-18 01:29:26 +00002033 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00002034 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002035 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002036 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002037 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2038 // Objective-C property reference.
2039
2040 // Add property results based on our interface.
2041 const ObjCObjectPointerType *ObjCPtr
2042 = BaseType->getAsObjCInterfacePointerType();
2043 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00002044 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002045
2046 // Add properties from the protocols in a qualified interface.
2047 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2048 E = ObjCPtr->qual_end();
2049 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002050 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002051 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2052 (!IsArrow && BaseType->isObjCInterfaceType())) {
2053 // Objective-C instance variable access.
2054 ObjCInterfaceDecl *Class = 0;
2055 if (const ObjCObjectPointerType *ObjCPtr
2056 = BaseType->getAs<ObjCObjectPointerType>())
2057 Class = ObjCPtr->getInterfaceDecl();
2058 else
2059 Class = BaseType->getAs<ObjCInterfaceType>()->getDecl();
2060
2061 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00002062 if (Class) {
2063 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2064 Results.setFilter(&ResultBuilder::IsObjCIvar);
2065 LookupVisibleDecls(Class, LookupMemberName, Consumer);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002066 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002067 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002068
2069 // FIXME: How do we cope with isa?
2070
2071 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002072
2073 // Add macros
2074 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002075 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002076
2077 // Hand off the results found for code completion.
2078 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002079}
2080
Douglas Gregor374929f2009-09-18 15:37:17 +00002081void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2082 if (!CodeCompleter)
2083 return;
2084
Douglas Gregor86d9a522009-09-21 16:56:56 +00002085 typedef CodeCompleteConsumer::Result Result;
2086 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +00002087 switch ((DeclSpec::TST)TagSpec) {
2088 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002089 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +00002090 break;
2091
2092 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002093 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +00002094 break;
2095
2096 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00002097 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002098 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00002099 break;
2100
2101 default:
2102 assert(false && "Unknown type specifier kind in CodeCompleteTag");
2103 return;
2104 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002105
2106 ResultBuilder Results(*this, Filter);
Douglas Gregor45bcd432010-01-14 03:21:49 +00002107 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002108 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2109 LookupVisibleDecls(S, LookupTagName, Consumer);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002110
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002111 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002112 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002113 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00002114}
2115
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002116void Sema::CodeCompleteCase(Scope *S) {
2117 if (getSwitchStack().empty() || !CodeCompleter)
2118 return;
2119
2120 SwitchStmt *Switch = getSwitchStack().back();
2121 if (!Switch->getCond()->getType()->isEnumeralType())
2122 return;
2123
2124 // Code-complete the cases of a switch statement over an enumeration type
2125 // by providing the list of
2126 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2127
2128 // Determine which enumerators we have already seen in the switch statement.
2129 // FIXME: Ideally, we would also be able to look *past* the code-completion
2130 // token, in case we are code-completing in the middle of the switch and not
2131 // at the end. However, we aren't able to do so at the moment.
2132 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002133 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002134 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2135 SC = SC->getNextSwitchCase()) {
2136 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2137 if (!Case)
2138 continue;
2139
2140 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2141 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2142 if (EnumConstantDecl *Enumerator
2143 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2144 // We look into the AST of the case statement to determine which
2145 // enumerator was named. Alternatively, we could compute the value of
2146 // the integral constant expression, then compare it against the
2147 // values of each enumerator. However, value-based approach would not
2148 // work as well with C++ templates where enumerators declared within a
2149 // template are type- and value-dependent.
2150 EnumeratorsSeen.insert(Enumerator);
2151
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002152 // If this is a qualified-id, keep track of the nested-name-specifier
2153 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002154 //
2155 // switch (TagD.getKind()) {
2156 // case TagDecl::TK_enum:
2157 // break;
2158 // case XXX
2159 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002160 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002161 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2162 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002163 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002164 }
2165 }
2166
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002167 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2168 // If there are no prior enumerators in C++, check whether we have to
2169 // qualify the names of the enumerators that we suggest, because they
2170 // may not be visible in this scope.
2171 Qualifier = getRequiredQualification(Context, CurContext,
2172 Enum->getDeclContext());
2173
2174 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2175 }
2176
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002177 // Add any enumerators that have not yet been mentioned.
2178 ResultBuilder Results(*this);
2179 Results.EnterNewScope();
2180 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2181 EEnd = Enum->enumerator_end();
2182 E != EEnd; ++E) {
2183 if (EnumeratorsSeen.count(*E))
2184 continue;
2185
Douglas Gregor608300b2010-01-14 16:14:35 +00002186 Results.AddResult(CodeCompleteConsumer::Result(*E, Qualifier),
2187 CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002188 }
2189 Results.ExitScope();
2190
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002191 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002192 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002193 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002194}
2195
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002196namespace {
2197 struct IsBetterOverloadCandidate {
2198 Sema &S;
2199
2200 public:
2201 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
2202
2203 bool
2204 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
2205 return S.isBetterOverloadCandidate(X, Y);
2206 }
2207 };
2208}
2209
2210void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2211 ExprTy **ArgsIn, unsigned NumArgs) {
2212 if (!CodeCompleter)
2213 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002214
2215 // When we're code-completing for a call, we fall back to ordinary
2216 // name code-completion whenever we can't produce specific
2217 // results. We may want to revisit this strategy in the future,
2218 // e.g., by merging the two kinds of results.
2219
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002220 Expr *Fn = (Expr *)FnIn;
2221 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002222
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002223 // Ignore type-dependent call expressions entirely.
2224 if (Fn->isTypeDependent() ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00002225 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00002226 CodeCompleteOrdinaryName(S, CCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002227 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002228 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002229
John McCall3b4294e2009-12-16 12:17:52 +00002230 // Build an overload candidate set based on the functions we find.
2231 OverloadCandidateSet CandidateSet;
2232
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002233 // FIXME: What if we're calling something that isn't a function declaration?
2234 // FIXME: What if we're calling a pseudo-destructor?
2235 // FIXME: What if we're calling a member function?
2236
Douglas Gregorc0265402010-01-21 15:46:19 +00002237 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
2238 llvm::SmallVector<ResultCandidate, 8> Results;
2239
John McCall3b4294e2009-12-16 12:17:52 +00002240 Expr *NakedFn = Fn->IgnoreParenCasts();
2241 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
2242 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
2243 /*PartialOverloading=*/ true);
2244 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
2245 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00002246 if (FDecl) {
2247 if (!FDecl->getType()->getAs<FunctionProtoType>())
2248 Results.push_back(ResultCandidate(FDecl));
2249 else
John McCall86820f52010-01-26 01:37:31 +00002250 // FIXME: access?
2251 AddOverloadCandidate(FDecl, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregorc0265402010-01-21 15:46:19 +00002252 false, false, /*PartialOverloading*/ true);
2253 }
John McCall3b4294e2009-12-16 12:17:52 +00002254 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002255
Douglas Gregorc0265402010-01-21 15:46:19 +00002256 if (!CandidateSet.empty()) {
2257 // Sort the overload candidate set by placing the best overloads first.
2258 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
2259 IsBetterOverloadCandidate(*this));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002260
Douglas Gregorc0265402010-01-21 15:46:19 +00002261 // Add the remaining viable overload candidates as code-completion reslults.
2262 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2263 CandEnd = CandidateSet.end();
2264 Cand != CandEnd; ++Cand) {
2265 if (Cand->Viable)
2266 Results.push_back(ResultCandidate(Cand->Function));
2267 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002268 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00002269
2270 if (Results.empty())
Douglas Gregor01dfea02010-01-10 23:08:15 +00002271 CodeCompleteOrdinaryName(S, CCC_Expression);
Douglas Gregoref96eac2009-12-11 19:06:04 +00002272 else
2273 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
2274 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002275}
2276
Douglas Gregor81b747b2009-09-17 21:32:03 +00002277void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
2278 bool EnteringContext) {
2279 if (!SS.getScopeRep() || !CodeCompleter)
2280 return;
2281
Douglas Gregor86d9a522009-09-21 16:56:56 +00002282 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
2283 if (!Ctx)
2284 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00002285
2286 // Try to instantiate any non-dependent declaration contexts before
2287 // we look in them.
2288 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS))
2289 return;
2290
Douglas Gregor86d9a522009-09-21 16:56:56 +00002291 ResultBuilder Results(*this);
Douglas Gregordef91072010-01-14 03:35:48 +00002292 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2293 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002294
2295 // The "template" keyword can follow "::" in the grammar, but only
2296 // put it into the grammar if the nested-name-specifier is dependent.
2297 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
2298 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00002299 Results.AddResult("template");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002300
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002301 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002302 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002303 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002304}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002305
2306void Sema::CodeCompleteUsing(Scope *S) {
2307 if (!CodeCompleter)
2308 return;
2309
Douglas Gregor86d9a522009-09-21 16:56:56 +00002310 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002311 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002312
2313 // If we aren't in class scope, we could see the "namespace" keyword.
2314 if (!S->isClassScope())
Douglas Gregora4477812010-01-14 16:01:26 +00002315 Results.AddResult(CodeCompleteConsumer::Result("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002316
2317 // After "using", we can see anything that would start a
2318 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002319 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2320 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002321 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002322
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002323 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002324 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002325 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002326}
2327
2328void Sema::CodeCompleteUsingDirective(Scope *S) {
2329 if (!CodeCompleter)
2330 return;
2331
Douglas Gregor86d9a522009-09-21 16:56:56 +00002332 // After "using namespace", we expect to see a namespace name or namespace
2333 // alias.
2334 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002335 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002336 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2337 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002338 Results.ExitScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002339 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002340 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002341 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002342}
2343
2344void Sema::CodeCompleteNamespaceDecl(Scope *S) {
2345 if (!CodeCompleter)
2346 return;
2347
Douglas Gregor86d9a522009-09-21 16:56:56 +00002348 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
2349 DeclContext *Ctx = (DeclContext *)S->getEntity();
2350 if (!S->getParent())
2351 Ctx = Context.getTranslationUnitDecl();
2352
2353 if (Ctx && Ctx->isFileContext()) {
2354 // We only want to see those namespaces that have already been defined
2355 // within this scope, because its likely that the user is creating an
2356 // extended namespace declaration. Keep track of the most recent
2357 // definition of each namespace.
2358 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
2359 for (DeclContext::specific_decl_iterator<NamespaceDecl>
2360 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
2361 NS != NSEnd; ++NS)
2362 OrigToLatest[NS->getOriginalNamespace()] = *NS;
2363
2364 // Add the most recent definition (or extended definition) of each
2365 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002366 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002367 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
2368 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
2369 NS != NSEnd; ++NS)
Douglas Gregor608300b2010-01-14 16:14:35 +00002370 Results.AddResult(CodeCompleteConsumer::Result(NS->second, 0),
2371 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002372 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002373 }
2374
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002375 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002376 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002377 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002378}
2379
2380void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
2381 if (!CodeCompleter)
2382 return;
2383
Douglas Gregor86d9a522009-09-21 16:56:56 +00002384 // After "namespace", we expect to see a namespace or alias.
2385 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002386 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2387 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002388 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002389 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002390 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002391}
2392
Douglas Gregored8d3222009-09-18 20:05:18 +00002393void Sema::CodeCompleteOperatorName(Scope *S) {
2394 if (!CodeCompleter)
2395 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002396
2397 typedef CodeCompleteConsumer::Result Result;
2398 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002399 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00002400
Douglas Gregor86d9a522009-09-21 16:56:56 +00002401 // Add the names of overloadable operators.
2402#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2403 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00002404 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002405#include "clang/Basic/OperatorKinds.def"
2406
2407 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00002408 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002409 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2410 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002411
2412 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00002413 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002414 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002415
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002416 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002417 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002418 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00002419}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002420
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002421// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
2422// true or false.
2423#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00002424static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002425 ResultBuilder &Results,
2426 bool NeedAt) {
2427 typedef CodeCompleteConsumer::Result Result;
2428 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00002429 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002430
2431 CodeCompletionString *Pattern = 0;
2432 if (LangOpts.ObjC2) {
2433 // @dynamic
2434 Pattern = new CodeCompletionString;
2435 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
2436 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2437 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00002438 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002439
2440 // @synthesize
2441 Pattern = new CodeCompletionString;
2442 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
2443 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2444 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00002445 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002446 }
2447}
2448
Douglas Gregorbca403c2010-01-13 23:51:12 +00002449static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002450 ResultBuilder &Results,
2451 bool NeedAt) {
2452 typedef CodeCompleteConsumer::Result Result;
2453
2454 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00002455 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002456
2457 if (LangOpts.ObjC2) {
2458 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00002459 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002460
2461 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00002462 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002463
2464 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00002465 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002466 }
2467}
2468
Douglas Gregorbca403c2010-01-13 23:51:12 +00002469static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002470 typedef CodeCompleteConsumer::Result Result;
2471 CodeCompletionString *Pattern = 0;
2472
2473 // @class name ;
2474 Pattern = new CodeCompletionString;
2475 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
2476 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2477 Pattern->AddPlaceholderChunk("identifier");
2478 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +00002479 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002480
2481 // @interface name
2482 // FIXME: Could introduce the whole pattern, including superclasses and
2483 // such.
2484 Pattern = new CodeCompletionString;
2485 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
2486 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2487 Pattern->AddPlaceholderChunk("class");
Douglas Gregora4477812010-01-14 16:01:26 +00002488 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002489
2490 // @protocol name
2491 Pattern = new CodeCompletionString;
2492 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
2493 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2494 Pattern->AddPlaceholderChunk("protocol");
Douglas Gregora4477812010-01-14 16:01:26 +00002495 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002496
2497 // @implementation name
2498 Pattern = new CodeCompletionString;
2499 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
2500 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2501 Pattern->AddPlaceholderChunk("class");
Douglas Gregora4477812010-01-14 16:01:26 +00002502 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002503
2504 // @compatibility_alias name
2505 Pattern = new CodeCompletionString;
2506 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
2507 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2508 Pattern->AddPlaceholderChunk("alias");
2509 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2510 Pattern->AddPlaceholderChunk("class");
Douglas Gregora4477812010-01-14 16:01:26 +00002511 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002512}
2513
Douglas Gregorc464ae82009-12-07 09:27:33 +00002514void Sema::CodeCompleteObjCAtDirective(Scope *S, DeclPtrTy ObjCImpDecl,
2515 bool InInterface) {
2516 typedef CodeCompleteConsumer::Result Result;
2517 ResultBuilder Results(*this);
2518 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002519 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00002520 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002521 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00002522 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002523 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00002524 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00002525 Results.ExitScope();
2526 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2527}
2528
Douglas Gregorbca403c2010-01-13 23:51:12 +00002529static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002530 typedef CodeCompleteConsumer::Result Result;
2531 CodeCompletionString *Pattern = 0;
2532
2533 // @encode ( type-name )
2534 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002535 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002536 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2537 Pattern->AddPlaceholderChunk("type-name");
2538 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00002539 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002540
2541 // @protocol ( protocol-name )
2542 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002543 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002544 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2545 Pattern->AddPlaceholderChunk("protocol-name");
2546 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00002547 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002548
2549 // @selector ( selector )
2550 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002551 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002552 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2553 Pattern->AddPlaceholderChunk("selector");
2554 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00002555 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002556}
2557
Douglas Gregorbca403c2010-01-13 23:51:12 +00002558static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002559 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002560 CodeCompletionString *Pattern = 0;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002561
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002562 // @try { statements } @catch ( declaration ) { statements } @finally
2563 // { statements }
2564 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002565 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002566 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2567 Pattern->AddPlaceholderChunk("statements");
2568 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2569 Pattern->AddTextChunk("@catch");
2570 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2571 Pattern->AddPlaceholderChunk("parameter");
2572 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2573 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2574 Pattern->AddPlaceholderChunk("statements");
2575 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2576 Pattern->AddTextChunk("@finally");
2577 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2578 Pattern->AddPlaceholderChunk("statements");
2579 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00002580 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002581
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002582 // @throw
2583 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002584 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
Douglas Gregor834389b2010-01-12 06:38:28 +00002585 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002586 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor834389b2010-01-12 06:38:28 +00002587 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregora4477812010-01-14 16:01:26 +00002588 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002589
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002590 // @synchronized ( expression ) { statements }
2591 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002592 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
Douglas Gregor834389b2010-01-12 06:38:28 +00002593 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002594 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2595 Pattern->AddPlaceholderChunk("expression");
2596 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2597 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2598 Pattern->AddPlaceholderChunk("statements");
2599 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00002600 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002601}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002602
Douglas Gregorbca403c2010-01-13 23:51:12 +00002603static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00002604 ResultBuilder &Results,
2605 bool NeedAt) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002606 typedef CodeCompleteConsumer::Result Result;
Douglas Gregora4477812010-01-14 16:01:26 +00002607 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
2608 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
2609 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00002610 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00002611 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00002612}
2613
2614void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
2615 ResultBuilder Results(*this);
2616 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00002617 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00002618 Results.ExitScope();
2619 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2620}
2621
2622void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002623 ResultBuilder Results(*this);
2624 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00002625 AddObjCStatementResults(Results, false);
2626 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002627 Results.ExitScope();
2628 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2629}
2630
2631void Sema::CodeCompleteObjCAtExpression(Scope *S) {
2632 ResultBuilder Results(*this);
2633 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00002634 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002635 Results.ExitScope();
2636 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2637}
2638
Douglas Gregor988358f2009-11-19 00:14:45 +00002639/// \brief Determine whether the addition of the given flag to an Objective-C
2640/// property's attributes will cause a conflict.
2641static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
2642 // Check if we've already added this flag.
2643 if (Attributes & NewFlag)
2644 return true;
2645
2646 Attributes |= NewFlag;
2647
2648 // Check for collisions with "readonly".
2649 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
2650 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
2651 ObjCDeclSpec::DQ_PR_assign |
2652 ObjCDeclSpec::DQ_PR_copy |
2653 ObjCDeclSpec::DQ_PR_retain)))
2654 return true;
2655
2656 // Check for more than one of { assign, copy, retain }.
2657 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
2658 ObjCDeclSpec::DQ_PR_copy |
2659 ObjCDeclSpec::DQ_PR_retain);
2660 if (AssignCopyRetMask &&
2661 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
2662 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
2663 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
2664 return true;
2665
2666 return false;
2667}
2668
Douglas Gregora93b1082009-11-18 23:08:07 +00002669void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00002670 if (!CodeCompleter)
2671 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00002672
Steve Naroffece8e712009-10-08 21:55:05 +00002673 unsigned Attributes = ODS.getPropertyAttributes();
2674
2675 typedef CodeCompleteConsumer::Result Result;
2676 ResultBuilder Results(*this);
2677 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00002678 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
Douglas Gregora4477812010-01-14 16:01:26 +00002679 Results.AddResult(CodeCompleteConsumer::Result("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00002680 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
Douglas Gregora4477812010-01-14 16:01:26 +00002681 Results.AddResult(CodeCompleteConsumer::Result("assign"));
Douglas Gregor988358f2009-11-19 00:14:45 +00002682 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregora4477812010-01-14 16:01:26 +00002683 Results.AddResult(CodeCompleteConsumer::Result("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00002684 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
Douglas Gregora4477812010-01-14 16:01:26 +00002685 Results.AddResult(CodeCompleteConsumer::Result("retain"));
Douglas Gregor988358f2009-11-19 00:14:45 +00002686 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
Douglas Gregora4477812010-01-14 16:01:26 +00002687 Results.AddResult(CodeCompleteConsumer::Result("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00002688 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
Douglas Gregora4477812010-01-14 16:01:26 +00002689 Results.AddResult(CodeCompleteConsumer::Result("nonatomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00002690 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00002691 CodeCompletionString *Setter = new CodeCompletionString;
2692 Setter->AddTypedTextChunk("setter");
2693 Setter->AddTextChunk(" = ");
2694 Setter->AddPlaceholderChunk("method");
Douglas Gregora4477812010-01-14 16:01:26 +00002695 Results.AddResult(CodeCompleteConsumer::Result(Setter));
Douglas Gregor54f01612009-11-19 00:01:57 +00002696 }
Douglas Gregor988358f2009-11-19 00:14:45 +00002697 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00002698 CodeCompletionString *Getter = new CodeCompletionString;
2699 Getter->AddTypedTextChunk("getter");
2700 Getter->AddTextChunk(" = ");
2701 Getter->AddPlaceholderChunk("method");
Douglas Gregora4477812010-01-14 16:01:26 +00002702 Results.AddResult(CodeCompleteConsumer::Result(Getter));
Douglas Gregor54f01612009-11-19 00:01:57 +00002703 }
Steve Naroffece8e712009-10-08 21:55:05 +00002704 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002705 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00002706}
Steve Naroffc4df6d22009-11-07 02:08:14 +00002707
Douglas Gregor4ad96852009-11-19 07:41:15 +00002708/// \brief Descripts the kind of Objective-C method that we want to find
2709/// via code completion.
2710enum ObjCMethodKind {
2711 MK_Any, //< Any kind of method, provided it means other specified criteria.
2712 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
2713 MK_OneArgSelector //< One-argument selector.
2714};
2715
2716static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
2717 ObjCMethodKind WantKind,
2718 IdentifierInfo **SelIdents,
2719 unsigned NumSelIdents) {
2720 Selector Sel = Method->getSelector();
2721 if (NumSelIdents > Sel.getNumArgs())
2722 return false;
2723
2724 switch (WantKind) {
2725 case MK_Any: break;
2726 case MK_ZeroArgSelector: return Sel.isUnarySelector();
2727 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
2728 }
2729
2730 for (unsigned I = 0; I != NumSelIdents; ++I)
2731 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
2732 return false;
2733
2734 return true;
2735}
2736
Douglas Gregor36ecb042009-11-17 23:22:23 +00002737/// \brief Add all of the Objective-C methods in the given Objective-C
2738/// container to the set of results.
2739///
2740/// The container will be a class, protocol, category, or implementation of
2741/// any of the above. This mether will recurse to include methods from
2742/// the superclasses of classes along with their categories, protocols, and
2743/// implementations.
2744///
2745/// \param Container the container in which we'll look to find methods.
2746///
2747/// \param WantInstance whether to add instance methods (only); if false, this
2748/// routine will add factory methods (only).
2749///
2750/// \param CurContext the context in which we're performing the lookup that
2751/// finds methods.
2752///
2753/// \param Results the structure into which we'll add results.
2754static void AddObjCMethods(ObjCContainerDecl *Container,
2755 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00002756 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00002757 IdentifierInfo **SelIdents,
2758 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00002759 DeclContext *CurContext,
2760 ResultBuilder &Results) {
2761 typedef CodeCompleteConsumer::Result Result;
2762 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
2763 MEnd = Container->meth_end();
2764 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002765 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
2766 // Check whether the selector identifiers we've been given are a
2767 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00002768 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00002769 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00002770
Douglas Gregord3c68542009-11-19 01:08:35 +00002771 Result R = Result(*M, 0);
2772 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00002773 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregord3c68542009-11-19 01:08:35 +00002774 Results.MaybeAddResult(R, CurContext);
2775 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00002776 }
2777
2778 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
2779 if (!IFace)
2780 return;
2781
2782 // Add methods in protocols.
2783 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
2784 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
2785 E = Protocols.end();
2786 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002787 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord3c68542009-11-19 01:08:35 +00002788 CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00002789
2790 // Add methods in categories.
2791 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
2792 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00002793 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
2794 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00002795
2796 // Add a categories protocol methods.
2797 const ObjCList<ObjCProtocolDecl> &Protocols
2798 = CatDecl->getReferencedProtocols();
2799 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
2800 E = Protocols.end();
2801 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002802 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
2803 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00002804
2805 // Add methods in category implementations.
2806 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00002807 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
2808 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00002809 }
2810
2811 // Add methods in superclass.
2812 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00002813 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
2814 SelIdents, NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00002815
2816 // Add methods in our implementation, if any.
2817 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00002818 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
2819 NumSelIdents, CurContext, Results);
2820}
2821
2822
2823void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
2824 DeclPtrTy *Methods,
2825 unsigned NumMethods) {
2826 typedef CodeCompleteConsumer::Result Result;
2827
2828 // Try to find the interface where getters might live.
2829 ObjCInterfaceDecl *Class
2830 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
2831 if (!Class) {
2832 if (ObjCCategoryDecl *Category
2833 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
2834 Class = Category->getClassInterface();
2835
2836 if (!Class)
2837 return;
2838 }
2839
2840 // Find all of the potential getters.
2841 ResultBuilder Results(*this);
2842 Results.EnterNewScope();
2843
2844 // FIXME: We need to do this because Objective-C methods don't get
2845 // pushed into DeclContexts early enough. Argh!
2846 for (unsigned I = 0; I != NumMethods; ++I) {
2847 if (ObjCMethodDecl *Method
2848 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
2849 if (Method->isInstanceMethod() &&
2850 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
2851 Result R = Result(Method, 0);
2852 R.AllParametersAreInformative = true;
2853 Results.MaybeAddResult(R, CurContext);
2854 }
2855 }
2856
2857 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
2858 Results.ExitScope();
2859 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
2860}
2861
2862void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
2863 DeclPtrTy *Methods,
2864 unsigned NumMethods) {
2865 typedef CodeCompleteConsumer::Result Result;
2866
2867 // Try to find the interface where setters might live.
2868 ObjCInterfaceDecl *Class
2869 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
2870 if (!Class) {
2871 if (ObjCCategoryDecl *Category
2872 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
2873 Class = Category->getClassInterface();
2874
2875 if (!Class)
2876 return;
2877 }
2878
2879 // Find all of the potential getters.
2880 ResultBuilder Results(*this);
2881 Results.EnterNewScope();
2882
2883 // FIXME: We need to do this because Objective-C methods don't get
2884 // pushed into DeclContexts early enough. Argh!
2885 for (unsigned I = 0; I != NumMethods; ++I) {
2886 if (ObjCMethodDecl *Method
2887 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
2888 if (Method->isInstanceMethod() &&
2889 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
2890 Result R = Result(Method, 0);
2891 R.AllParametersAreInformative = true;
2892 Results.MaybeAddResult(R, CurContext);
2893 }
2894 }
2895
2896 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
2897
2898 Results.ExitScope();
2899 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00002900}
2901
Douglas Gregor60b01cc2009-11-17 23:31:36 +00002902void Sema::CodeCompleteObjCClassMessage(Scope *S, IdentifierInfo *FName,
Douglas Gregord3c68542009-11-19 01:08:35 +00002903 SourceLocation FNameLoc,
2904 IdentifierInfo **SelIdents,
2905 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00002906 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00002907 ObjCInterfaceDecl *CDecl = 0;
2908
Douglas Gregor24a069f2009-11-17 17:59:40 +00002909 if (FName->isStr("super")) {
2910 // We're sending a message to "super".
2911 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
2912 // Figure out which interface we're in.
2913 CDecl = CurMethod->getClassInterface();
2914 if (!CDecl)
2915 return;
2916
2917 // Find the superclass of this class.
2918 CDecl = CDecl->getSuperClass();
2919 if (!CDecl)
2920 return;
2921
2922 if (CurMethod->isInstanceMethod()) {
2923 // We are inside an instance method, which means that the message
2924 // send [super ...] is actually calling an instance method on the
2925 // current object. Build the super expression and handle this like
2926 // an instance method.
2927 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
2928 SuperTy = Context.getObjCObjectPointerType(SuperTy);
2929 OwningExprResult Super
Douglas Gregor60b01cc2009-11-17 23:31:36 +00002930 = Owned(new (Context) ObjCSuperExpr(FNameLoc, SuperTy));
Douglas Gregord3c68542009-11-19 01:08:35 +00002931 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
2932 SelIdents, NumSelIdents);
Douglas Gregor24a069f2009-11-17 17:59:40 +00002933 }
2934
2935 // Okay, we're calling a factory method in our superclass.
2936 }
2937 }
2938
2939 // If the given name refers to an interface type, retrieve the
2940 // corresponding declaration.
2941 if (!CDecl)
Douglas Gregor60b01cc2009-11-17 23:31:36 +00002942 if (TypeTy *Ty = getTypeName(*FName, FNameLoc, S, 0, false)) {
Douglas Gregor24a069f2009-11-17 17:59:40 +00002943 QualType T = GetTypeFromParser(Ty, 0);
2944 if (!T.isNull())
2945 if (const ObjCInterfaceType *Interface = T->getAs<ObjCInterfaceType>())
2946 CDecl = Interface->getDecl();
2947 }
2948
2949 if (!CDecl && FName->isStr("super")) {
2950 // "super" may be the name of a variable, in which case we are
2951 // probably calling an instance method.
John McCallf7a1a742009-11-24 19:00:30 +00002952 CXXScopeSpec SS;
2953 UnqualifiedId id;
2954 id.setIdentifier(FName, FNameLoc);
2955 OwningExprResult Super = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregord3c68542009-11-19 01:08:35 +00002956 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
2957 SelIdents, NumSelIdents);
Douglas Gregor24a069f2009-11-17 17:59:40 +00002958 }
2959
Douglas Gregor36ecb042009-11-17 23:22:23 +00002960 // Add all of the factory methods in this Objective-C class, its protocols,
2961 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00002962 ResultBuilder Results(*this);
2963 Results.EnterNewScope();
Douglas Gregor4ad96852009-11-19 07:41:15 +00002964 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
2965 Results);
Steve Naroffc4df6d22009-11-07 02:08:14 +00002966 Results.ExitScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00002967
Steve Naroffc4df6d22009-11-07 02:08:14 +00002968 // This also suppresses remaining diagnostics.
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002969 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00002970}
2971
Douglas Gregord3c68542009-11-19 01:08:35 +00002972void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
2973 IdentifierInfo **SelIdents,
2974 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00002975 typedef CodeCompleteConsumer::Result Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00002976
2977 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00002978
Douglas Gregor36ecb042009-11-17 23:22:23 +00002979 // If necessary, apply function/array conversion to the receiver.
2980 // C99 6.7.5.3p[7,8].
2981 DefaultFunctionArrayConversion(RecExpr);
2982 QualType ReceiverType = RecExpr->getType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00002983
Douglas Gregor36ecb042009-11-17 23:22:23 +00002984 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType()) {
2985 // FIXME: We're messaging 'id'. Do we actually want to look up every method
2986 // in the universe?
2987 return;
2988 }
2989
Douglas Gregor36ecb042009-11-17 23:22:23 +00002990 // Build the set of methods we can see.
2991 ResultBuilder Results(*this);
2992 Results.EnterNewScope();
Douglas Gregor36ecb042009-11-17 23:22:23 +00002993
Douglas Gregorf74a4192009-11-18 00:06:18 +00002994 // Handle messages to Class. This really isn't a message to an instance
2995 // method, so we treat it the same way we would treat a message send to a
2996 // class method.
2997 if (ReceiverType->isObjCClassType() ||
2998 ReceiverType->isObjCQualifiedClassType()) {
2999 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3000 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003001 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
3002 CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003003 }
3004 }
3005 // Handle messages to a qualified ID ("id<foo>").
3006 else if (const ObjCObjectPointerType *QualID
3007 = ReceiverType->getAsObjCQualifiedIdType()) {
3008 // Search protocols for instance methods.
3009 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
3010 E = QualID->qual_end();
3011 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003012 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3013 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003014 }
3015 // Handle messages to a pointer to interface type.
3016 else if (const ObjCObjectPointerType *IFacePtr
3017 = ReceiverType->getAsObjCInterfacePointerType()) {
3018 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00003019 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
3020 NumSelIdents, CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003021
3022 // Search protocols for instance methods.
3023 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
3024 E = IFacePtr->qual_end();
3025 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003026 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3027 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003028 }
3029
Steve Naroffc4df6d22009-11-07 02:08:14 +00003030 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003031 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00003032}
Douglas Gregor55385fe2009-11-18 04:19:12 +00003033
3034/// \brief Add all of the protocol declarations that we find in the given
3035/// (translation unit) context.
3036static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00003037 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00003038 ResultBuilder &Results) {
3039 typedef CodeCompleteConsumer::Result Result;
3040
3041 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3042 DEnd = Ctx->decls_end();
3043 D != DEnd; ++D) {
3044 // Record any protocols we find.
3045 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00003046 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00003047 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003048
3049 // Record any forward-declared protocols we find.
3050 if (ObjCForwardProtocolDecl *Forward
3051 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
3052 for (ObjCForwardProtocolDecl::protocol_iterator
3053 P = Forward->protocol_begin(),
3054 PEnd = Forward->protocol_end();
3055 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00003056 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00003057 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003058 }
3059 }
3060}
3061
3062void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
3063 unsigned NumProtocols) {
3064 ResultBuilder Results(*this);
3065 Results.EnterNewScope();
3066
3067 // Tell the result set to ignore all of the protocols we have
3068 // already seen.
3069 for (unsigned I = 0; I != NumProtocols; ++I)
3070 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first))
3071 Results.Ignore(Protocol);
3072
3073 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00003074 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
3075 Results);
3076
3077 Results.ExitScope();
3078 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3079}
3080
3081void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
3082 ResultBuilder Results(*this);
3083 Results.EnterNewScope();
3084
3085 // Add all protocols.
3086 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
3087 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003088
3089 Results.ExitScope();
3090 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3091}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003092
3093/// \brief Add all of the Objective-C interface declarations that we find in
3094/// the given (translation unit) context.
3095static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
3096 bool OnlyForwardDeclarations,
3097 bool OnlyUnimplemented,
3098 ResultBuilder &Results) {
3099 typedef CodeCompleteConsumer::Result Result;
3100
3101 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3102 DEnd = Ctx->decls_end();
3103 D != DEnd; ++D) {
3104 // Record any interfaces we find.
3105 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
3106 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
3107 (!OnlyUnimplemented || !Class->getImplementation()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003108 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003109
3110 // Record any forward-declared interfaces we find.
3111 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
3112 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
3113 C != CEnd; ++C)
3114 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
3115 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003116 Results.AddResult(Result(C->getInterface(), 0), CurContext,
3117 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003118 }
3119 }
3120}
3121
3122void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
3123 ResultBuilder Results(*this);
3124 Results.EnterNewScope();
3125
3126 // Add all classes.
3127 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
3128 false, Results);
3129
3130 Results.ExitScope();
3131 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3132}
3133
3134void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName) {
3135 ResultBuilder Results(*this);
3136 Results.EnterNewScope();
3137
3138 // Make sure that we ignore the class we're currently defining.
3139 NamedDecl *CurClass
3140 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003141 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003142 Results.Ignore(CurClass);
3143
3144 // Add all classes.
3145 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3146 false, Results);
3147
3148 Results.ExitScope();
3149 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3150}
3151
3152void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
3153 ResultBuilder Results(*this);
3154 Results.EnterNewScope();
3155
3156 // Add all unimplemented classes.
3157 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3158 true, Results);
3159
3160 Results.ExitScope();
3161 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3162}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003163
3164void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
3165 IdentifierInfo *ClassName) {
3166 typedef CodeCompleteConsumer::Result Result;
3167
3168 ResultBuilder Results(*this);
3169
3170 // Ignore any categories we find that have already been implemented by this
3171 // interface.
3172 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3173 NamedDecl *CurClass
3174 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
3175 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
3176 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3177 Category = Category->getNextClassCategory())
3178 CategoryNames.insert(Category->getIdentifier());
3179
3180 // Add all of the categories we know about.
3181 Results.EnterNewScope();
3182 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3183 for (DeclContext::decl_iterator D = TU->decls_begin(),
3184 DEnd = TU->decls_end();
3185 D != DEnd; ++D)
3186 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
3187 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003188 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003189 Results.ExitScope();
3190
3191 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3192}
3193
3194void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
3195 IdentifierInfo *ClassName) {
3196 typedef CodeCompleteConsumer::Result Result;
3197
3198 // Find the corresponding interface. If we couldn't find the interface, the
3199 // program itself is ill-formed. However, we'll try to be helpful still by
3200 // providing the list of all of the categories we know about.
3201 NamedDecl *CurClass
3202 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
3203 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
3204 if (!Class)
3205 return CodeCompleteObjCInterfaceCategory(S, ClassName);
3206
3207 ResultBuilder Results(*this);
3208
3209 // Add all of the categories that have have corresponding interface
3210 // declarations in this class and any of its superclasses, except for
3211 // already-implemented categories in the class itself.
3212 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3213 Results.EnterNewScope();
3214 bool IgnoreImplemented = true;
3215 while (Class) {
3216 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3217 Category = Category->getNextClassCategory())
3218 if ((!IgnoreImplemented || !Category->getImplementation()) &&
3219 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003220 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003221
3222 Class = Class->getSuperClass();
3223 IgnoreImplemented = false;
3224 }
3225 Results.ExitScope();
3226
3227 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3228}
Douglas Gregor322328b2009-11-18 22:32:06 +00003229
Douglas Gregor424b2a52009-11-18 22:56:13 +00003230void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
Douglas Gregor322328b2009-11-18 22:32:06 +00003231 typedef CodeCompleteConsumer::Result Result;
3232 ResultBuilder Results(*this);
3233
3234 // Figure out where this @synthesize lives.
3235 ObjCContainerDecl *Container
3236 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3237 if (!Container ||
3238 (!isa<ObjCImplementationDecl>(Container) &&
3239 !isa<ObjCCategoryImplDecl>(Container)))
3240 return;
3241
3242 // Ignore any properties that have already been implemented.
3243 for (DeclContext::decl_iterator D = Container->decls_begin(),
3244 DEnd = Container->decls_end();
3245 D != DEnd; ++D)
3246 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
3247 Results.Ignore(PropertyImpl->getPropertyDecl());
3248
3249 // Add any properties that we find.
3250 Results.EnterNewScope();
3251 if (ObjCImplementationDecl *ClassImpl
3252 = dyn_cast<ObjCImplementationDecl>(Container))
3253 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
3254 Results);
3255 else
3256 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
3257 false, CurContext, Results);
3258 Results.ExitScope();
3259
3260 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3261}
3262
3263void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
3264 IdentifierInfo *PropertyName,
3265 DeclPtrTy ObjCImpDecl) {
3266 typedef CodeCompleteConsumer::Result Result;
3267 ResultBuilder Results(*this);
3268
3269 // Figure out where this @synthesize lives.
3270 ObjCContainerDecl *Container
3271 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3272 if (!Container ||
3273 (!isa<ObjCImplementationDecl>(Container) &&
3274 !isa<ObjCCategoryImplDecl>(Container)))
3275 return;
3276
3277 // Figure out which interface we're looking into.
3278 ObjCInterfaceDecl *Class = 0;
3279 if (ObjCImplementationDecl *ClassImpl
3280 = dyn_cast<ObjCImplementationDecl>(Container))
3281 Class = ClassImpl->getClassInterface();
3282 else
3283 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
3284 ->getClassInterface();
3285
3286 // Add all of the instance variables in this class and its superclasses.
3287 Results.EnterNewScope();
3288 for(; Class; Class = Class->getSuperClass()) {
3289 // FIXME: We could screen the type of each ivar for compatibility with
3290 // the property, but is that being too paternal?
3291 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
3292 IVarEnd = Class->ivar_end();
3293 IVar != IVarEnd; ++IVar)
Douglas Gregor608300b2010-01-14 16:14:35 +00003294 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor322328b2009-11-18 22:32:06 +00003295 }
3296 Results.ExitScope();
3297
3298 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3299}