blob: 55288750fd5f2dbf43dbded66fd47f4f1d32dd45 [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 Gregor719770d2010-04-06 17:30:22 +000016#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000019#include "clang/Lex/MacroInfo.h"
20#include "clang/Lex/Preprocessor.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000021#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000022#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000023#include "llvm/ADT/StringSwitch.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000024#include <list>
25#include <map>
26#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000027
28using namespace clang;
29
Douglas Gregor86d9a522009-09-21 16:56:56 +000030namespace {
31 /// \brief A container of code-completion results.
32 class ResultBuilder {
33 public:
34 /// \brief The type of a name-lookup filter, which can be provided to the
35 /// name-lookup routines to specify which declarations should be included in
36 /// the result set (when it returns true) and which declarations should be
37 /// filtered out (returns false).
38 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
39
40 typedef CodeCompleteConsumer::Result Result;
41
42 private:
43 /// \brief The actual results we have found.
44 std::vector<Result> Results;
45
46 /// \brief A record of all of the declarations we have found and placed
47 /// into the result set, used to ensure that no declaration ever gets into
48 /// the result set twice.
49 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
50
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000051 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
52
53 /// \brief An entry in the shadow map, which is optimized to store
54 /// a single (declaration, index) mapping (the common case) but
55 /// can also store a list of (declaration, index) mappings.
56 class ShadowMapEntry {
57 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
58
59 /// \brief Contains either the solitary NamedDecl * or a vector
60 /// of (declaration, index) pairs.
61 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
62
63 /// \brief When the entry contains a single declaration, this is
64 /// the index associated with that entry.
65 unsigned SingleDeclIndex;
66
67 public:
68 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
69
70 void Add(NamedDecl *ND, unsigned Index) {
71 if (DeclOrVector.isNull()) {
72 // 0 - > 1 elements: just set the single element information.
73 DeclOrVector = ND;
74 SingleDeclIndex = Index;
75 return;
76 }
77
78 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
79 // 1 -> 2 elements: create the vector of results and push in the
80 // existing declaration.
81 DeclIndexPairVector *Vec = new DeclIndexPairVector;
82 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
83 DeclOrVector = Vec;
84 }
85
86 // Add the new element to the end of the vector.
87 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
88 DeclIndexPair(ND, Index));
89 }
90
91 void Destroy() {
92 if (DeclIndexPairVector *Vec
93 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
94 delete Vec;
95 DeclOrVector = ((NamedDecl *)0);
96 }
97 }
98
99 // Iteration.
100 class iterator;
101 iterator begin() const;
102 iterator end() const;
103 };
104
Douglas Gregor86d9a522009-09-21 16:56:56 +0000105 /// \brief A mapping from declaration names to the declarations that have
106 /// this name within a particular scope and their index within the list of
107 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000108 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000109
110 /// \brief The semantic analysis object for which results are being
111 /// produced.
112 Sema &SemaRef;
113
114 /// \brief If non-NULL, a filter function used to remove any code-completion
115 /// results that are not desirable.
116 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000117
118 /// \brief Whether we should allow declarations as
119 /// nested-name-specifiers that would otherwise be filtered out.
120 bool AllowNestedNameSpecifiers;
121
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000122 /// \brief If set, the type that we would prefer our resulting value
123 /// declarations to have.
124 ///
125 /// Closely matching the preferred type gives a boost to a result's
126 /// priority.
127 CanQualType PreferredType;
128
Douglas Gregor86d9a522009-09-21 16:56:56 +0000129 /// \brief A list of shadow maps, which is used to model name hiding at
130 /// different levels of, e.g., the inheritance hierarchy.
131 std::list<ShadowMap> ShadowMaps;
132
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000133 void AdjustResultPriorityForPreferredType(Result &R);
134
Douglas Gregor86d9a522009-09-21 16:56:56 +0000135 public:
136 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
Douglas Gregor45bcd432010-01-14 03:21:49 +0000137 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false) { }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000138
Douglas Gregord8e8a582010-05-25 21:41:55 +0000139 /// \brief Whether we should include code patterns in the completion
140 /// results.
141 bool includeCodePatterns() const {
142 return SemaRef.CodeCompleter &&
143 SemaRef.CodeCompleter->includeCodePatterns();
144 }
145
Douglas Gregor86d9a522009-09-21 16:56:56 +0000146 /// \brief Set the filter used for code-completion results.
147 void setFilter(LookupFilter Filter) {
148 this->Filter = Filter;
149 }
150
151 typedef std::vector<Result>::iterator iterator;
152 iterator begin() { return Results.begin(); }
153 iterator end() { return Results.end(); }
154
155 Result *data() { return Results.empty()? 0 : &Results.front(); }
156 unsigned size() const { return Results.size(); }
157 bool empty() const { return Results.empty(); }
158
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000159 /// \brief Specify the preferred type.
160 void setPreferredType(QualType T) {
161 PreferredType = SemaRef.Context.getCanonicalType(T);
162 }
163
Douglas Gregor45bcd432010-01-14 03:21:49 +0000164 /// \brief Specify whether nested-name-specifiers are allowed.
165 void allowNestedNameSpecifiers(bool Allow = true) {
166 AllowNestedNameSpecifiers = Allow;
167 }
168
Douglas Gregore495b7f2010-01-14 00:20:49 +0000169 /// \brief Determine whether the given declaration is at all interesting
170 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000171 ///
172 /// \param ND the declaration that we are inspecting.
173 ///
174 /// \param AsNestedNameSpecifier will be set true if this declaration is
175 /// only interesting when it is a nested-name-specifier.
176 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000177
178 /// \brief Check whether the result is hidden by the Hiding declaration.
179 ///
180 /// \returns true if the result is hidden and cannot be found, false if
181 /// the hidden result could still be found. When false, \p R may be
182 /// modified to describe how the result can be found (e.g., via extra
183 /// qualification).
184 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
185 NamedDecl *Hiding);
186
Douglas Gregor86d9a522009-09-21 16:56:56 +0000187 /// \brief Add a new result to this result set (if it isn't already in one
188 /// of the shadow maps), or replace an existing result (for, e.g., a
189 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000190 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000191 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000192 ///
193 /// \param R the context in which this result will be named.
194 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000195
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000196 /// \brief Add a new result to this result set, where we already know
197 /// the hiding declation (if any).
198 ///
199 /// \param R the result to add (if it is unique).
200 ///
201 /// \param CurContext the context in which this result will be named.
202 ///
203 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000204 ///
205 /// \param InBaseClass whether the result was found in a base
206 /// class of the searched context.
207 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
208 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000209
Douglas Gregora4477812010-01-14 16:01:26 +0000210 /// \brief Add a new non-declaration result to this result set.
211 void AddResult(Result R);
212
Douglas Gregor86d9a522009-09-21 16:56:56 +0000213 /// \brief Enter into a new scope.
214 void EnterNewScope();
215
216 /// \brief Exit from the current scope.
217 void ExitScope();
218
Douglas Gregor55385fe2009-11-18 04:19:12 +0000219 /// \brief Ignore this declaration, if it is seen again.
220 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
221
Douglas Gregor86d9a522009-09-21 16:56:56 +0000222 /// \name Name lookup predicates
223 ///
224 /// These predicates can be passed to the name lookup functions to filter the
225 /// results of name lookup. All of the predicates have the same type, so that
226 ///
227 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000228 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000229 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000230 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000231 bool IsNestedNameSpecifier(NamedDecl *ND) const;
232 bool IsEnum(NamedDecl *ND) const;
233 bool IsClassOrStruct(NamedDecl *ND) const;
234 bool IsUnion(NamedDecl *ND) const;
235 bool IsNamespace(NamedDecl *ND) const;
236 bool IsNamespaceOrAlias(NamedDecl *ND) const;
237 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000238 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000239 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000240 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000241 //@}
242 };
243}
244
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000245class ResultBuilder::ShadowMapEntry::iterator {
246 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
247 unsigned SingleDeclIndex;
248
249public:
250 typedef DeclIndexPair value_type;
251 typedef value_type reference;
252 typedef std::ptrdiff_t difference_type;
253 typedef std::input_iterator_tag iterator_category;
254
255 class pointer {
256 DeclIndexPair Value;
257
258 public:
259 pointer(const DeclIndexPair &Value) : Value(Value) { }
260
261 const DeclIndexPair *operator->() const {
262 return &Value;
263 }
264 };
265
266 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
267
268 iterator(NamedDecl *SingleDecl, unsigned Index)
269 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
270
271 iterator(const DeclIndexPair *Iterator)
272 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
273
274 iterator &operator++() {
275 if (DeclOrIterator.is<NamedDecl *>()) {
276 DeclOrIterator = (NamedDecl *)0;
277 SingleDeclIndex = 0;
278 return *this;
279 }
280
281 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
282 ++I;
283 DeclOrIterator = I;
284 return *this;
285 }
286
287 iterator operator++(int) {
288 iterator tmp(*this);
289 ++(*this);
290 return tmp;
291 }
292
293 reference operator*() const {
294 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
295 return reference(ND, SingleDeclIndex);
296
Douglas Gregord490f952009-12-06 21:27:58 +0000297 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000298 }
299
300 pointer operator->() const {
301 return pointer(**this);
302 }
303
304 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000305 return X.DeclOrIterator.getOpaqueValue()
306 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000307 X.SingleDeclIndex == Y.SingleDeclIndex;
308 }
309
310 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000311 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000312 }
313};
314
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000315ResultBuilder::ShadowMapEntry::iterator
316ResultBuilder::ShadowMapEntry::begin() const {
317 if (DeclOrVector.isNull())
318 return iterator();
319
320 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
321 return iterator(ND, SingleDeclIndex);
322
323 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
324}
325
326ResultBuilder::ShadowMapEntry::iterator
327ResultBuilder::ShadowMapEntry::end() const {
328 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
329 return iterator();
330
331 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
332}
333
Douglas Gregor456c4a12009-09-21 20:12:40 +0000334/// \brief Compute the qualification required to get from the current context
335/// (\p CurContext) to the target context (\p TargetContext).
336///
337/// \param Context the AST context in which the qualification will be used.
338///
339/// \param CurContext the context where an entity is being named, which is
340/// typically based on the current scope.
341///
342/// \param TargetContext the context in which the named entity actually
343/// resides.
344///
345/// \returns a nested name specifier that refers into the target context, or
346/// NULL if no qualification is needed.
347static NestedNameSpecifier *
348getRequiredQualification(ASTContext &Context,
349 DeclContext *CurContext,
350 DeclContext *TargetContext) {
351 llvm::SmallVector<DeclContext *, 4> TargetParents;
352
353 for (DeclContext *CommonAncestor = TargetContext;
354 CommonAncestor && !CommonAncestor->Encloses(CurContext);
355 CommonAncestor = CommonAncestor->getLookupParent()) {
356 if (CommonAncestor->isTransparentContext() ||
357 CommonAncestor->isFunctionOrMethod())
358 continue;
359
360 TargetParents.push_back(CommonAncestor);
361 }
362
363 NestedNameSpecifier *Result = 0;
364 while (!TargetParents.empty()) {
365 DeclContext *Parent = TargetParents.back();
366 TargetParents.pop_back();
367
368 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
369 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
370 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
371 Result = NestedNameSpecifier::Create(Context, Result,
372 false,
373 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000374 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000375 return Result;
376}
377
Douglas Gregor45bcd432010-01-14 03:21:49 +0000378bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
379 bool &AsNestedNameSpecifier) const {
380 AsNestedNameSpecifier = false;
381
Douglas Gregore495b7f2010-01-14 00:20:49 +0000382 ND = ND->getUnderlyingDecl();
383 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000384
385 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000386 if (!ND->getDeclName())
387 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000388
389 // Friend declarations and declarations introduced due to friends are never
390 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000391 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000392 return false;
393
Douglas Gregor76282942009-12-11 17:31:05 +0000394 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000395 if (isa<ClassTemplateSpecializationDecl>(ND) ||
396 isa<ClassTemplatePartialSpecializationDecl>(ND))
397 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000398
Douglas Gregor76282942009-12-11 17:31:05 +0000399 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000400 if (isa<UsingDecl>(ND))
401 return false;
402
403 // Some declarations have reserved names that we don't want to ever show.
404 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000405 // __va_list_tag is a freak of nature. Find it and skip it.
406 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000407 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000408
Douglas Gregorf52cede2009-10-09 22:16:47 +0000409 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000410 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000411 //
412 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000413 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000414 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000415 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000416 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
417 (ND->getLocation().isInvalid() ||
418 SemaRef.SourceMgr.isInSystemHeader(
419 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000420 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000421 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000422 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000423
Douglas Gregor86d9a522009-09-21 16:56:56 +0000424 // C++ constructors are never found by name lookup.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000425 if (isa<CXXConstructorDecl>(ND))
426 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000427
428 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000429 if (Filter && !(this->*Filter)(ND)) {
430 // Check whether it is interesting as a nested-name-specifier.
431 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
432 IsNestedNameSpecifier(ND) &&
433 (Filter != &ResultBuilder::IsMember ||
434 (isa<CXXRecordDecl>(ND) &&
435 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
436 AsNestedNameSpecifier = true;
437 return true;
438 }
439
Douglas Gregore495b7f2010-01-14 00:20:49 +0000440 return false;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000441 }
John McCall0d6b1642010-04-23 18:46:30 +0000442
443 if (Filter == &ResultBuilder::IsNestedNameSpecifier)
444 AsNestedNameSpecifier = true;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000445
Douglas Gregore495b7f2010-01-14 00:20:49 +0000446 // ... then it must be interesting!
447 return true;
448}
449
Douglas Gregor6660d842010-01-14 00:41:07 +0000450bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
451 NamedDecl *Hiding) {
452 // In C, there is no way to refer to a hidden name.
453 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
454 // name if we introduce the tag type.
455 if (!SemaRef.getLangOptions().CPlusPlus)
456 return true;
457
458 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext();
459
460 // There is no way to qualify a name declared in a function or method.
461 if (HiddenCtx->isFunctionOrMethod())
462 return true;
463
464 if (HiddenCtx == Hiding->getDeclContext()->getLookupContext())
465 return true;
466
467 // We can refer to the result with the appropriate qualification. Do it.
468 R.Hidden = true;
469 R.QualifierIsInformative = false;
470
471 if (!R.Qualifier)
472 R.Qualifier = getRequiredQualification(SemaRef.Context,
473 CurContext,
474 R.Declaration->getDeclContext());
475 return false;
476}
477
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000478enum SimplifiedTypeClass {
479 STC_Arithmetic,
480 STC_Array,
481 STC_Block,
482 STC_Function,
483 STC_ObjectiveC,
484 STC_Other,
485 STC_Pointer,
486 STC_Record,
487 STC_Void
488};
489
490/// \brief A simplified classification of types used to determine whether two
491/// types are "similar enough" when adjusting priorities.
492static SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T) {
493 switch (T->getTypeClass()) {
494 case Type::Builtin:
495 switch (cast<BuiltinType>(T)->getKind()) {
496 case BuiltinType::Void:
497 return STC_Void;
498
499 case BuiltinType::NullPtr:
500 return STC_Pointer;
501
502 case BuiltinType::Overload:
503 case BuiltinType::Dependent:
504 case BuiltinType::UndeducedAuto:
505 return STC_Other;
506
507 case BuiltinType::ObjCId:
508 case BuiltinType::ObjCClass:
509 case BuiltinType::ObjCSel:
510 return STC_ObjectiveC;
511
512 default:
513 return STC_Arithmetic;
514 }
515 return STC_Other;
516
517 case Type::Complex:
518 return STC_Arithmetic;
519
520 case Type::Pointer:
521 return STC_Pointer;
522
523 case Type::BlockPointer:
524 return STC_Block;
525
526 case Type::LValueReference:
527 case Type::RValueReference:
528 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
529
530 case Type::ConstantArray:
531 case Type::IncompleteArray:
532 case Type::VariableArray:
533 case Type::DependentSizedArray:
534 return STC_Array;
535
536 case Type::DependentSizedExtVector:
537 case Type::Vector:
538 case Type::ExtVector:
539 return STC_Arithmetic;
540
541 case Type::FunctionProto:
542 case Type::FunctionNoProto:
543 return STC_Function;
544
545 case Type::Record:
546 return STC_Record;
547
548 case Type::Enum:
549 return STC_Arithmetic;
550
551 case Type::ObjCObject:
552 case Type::ObjCInterface:
553 case Type::ObjCObjectPointer:
554 return STC_ObjectiveC;
555
556 default:
557 return STC_Other;
558 }
559}
560
561/// \brief Get the type that a given expression will have if this declaration
562/// is used as an expression in its "typical" code-completion form.
563static QualType getDeclUsageType(ASTContext &C, NamedDecl *ND) {
564 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
565
566 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
567 return C.getTypeDeclType(Type);
568 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
569 return C.getObjCInterfaceType(Iface);
570
571 QualType T;
572 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000573 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000574 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000575 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000576 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000577 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000578 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
579 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
580 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
581 T = Property->getType();
582 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
583 T = Value->getType();
584 else
585 return QualType();
586
587 return T.getNonReferenceType();
588}
589
590void ResultBuilder::AdjustResultPriorityForPreferredType(Result &R) {
591 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
592 if (T.isNull())
593 return;
594
595 CanQualType TC = SemaRef.Context.getCanonicalType(T);
596 // Check for exactly-matching types (modulo qualifiers).
597 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
598 R.Priority /= CCF_ExactTypeMatch;
599 // Check for nearly-matching types, based on classification of each.
600 else if ((getSimplifiedTypeClass(PreferredType)
601 == getSimplifiedTypeClass(TC)) &&
602 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
603 R.Priority /= CCF_SimilarTypeMatch;
604}
605
Douglas Gregore495b7f2010-01-14 00:20:49 +0000606void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
607 assert(!ShadowMaps.empty() && "Must enter into a results scope");
608
609 if (R.Kind != Result::RK_Declaration) {
610 // For non-declaration results, just add the result.
611 Results.push_back(R);
612 return;
613 }
614
615 // Look through using declarations.
616 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
617 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
618 return;
619 }
620
621 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
622 unsigned IDNS = CanonDecl->getIdentifierNamespace();
623
Douglas Gregor45bcd432010-01-14 03:21:49 +0000624 bool AsNestedNameSpecifier = false;
625 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000626 return;
627
Douglas Gregor86d9a522009-09-21 16:56:56 +0000628 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000629 ShadowMapEntry::iterator I, IEnd;
630 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
631 if (NamePos != SMap.end()) {
632 I = NamePos->second.begin();
633 IEnd = NamePos->second.end();
634 }
635
636 for (; I != IEnd; ++I) {
637 NamedDecl *ND = I->first;
638 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000639 if (ND->getCanonicalDecl() == CanonDecl) {
640 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000641 Results[Index].Declaration = R.Declaration;
642
Douglas Gregor86d9a522009-09-21 16:56:56 +0000643 // We're done.
644 return;
645 }
646 }
647
648 // This is a new declaration in this scope. However, check whether this
649 // declaration name is hidden by a similarly-named declaration in an outer
650 // scope.
651 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
652 --SMEnd;
653 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000654 ShadowMapEntry::iterator I, IEnd;
655 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
656 if (NamePos != SM->end()) {
657 I = NamePos->second.begin();
658 IEnd = NamePos->second.end();
659 }
660 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000661 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000662 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000663 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
664 Decl::IDNS_ObjCProtocol)))
665 continue;
666
667 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000668 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000669 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000670 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000671 continue;
672
673 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000674 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000675 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000676
677 break;
678 }
679 }
680
681 // Make sure that any given declaration only shows up in the result set once.
682 if (!AllDeclsFound.insert(CanonDecl))
683 return;
684
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000685 // If the filter is for nested-name-specifiers, then this result starts a
686 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000687 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000688 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000689 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000690 } else if (!PreferredType.isNull())
691 AdjustResultPriorityForPreferredType(R);
692
Douglas Gregor0563c262009-09-22 23:15:58 +0000693 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000694 if (R.QualifierIsInformative && !R.Qualifier &&
695 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000696 DeclContext *Ctx = R.Declaration->getDeclContext();
697 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
698 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
699 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
700 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
701 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
702 else
703 R.QualifierIsInformative = false;
704 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000705
Douglas Gregor86d9a522009-09-21 16:56:56 +0000706 // Insert this result into the set of results and into the current shadow
707 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000708 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000709 Results.push_back(R);
710}
711
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000712void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000713 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000714 if (R.Kind != Result::RK_Declaration) {
715 // For non-declaration results, just add the result.
716 Results.push_back(R);
717 return;
718 }
719
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000720 // Look through using declarations.
721 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
722 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
723 return;
724 }
725
Douglas Gregor45bcd432010-01-14 03:21:49 +0000726 bool AsNestedNameSpecifier = false;
727 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000728 return;
729
730 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
731 return;
732
733 // Make sure that any given declaration only shows up in the result set once.
734 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
735 return;
736
737 // If the filter is for nested-name-specifiers, then this result starts a
738 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000739 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000740 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000741 R.Priority = CCP_NestedNameSpecifier;
742 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000743 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
744 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
745 ->getLookupContext()))
746 R.QualifierIsInformative = true;
747
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000748 // If this result is supposed to have an informative qualifier, add one.
749 if (R.QualifierIsInformative && !R.Qualifier &&
750 !R.StartsNestedNameSpecifier) {
751 DeclContext *Ctx = R.Declaration->getDeclContext();
752 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
753 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
754 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
755 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000756 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000757 else
758 R.QualifierIsInformative = false;
759 }
760
Douglas Gregor12e13132010-05-26 22:00:08 +0000761 // Adjust the priority if this result comes from a base class.
762 if (InBaseClass)
763 R.Priority += CCD_InBaseClass;
764
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000765 if (!PreferredType.isNull())
766 AdjustResultPriorityForPreferredType(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000767
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000768 // Insert this result into the set of results.
769 Results.push_back(R);
770}
771
Douglas Gregora4477812010-01-14 16:01:26 +0000772void ResultBuilder::AddResult(Result R) {
773 assert(R.Kind != Result::RK_Declaration &&
774 "Declaration results need more context");
775 Results.push_back(R);
776}
777
Douglas Gregor86d9a522009-09-21 16:56:56 +0000778/// \brief Enter into a new scope.
779void ResultBuilder::EnterNewScope() {
780 ShadowMaps.push_back(ShadowMap());
781}
782
783/// \brief Exit from the current scope.
784void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000785 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
786 EEnd = ShadowMaps.back().end();
787 E != EEnd;
788 ++E)
789 E->second.Destroy();
790
Douglas Gregor86d9a522009-09-21 16:56:56 +0000791 ShadowMaps.pop_back();
792}
793
Douglas Gregor791215b2009-09-21 20:51:25 +0000794/// \brief Determines whether this given declaration will be found by
795/// ordinary name lookup.
796bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000797 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
798
Douglas Gregor791215b2009-09-21 20:51:25 +0000799 unsigned IDNS = Decl::IDNS_Ordinary;
800 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000801 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000802 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
803 return true;
804
Douglas Gregor791215b2009-09-21 20:51:25 +0000805 return ND->getIdentifierNamespace() & IDNS;
806}
807
Douglas Gregor01dfea02010-01-10 23:08:15 +0000808/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000809/// ordinary name lookup but is not a type name.
810bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
811 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
812 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
813 return false;
814
815 unsigned IDNS = Decl::IDNS_Ordinary;
816 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000817 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000818 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
819 return true;
820
821 return ND->getIdentifierNamespace() & IDNS;
822}
823
824/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +0000825/// ordinary name lookup.
826bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000827 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
828
Douglas Gregor01dfea02010-01-10 23:08:15 +0000829 unsigned IDNS = Decl::IDNS_Ordinary;
830 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +0000831 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000832
833 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000834 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
835 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +0000836}
837
Douglas Gregor86d9a522009-09-21 16:56:56 +0000838/// \brief Determines whether the given declaration is suitable as the
839/// start of a C++ nested-name-specifier, e.g., a class or namespace.
840bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
841 // Allow us to find class templates, too.
842 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
843 ND = ClassTemplate->getTemplatedDecl();
844
845 return SemaRef.isAcceptableNestedNameSpecifier(ND);
846}
847
848/// \brief Determines whether the given declaration is an enumeration.
849bool ResultBuilder::IsEnum(NamedDecl *ND) const {
850 return isa<EnumDecl>(ND);
851}
852
853/// \brief Determines whether the given declaration is a class or struct.
854bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
855 // Allow us to find class templates, too.
856 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
857 ND = ClassTemplate->getTemplatedDecl();
858
859 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000860 return RD->getTagKind() == TTK_Class ||
861 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000862
863 return false;
864}
865
866/// \brief Determines whether the given declaration is a union.
867bool ResultBuilder::IsUnion(NamedDecl *ND) const {
868 // Allow us to find class templates, too.
869 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
870 ND = ClassTemplate->getTemplatedDecl();
871
872 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000873 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000874
875 return false;
876}
877
878/// \brief Determines whether the given declaration is a namespace.
879bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
880 return isa<NamespaceDecl>(ND);
881}
882
883/// \brief Determines whether the given declaration is a namespace or
884/// namespace alias.
885bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
886 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
887}
888
Douglas Gregor76282942009-12-11 17:31:05 +0000889/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000890bool ResultBuilder::IsType(NamedDecl *ND) const {
891 return isa<TypeDecl>(ND);
892}
893
Douglas Gregor76282942009-12-11 17:31:05 +0000894/// \brief Determines which members of a class should be visible via
895/// "." or "->". Only value declarations, nested name specifiers, and
896/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000897bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +0000898 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
899 ND = Using->getTargetDecl();
900
Douglas Gregorce821962009-12-11 18:14:22 +0000901 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
902 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000903}
904
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000905static bool isObjCReceiverType(ASTContext &C, QualType T) {
906 T = C.getCanonicalType(T);
907 switch (T->getTypeClass()) {
908 case Type::ObjCObject:
909 case Type::ObjCInterface:
910 case Type::ObjCObjectPointer:
911 return true;
912
913 case Type::Builtin:
914 switch (cast<BuiltinType>(T)->getKind()) {
915 case BuiltinType::ObjCId:
916 case BuiltinType::ObjCClass:
917 case BuiltinType::ObjCSel:
918 return true;
919
920 default:
921 break;
922 }
923 return false;
924
925 default:
926 break;
927 }
928
929 if (!C.getLangOptions().CPlusPlus)
930 return false;
931
932 // FIXME: We could perform more analysis here to determine whether a
933 // particular class type has any conversions to Objective-C types. For now,
934 // just accept all class types.
935 return T->isDependentType() || T->isRecordType();
936}
937
938bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
939 QualType T = getDeclUsageType(SemaRef.Context, ND);
940 if (T.isNull())
941 return false;
942
943 T = SemaRef.Context.getBaseElementType(T);
944 return isObjCReceiverType(SemaRef.Context, T);
945}
946
947
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000948/// \rief Determines whether the given declaration is an Objective-C
949/// instance variable.
950bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
951 return isa<ObjCIvarDecl>(ND);
952}
953
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000954namespace {
955 /// \brief Visible declaration consumer that adds a code-completion result
956 /// for each visible declaration.
957 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
958 ResultBuilder &Results;
959 DeclContext *CurContext;
960
961 public:
962 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
963 : Results(Results), CurContext(CurContext) { }
964
Douglas Gregor0cc84042010-01-14 15:47:35 +0000965 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
966 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000967 }
968 };
969}
970
Douglas Gregor86d9a522009-09-21 16:56:56 +0000971/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +0000972static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000973 ResultBuilder &Results) {
974 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor12e13132010-05-26 22:00:08 +0000975 Results.AddResult(Result("short", CCP_Type));
976 Results.AddResult(Result("long", CCP_Type));
977 Results.AddResult(Result("signed", CCP_Type));
978 Results.AddResult(Result("unsigned", CCP_Type));
979 Results.AddResult(Result("void", CCP_Type));
980 Results.AddResult(Result("char", CCP_Type));
981 Results.AddResult(Result("int", CCP_Type));
982 Results.AddResult(Result("float", CCP_Type));
983 Results.AddResult(Result("double", CCP_Type));
984 Results.AddResult(Result("enum", CCP_Type));
985 Results.AddResult(Result("struct", CCP_Type));
986 Results.AddResult(Result("union", CCP_Type));
987 Results.AddResult(Result("const", CCP_Type));
988 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000989
Douglas Gregor86d9a522009-09-21 16:56:56 +0000990 if (LangOpts.C99) {
991 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +0000992 Results.AddResult(Result("_Complex", CCP_Type));
993 Results.AddResult(Result("_Imaginary", CCP_Type));
994 Results.AddResult(Result("_Bool", CCP_Type));
995 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000996 }
997
998 if (LangOpts.CPlusPlus) {
999 // C++-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001000 Results.AddResult(Result("bool", CCP_Type));
1001 Results.AddResult(Result("class", CCP_Type));
1002 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001003
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001004 // typename qualified-id
1005 CodeCompletionString *Pattern = new CodeCompletionString;
1006 Pattern->AddTypedTextChunk("typename");
1007 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1008 Pattern->AddPlaceholderChunk("qualifier");
1009 Pattern->AddTextChunk("::");
1010 Pattern->AddPlaceholderChunk("name");
1011 Results.AddResult(Result(Pattern));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001012
Douglas Gregor86d9a522009-09-21 16:56:56 +00001013 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001014 Results.AddResult(Result("auto", CCP_Type));
1015 Results.AddResult(Result("char16_t", CCP_Type));
1016 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001017
1018 CodeCompletionString *Pattern = new CodeCompletionString;
1019 Pattern->AddTypedTextChunk("decltype");
1020 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1021 Pattern->AddPlaceholderChunk("expression");
1022 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1023 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001024 }
1025 }
1026
1027 // GNU extensions
1028 if (LangOpts.GNUMode) {
1029 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001030 // Results.AddResult(Result("_Decimal32"));
1031 // Results.AddResult(Result("_Decimal64"));
1032 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001033
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001034 CodeCompletionString *Pattern = new CodeCompletionString;
1035 Pattern->AddTypedTextChunk("typeof");
1036 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1037 Pattern->AddPlaceholderChunk("expression");
1038 Results.AddResult(Result(Pattern));
1039
1040 Pattern = new CodeCompletionString;
1041 Pattern->AddTypedTextChunk("typeof");
1042 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1043 Pattern->AddPlaceholderChunk("type");
1044 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1045 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001046 }
1047}
1048
Douglas Gregor01dfea02010-01-10 23:08:15 +00001049static void AddStorageSpecifiers(Action::CodeCompletionContext CCC,
1050 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001051 ResultBuilder &Results) {
1052 typedef CodeCompleteConsumer::Result Result;
1053 // Note: we don't suggest either "auto" or "register", because both
1054 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1055 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001056 Results.AddResult(Result("extern"));
1057 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001058}
1059
1060static void AddFunctionSpecifiers(Action::CodeCompletionContext CCC,
1061 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001062 ResultBuilder &Results) {
1063 typedef CodeCompleteConsumer::Result Result;
1064 switch (CCC) {
1065 case Action::CCC_Class:
1066 case Action::CCC_MemberTemplate:
1067 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001068 Results.AddResult(Result("explicit"));
1069 Results.AddResult(Result("friend"));
1070 Results.AddResult(Result("mutable"));
1071 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001072 }
1073 // Fall through
1074
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001075 case Action::CCC_ObjCInterface:
1076 case Action::CCC_ObjCImplementation:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001077 case Action::CCC_Namespace:
1078 case Action::CCC_Template:
1079 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001080 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001081 break;
1082
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001083 case Action::CCC_ObjCInstanceVariableList:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001084 case Action::CCC_Expression:
1085 case Action::CCC_Statement:
1086 case Action::CCC_ForInit:
1087 case Action::CCC_Condition:
Douglas Gregordc845342010-05-25 05:58:43 +00001088 case Action::CCC_RecoveryInFunction:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001089 break;
1090 }
1091}
1092
Douglas Gregorbca403c2010-01-13 23:51:12 +00001093static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1094static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1095static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001096 ResultBuilder &Results,
1097 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001098static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001099 ResultBuilder &Results,
1100 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001101static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001102 ResultBuilder &Results,
1103 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001104static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001105
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001106static void AddTypedefResult(ResultBuilder &Results) {
1107 CodeCompletionString *Pattern = new CodeCompletionString;
1108 Pattern->AddTypedTextChunk("typedef");
1109 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1110 Pattern->AddPlaceholderChunk("type");
1111 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1112 Pattern->AddPlaceholderChunk("name");
1113 Results.AddResult(CodeCompleteConsumer::Result(Pattern));
1114}
1115
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001116static bool WantTypesInContext(Action::CodeCompletionContext CCC,
1117 const LangOptions &LangOpts) {
1118 if (LangOpts.CPlusPlus)
1119 return true;
1120
1121 switch (CCC) {
1122 case Action::CCC_Namespace:
1123 case Action::CCC_Class:
1124 case Action::CCC_ObjCInstanceVariableList:
1125 case Action::CCC_Template:
1126 case Action::CCC_MemberTemplate:
1127 case Action::CCC_Statement:
1128 case Action::CCC_RecoveryInFunction:
1129 return true;
1130
1131 case Action::CCC_ObjCInterface:
1132 case Action::CCC_ObjCImplementation:
1133 case Action::CCC_Expression:
1134 case Action::CCC_Condition:
1135 return false;
1136
1137 case Action::CCC_ForInit:
1138 return LangOpts.ObjC1 || LangOpts.C99;
1139 }
1140
1141 return false;
1142}
1143
Douglas Gregor01dfea02010-01-10 23:08:15 +00001144/// \brief Add language constructs that show up for "ordinary" names.
1145static void AddOrdinaryNameResults(Action::CodeCompletionContext CCC,
1146 Scope *S,
1147 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001148 ResultBuilder &Results) {
1149 typedef CodeCompleteConsumer::Result Result;
1150 switch (CCC) {
1151 case Action::CCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001152 if (SemaRef.getLangOptions().CPlusPlus) {
1153 CodeCompletionString *Pattern = 0;
1154
1155 if (Results.includeCodePatterns()) {
1156 // namespace <identifier> { declarations }
1157 CodeCompletionString *Pattern = new CodeCompletionString;
1158 Pattern->AddTypedTextChunk("namespace");
1159 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1160 Pattern->AddPlaceholderChunk("identifier");
1161 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1162 Pattern->AddPlaceholderChunk("declarations");
1163 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1164 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1165 Results.AddResult(Result(Pattern));
1166 }
1167
Douglas Gregor01dfea02010-01-10 23:08:15 +00001168 // namespace identifier = identifier ;
1169 Pattern = new CodeCompletionString;
1170 Pattern->AddTypedTextChunk("namespace");
1171 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001172 Pattern->AddPlaceholderChunk("name");
Douglas Gregor01dfea02010-01-10 23:08:15 +00001173 Pattern->AddChunk(CodeCompletionString::CK_Equal);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001174 Pattern->AddPlaceholderChunk("namespace");
Douglas Gregora4477812010-01-14 16:01:26 +00001175 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001176
1177 // Using directives
1178 Pattern = new CodeCompletionString;
1179 Pattern->AddTypedTextChunk("using");
1180 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1181 Pattern->AddTextChunk("namespace");
1182 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1183 Pattern->AddPlaceholderChunk("identifier");
Douglas Gregora4477812010-01-14 16:01:26 +00001184 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001185
1186 // asm(string-literal)
1187 Pattern = new CodeCompletionString;
1188 Pattern->AddTypedTextChunk("asm");
1189 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1190 Pattern->AddPlaceholderChunk("string-literal");
1191 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001192 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001193
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001194 if (Results.includeCodePatterns()) {
1195 // Explicit template instantiation
1196 Pattern = new CodeCompletionString;
1197 Pattern->AddTypedTextChunk("template");
1198 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1199 Pattern->AddPlaceholderChunk("declaration");
1200 Results.AddResult(Result(Pattern));
1201 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001202 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001203
1204 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001205 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001206
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001207 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001208 // Fall through
1209
1210 case Action::CCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001211 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001212 // Using declaration
1213 CodeCompletionString *Pattern = new CodeCompletionString;
1214 Pattern->AddTypedTextChunk("using");
1215 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001216 Pattern->AddPlaceholderChunk("qualifier");
1217 Pattern->AddTextChunk("::");
1218 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001219 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001220
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001221 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001222 if (SemaRef.CurContext->isDependentContext()) {
1223 Pattern = new CodeCompletionString;
1224 Pattern->AddTypedTextChunk("using");
1225 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1226 Pattern->AddTextChunk("typename");
1227 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001228 Pattern->AddPlaceholderChunk("qualifier");
1229 Pattern->AddTextChunk("::");
1230 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001231 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001232 }
1233
1234 if (CCC == Action::CCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001235 AddTypedefResult(Results);
1236
Douglas Gregor01dfea02010-01-10 23:08:15 +00001237 // public:
1238 Pattern = new CodeCompletionString;
1239 Pattern->AddTypedTextChunk("public");
1240 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001241 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001242
1243 // protected:
1244 Pattern = new CodeCompletionString;
1245 Pattern->AddTypedTextChunk("protected");
1246 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001247 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001248
1249 // private:
1250 Pattern = new CodeCompletionString;
1251 Pattern->AddTypedTextChunk("private");
1252 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001253 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001254 }
1255 }
1256 // Fall through
1257
1258 case Action::CCC_Template:
1259 case Action::CCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001260 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001261 // template < parameters >
1262 CodeCompletionString *Pattern = new CodeCompletionString;
1263 Pattern->AddTypedTextChunk("template");
1264 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1265 Pattern->AddPlaceholderChunk("parameters");
1266 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregora4477812010-01-14 16:01:26 +00001267 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001268 }
1269
Douglas Gregorbca403c2010-01-13 23:51:12 +00001270 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1271 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001272 break;
1273
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001274 case Action::CCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001275 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1276 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1277 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001278 break;
1279
1280 case Action::CCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001281 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1282 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1283 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001284 break;
1285
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001286 case Action::CCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001287 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001288 break;
1289
Douglas Gregordc845342010-05-25 05:58:43 +00001290 case Action::CCC_RecoveryInFunction:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001291 case Action::CCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001292 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001293
1294 CodeCompletionString *Pattern = 0;
Douglas Gregord8e8a582010-05-25 21:41:55 +00001295 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001296 Pattern = new CodeCompletionString;
1297 Pattern->AddTypedTextChunk("try");
1298 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1299 Pattern->AddPlaceholderChunk("statements");
1300 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1301 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1302 Pattern->AddTextChunk("catch");
1303 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1304 Pattern->AddPlaceholderChunk("declaration");
1305 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1306 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1307 Pattern->AddPlaceholderChunk("statements");
1308 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1309 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001310 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001311 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001312 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001313 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001314
Douglas Gregord8e8a582010-05-25 21:41:55 +00001315 if (Results.includeCodePatterns()) {
1316 // if (condition) { statements }
1317 Pattern = new CodeCompletionString;
1318 Pattern->AddTypedTextChunk("if");
1319 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1320 if (SemaRef.getLangOptions().CPlusPlus)
1321 Pattern->AddPlaceholderChunk("condition");
1322 else
1323 Pattern->AddPlaceholderChunk("expression");
1324 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1325 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1326 Pattern->AddPlaceholderChunk("statements");
1327 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1328 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1329 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001330
Douglas Gregord8e8a582010-05-25 21:41:55 +00001331 // switch (condition) { }
1332 Pattern = new CodeCompletionString;
1333 Pattern->AddTypedTextChunk("switch");
1334 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1335 if (SemaRef.getLangOptions().CPlusPlus)
1336 Pattern->AddPlaceholderChunk("condition");
1337 else
1338 Pattern->AddPlaceholderChunk("expression");
1339 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1340 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1341 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1342 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1343 Results.AddResult(Result(Pattern));
1344 }
1345
Douglas Gregor01dfea02010-01-10 23:08:15 +00001346 // Switch-specific statements.
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001347 if (!SemaRef.getSwitchStack().empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001348 // case expression:
1349 Pattern = new CodeCompletionString;
1350 Pattern->AddTypedTextChunk("case");
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001351 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001352 Pattern->AddPlaceholderChunk("expression");
1353 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001354 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001355
1356 // default:
1357 Pattern = new CodeCompletionString;
1358 Pattern->AddTypedTextChunk("default");
1359 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001360 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001361 }
1362
Douglas Gregord8e8a582010-05-25 21:41:55 +00001363 if (Results.includeCodePatterns()) {
1364 /// while (condition) { statements }
1365 Pattern = new CodeCompletionString;
1366 Pattern->AddTypedTextChunk("while");
1367 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1368 if (SemaRef.getLangOptions().CPlusPlus)
1369 Pattern->AddPlaceholderChunk("condition");
1370 else
1371 Pattern->AddPlaceholderChunk("expression");
1372 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1373 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1374 Pattern->AddPlaceholderChunk("statements");
1375 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1376 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1377 Results.AddResult(Result(Pattern));
1378
1379 // do { statements } while ( expression );
1380 Pattern = new CodeCompletionString;
1381 Pattern->AddTypedTextChunk("do");
1382 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1383 Pattern->AddPlaceholderChunk("statements");
1384 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1385 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1386 Pattern->AddTextChunk("while");
1387 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001388 Pattern->AddPlaceholderChunk("expression");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001389 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1390 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001391
Douglas Gregord8e8a582010-05-25 21:41:55 +00001392 // for ( for-init-statement ; condition ; expression ) { statements }
1393 Pattern = new CodeCompletionString;
1394 Pattern->AddTypedTextChunk("for");
1395 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1396 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1397 Pattern->AddPlaceholderChunk("init-statement");
1398 else
1399 Pattern->AddPlaceholderChunk("init-expression");
1400 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1401 Pattern->AddPlaceholderChunk("condition");
1402 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1403 Pattern->AddPlaceholderChunk("inc-expression");
1404 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1405 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1406 Pattern->AddPlaceholderChunk("statements");
1407 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1408 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1409 Results.AddResult(Result(Pattern));
1410 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001411
1412 if (S->getContinueParent()) {
1413 // continue ;
1414 Pattern = new CodeCompletionString;
1415 Pattern->AddTypedTextChunk("continue");
Douglas Gregora4477812010-01-14 16:01:26 +00001416 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001417 }
1418
1419 if (S->getBreakParent()) {
1420 // break ;
1421 Pattern = new CodeCompletionString;
1422 Pattern->AddTypedTextChunk("break");
Douglas Gregora4477812010-01-14 16:01:26 +00001423 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001424 }
1425
1426 // "return expression ;" or "return ;", depending on whether we
1427 // know the function is void or not.
1428 bool isVoid = false;
1429 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1430 isVoid = Function->getResultType()->isVoidType();
1431 else if (ObjCMethodDecl *Method
1432 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1433 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001434 else if (SemaRef.getCurBlock() &&
1435 !SemaRef.getCurBlock()->ReturnType.isNull())
1436 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor01dfea02010-01-10 23:08:15 +00001437 Pattern = new CodeCompletionString;
1438 Pattern->AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001439 if (!isVoid) {
1440 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001441 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001442 }
Douglas Gregora4477812010-01-14 16:01:26 +00001443 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001444
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001445 // goto identifier ;
1446 Pattern = new CodeCompletionString;
1447 Pattern->AddTypedTextChunk("goto");
1448 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1449 Pattern->AddPlaceholderChunk("label");
1450 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001451
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001452 // Using directives
1453 Pattern = new CodeCompletionString;
1454 Pattern->AddTypedTextChunk("using");
1455 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1456 Pattern->AddTextChunk("namespace");
1457 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1458 Pattern->AddPlaceholderChunk("identifier");
1459 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001460 }
1461
1462 // Fall through (for statement expressions).
1463 case Action::CCC_ForInit:
1464 case Action::CCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001465 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001466 // Fall through: conditions and statements can have expressions.
1467
1468 case Action::CCC_Expression: {
1469 CodeCompletionString *Pattern = 0;
1470 if (SemaRef.getLangOptions().CPlusPlus) {
1471 // 'this', if we're in a non-static member function.
1472 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1473 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001474 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001475
1476 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001477 Results.AddResult(Result("true"));
1478 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001479
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001480 // dynamic_cast < type-id > ( expression )
1481 Pattern = new CodeCompletionString;
1482 Pattern->AddTypedTextChunk("dynamic_cast");
1483 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1484 Pattern->AddPlaceholderChunk("type");
1485 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1486 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1487 Pattern->AddPlaceholderChunk("expression");
1488 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1489 Results.AddResult(Result(Pattern));
1490
1491 // static_cast < type-id > ( expression )
1492 Pattern = new CodeCompletionString;
1493 Pattern->AddTypedTextChunk("static_cast");
1494 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1495 Pattern->AddPlaceholderChunk("type");
1496 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1497 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1498 Pattern->AddPlaceholderChunk("expression");
1499 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1500 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001501
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001502 // reinterpret_cast < type-id > ( expression )
1503 Pattern = new CodeCompletionString;
1504 Pattern->AddTypedTextChunk("reinterpret_cast");
1505 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1506 Pattern->AddPlaceholderChunk("type");
1507 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1508 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1509 Pattern->AddPlaceholderChunk("expression");
1510 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1511 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001512
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001513 // const_cast < type-id > ( expression )
1514 Pattern = new CodeCompletionString;
1515 Pattern->AddTypedTextChunk("const_cast");
1516 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1517 Pattern->AddPlaceholderChunk("type");
1518 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1519 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1520 Pattern->AddPlaceholderChunk("expression");
1521 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1522 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001523
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001524 // typeid ( expression-or-type )
1525 Pattern = new CodeCompletionString;
1526 Pattern->AddTypedTextChunk("typeid");
1527 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1528 Pattern->AddPlaceholderChunk("expression-or-type");
1529 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1530 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001531
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001532 // new T ( ... )
1533 Pattern = new CodeCompletionString;
1534 Pattern->AddTypedTextChunk("new");
1535 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1536 Pattern->AddPlaceholderChunk("type");
1537 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1538 Pattern->AddPlaceholderChunk("expressions");
1539 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1540 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001541
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001542 // new T [ ] ( ... )
1543 Pattern = new CodeCompletionString;
1544 Pattern->AddTypedTextChunk("new");
1545 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1546 Pattern->AddPlaceholderChunk("type");
1547 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1548 Pattern->AddPlaceholderChunk("size");
1549 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1550 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1551 Pattern->AddPlaceholderChunk("expressions");
1552 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1553 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001554
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001555 // delete expression
1556 Pattern = new CodeCompletionString;
1557 Pattern->AddTypedTextChunk("delete");
1558 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1559 Pattern->AddPlaceholderChunk("expression");
1560 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001561
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001562 // delete [] expression
1563 Pattern = new CodeCompletionString;
1564 Pattern->AddTypedTextChunk("delete");
1565 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1566 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1567 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1568 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1569 Pattern->AddPlaceholderChunk("expression");
1570 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001571
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001572 // throw expression
1573 Pattern = new CodeCompletionString;
1574 Pattern->AddTypedTextChunk("throw");
1575 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1576 Pattern->AddPlaceholderChunk("expression");
1577 Results.AddResult(Result(Pattern));
Douglas Gregor12e13132010-05-26 22:00:08 +00001578
1579 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001580 }
1581
1582 if (SemaRef.getLangOptions().ObjC1) {
1583 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001584 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1585 // The interface can be NULL.
1586 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1587 if (ID->getSuperClass())
1588 Results.AddResult(Result("super"));
1589 }
1590
Douglas Gregorbca403c2010-01-13 23:51:12 +00001591 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001592 }
1593
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001594 // sizeof expression
1595 Pattern = new CodeCompletionString;
1596 Pattern->AddTypedTextChunk("sizeof");
1597 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1598 Pattern->AddPlaceholderChunk("expression-or-type");
1599 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1600 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001601 break;
1602 }
1603 }
1604
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001605 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1606 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001607
1608 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregora4477812010-01-14 16:01:26 +00001609 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001610}
1611
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001612/// \brief If the given declaration has an associated type, add it as a result
1613/// type chunk.
1614static void AddResultTypeChunk(ASTContext &Context,
1615 NamedDecl *ND,
1616 CodeCompletionString *Result) {
1617 if (!ND)
1618 return;
1619
1620 // Determine the type of the declaration (if it has a type).
1621 QualType T;
1622 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1623 T = Function->getResultType();
1624 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1625 T = Method->getResultType();
1626 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1627 T = FunTmpl->getTemplatedDecl()->getResultType();
1628 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1629 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1630 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1631 /* Do nothing: ignore unresolved using declarations*/
1632 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1633 T = Value->getType();
1634 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1635 T = Property->getType();
1636
1637 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1638 return;
1639
Douglas Gregor84139d62010-04-05 21:25:31 +00001640 PrintingPolicy Policy(Context.PrintingPolicy);
1641 Policy.AnonymousTagLocations = false;
1642
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001643 std::string TypeStr;
Douglas Gregor84139d62010-04-05 21:25:31 +00001644 T.getAsStringInternal(TypeStr, Policy);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001645 Result->AddResultTypeChunk(TypeStr);
1646}
1647
Douglas Gregor86d9a522009-09-21 16:56:56 +00001648/// \brief Add function parameter chunks to the given code completion string.
1649static void AddFunctionParameterChunks(ASTContext &Context,
1650 FunctionDecl *Function,
1651 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001652 typedef CodeCompletionString::Chunk Chunk;
1653
Douglas Gregor86d9a522009-09-21 16:56:56 +00001654 CodeCompletionString *CCStr = Result;
1655
1656 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1657 ParmVarDecl *Param = Function->getParamDecl(P);
1658
1659 if (Param->hasDefaultArg()) {
1660 // When we see an optional default argument, put that argument and
1661 // the remaining default arguments into a new, optional string.
1662 CodeCompletionString *Opt = new CodeCompletionString;
1663 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1664 CCStr = Opt;
1665 }
1666
1667 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001668 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001669
1670 // Format the placeholder string.
1671 std::string PlaceholderStr;
1672 if (Param->getIdentifier())
1673 PlaceholderStr = Param->getIdentifier()->getName();
1674
1675 Param->getType().getAsStringInternal(PlaceholderStr,
1676 Context.PrintingPolicy);
1677
1678 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001679 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001680 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00001681
1682 if (const FunctionProtoType *Proto
1683 = Function->getType()->getAs<FunctionProtoType>())
1684 if (Proto->isVariadic())
1685 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-09-21 16:56:56 +00001686}
1687
1688/// \brief Add template parameter chunks to the given code completion string.
1689static void AddTemplateParameterChunks(ASTContext &Context,
1690 TemplateDecl *Template,
1691 CodeCompletionString *Result,
1692 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001693 typedef CodeCompletionString::Chunk Chunk;
1694
Douglas Gregor86d9a522009-09-21 16:56:56 +00001695 CodeCompletionString *CCStr = Result;
1696 bool FirstParameter = true;
1697
1698 TemplateParameterList *Params = Template->getTemplateParameters();
1699 TemplateParameterList::iterator PEnd = Params->end();
1700 if (MaxParameters)
1701 PEnd = Params->begin() + MaxParameters;
1702 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1703 bool HasDefaultArg = false;
1704 std::string PlaceholderStr;
1705 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1706 if (TTP->wasDeclaredWithTypename())
1707 PlaceholderStr = "typename";
1708 else
1709 PlaceholderStr = "class";
1710
1711 if (TTP->getIdentifier()) {
1712 PlaceholderStr += ' ';
1713 PlaceholderStr += TTP->getIdentifier()->getName();
1714 }
1715
1716 HasDefaultArg = TTP->hasDefaultArgument();
1717 } else if (NonTypeTemplateParmDecl *NTTP
1718 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1719 if (NTTP->getIdentifier())
1720 PlaceholderStr = NTTP->getIdentifier()->getName();
1721 NTTP->getType().getAsStringInternal(PlaceholderStr,
1722 Context.PrintingPolicy);
1723 HasDefaultArg = NTTP->hasDefaultArgument();
1724 } else {
1725 assert(isa<TemplateTemplateParmDecl>(*P));
1726 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1727
1728 // Since putting the template argument list into the placeholder would
1729 // be very, very long, we just use an abbreviation.
1730 PlaceholderStr = "template<...> class";
1731 if (TTP->getIdentifier()) {
1732 PlaceholderStr += ' ';
1733 PlaceholderStr += TTP->getIdentifier()->getName();
1734 }
1735
1736 HasDefaultArg = TTP->hasDefaultArgument();
1737 }
1738
1739 if (HasDefaultArg) {
1740 // When we see an optional default argument, put that argument and
1741 // the remaining default arguments into a new, optional string.
1742 CodeCompletionString *Opt = new CodeCompletionString;
1743 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1744 CCStr = Opt;
1745 }
1746
1747 if (FirstParameter)
1748 FirstParameter = false;
1749 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001750 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001751
1752 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001753 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001754 }
1755}
1756
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001757/// \brief Add a qualifier to the given code-completion string, if the
1758/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00001759static void
1760AddQualifierToCompletionString(CodeCompletionString *Result,
1761 NestedNameSpecifier *Qualifier,
1762 bool QualifierIsInformative,
1763 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001764 if (!Qualifier)
1765 return;
1766
1767 std::string PrintedNNS;
1768 {
1769 llvm::raw_string_ostream OS(PrintedNNS);
1770 Qualifier->print(OS, Context.PrintingPolicy);
1771 }
Douglas Gregor0563c262009-09-22 23:15:58 +00001772 if (QualifierIsInformative)
Benjamin Kramer660cc182009-11-29 20:18:50 +00001773 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor0563c262009-09-22 23:15:58 +00001774 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00001775 Result->AddTextChunk(PrintedNNS);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001776}
1777
Douglas Gregora61a8792009-12-11 18:44:16 +00001778static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1779 FunctionDecl *Function) {
1780 const FunctionProtoType *Proto
1781 = Function->getType()->getAs<FunctionProtoType>();
1782 if (!Proto || !Proto->getTypeQuals())
1783 return;
1784
1785 std::string QualsStr;
1786 if (Proto->getTypeQuals() & Qualifiers::Const)
1787 QualsStr += " const";
1788 if (Proto->getTypeQuals() & Qualifiers::Volatile)
1789 QualsStr += " volatile";
1790 if (Proto->getTypeQuals() & Qualifiers::Restrict)
1791 QualsStr += " restrict";
1792 Result->AddInformativeChunk(QualsStr);
1793}
1794
Douglas Gregor86d9a522009-09-21 16:56:56 +00001795/// \brief If possible, create a new code completion string for the given
1796/// result.
1797///
1798/// \returns Either a new, heap-allocated code completion string describing
1799/// how to use this result, or NULL to indicate that the string or name of the
1800/// result is all that is needed.
1801CodeCompletionString *
1802CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001803 typedef CodeCompletionString::Chunk Chunk;
1804
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001805 if (Kind == RK_Pattern)
1806 return Pattern->Clone();
1807
1808 CodeCompletionString *Result = new CodeCompletionString;
1809
1810 if (Kind == RK_Keyword) {
1811 Result->AddTypedTextChunk(Keyword);
1812 return Result;
1813 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001814
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001815 if (Kind == RK_Macro) {
1816 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001817 assert(MI && "Not a macro?");
1818
1819 Result->AddTypedTextChunk(Macro->getName());
1820
1821 if (!MI->isFunctionLike())
1822 return Result;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001823
1824 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001825 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001826 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
1827 A != AEnd; ++A) {
1828 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001829 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001830
1831 if (!MI->isVariadic() || A != AEnd - 1) {
1832 // Non-variadic argument.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001833 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001834 continue;
1835 }
1836
1837 // Variadic argument; cope with the different between GNU and C99
1838 // variadic macros, providing a single placeholder for the rest of the
1839 // arguments.
1840 if ((*A)->isStr("__VA_ARGS__"))
1841 Result->AddPlaceholderChunk("...");
1842 else {
1843 std::string Arg = (*A)->getName();
1844 Arg += "...";
Benjamin Kramer660cc182009-11-29 20:18:50 +00001845 Result->AddPlaceholderChunk(Arg);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001846 }
1847 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001848 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001849 return Result;
1850 }
1851
Douglas Gregord8e8a582010-05-25 21:41:55 +00001852 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00001853 NamedDecl *ND = Declaration;
1854
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001855 if (StartsNestedNameSpecifier) {
Benjamin Kramer660cc182009-11-29 20:18:50 +00001856 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001857 Result->AddTextChunk("::");
1858 return Result;
1859 }
1860
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001861 AddResultTypeChunk(S.Context, ND, Result);
1862
Douglas Gregor86d9a522009-09-21 16:56:56 +00001863 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001864 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1865 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00001866 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001867 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001868 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001869 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00001870 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001871 return Result;
1872 }
1873
1874 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001875 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1876 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001877 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramer660cc182009-11-29 20:18:50 +00001878 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001879
1880 // Figure out which template parameters are deduced (or have default
1881 // arguments).
1882 llvm::SmallVector<bool, 16> Deduced;
1883 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
1884 unsigned LastDeducibleArgument;
1885 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
1886 --LastDeducibleArgument) {
1887 if (!Deduced[LastDeducibleArgument - 1]) {
1888 // C++0x: Figure out if the template argument has a default. If so,
1889 // the user doesn't need to type this argument.
1890 // FIXME: We need to abstract template parameters better!
1891 bool HasDefaultArg = false;
1892 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
1893 LastDeducibleArgument - 1);
1894 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1895 HasDefaultArg = TTP->hasDefaultArgument();
1896 else if (NonTypeTemplateParmDecl *NTTP
1897 = dyn_cast<NonTypeTemplateParmDecl>(Param))
1898 HasDefaultArg = NTTP->hasDefaultArgument();
1899 else {
1900 assert(isa<TemplateTemplateParmDecl>(Param));
1901 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001902 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001903 }
1904
1905 if (!HasDefaultArg)
1906 break;
1907 }
1908 }
1909
1910 if (LastDeducibleArgument) {
1911 // Some of the function template arguments cannot be deduced from a
1912 // function call, so we introduce an explicit template argument list
1913 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001914 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001915 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
1916 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001917 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001918 }
1919
1920 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001921 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001922 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001923 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00001924 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001925 return Result;
1926 }
1927
1928 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001929 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1930 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00001931 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001932 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001933 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001934 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001935 return Result;
1936 }
1937
Douglas Gregor9630eb62009-11-17 16:44:22 +00001938 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00001939 Selector Sel = Method->getSelector();
1940 if (Sel.isUnarySelector()) {
1941 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
1942 return Result;
1943 }
1944
Douglas Gregord3c68542009-11-19 01:08:35 +00001945 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
1946 SelName += ':';
1947 if (StartParameter == 0)
1948 Result->AddTypedTextChunk(SelName);
1949 else {
1950 Result->AddInformativeChunk(SelName);
1951
1952 // If there is only one parameter, and we're past it, add an empty
1953 // typed-text chunk since there is nothing to type.
1954 if (Method->param_size() == 1)
1955 Result->AddTypedTextChunk("");
1956 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00001957 unsigned Idx = 0;
1958 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
1959 PEnd = Method->param_end();
1960 P != PEnd; (void)++P, ++Idx) {
1961 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00001962 std::string Keyword;
1963 if (Idx > StartParameter)
Douglas Gregor834389b2010-01-12 06:38:28 +00001964 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001965 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
1966 Keyword += II->getName().str();
1967 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00001968 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregord3c68542009-11-19 01:08:35 +00001969 Result->AddInformativeChunk(Keyword);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00001970 else if (Idx == StartParameter)
Douglas Gregord3c68542009-11-19 01:08:35 +00001971 Result->AddTypedTextChunk(Keyword);
1972 else
1973 Result->AddTextChunk(Keyword);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001974 }
Douglas Gregord3c68542009-11-19 01:08:35 +00001975
1976 // If we're before the starting parameter, skip the placeholder.
1977 if (Idx < StartParameter)
1978 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00001979
1980 std::string Arg;
1981 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
1982 Arg = "(" + Arg + ")";
1983 if (IdentifierInfo *II = (*P)->getIdentifier())
1984 Arg += II->getName().str();
Douglas Gregor1f5537a2010-07-08 23:20:03 +00001985 if (DeclaringEntity)
1986 Result->AddTextChunk(Arg);
1987 else if (AllParametersAreInformative)
Douglas Gregor4ad96852009-11-19 07:41:15 +00001988 Result->AddInformativeChunk(Arg);
1989 else
1990 Result->AddPlaceholderChunk(Arg);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001991 }
1992
Douglas Gregor2a17af02009-12-23 00:21:46 +00001993 if (Method->isVariadic()) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00001994 if (DeclaringEntity)
1995 Result->AddTextChunk(", ...");
1996 else if (AllParametersAreInformative)
Douglas Gregor2a17af02009-12-23 00:21:46 +00001997 Result->AddInformativeChunk(", ...");
1998 else
1999 Result->AddPlaceholderChunk(", ...");
2000 }
2001
Douglas Gregor9630eb62009-11-17 16:44:22 +00002002 return Result;
2003 }
2004
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002005 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002006 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2007 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002008
2009 Result->AddTypedTextChunk(ND->getNameAsString());
2010 return Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002011}
2012
Douglas Gregor86d802e2009-09-23 00:34:09 +00002013CodeCompletionString *
2014CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2015 unsigned CurrentArg,
2016 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002017 typedef CodeCompletionString::Chunk Chunk;
2018
Douglas Gregor86d802e2009-09-23 00:34:09 +00002019 CodeCompletionString *Result = new CodeCompletionString;
2020 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002021 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002022 const FunctionProtoType *Proto
2023 = dyn_cast<FunctionProtoType>(getFunctionType());
2024 if (!FDecl && !Proto) {
2025 // Function without a prototype. Just give the return type and a
2026 // highlighted ellipsis.
2027 const FunctionType *FT = getFunctionType();
2028 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002029 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002030 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2031 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2032 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002033 return Result;
2034 }
2035
2036 if (FDecl)
Benjamin Kramer660cc182009-11-29 20:18:50 +00002037 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregor86d802e2009-09-23 00:34:09 +00002038 else
2039 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002040 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002041
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002042 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002043 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2044 for (unsigned I = 0; I != NumParams; ++I) {
2045 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002046 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002047
2048 std::string ArgString;
2049 QualType ArgType;
2050
2051 if (FDecl) {
2052 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2053 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2054 } else {
2055 ArgType = Proto->getArgType(I);
2056 }
2057
2058 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2059
2060 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002061 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramer660cc182009-11-29 20:18:50 +00002062 ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002063 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00002064 Result->AddTextChunk(ArgString);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002065 }
2066
2067 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002068 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002069 if (CurrentArg < NumParams)
2070 Result->AddTextChunk("...");
2071 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002072 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002073 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002074 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002075
2076 return Result;
2077}
2078
Douglas Gregor86d9a522009-09-21 16:56:56 +00002079namespace {
2080 struct SortCodeCompleteResult {
2081 typedef CodeCompleteConsumer::Result Result;
2082
Douglas Gregor6a684032009-09-28 03:51:44 +00002083 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregor2b0cc122009-12-05 09:08:56 +00002084 Selector XSel = X.getObjCSelector();
2085 Selector YSel = Y.getObjCSelector();
2086 if (!XSel.isNull() && !YSel.isNull()) {
2087 // We are comparing two selectors.
2088 unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
2089 if (N == 0)
2090 ++N;
2091 for (unsigned I = 0; I != N; ++I) {
2092 IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
2093 IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
2094 if (!XId || !YId)
2095 return XId && !YId;
2096
2097 switch (XId->getName().compare_lower(YId->getName())) {
2098 case -1: return true;
2099 case 1: return false;
2100 default: break;
2101 }
2102 }
2103
2104 return XSel.getNumArgs() < YSel.getNumArgs();
2105 }
2106
2107 // For non-selectors, order by kind.
2108 if (X.getNameKind() != Y.getNameKind())
Douglas Gregor6a684032009-09-28 03:51:44 +00002109 return X.getNameKind() < Y.getNameKind();
2110
Douglas Gregor2b0cc122009-12-05 09:08:56 +00002111 // Order identifiers by comparison of their lowercased names.
2112 if (IdentifierInfo *XId = X.getAsIdentifierInfo())
2113 return XId->getName().compare_lower(
2114 Y.getAsIdentifierInfo()->getName()) < 0;
2115
2116 // Order overloaded operators by the order in which they appear
2117 // in our list of operators.
2118 if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
2119 return XOp < Y.getCXXOverloadedOperator();
2120
2121 // Order C++0x user-defined literal operators lexically by their
2122 // lowercased suffixes.
2123 if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
2124 return XLit->getName().compare_lower(
2125 Y.getCXXLiteralIdentifier()->getName()) < 0;
2126
2127 // The only stable ordering we have is to turn the name into a
2128 // string and then compare the lower-case strings. This is
2129 // inefficient, but thankfully does not happen too often.
Benjamin Kramer0e7049f2009-12-05 10:22:15 +00002130 return llvm::StringRef(X.getAsString()).compare_lower(
2131 Y.getAsString()) < 0;
Douglas Gregor6a684032009-09-28 03:51:44 +00002132 }
2133
Douglas Gregorab0b4f12010-01-13 23:24:38 +00002134 /// \brief Retrieve the name that should be used to order a result.
2135 ///
2136 /// If the name needs to be constructed as a string, that string will be
2137 /// saved into Saved and the returned StringRef will refer to it.
2138 static llvm::StringRef getOrderedName(const Result &R,
2139 std::string &Saved) {
2140 switch (R.Kind) {
2141 case Result::RK_Keyword:
2142 return R.Keyword;
2143
2144 case Result::RK_Pattern:
2145 return R.Pattern->getTypedText();
2146
2147 case Result::RK_Macro:
2148 return R.Macro->getName();
2149
2150 case Result::RK_Declaration:
2151 // Handle declarations below.
2152 break;
Douglas Gregor54f01612009-11-19 00:01:57 +00002153 }
Douglas Gregorab0b4f12010-01-13 23:24:38 +00002154
2155 DeclarationName Name = R.Declaration->getDeclName();
Douglas Gregor54f01612009-11-19 00:01:57 +00002156
Douglas Gregorab0b4f12010-01-13 23:24:38 +00002157 // If the name is a simple identifier (by far the common case), or a
2158 // zero-argument selector, just return a reference to that identifier.
2159 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
2160 return Id->getName();
2161 if (Name.isObjCZeroArgSelector())
2162 if (IdentifierInfo *Id
2163 = Name.getObjCSelector().getIdentifierInfoForSlot(0))
2164 return Id->getName();
2165
2166 Saved = Name.getAsString();
2167 return Saved;
2168 }
2169
2170 bool operator()(const Result &X, const Result &Y) const {
2171 std::string XSaved, YSaved;
2172 llvm::StringRef XStr = getOrderedName(X, XSaved);
2173 llvm::StringRef YStr = getOrderedName(Y, YSaved);
2174 int cmp = XStr.compare_lower(YStr);
2175 if (cmp)
2176 return cmp < 0;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002177
2178 // Non-hidden names precede hidden names.
2179 if (X.Hidden != Y.Hidden)
2180 return !X.Hidden;
2181
Douglas Gregoreb5758b2009-09-23 22:26:46 +00002182 // Non-nested-name-specifiers precede nested-name-specifiers.
2183 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
2184 return !X.StartsNestedNameSpecifier;
2185
Douglas Gregor86d9a522009-09-21 16:56:56 +00002186 return false;
2187 }
2188 };
2189}
2190
Douglas Gregor590c7d52010-07-08 20:55:51 +00002191static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2192 bool TargetTypeIsPointer = false) {
2193 typedef CodeCompleteConsumer::Result Result;
2194
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002195 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002196 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2197 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002198 M != MEnd; ++M) {
2199 unsigned Priority = CCP_Macro;
2200
2201 // Treat the "nil" and "NULL" macros as null pointer constants.
2202 if (M->first->isStr("nil") || M->first->isStr("NULL")) {
2203 Priority = CCP_Constant;
2204 if (TargetTypeIsPointer)
2205 Priority = Priority / CCF_SimilarTypeMatch;
2206 }
2207
2208 Results.AddResult(Result(M->first, Priority));
2209 }
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002210 Results.ExitScope();
2211}
2212
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002213static void HandleCodeCompleteResults(Sema *S,
2214 CodeCompleteConsumer *CodeCompleter,
2215 CodeCompleteConsumer::Result *Results,
2216 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002217 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
2218
2219 if (CodeCompleter)
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002220 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00002221
2222 for (unsigned I = 0; I != NumResults; ++I)
2223 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002224}
2225
Douglas Gregor01dfea02010-01-10 23:08:15 +00002226void Sema::CodeCompleteOrdinaryName(Scope *S,
2227 CodeCompletionContext CompletionContext) {
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002228 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002229 ResultBuilder Results(*this);
2230
2231 // Determine how to filter results, e.g., so that the names of
2232 // values (functions, enumerators, function templates, etc.) are
2233 // only allowed where we can have an expression.
2234 switch (CompletionContext) {
2235 case CCC_Namespace:
2236 case CCC_Class:
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002237 case CCC_ObjCInterface:
2238 case CCC_ObjCImplementation:
Douglas Gregorc38c3e12010-01-13 21:54:15 +00002239 case CCC_ObjCInstanceVariableList:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002240 case CCC_Template:
2241 case CCC_MemberTemplate:
2242 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2243 break;
2244
2245 case CCC_Expression:
2246 case CCC_Statement:
2247 case CCC_ForInit:
2248 case CCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002249 if (WantTypesInContext(CompletionContext, getLangOptions()))
2250 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2251 else
2252 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002253 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002254
2255 case CCC_RecoveryInFunction:
2256 // Unfiltered
2257 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002258 }
2259
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002260 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2261 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002262
2263 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00002264 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002265 Results.ExitScope();
2266
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002267 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002268 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002269 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002270}
2271
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002272/// \brief Perform code-completion in an expression context when we know what
2273/// type we're looking for.
2274void Sema::CodeCompleteExpression(Scope *S, QualType T) {
2275 typedef CodeCompleteConsumer::Result Result;
2276 ResultBuilder Results(*this);
2277
2278 if (WantTypesInContext(CCC_Expression, getLangOptions()))
2279 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2280 else
2281 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
2282 Results.setPreferredType(T.getNonReferenceType());
2283
2284 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2285 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2286
2287 Results.EnterNewScope();
2288 AddOrdinaryNameResults(CCC_Expression, S, *this, Results);
2289 Results.ExitScope();
2290
Douglas Gregor590c7d52010-07-08 20:55:51 +00002291 bool PreferredTypeIsPointer = false;
2292 if (!T.isNull())
2293 PreferredTypeIsPointer = T->isAnyPointerType() ||
2294 T->isMemberPointerType() || T->isBlockPointerType();
2295
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002296 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00002297 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002298 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2299}
2300
2301
Douglas Gregor95ac6552009-11-18 01:29:26 +00002302static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00002303 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00002304 DeclContext *CurContext,
2305 ResultBuilder &Results) {
2306 typedef CodeCompleteConsumer::Result Result;
2307
2308 // Add properties in this container.
2309 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2310 PEnd = Container->prop_end();
2311 P != PEnd;
2312 ++P)
2313 Results.MaybeAddResult(Result(*P, 0), CurContext);
2314
2315 // Add properties in referenced protocols.
2316 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2317 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2318 PEnd = Protocol->protocol_end();
2319 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002320 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002321 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00002322 if (AllowCategories) {
2323 // Look through categories.
2324 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2325 Category; Category = Category->getNextClassCategory())
2326 AddObjCProperties(Category, AllowCategories, CurContext, Results);
2327 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002328
2329 // Look through protocols.
2330 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2331 E = IFace->protocol_end();
2332 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002333 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002334
2335 // Look in the superclass.
2336 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00002337 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2338 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002339 } else if (const ObjCCategoryDecl *Category
2340 = dyn_cast<ObjCCategoryDecl>(Container)) {
2341 // Look through protocols.
2342 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
2343 PEnd = Category->protocol_end();
2344 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002345 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002346 }
2347}
2348
Douglas Gregor81b747b2009-09-17 21:32:03 +00002349void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2350 SourceLocation OpLoc,
2351 bool IsArrow) {
2352 if (!BaseE || !CodeCompleter)
2353 return;
2354
Douglas Gregor86d9a522009-09-21 16:56:56 +00002355 typedef CodeCompleteConsumer::Result Result;
2356
Douglas Gregor81b747b2009-09-17 21:32:03 +00002357 Expr *Base = static_cast<Expr *>(BaseE);
2358 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002359
2360 if (IsArrow) {
2361 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2362 BaseType = Ptr->getPointeeType();
2363 else if (BaseType->isObjCObjectPointerType())
2364 /*Do nothing*/ ;
2365 else
2366 return;
2367 }
2368
Douglas Gregoreb5758b2009-09-23 22:26:46 +00002369 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002370 Results.EnterNewScope();
2371 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
2372 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00002373 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00002374 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2375 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002376
Douglas Gregor95ac6552009-11-18 01:29:26 +00002377 if (getLangOptions().CPlusPlus) {
2378 if (!Results.empty()) {
2379 // The "template" keyword can follow "->" or "." in the grammar.
2380 // However, we only want to suggest the template keyword if something
2381 // is dependent.
2382 bool IsDependent = BaseType->isDependentType();
2383 if (!IsDependent) {
2384 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2385 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2386 IsDependent = Ctx->isDependentContext();
2387 break;
2388 }
2389 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002390
Douglas Gregor95ac6552009-11-18 01:29:26 +00002391 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00002392 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002393 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002394 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002395 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2396 // Objective-C property reference.
2397
2398 // Add property results based on our interface.
2399 const ObjCObjectPointerType *ObjCPtr
2400 = BaseType->getAsObjCInterfacePointerType();
2401 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00002402 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002403
2404 // Add properties from the protocols in a qualified interface.
2405 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2406 E = ObjCPtr->qual_end();
2407 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002408 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002409 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00002410 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00002411 // Objective-C instance variable access.
2412 ObjCInterfaceDecl *Class = 0;
2413 if (const ObjCObjectPointerType *ObjCPtr
2414 = BaseType->getAs<ObjCObjectPointerType>())
2415 Class = ObjCPtr->getInterfaceDecl();
2416 else
John McCallc12c5bb2010-05-15 11:32:37 +00002417 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00002418
2419 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00002420 if (Class) {
2421 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2422 Results.setFilter(&ResultBuilder::IsObjCIvar);
2423 LookupVisibleDecls(Class, LookupMemberName, Consumer);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002424 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002425 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002426
2427 // FIXME: How do we cope with isa?
2428
2429 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002430
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002431 // Hand off the results found for code completion.
2432 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002433}
2434
Douglas Gregor374929f2009-09-18 15:37:17 +00002435void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2436 if (!CodeCompleter)
2437 return;
2438
Douglas Gregor86d9a522009-09-21 16:56:56 +00002439 typedef CodeCompleteConsumer::Result Result;
2440 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor374929f2009-09-18 15:37:17 +00002441 switch ((DeclSpec::TST)TagSpec) {
2442 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002443 Filter = &ResultBuilder::IsEnum;
Douglas Gregor374929f2009-09-18 15:37:17 +00002444 break;
2445
2446 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002447 Filter = &ResultBuilder::IsUnion;
Douglas Gregor374929f2009-09-18 15:37:17 +00002448 break;
2449
2450 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00002451 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002452 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor374929f2009-09-18 15:37:17 +00002453 break;
2454
2455 default:
2456 assert(false && "Unknown type specifier kind in CodeCompleteTag");
2457 return;
2458 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002459
John McCall0d6b1642010-04-23 18:46:30 +00002460 ResultBuilder Results(*this);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002461 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00002462
2463 // First pass: look for tags.
2464 Results.setFilter(Filter);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002465 LookupVisibleDecls(S, LookupTagName, Consumer);
John McCall0d6b1642010-04-23 18:46:30 +00002466
2467 // Second pass: look for nested name specifiers.
2468 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
2469 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002470
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002471 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00002472}
2473
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002474void Sema::CodeCompleteCase(Scope *S) {
2475 if (getSwitchStack().empty() || !CodeCompleter)
2476 return;
2477
2478 SwitchStmt *Switch = getSwitchStack().back();
2479 if (!Switch->getCond()->getType()->isEnumeralType())
2480 return;
2481
2482 // Code-complete the cases of a switch statement over an enumeration type
2483 // by providing the list of
2484 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2485
2486 // Determine which enumerators we have already seen in the switch statement.
2487 // FIXME: Ideally, we would also be able to look *past* the code-completion
2488 // token, in case we are code-completing in the middle of the switch and not
2489 // at the end. However, we aren't able to do so at the moment.
2490 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002491 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002492 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2493 SC = SC->getNextSwitchCase()) {
2494 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2495 if (!Case)
2496 continue;
2497
2498 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2499 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2500 if (EnumConstantDecl *Enumerator
2501 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2502 // We look into the AST of the case statement to determine which
2503 // enumerator was named. Alternatively, we could compute the value of
2504 // the integral constant expression, then compare it against the
2505 // values of each enumerator. However, value-based approach would not
2506 // work as well with C++ templates where enumerators declared within a
2507 // template are type- and value-dependent.
2508 EnumeratorsSeen.insert(Enumerator);
2509
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002510 // If this is a qualified-id, keep track of the nested-name-specifier
2511 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002512 //
2513 // switch (TagD.getKind()) {
2514 // case TagDecl::TK_enum:
2515 // break;
2516 // case XXX
2517 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002518 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002519 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2520 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002521 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002522 }
2523 }
2524
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002525 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2526 // If there are no prior enumerators in C++, check whether we have to
2527 // qualify the names of the enumerators that we suggest, because they
2528 // may not be visible in this scope.
2529 Qualifier = getRequiredQualification(Context, CurContext,
2530 Enum->getDeclContext());
2531
2532 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2533 }
2534
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002535 // Add any enumerators that have not yet been mentioned.
2536 ResultBuilder Results(*this);
2537 Results.EnterNewScope();
2538 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2539 EEnd = Enum->enumerator_end();
2540 E != EEnd; ++E) {
2541 if (EnumeratorsSeen.count(*E))
2542 continue;
2543
Douglas Gregor608300b2010-01-14 16:14:35 +00002544 Results.AddResult(CodeCompleteConsumer::Result(*E, Qualifier),
2545 CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002546 }
2547 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00002548
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002549 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002550 AddMacroResults(PP, Results);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002551 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002552}
2553
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002554namespace {
2555 struct IsBetterOverloadCandidate {
2556 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00002557 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002558
2559 public:
John McCall5769d612010-02-08 23:07:23 +00002560 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
2561 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002562
2563 bool
2564 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall5769d612010-02-08 23:07:23 +00002565 return S.isBetterOverloadCandidate(X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002566 }
2567 };
2568}
2569
Douglas Gregord28dcd72010-05-30 06:10:08 +00002570static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
2571 if (NumArgs && !Args)
2572 return true;
2573
2574 for (unsigned I = 0; I != NumArgs; ++I)
2575 if (!Args[I])
2576 return true;
2577
2578 return false;
2579}
2580
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002581void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2582 ExprTy **ArgsIn, unsigned NumArgs) {
2583 if (!CodeCompleter)
2584 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002585
2586 // When we're code-completing for a call, we fall back to ordinary
2587 // name code-completion whenever we can't produce specific
2588 // results. We may want to revisit this strategy in the future,
2589 // e.g., by merging the two kinds of results.
2590
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002591 Expr *Fn = (Expr *)FnIn;
2592 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002593
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002594 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00002595 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00002596 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00002597 CodeCompleteOrdinaryName(S, CCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002598 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002599 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002600
John McCall3b4294e2009-12-16 12:17:52 +00002601 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00002602 SourceLocation Loc = Fn->getExprLoc();
2603 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00002604
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002605 // FIXME: What if we're calling something that isn't a function declaration?
2606 // FIXME: What if we're calling a pseudo-destructor?
2607 // FIXME: What if we're calling a member function?
2608
Douglas Gregorc0265402010-01-21 15:46:19 +00002609 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
2610 llvm::SmallVector<ResultCandidate, 8> Results;
2611
John McCall3b4294e2009-12-16 12:17:52 +00002612 Expr *NakedFn = Fn->IgnoreParenCasts();
2613 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
2614 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
2615 /*PartialOverloading=*/ true);
2616 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
2617 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00002618 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00002619 if (!getLangOptions().CPlusPlus ||
2620 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00002621 Results.push_back(ResultCandidate(FDecl));
2622 else
John McCall86820f52010-01-26 01:37:31 +00002623 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00002624 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
2625 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00002626 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00002627 }
John McCall3b4294e2009-12-16 12:17:52 +00002628 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002629
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002630 QualType ParamType;
2631
Douglas Gregorc0265402010-01-21 15:46:19 +00002632 if (!CandidateSet.empty()) {
2633 // Sort the overload candidate set by placing the best overloads first.
2634 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00002635 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002636
Douglas Gregorc0265402010-01-21 15:46:19 +00002637 // Add the remaining viable overload candidates as code-completion reslults.
2638 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2639 CandEnd = CandidateSet.end();
2640 Cand != CandEnd; ++Cand) {
2641 if (Cand->Viable)
2642 Results.push_back(ResultCandidate(Cand->Function));
2643 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002644
2645 // From the viable candidates, try to determine the type of this parameter.
2646 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
2647 if (const FunctionType *FType = Results[I].getFunctionType())
2648 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
2649 if (NumArgs < Proto->getNumArgs()) {
2650 if (ParamType.isNull())
2651 ParamType = Proto->getArgType(NumArgs);
2652 else if (!Context.hasSameUnqualifiedType(
2653 ParamType.getNonReferenceType(),
2654 Proto->getArgType(NumArgs).getNonReferenceType())) {
2655 ParamType = QualType();
2656 break;
2657 }
2658 }
2659 }
2660 } else {
2661 // Try to determine the parameter type from the type of the expression
2662 // being called.
2663 QualType FunctionType = Fn->getType();
2664 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
2665 FunctionType = Ptr->getPointeeType();
2666 else if (const BlockPointerType *BlockPtr
2667 = FunctionType->getAs<BlockPointerType>())
2668 FunctionType = BlockPtr->getPointeeType();
2669 else if (const MemberPointerType *MemPtr
2670 = FunctionType->getAs<MemberPointerType>())
2671 FunctionType = MemPtr->getPointeeType();
2672
2673 if (const FunctionProtoType *Proto
2674 = FunctionType->getAs<FunctionProtoType>()) {
2675 if (NumArgs < Proto->getNumArgs())
2676 ParamType = Proto->getArgType(NumArgs);
2677 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002678 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00002679
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002680 if (ParamType.isNull())
2681 CodeCompleteOrdinaryName(S, CCC_Expression);
2682 else
2683 CodeCompleteExpression(S, ParamType);
2684
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00002685 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00002686 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
2687 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002688}
2689
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002690void Sema::CodeCompleteInitializer(Scope *S, DeclPtrTy D) {
2691 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D.getAs<Decl>());
2692 if (!VD) {
2693 CodeCompleteOrdinaryName(S, CCC_Expression);
2694 return;
2695 }
2696
2697 CodeCompleteExpression(S, VD->getType());
2698}
2699
2700void Sema::CodeCompleteReturn(Scope *S) {
2701 QualType ResultType;
2702 if (isa<BlockDecl>(CurContext)) {
2703 if (BlockScopeInfo *BSI = getCurBlock())
2704 ResultType = BSI->ReturnType;
2705 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
2706 ResultType = Function->getResultType();
2707 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
2708 ResultType = Method->getResultType();
2709
2710 if (ResultType.isNull())
2711 CodeCompleteOrdinaryName(S, CCC_Expression);
2712 else
2713 CodeCompleteExpression(S, ResultType);
2714}
2715
2716void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
2717 if (LHS)
2718 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
2719 else
2720 CodeCompleteOrdinaryName(S, CCC_Expression);
2721}
2722
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002723void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00002724 bool EnteringContext) {
2725 if (!SS.getScopeRep() || !CodeCompleter)
2726 return;
2727
Douglas Gregor86d9a522009-09-21 16:56:56 +00002728 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
2729 if (!Ctx)
2730 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00002731
2732 // Try to instantiate any non-dependent declaration contexts before
2733 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00002734 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00002735 return;
2736
Douglas Gregor86d9a522009-09-21 16:56:56 +00002737 ResultBuilder Results(*this);
Douglas Gregordef91072010-01-14 03:35:48 +00002738 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2739 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002740
2741 // The "template" keyword can follow "::" in the grammar, but only
2742 // put it into the grammar if the nested-name-specifier is dependent.
2743 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
2744 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00002745 Results.AddResult("template");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002746
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002747 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002748}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002749
2750void Sema::CodeCompleteUsing(Scope *S) {
2751 if (!CodeCompleter)
2752 return;
2753
Douglas Gregor86d9a522009-09-21 16:56:56 +00002754 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002755 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002756
2757 // If we aren't in class scope, we could see the "namespace" keyword.
2758 if (!S->isClassScope())
Douglas Gregora4477812010-01-14 16:01:26 +00002759 Results.AddResult(CodeCompleteConsumer::Result("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002760
2761 // After "using", we can see anything that would start a
2762 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002763 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2764 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002765 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002766
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002767 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002768}
2769
2770void Sema::CodeCompleteUsingDirective(Scope *S) {
2771 if (!CodeCompleter)
2772 return;
2773
Douglas Gregor86d9a522009-09-21 16:56:56 +00002774 // After "using namespace", we expect to see a namespace name or namespace
2775 // alias.
2776 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002777 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002778 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2779 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002780 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002781 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002782}
2783
2784void Sema::CodeCompleteNamespaceDecl(Scope *S) {
2785 if (!CodeCompleter)
2786 return;
2787
Douglas Gregor86d9a522009-09-21 16:56:56 +00002788 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
2789 DeclContext *Ctx = (DeclContext *)S->getEntity();
2790 if (!S->getParent())
2791 Ctx = Context.getTranslationUnitDecl();
2792
2793 if (Ctx && Ctx->isFileContext()) {
2794 // We only want to see those namespaces that have already been defined
2795 // within this scope, because its likely that the user is creating an
2796 // extended namespace declaration. Keep track of the most recent
2797 // definition of each namespace.
2798 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
2799 for (DeclContext::specific_decl_iterator<NamespaceDecl>
2800 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
2801 NS != NSEnd; ++NS)
2802 OrigToLatest[NS->getOriginalNamespace()] = *NS;
2803
2804 // Add the most recent definition (or extended definition) of each
2805 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002806 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002807 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
2808 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
2809 NS != NSEnd; ++NS)
Douglas Gregor608300b2010-01-14 16:14:35 +00002810 Results.AddResult(CodeCompleteConsumer::Result(NS->second, 0),
2811 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002812 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002813 }
2814
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002815 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002816}
2817
2818void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
2819 if (!CodeCompleter)
2820 return;
2821
Douglas Gregor86d9a522009-09-21 16:56:56 +00002822 // After "namespace", we expect to see a namespace or alias.
2823 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002824 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2825 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002826 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002827}
2828
Douglas Gregored8d3222009-09-18 20:05:18 +00002829void Sema::CodeCompleteOperatorName(Scope *S) {
2830 if (!CodeCompleter)
2831 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002832
2833 typedef CodeCompleteConsumer::Result Result;
2834 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002835 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00002836
Douglas Gregor86d9a522009-09-21 16:56:56 +00002837 // Add the names of overloadable operators.
2838#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2839 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00002840 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002841#include "clang/Basic/OperatorKinds.def"
2842
2843 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00002844 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002845 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2846 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002847
2848 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00002849 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002850 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002851
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002852 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00002853}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002854
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002855// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
2856// true or false.
2857#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00002858static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002859 ResultBuilder &Results,
2860 bool NeedAt) {
2861 typedef CodeCompleteConsumer::Result Result;
2862 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00002863 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002864
2865 CodeCompletionString *Pattern = 0;
2866 if (LangOpts.ObjC2) {
2867 // @dynamic
2868 Pattern = new CodeCompletionString;
2869 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
2870 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2871 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00002872 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002873
2874 // @synthesize
2875 Pattern = new CodeCompletionString;
2876 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
2877 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2878 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00002879 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002880 }
2881}
2882
Douglas Gregorbca403c2010-01-13 23:51:12 +00002883static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002884 ResultBuilder &Results,
2885 bool NeedAt) {
2886 typedef CodeCompleteConsumer::Result Result;
2887
2888 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00002889 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002890
2891 if (LangOpts.ObjC2) {
2892 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00002893 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002894
2895 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00002896 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002897
2898 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00002899 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002900 }
2901}
2902
Douglas Gregorbca403c2010-01-13 23:51:12 +00002903static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002904 typedef CodeCompleteConsumer::Result Result;
2905 CodeCompletionString *Pattern = 0;
2906
2907 // @class name ;
2908 Pattern = new CodeCompletionString;
2909 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
2910 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00002911 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00002912 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002913
Douglas Gregorc8bddde2010-05-28 00:22:41 +00002914 if (Results.includeCodePatterns()) {
2915 // @interface name
2916 // FIXME: Could introduce the whole pattern, including superclasses and
2917 // such.
2918 Pattern = new CodeCompletionString;
2919 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
2920 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2921 Pattern->AddPlaceholderChunk("class");
2922 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002923
Douglas Gregorc8bddde2010-05-28 00:22:41 +00002924 // @protocol name
2925 Pattern = new CodeCompletionString;
2926 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
2927 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2928 Pattern->AddPlaceholderChunk("protocol");
2929 Results.AddResult(Result(Pattern));
2930
2931 // @implementation name
2932 Pattern = new CodeCompletionString;
2933 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
2934 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2935 Pattern->AddPlaceholderChunk("class");
2936 Results.AddResult(Result(Pattern));
2937 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002938
2939 // @compatibility_alias name
2940 Pattern = new CodeCompletionString;
2941 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
2942 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2943 Pattern->AddPlaceholderChunk("alias");
2944 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2945 Pattern->AddPlaceholderChunk("class");
Douglas Gregora4477812010-01-14 16:01:26 +00002946 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002947}
2948
Douglas Gregorc464ae82009-12-07 09:27:33 +00002949void Sema::CodeCompleteObjCAtDirective(Scope *S, DeclPtrTy ObjCImpDecl,
2950 bool InInterface) {
2951 typedef CodeCompleteConsumer::Result Result;
2952 ResultBuilder Results(*this);
2953 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002954 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00002955 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002956 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00002957 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002958 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00002959 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00002960 Results.ExitScope();
2961 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2962}
2963
Douglas Gregorbca403c2010-01-13 23:51:12 +00002964static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002965 typedef CodeCompleteConsumer::Result Result;
2966 CodeCompletionString *Pattern = 0;
2967
2968 // @encode ( type-name )
2969 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002970 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002971 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2972 Pattern->AddPlaceholderChunk("type-name");
2973 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00002974 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002975
2976 // @protocol ( protocol-name )
2977 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002978 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002979 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2980 Pattern->AddPlaceholderChunk("protocol-name");
2981 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00002982 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002983
2984 // @selector ( selector )
2985 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002986 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002987 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2988 Pattern->AddPlaceholderChunk("selector");
2989 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00002990 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002991}
2992
Douglas Gregorbca403c2010-01-13 23:51:12 +00002993static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002994 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00002995 CodeCompletionString *Pattern = 0;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002996
Douglas Gregorc8bddde2010-05-28 00:22:41 +00002997 if (Results.includeCodePatterns()) {
2998 // @try { statements } @catch ( declaration ) { statements } @finally
2999 // { statements }
3000 Pattern = new CodeCompletionString;
3001 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
3002 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3003 Pattern->AddPlaceholderChunk("statements");
3004 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3005 Pattern->AddTextChunk("@catch");
3006 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3007 Pattern->AddPlaceholderChunk("parameter");
3008 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3009 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3010 Pattern->AddPlaceholderChunk("statements");
3011 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3012 Pattern->AddTextChunk("@finally");
3013 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3014 Pattern->AddPlaceholderChunk("statements");
3015 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3016 Results.AddResult(Result(Pattern));
3017 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003018
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003019 // @throw
3020 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003021 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
Douglas Gregor834389b2010-01-12 06:38:28 +00003022 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003023 Pattern->AddPlaceholderChunk("expression");
Douglas Gregora4477812010-01-14 16:01:26 +00003024 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003025
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003026 if (Results.includeCodePatterns()) {
3027 // @synchronized ( expression ) { statements }
3028 Pattern = new CodeCompletionString;
3029 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3030 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3031 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3032 Pattern->AddPlaceholderChunk("expression");
3033 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3034 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3035 Pattern->AddPlaceholderChunk("statements");
3036 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3037 Results.AddResult(Result(Pattern));
3038 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003039}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003040
Douglas Gregorbca403c2010-01-13 23:51:12 +00003041static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003042 ResultBuilder &Results,
3043 bool NeedAt) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003044 typedef CodeCompleteConsumer::Result Result;
Douglas Gregora4477812010-01-14 16:01:26 +00003045 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3046 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3047 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003048 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00003049 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003050}
3051
3052void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
3053 ResultBuilder Results(*this);
3054 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003055 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003056 Results.ExitScope();
3057 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3058}
3059
3060void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003061 ResultBuilder Results(*this);
3062 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003063 AddObjCStatementResults(Results, false);
3064 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003065 Results.ExitScope();
3066 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3067}
3068
3069void Sema::CodeCompleteObjCAtExpression(Scope *S) {
3070 ResultBuilder Results(*this);
3071 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003072 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003073 Results.ExitScope();
3074 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3075}
3076
Douglas Gregor988358f2009-11-19 00:14:45 +00003077/// \brief Determine whether the addition of the given flag to an Objective-C
3078/// property's attributes will cause a conflict.
3079static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3080 // Check if we've already added this flag.
3081 if (Attributes & NewFlag)
3082 return true;
3083
3084 Attributes |= NewFlag;
3085
3086 // Check for collisions with "readonly".
3087 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3088 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3089 ObjCDeclSpec::DQ_PR_assign |
3090 ObjCDeclSpec::DQ_PR_copy |
3091 ObjCDeclSpec::DQ_PR_retain)))
3092 return true;
3093
3094 // Check for more than one of { assign, copy, retain }.
3095 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3096 ObjCDeclSpec::DQ_PR_copy |
3097 ObjCDeclSpec::DQ_PR_retain);
3098 if (AssignCopyRetMask &&
3099 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3100 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3101 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3102 return true;
3103
3104 return false;
3105}
3106
Douglas Gregora93b1082009-11-18 23:08:07 +00003107void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00003108 if (!CodeCompleter)
3109 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00003110
Steve Naroffece8e712009-10-08 21:55:05 +00003111 unsigned Attributes = ODS.getPropertyAttributes();
3112
3113 typedef CodeCompleteConsumer::Result Result;
3114 ResultBuilder Results(*this);
3115 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00003116 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
Douglas Gregora4477812010-01-14 16:01:26 +00003117 Results.AddResult(CodeCompleteConsumer::Result("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003118 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
Douglas Gregora4477812010-01-14 16:01:26 +00003119 Results.AddResult(CodeCompleteConsumer::Result("assign"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003120 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregora4477812010-01-14 16:01:26 +00003121 Results.AddResult(CodeCompleteConsumer::Result("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003122 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
Douglas Gregora4477812010-01-14 16:01:26 +00003123 Results.AddResult(CodeCompleteConsumer::Result("retain"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003124 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
Douglas Gregora4477812010-01-14 16:01:26 +00003125 Results.AddResult(CodeCompleteConsumer::Result("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003126 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
Douglas Gregora4477812010-01-14 16:01:26 +00003127 Results.AddResult(CodeCompleteConsumer::Result("nonatomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003128 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003129 CodeCompletionString *Setter = new CodeCompletionString;
3130 Setter->AddTypedTextChunk("setter");
3131 Setter->AddTextChunk(" = ");
3132 Setter->AddPlaceholderChunk("method");
Douglas Gregora4477812010-01-14 16:01:26 +00003133 Results.AddResult(CodeCompleteConsumer::Result(Setter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003134 }
Douglas Gregor988358f2009-11-19 00:14:45 +00003135 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003136 CodeCompletionString *Getter = new CodeCompletionString;
3137 Getter->AddTypedTextChunk("getter");
3138 Getter->AddTextChunk(" = ");
3139 Getter->AddPlaceholderChunk("method");
Douglas Gregora4477812010-01-14 16:01:26 +00003140 Results.AddResult(CodeCompleteConsumer::Result(Getter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003141 }
Steve Naroffece8e712009-10-08 21:55:05 +00003142 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003143 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00003144}
Steve Naroffc4df6d22009-11-07 02:08:14 +00003145
Douglas Gregor4ad96852009-11-19 07:41:15 +00003146/// \brief Descripts the kind of Objective-C method that we want to find
3147/// via code completion.
3148enum ObjCMethodKind {
3149 MK_Any, //< Any kind of method, provided it means other specified criteria.
3150 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3151 MK_OneArgSelector //< One-argument selector.
3152};
3153
3154static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
3155 ObjCMethodKind WantKind,
3156 IdentifierInfo **SelIdents,
3157 unsigned NumSelIdents) {
3158 Selector Sel = Method->getSelector();
3159 if (NumSelIdents > Sel.getNumArgs())
3160 return false;
3161
3162 switch (WantKind) {
3163 case MK_Any: break;
3164 case MK_ZeroArgSelector: return Sel.isUnarySelector();
3165 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
3166 }
3167
3168 for (unsigned I = 0; I != NumSelIdents; ++I)
3169 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
3170 return false;
3171
3172 return true;
3173}
3174
Douglas Gregor36ecb042009-11-17 23:22:23 +00003175/// \brief Add all of the Objective-C methods in the given Objective-C
3176/// container to the set of results.
3177///
3178/// The container will be a class, protocol, category, or implementation of
3179/// any of the above. This mether will recurse to include methods from
3180/// the superclasses of classes along with their categories, protocols, and
3181/// implementations.
3182///
3183/// \param Container the container in which we'll look to find methods.
3184///
3185/// \param WantInstance whether to add instance methods (only); if false, this
3186/// routine will add factory methods (only).
3187///
3188/// \param CurContext the context in which we're performing the lookup that
3189/// finds methods.
3190///
3191/// \param Results the structure into which we'll add results.
3192static void AddObjCMethods(ObjCContainerDecl *Container,
3193 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003194 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00003195 IdentifierInfo **SelIdents,
3196 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00003197 DeclContext *CurContext,
3198 ResultBuilder &Results) {
3199 typedef CodeCompleteConsumer::Result Result;
3200 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3201 MEnd = Container->meth_end();
3202 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00003203 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3204 // Check whether the selector identifiers we've been given are a
3205 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00003206 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00003207 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003208
Douglas Gregord3c68542009-11-19 01:08:35 +00003209 Result R = Result(*M, 0);
3210 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003211 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregord3c68542009-11-19 01:08:35 +00003212 Results.MaybeAddResult(R, CurContext);
3213 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00003214 }
3215
3216 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
3217 if (!IFace)
3218 return;
3219
3220 // Add methods in protocols.
3221 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
3222 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3223 E = Protocols.end();
3224 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003225 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord3c68542009-11-19 01:08:35 +00003226 CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003227
3228 // Add methods in categories.
3229 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
3230 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00003231 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
3232 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003233
3234 // Add a categories protocol methods.
3235 const ObjCList<ObjCProtocolDecl> &Protocols
3236 = CatDecl->getReferencedProtocols();
3237 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3238 E = Protocols.end();
3239 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003240 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
3241 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003242
3243 // Add methods in category implementations.
3244 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003245 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3246 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003247 }
3248
3249 // Add methods in superclass.
3250 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003251 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
3252 SelIdents, NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003253
3254 // Add methods in our implementation, if any.
3255 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003256 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3257 NumSelIdents, CurContext, Results);
3258}
3259
3260
3261void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
3262 DeclPtrTy *Methods,
3263 unsigned NumMethods) {
3264 typedef CodeCompleteConsumer::Result Result;
3265
3266 // Try to find the interface where getters might live.
3267 ObjCInterfaceDecl *Class
3268 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
3269 if (!Class) {
3270 if (ObjCCategoryDecl *Category
3271 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
3272 Class = Category->getClassInterface();
3273
3274 if (!Class)
3275 return;
3276 }
3277
3278 // Find all of the potential getters.
3279 ResultBuilder Results(*this);
3280 Results.EnterNewScope();
3281
3282 // FIXME: We need to do this because Objective-C methods don't get
3283 // pushed into DeclContexts early enough. Argh!
3284 for (unsigned I = 0; I != NumMethods; ++I) {
3285 if (ObjCMethodDecl *Method
3286 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3287 if (Method->isInstanceMethod() &&
3288 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
3289 Result R = Result(Method, 0);
3290 R.AllParametersAreInformative = true;
3291 Results.MaybeAddResult(R, CurContext);
3292 }
3293 }
3294
3295 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
3296 Results.ExitScope();
3297 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
3298}
3299
3300void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
3301 DeclPtrTy *Methods,
3302 unsigned NumMethods) {
3303 typedef CodeCompleteConsumer::Result Result;
3304
3305 // Try to find the interface where setters might live.
3306 ObjCInterfaceDecl *Class
3307 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
3308 if (!Class) {
3309 if (ObjCCategoryDecl *Category
3310 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
3311 Class = Category->getClassInterface();
3312
3313 if (!Class)
3314 return;
3315 }
3316
3317 // Find all of the potential getters.
3318 ResultBuilder Results(*this);
3319 Results.EnterNewScope();
3320
3321 // FIXME: We need to do this because Objective-C methods don't get
3322 // pushed into DeclContexts early enough. Argh!
3323 for (unsigned I = 0; I != NumMethods; ++I) {
3324 if (ObjCMethodDecl *Method
3325 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3326 if (Method->isInstanceMethod() &&
3327 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
3328 Result R = Result(Method, 0);
3329 R.AllParametersAreInformative = true;
3330 Results.MaybeAddResult(R, CurContext);
3331 }
3332 }
3333
3334 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
3335
3336 Results.ExitScope();
3337 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00003338}
3339
Douglas Gregor22f56992010-04-06 19:22:33 +00003340/// \brief When we have an expression with type "id", we may assume
3341/// that it has some more-specific class type based on knowledge of
3342/// common uses of Objective-C. This routine returns that class type,
3343/// or NULL if no better result could be determined.
3344static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
3345 ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E);
3346 if (!Msg)
3347 return 0;
3348
3349 Selector Sel = Msg->getSelector();
3350 if (Sel.isNull())
3351 return 0;
3352
3353 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
3354 if (!Id)
3355 return 0;
3356
3357 ObjCMethodDecl *Method = Msg->getMethodDecl();
3358 if (!Method)
3359 return 0;
3360
3361 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00003362 ObjCInterfaceDecl *IFace = 0;
3363 switch (Msg->getReceiverKind()) {
3364 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00003365 if (const ObjCObjectType *ObjType
3366 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
3367 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00003368 break;
3369
3370 case ObjCMessageExpr::Instance: {
3371 QualType T = Msg->getInstanceReceiver()->getType();
3372 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
3373 IFace = Ptr->getInterfaceDecl();
3374 break;
3375 }
3376
3377 case ObjCMessageExpr::SuperInstance:
3378 case ObjCMessageExpr::SuperClass:
3379 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00003380 }
3381
3382 if (!IFace)
3383 return 0;
3384
3385 ObjCInterfaceDecl *Super = IFace->getSuperClass();
3386 if (Method->isInstanceMethod())
3387 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3388 .Case("retain", IFace)
3389 .Case("autorelease", IFace)
3390 .Case("copy", IFace)
3391 .Case("copyWithZone", IFace)
3392 .Case("mutableCopy", IFace)
3393 .Case("mutableCopyWithZone", IFace)
3394 .Case("awakeFromCoder", IFace)
3395 .Case("replacementObjectFromCoder", IFace)
3396 .Case("class", IFace)
3397 .Case("classForCoder", IFace)
3398 .Case("superclass", Super)
3399 .Default(0);
3400
3401 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3402 .Case("new", IFace)
3403 .Case("alloc", IFace)
3404 .Case("allocWithZone", IFace)
3405 .Case("class", IFace)
3406 .Case("superclass", Super)
3407 .Default(0);
3408}
3409
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003410void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
3411 typedef CodeCompleteConsumer::Result Result;
3412 ResultBuilder Results(*this);
3413
3414 // Find anything that looks like it could be a message receiver.
3415 Results.setFilter(&ResultBuilder::IsObjCMessageReceiver);
3416 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3417 Results.EnterNewScope();
3418 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
3419
3420 // If we are in an Objective-C method inside a class that has a superclass,
3421 // add "super" as an option.
3422 if (ObjCMethodDecl *Method = getCurMethodDecl())
3423 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
3424 if (Iface->getSuperClass())
3425 Results.AddResult(Result("super"));
3426
3427 Results.ExitScope();
3428
3429 if (CodeCompleter->includeMacros())
3430 AddMacroResults(PP, Results);
3431 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3432
3433}
3434
Douglas Gregor2725ca82010-04-21 19:57:20 +00003435void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
3436 IdentifierInfo **SelIdents,
3437 unsigned NumSelIdents) {
3438 ObjCInterfaceDecl *CDecl = 0;
3439 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3440 // Figure out which interface we're in.
3441 CDecl = CurMethod->getClassInterface();
3442 if (!CDecl)
3443 return;
3444
3445 // Find the superclass of this class.
3446 CDecl = CDecl->getSuperClass();
3447 if (!CDecl)
3448 return;
3449
3450 if (CurMethod->isInstanceMethod()) {
3451 // We are inside an instance method, which means that the message
3452 // send [super ...] is actually calling an instance method on the
3453 // current object. Build the super expression and handle this like
3454 // an instance method.
3455 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
3456 SuperTy = Context.getObjCObjectPointerType(SuperTy);
3457 OwningExprResult Super
3458 = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
3459 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
3460 SelIdents, NumSelIdents);
3461 }
3462
3463 // Fall through to send to the superclass in CDecl.
3464 } else {
3465 // "super" may be the name of a type or variable. Figure out which
3466 // it is.
3467 IdentifierInfo *Super = &Context.Idents.get("super");
3468 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
3469 LookupOrdinaryName);
3470 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
3471 // "super" names an interface. Use it.
3472 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00003473 if (const ObjCObjectType *Iface
3474 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
3475 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00003476 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
3477 // "super" names an unresolved type; we can't be more specific.
3478 } else {
3479 // Assume that "super" names some kind of value and parse that way.
3480 CXXScopeSpec SS;
3481 UnqualifiedId id;
3482 id.setIdentifier(Super, SuperLoc);
3483 OwningExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
3484 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
3485 SelIdents, NumSelIdents);
3486 }
3487
3488 // Fall through
3489 }
3490
3491 TypeTy *Receiver = 0;
3492 if (CDecl)
3493 Receiver = Context.getObjCInterfaceType(CDecl).getAsOpaquePtr();
3494 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
3495 NumSelIdents);
3496}
3497
3498void Sema::CodeCompleteObjCClassMessage(Scope *S, TypeTy *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00003499 IdentifierInfo **SelIdents,
3500 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00003501 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00003502 ObjCInterfaceDecl *CDecl = 0;
3503
Douglas Gregor24a069f2009-11-17 17:59:40 +00003504 // If the given name refers to an interface type, retrieve the
3505 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00003506 if (Receiver) {
3507 QualType T = GetTypeFromParser(Receiver, 0);
3508 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00003509 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
3510 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00003511 }
3512
Douglas Gregor36ecb042009-11-17 23:22:23 +00003513 // Add all of the factory methods in this Objective-C class, its protocols,
3514 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00003515 ResultBuilder Results(*this);
3516 Results.EnterNewScope();
Douglas Gregor13438f92010-04-06 16:40:00 +00003517
3518 if (CDecl)
3519 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
3520 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00003521 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00003522 // We're messaging "id" as a type; provide all class/factory methods.
3523
Douglas Gregor719770d2010-04-06 17:30:22 +00003524 // If we have an external source, load the entire class method
3525 // pool from the PCH file.
3526 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00003527 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3528 I != N; ++I) {
3529 Selector Sel = ExternalSource->GetExternalSelector(I);
Douglas Gregor719770d2010-04-06 17:30:22 +00003530 if (Sel.isNull() || FactoryMethodPool.count(Sel) ||
3531 InstanceMethodPool.count(Sel))
3532 continue;
3533
3534 ReadMethodPool(Sel, /*isInstance=*/false);
3535 }
3536 }
3537
Douglas Gregor13438f92010-04-06 16:40:00 +00003538 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
3539 M = FactoryMethodPool.begin(),
3540 MEnd = FactoryMethodPool.end();
3541 M != MEnd;
3542 ++M) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003543 for (ObjCMethodList *MethList = &M->second; MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00003544 MethList = MethList->Next) {
3545 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3546 NumSelIdents))
3547 continue;
3548
3549 Result R(MethList->Method, 0);
3550 R.StartParameter = NumSelIdents;
3551 R.AllParametersAreInformative = false;
3552 Results.MaybeAddResult(R, CurContext);
3553 }
3554 }
3555 }
3556
Steve Naroffc4df6d22009-11-07 02:08:14 +00003557 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003558 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00003559}
3560
Douglas Gregord3c68542009-11-19 01:08:35 +00003561void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
3562 IdentifierInfo **SelIdents,
3563 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00003564 typedef CodeCompleteConsumer::Result Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00003565
3566 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00003567
Douglas Gregor36ecb042009-11-17 23:22:23 +00003568 // If necessary, apply function/array conversion to the receiver.
3569 // C99 6.7.5.3p[7,8].
Douglas Gregora873dfc2010-02-03 00:27:59 +00003570 DefaultFunctionArrayLvalueConversion(RecExpr);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003571 QualType ReceiverType = RecExpr->getType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00003572
Douglas Gregor36ecb042009-11-17 23:22:23 +00003573 // Build the set of methods we can see.
3574 ResultBuilder Results(*this);
3575 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00003576
3577 // If we're messaging an expression with type "id" or "Class", check
3578 // whether we know something special about the receiver that allows
3579 // us to assume a more-specific receiver type.
3580 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
3581 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
3582 ReceiverType = Context.getObjCObjectPointerType(
3583 Context.getObjCInterfaceType(IFace));
Douglas Gregor36ecb042009-11-17 23:22:23 +00003584
Douglas Gregorf74a4192009-11-18 00:06:18 +00003585 // Handle messages to Class. This really isn't a message to an instance
3586 // method, so we treat it the same way we would treat a message send to a
3587 // class method.
3588 if (ReceiverType->isObjCClassType() ||
3589 ReceiverType->isObjCQualifiedClassType()) {
3590 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3591 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003592 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
3593 CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003594 }
3595 }
3596 // Handle messages to a qualified ID ("id<foo>").
3597 else if (const ObjCObjectPointerType *QualID
3598 = ReceiverType->getAsObjCQualifiedIdType()) {
3599 // Search protocols for instance methods.
3600 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
3601 E = QualID->qual_end();
3602 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003603 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3604 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003605 }
3606 // Handle messages to a pointer to interface type.
3607 else if (const ObjCObjectPointerType *IFacePtr
3608 = ReceiverType->getAsObjCInterfacePointerType()) {
3609 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00003610 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
3611 NumSelIdents, CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003612
3613 // Search protocols for instance methods.
3614 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
3615 E = IFacePtr->qual_end();
3616 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003617 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3618 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003619 }
Douglas Gregor13438f92010-04-06 16:40:00 +00003620 // Handle messages to "id".
3621 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003622 // We're messaging "id", so provide all instance methods we know
3623 // about as code-completion results.
3624
3625 // If we have an external source, load the entire class method
3626 // pool from the PCH file.
3627 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00003628 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3629 I != N; ++I) {
3630 Selector Sel = ExternalSource->GetExternalSelector(I);
Douglas Gregor719770d2010-04-06 17:30:22 +00003631 if (Sel.isNull() || InstanceMethodPool.count(Sel) ||
3632 FactoryMethodPool.count(Sel))
3633 continue;
3634
3635 ReadMethodPool(Sel, /*isInstance=*/true);
3636 }
3637 }
3638
Douglas Gregor13438f92010-04-06 16:40:00 +00003639 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
3640 M = InstanceMethodPool.begin(),
3641 MEnd = InstanceMethodPool.end();
3642 M != MEnd;
3643 ++M) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003644 for (ObjCMethodList *MethList = &M->second; MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00003645 MethList = MethList->Next) {
3646 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3647 NumSelIdents))
3648 continue;
3649
3650 Result R(MethList->Method, 0);
3651 R.StartParameter = NumSelIdents;
3652 R.AllParametersAreInformative = false;
3653 Results.MaybeAddResult(R, CurContext);
3654 }
3655 }
3656 }
3657
Steve Naroffc4df6d22009-11-07 02:08:14 +00003658 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003659 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00003660}
Douglas Gregor55385fe2009-11-18 04:19:12 +00003661
3662/// \brief Add all of the protocol declarations that we find in the given
3663/// (translation unit) context.
3664static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00003665 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00003666 ResultBuilder &Results) {
3667 typedef CodeCompleteConsumer::Result Result;
3668
3669 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3670 DEnd = Ctx->decls_end();
3671 D != DEnd; ++D) {
3672 // Record any protocols we find.
3673 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00003674 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00003675 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003676
3677 // Record any forward-declared protocols we find.
3678 if (ObjCForwardProtocolDecl *Forward
3679 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
3680 for (ObjCForwardProtocolDecl::protocol_iterator
3681 P = Forward->protocol_begin(),
3682 PEnd = Forward->protocol_end();
3683 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00003684 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00003685 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003686 }
3687 }
3688}
3689
3690void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
3691 unsigned NumProtocols) {
3692 ResultBuilder Results(*this);
3693 Results.EnterNewScope();
3694
3695 // Tell the result set to ignore all of the protocols we have
3696 // already seen.
3697 for (unsigned I = 0; I != NumProtocols; ++I)
Douglas Gregorc83c6872010-04-15 22:33:43 +00003698 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
3699 Protocols[I].second))
Douglas Gregor55385fe2009-11-18 04:19:12 +00003700 Results.Ignore(Protocol);
3701
3702 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00003703 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
3704 Results);
3705
3706 Results.ExitScope();
3707 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3708}
3709
3710void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
3711 ResultBuilder Results(*this);
3712 Results.EnterNewScope();
3713
3714 // Add all protocols.
3715 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
3716 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003717
3718 Results.ExitScope();
3719 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3720}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003721
3722/// \brief Add all of the Objective-C interface declarations that we find in
3723/// the given (translation unit) context.
3724static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
3725 bool OnlyForwardDeclarations,
3726 bool OnlyUnimplemented,
3727 ResultBuilder &Results) {
3728 typedef CodeCompleteConsumer::Result Result;
3729
3730 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3731 DEnd = Ctx->decls_end();
3732 D != DEnd; ++D) {
3733 // Record any interfaces we find.
3734 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
3735 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
3736 (!OnlyUnimplemented || !Class->getImplementation()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003737 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003738
3739 // Record any forward-declared interfaces we find.
3740 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
3741 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
3742 C != CEnd; ++C)
3743 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
3744 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003745 Results.AddResult(Result(C->getInterface(), 0), CurContext,
3746 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003747 }
3748 }
3749}
3750
3751void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
3752 ResultBuilder Results(*this);
3753 Results.EnterNewScope();
3754
3755 // Add all classes.
3756 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
3757 false, Results);
3758
3759 Results.ExitScope();
3760 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3761}
3762
Douglas Gregorc83c6872010-04-15 22:33:43 +00003763void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
3764 SourceLocation ClassNameLoc) {
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003765 ResultBuilder Results(*this);
3766 Results.EnterNewScope();
3767
3768 // Make sure that we ignore the class we're currently defining.
3769 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00003770 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003771 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003772 Results.Ignore(CurClass);
3773
3774 // Add all classes.
3775 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3776 false, Results);
3777
3778 Results.ExitScope();
3779 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3780}
3781
3782void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
3783 ResultBuilder Results(*this);
3784 Results.EnterNewScope();
3785
3786 // Add all unimplemented classes.
3787 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3788 true, Results);
3789
3790 Results.ExitScope();
3791 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3792}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003793
3794void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00003795 IdentifierInfo *ClassName,
3796 SourceLocation ClassNameLoc) {
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003797 typedef CodeCompleteConsumer::Result Result;
3798
3799 ResultBuilder Results(*this);
3800
3801 // Ignore any categories we find that have already been implemented by this
3802 // interface.
3803 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3804 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00003805 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003806 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
3807 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3808 Category = Category->getNextClassCategory())
3809 CategoryNames.insert(Category->getIdentifier());
3810
3811 // Add all of the categories we know about.
3812 Results.EnterNewScope();
3813 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3814 for (DeclContext::decl_iterator D = TU->decls_begin(),
3815 DEnd = TU->decls_end();
3816 D != DEnd; ++D)
3817 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
3818 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003819 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003820 Results.ExitScope();
3821
3822 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3823}
3824
3825void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00003826 IdentifierInfo *ClassName,
3827 SourceLocation ClassNameLoc) {
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003828 typedef CodeCompleteConsumer::Result Result;
3829
3830 // Find the corresponding interface. If we couldn't find the interface, the
3831 // program itself is ill-formed. However, we'll try to be helpful still by
3832 // providing the list of all of the categories we know about.
3833 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00003834 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003835 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
3836 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00003837 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003838
3839 ResultBuilder Results(*this);
3840
3841 // Add all of the categories that have have corresponding interface
3842 // declarations in this class and any of its superclasses, except for
3843 // already-implemented categories in the class itself.
3844 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3845 Results.EnterNewScope();
3846 bool IgnoreImplemented = true;
3847 while (Class) {
3848 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3849 Category = Category->getNextClassCategory())
3850 if ((!IgnoreImplemented || !Category->getImplementation()) &&
3851 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003852 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003853
3854 Class = Class->getSuperClass();
3855 IgnoreImplemented = false;
3856 }
3857 Results.ExitScope();
3858
3859 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3860}
Douglas Gregor322328b2009-11-18 22:32:06 +00003861
Douglas Gregor424b2a52009-11-18 22:56:13 +00003862void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
Douglas Gregor322328b2009-11-18 22:32:06 +00003863 typedef CodeCompleteConsumer::Result Result;
3864 ResultBuilder Results(*this);
3865
3866 // Figure out where this @synthesize lives.
3867 ObjCContainerDecl *Container
3868 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3869 if (!Container ||
3870 (!isa<ObjCImplementationDecl>(Container) &&
3871 !isa<ObjCCategoryImplDecl>(Container)))
3872 return;
3873
3874 // Ignore any properties that have already been implemented.
3875 for (DeclContext::decl_iterator D = Container->decls_begin(),
3876 DEnd = Container->decls_end();
3877 D != DEnd; ++D)
3878 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
3879 Results.Ignore(PropertyImpl->getPropertyDecl());
3880
3881 // Add any properties that we find.
3882 Results.EnterNewScope();
3883 if (ObjCImplementationDecl *ClassImpl
3884 = dyn_cast<ObjCImplementationDecl>(Container))
3885 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
3886 Results);
3887 else
3888 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
3889 false, CurContext, Results);
3890 Results.ExitScope();
3891
3892 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3893}
3894
3895void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
3896 IdentifierInfo *PropertyName,
3897 DeclPtrTy ObjCImpDecl) {
3898 typedef CodeCompleteConsumer::Result Result;
3899 ResultBuilder Results(*this);
3900
3901 // Figure out where this @synthesize lives.
3902 ObjCContainerDecl *Container
3903 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3904 if (!Container ||
3905 (!isa<ObjCImplementationDecl>(Container) &&
3906 !isa<ObjCCategoryImplDecl>(Container)))
3907 return;
3908
3909 // Figure out which interface we're looking into.
3910 ObjCInterfaceDecl *Class = 0;
3911 if (ObjCImplementationDecl *ClassImpl
3912 = dyn_cast<ObjCImplementationDecl>(Container))
3913 Class = ClassImpl->getClassInterface();
3914 else
3915 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
3916 ->getClassInterface();
3917
3918 // Add all of the instance variables in this class and its superclasses.
3919 Results.EnterNewScope();
3920 for(; Class; Class = Class->getSuperClass()) {
3921 // FIXME: We could screen the type of each ivar for compatibility with
3922 // the property, but is that being too paternal?
3923 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
3924 IVarEnd = Class->ivar_end();
3925 IVar != IVarEnd; ++IVar)
Douglas Gregor608300b2010-01-14 16:14:35 +00003926 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor322328b2009-11-18 22:32:06 +00003927 }
3928 Results.ExitScope();
3929
3930 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3931}
Douglas Gregore8f5a172010-04-07 00:21:17 +00003932
3933typedef llvm::DenseMap<Selector, ObjCMethodDecl *> KnownMethodsMap;
3934
3935/// \brief Find all of the methods that reside in the given container
3936/// (and its superclasses, protocols, etc.) that meet the given
3937/// criteria. Insert those methods into the map of known methods,
3938/// indexed by selector so they can be easily found.
3939static void FindImplementableMethods(ASTContext &Context,
3940 ObjCContainerDecl *Container,
3941 bool WantInstanceMethods,
3942 QualType ReturnType,
3943 bool IsInImplementation,
3944 KnownMethodsMap &KnownMethods) {
3945 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
3946 // Recurse into protocols.
3947 const ObjCList<ObjCProtocolDecl> &Protocols
3948 = IFace->getReferencedProtocols();
3949 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3950 E = Protocols.end();
3951 I != E; ++I)
3952 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3953 IsInImplementation, KnownMethods);
3954
3955 // If we're not in the implementation of a class, also visit the
3956 // superclass.
3957 if (!IsInImplementation && IFace->getSuperClass())
3958 FindImplementableMethods(Context, IFace->getSuperClass(),
3959 WantInstanceMethods, ReturnType,
3960 IsInImplementation, KnownMethods);
3961
3962 // Add methods from any class extensions (but not from categories;
3963 // those should go into category implementations).
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00003964 for (const ObjCCategoryDecl *Cat = IFace->getFirstClassExtension(); Cat;
3965 Cat = Cat->getNextClassExtension())
3966 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
3967 WantInstanceMethods, ReturnType,
Douglas Gregore8f5a172010-04-07 00:21:17 +00003968 IsInImplementation, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00003969 }
3970
3971 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
3972 // Recurse into protocols.
3973 const ObjCList<ObjCProtocolDecl> &Protocols
3974 = Category->getReferencedProtocols();
3975 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3976 E = Protocols.end();
3977 I != E; ++I)
3978 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3979 IsInImplementation, KnownMethods);
3980 }
3981
3982 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3983 // Recurse into protocols.
3984 const ObjCList<ObjCProtocolDecl> &Protocols
3985 = Protocol->getReferencedProtocols();
3986 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3987 E = Protocols.end();
3988 I != E; ++I)
3989 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
3990 IsInImplementation, KnownMethods);
3991 }
3992
3993 // Add methods in this container. This operation occurs last because
3994 // we want the methods from this container to override any methods
3995 // we've previously seen with the same selector.
3996 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3997 MEnd = Container->meth_end();
3998 M != MEnd; ++M) {
3999 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4000 if (!ReturnType.isNull() &&
4001 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
4002 continue;
4003
4004 KnownMethods[(*M)->getSelector()] = *M;
4005 }
4006 }
4007}
4008
4009void Sema::CodeCompleteObjCMethodDecl(Scope *S,
4010 bool IsInstanceMethod,
4011 TypeTy *ReturnTy,
4012 DeclPtrTy IDecl) {
4013 // Determine the return type of the method we're declaring, if
4014 // provided.
4015 QualType ReturnType = GetTypeFromParser(ReturnTy);
4016
4017 // Determine where we should start searching for methods, and where we
4018 ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
4019 bool IsInImplementation = false;
4020 if (Decl *D = IDecl.getAs<Decl>()) {
4021 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
4022 SearchDecl = Impl->getClassInterface();
4023 CurrentDecl = Impl;
4024 IsInImplementation = true;
4025 } else if (ObjCCategoryImplDecl *CatImpl
4026 = dyn_cast<ObjCCategoryImplDecl>(D)) {
4027 SearchDecl = CatImpl->getCategoryDecl();
4028 CurrentDecl = CatImpl;
4029 IsInImplementation = true;
4030 } else {
4031 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
4032 CurrentDecl = SearchDecl;
4033 }
4034 }
4035
4036 if (!SearchDecl && S) {
4037 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
4038 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
4039 CurrentDecl = SearchDecl;
4040 }
4041 }
4042
4043 if (!SearchDecl || !CurrentDecl) {
4044 HandleCodeCompleteResults(this, CodeCompleter, 0, 0);
4045 return;
4046 }
4047
4048 // Find all of the methods that we could declare/implement here.
4049 KnownMethodsMap KnownMethods;
4050 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
4051 ReturnType, IsInImplementation, KnownMethods);
4052
4053 // Erase any methods that have already been declared or
4054 // implemented here.
4055 for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
4056 MEnd = CurrentDecl->meth_end();
4057 M != MEnd; ++M) {
4058 if ((*M)->isInstanceMethod() != IsInstanceMethod)
4059 continue;
4060
4061 KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
4062 if (Pos != KnownMethods.end())
4063 KnownMethods.erase(Pos);
4064 }
4065
4066 // Add declarations or definitions for each of the known methods.
4067 typedef CodeCompleteConsumer::Result Result;
4068 ResultBuilder Results(*this);
4069 Results.EnterNewScope();
4070 PrintingPolicy Policy(Context.PrintingPolicy);
4071 Policy.AnonymousTagLocations = false;
4072 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
4073 MEnd = KnownMethods.end();
4074 M != MEnd; ++M) {
4075 ObjCMethodDecl *Method = M->second;
4076 CodeCompletionString *Pattern = new CodeCompletionString;
4077
4078 // If the result type was not already provided, add it to the
4079 // pattern as (type).
4080 if (ReturnType.isNull()) {
4081 std::string TypeStr;
4082 Method->getResultType().getAsStringInternal(TypeStr, Policy);
4083 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4084 Pattern->AddTextChunk(TypeStr);
4085 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4086 }
4087
4088 Selector Sel = Method->getSelector();
4089
4090 // Add the first part of the selector to the pattern.
4091 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4092
4093 // Add parameters to the pattern.
4094 unsigned I = 0;
4095 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4096 PEnd = Method->param_end();
4097 P != PEnd; (void)++P, ++I) {
4098 // Add the part of the selector name.
4099 if (I == 0)
4100 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4101 else if (I < Sel.getNumArgs()) {
4102 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4103 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(1)->getName());
4104 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4105 } else
4106 break;
4107
4108 // Add the parameter type.
4109 std::string TypeStr;
4110 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
4111 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4112 Pattern->AddTextChunk(TypeStr);
4113 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4114
4115 if (IdentifierInfo *Id = (*P)->getIdentifier())
4116 Pattern->AddTextChunk(Id->getName());
4117 }
4118
4119 if (Method->isVariadic()) {
4120 if (Method->param_size() > 0)
4121 Pattern->AddChunk(CodeCompletionString::CK_Comma);
4122 Pattern->AddTextChunk("...");
4123 }
4124
Douglas Gregor447107d2010-05-28 00:57:46 +00004125 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004126 // We will be defining the method here, so add a compound statement.
4127 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4128 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
4129 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4130 if (!Method->getResultType()->isVoidType()) {
4131 // If the result type is not void, add a return clause.
4132 Pattern->AddTextChunk("return");
4133 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4134 Pattern->AddPlaceholderChunk("expression");
4135 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
4136 } else
4137 Pattern->AddPlaceholderChunk("statements");
4138
4139 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4140 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
4141 }
4142
4143 Results.AddResult(Result(Pattern));
4144 }
4145
4146 Results.ExitScope();
4147
4148 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
4149}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004150
4151void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
4152 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00004153 bool AtParameterName,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004154 TypeTy *ReturnTy,
4155 IdentifierInfo **SelIdents,
4156 unsigned NumSelIdents) {
4157 llvm::DenseMap<Selector, ObjCMethodList> &Pool
4158 = IsInstanceMethod? InstanceMethodPool : FactoryMethodPool;
4159
4160 // If we have an external source, load the entire class method
4161 // pool from the PCH file.
4162 if (ExternalSource) {
4163 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4164 I != N; ++I) {
4165 Selector Sel = ExternalSource->GetExternalSelector(I);
4166 if (Sel.isNull() || InstanceMethodPool.count(Sel) ||
4167 FactoryMethodPool.count(Sel))
4168 continue;
4169
4170 ReadMethodPool(Sel, IsInstanceMethod);
4171 }
4172 }
4173
4174 // Build the set of methods we can see.
4175 typedef CodeCompleteConsumer::Result Result;
4176 ResultBuilder Results(*this);
4177
4178 if (ReturnTy)
4179 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
4180
4181 Results.EnterNewScope();
4182 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator M = Pool.begin(),
4183 MEnd = Pool.end();
4184 M != MEnd;
4185 ++M) {
4186 for (ObjCMethodList *MethList = &M->second; MethList && MethList->Method;
4187 MethList = MethList->Next) {
4188 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4189 NumSelIdents))
4190 continue;
4191
Douglas Gregor40ed9a12010-07-08 23:37:41 +00004192 if (AtParameterName) {
4193 // Suggest parameter names we've seen before.
4194 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
4195 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
4196 if (Param->getIdentifier()) {
4197 CodeCompletionString *Pattern = new CodeCompletionString;
4198 Pattern->AddTypedTextChunk(Param->getIdentifier()->getName());
4199 Results.AddResult(Pattern);
4200 }
4201 }
4202
4203 continue;
4204 }
4205
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004206 Result R(MethList->Method, 0);
4207 R.StartParameter = NumSelIdents;
4208 R.AllParametersAreInformative = false;
4209 R.DeclaringEntity = true;
4210 Results.MaybeAddResult(R, CurContext);
4211 }
4212 }
4213
4214 Results.ExitScope();
4215 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
4216}