blob: d61c430141328dad6a0ca0bbd19a37d5ba269a7e [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//===----------------------------------------------------------------------===//
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
14#include "clang/Sema/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 Gregorf9578432010-07-28 21:50:18 +0000230 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000231 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000232 bool IsNestedNameSpecifier(NamedDecl *ND) const;
233 bool IsEnum(NamedDecl *ND) const;
234 bool IsClassOrStruct(NamedDecl *ND) const;
235 bool IsUnion(NamedDecl *ND) const;
236 bool IsNamespace(NamedDecl *ND) const;
237 bool IsNamespaceOrAlias(NamedDecl *ND) const;
238 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000239 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000240 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000241 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000242 //@}
243 };
244}
245
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000246class ResultBuilder::ShadowMapEntry::iterator {
247 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
248 unsigned SingleDeclIndex;
249
250public:
251 typedef DeclIndexPair value_type;
252 typedef value_type reference;
253 typedef std::ptrdiff_t difference_type;
254 typedef std::input_iterator_tag iterator_category;
255
256 class pointer {
257 DeclIndexPair Value;
258
259 public:
260 pointer(const DeclIndexPair &Value) : Value(Value) { }
261
262 const DeclIndexPair *operator->() const {
263 return &Value;
264 }
265 };
266
267 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
268
269 iterator(NamedDecl *SingleDecl, unsigned Index)
270 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
271
272 iterator(const DeclIndexPair *Iterator)
273 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
274
275 iterator &operator++() {
276 if (DeclOrIterator.is<NamedDecl *>()) {
277 DeclOrIterator = (NamedDecl *)0;
278 SingleDeclIndex = 0;
279 return *this;
280 }
281
282 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
283 ++I;
284 DeclOrIterator = I;
285 return *this;
286 }
287
288 iterator operator++(int) {
289 iterator tmp(*this);
290 ++(*this);
291 return tmp;
292 }
293
294 reference operator*() const {
295 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
296 return reference(ND, SingleDeclIndex);
297
Douglas Gregord490f952009-12-06 21:27:58 +0000298 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000299 }
300
301 pointer operator->() const {
302 return pointer(**this);
303 }
304
305 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000306 return X.DeclOrIterator.getOpaqueValue()
307 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000308 X.SingleDeclIndex == Y.SingleDeclIndex;
309 }
310
311 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000312 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000313 }
314};
315
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000316ResultBuilder::ShadowMapEntry::iterator
317ResultBuilder::ShadowMapEntry::begin() const {
318 if (DeclOrVector.isNull())
319 return iterator();
320
321 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
322 return iterator(ND, SingleDeclIndex);
323
324 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
325}
326
327ResultBuilder::ShadowMapEntry::iterator
328ResultBuilder::ShadowMapEntry::end() const {
329 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
330 return iterator();
331
332 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
333}
334
Douglas Gregor456c4a12009-09-21 20:12:40 +0000335/// \brief Compute the qualification required to get from the current context
336/// (\p CurContext) to the target context (\p TargetContext).
337///
338/// \param Context the AST context in which the qualification will be used.
339///
340/// \param CurContext the context where an entity is being named, which is
341/// typically based on the current scope.
342///
343/// \param TargetContext the context in which the named entity actually
344/// resides.
345///
346/// \returns a nested name specifier that refers into the target context, or
347/// NULL if no qualification is needed.
348static NestedNameSpecifier *
349getRequiredQualification(ASTContext &Context,
350 DeclContext *CurContext,
351 DeclContext *TargetContext) {
352 llvm::SmallVector<DeclContext *, 4> TargetParents;
353
354 for (DeclContext *CommonAncestor = TargetContext;
355 CommonAncestor && !CommonAncestor->Encloses(CurContext);
356 CommonAncestor = CommonAncestor->getLookupParent()) {
357 if (CommonAncestor->isTransparentContext() ||
358 CommonAncestor->isFunctionOrMethod())
359 continue;
360
361 TargetParents.push_back(CommonAncestor);
362 }
363
364 NestedNameSpecifier *Result = 0;
365 while (!TargetParents.empty()) {
366 DeclContext *Parent = TargetParents.back();
367 TargetParents.pop_back();
368
369 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
370 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
371 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
372 Result = NestedNameSpecifier::Create(Context, Result,
373 false,
374 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000375 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000376 return Result;
377}
378
Douglas Gregor45bcd432010-01-14 03:21:49 +0000379bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
380 bool &AsNestedNameSpecifier) const {
381 AsNestedNameSpecifier = false;
382
Douglas Gregore495b7f2010-01-14 00:20:49 +0000383 ND = ND->getUnderlyingDecl();
384 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000385
386 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000387 if (!ND->getDeclName())
388 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000389
390 // Friend declarations and declarations introduced due to friends are never
391 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000392 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000393 return false;
394
Douglas Gregor76282942009-12-11 17:31:05 +0000395 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000396 if (isa<ClassTemplateSpecializationDecl>(ND) ||
397 isa<ClassTemplatePartialSpecializationDecl>(ND))
398 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000399
Douglas Gregor76282942009-12-11 17:31:05 +0000400 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000401 if (isa<UsingDecl>(ND))
402 return false;
403
404 // Some declarations have reserved names that we don't want to ever show.
405 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000406 // __va_list_tag is a freak of nature. Find it and skip it.
407 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000408 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000409
Douglas Gregorf52cede2009-10-09 22:16:47 +0000410 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000411 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000412 //
413 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000414 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000415 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000416 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000417 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
418 (ND->getLocation().isInvalid() ||
419 SemaRef.SourceMgr.isInSystemHeader(
420 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000421 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000422 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000423 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000424
Douglas Gregor86d9a522009-09-21 16:56:56 +0000425 // C++ constructors are never found by name lookup.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000426 if (isa<CXXConstructorDecl>(ND))
427 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000428
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000429 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
430 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
431 Filter != &ResultBuilder::IsNamespace &&
432 Filter != &ResultBuilder::IsNamespaceOrAlias))
433 AsNestedNameSpecifier = true;
434
Douglas Gregor86d9a522009-09-21 16:56:56 +0000435 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000436 if (Filter && !(this->*Filter)(ND)) {
437 // Check whether it is interesting as a nested-name-specifier.
438 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
439 IsNestedNameSpecifier(ND) &&
440 (Filter != &ResultBuilder::IsMember ||
441 (isa<CXXRecordDecl>(ND) &&
442 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
443 AsNestedNameSpecifier = true;
444 return true;
445 }
446
Douglas Gregore495b7f2010-01-14 00:20:49 +0000447 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000448 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000449 // ... then it must be interesting!
450 return true;
451}
452
Douglas Gregor6660d842010-01-14 00:41:07 +0000453bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
454 NamedDecl *Hiding) {
455 // In C, there is no way to refer to a hidden name.
456 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
457 // name if we introduce the tag type.
458 if (!SemaRef.getLangOptions().CPlusPlus)
459 return true;
460
461 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext();
462
463 // There is no way to qualify a name declared in a function or method.
464 if (HiddenCtx->isFunctionOrMethod())
465 return true;
466
467 if (HiddenCtx == Hiding->getDeclContext()->getLookupContext())
468 return true;
469
470 // We can refer to the result with the appropriate qualification. Do it.
471 R.Hidden = true;
472 R.QualifierIsInformative = false;
473
474 if (!R.Qualifier)
475 R.Qualifier = getRequiredQualification(SemaRef.Context,
476 CurContext,
477 R.Declaration->getDeclContext());
478 return false;
479}
480
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000481/// \brief A simplified classification of types used to determine whether two
482/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000483SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000484 switch (T->getTypeClass()) {
485 case Type::Builtin:
486 switch (cast<BuiltinType>(T)->getKind()) {
487 case BuiltinType::Void:
488 return STC_Void;
489
490 case BuiltinType::NullPtr:
491 return STC_Pointer;
492
493 case BuiltinType::Overload:
494 case BuiltinType::Dependent:
495 case BuiltinType::UndeducedAuto:
496 return STC_Other;
497
498 case BuiltinType::ObjCId:
499 case BuiltinType::ObjCClass:
500 case BuiltinType::ObjCSel:
501 return STC_ObjectiveC;
502
503 default:
504 return STC_Arithmetic;
505 }
506 return STC_Other;
507
508 case Type::Complex:
509 return STC_Arithmetic;
510
511 case Type::Pointer:
512 return STC_Pointer;
513
514 case Type::BlockPointer:
515 return STC_Block;
516
517 case Type::LValueReference:
518 case Type::RValueReference:
519 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
520
521 case Type::ConstantArray:
522 case Type::IncompleteArray:
523 case Type::VariableArray:
524 case Type::DependentSizedArray:
525 return STC_Array;
526
527 case Type::DependentSizedExtVector:
528 case Type::Vector:
529 case Type::ExtVector:
530 return STC_Arithmetic;
531
532 case Type::FunctionProto:
533 case Type::FunctionNoProto:
534 return STC_Function;
535
536 case Type::Record:
537 return STC_Record;
538
539 case Type::Enum:
540 return STC_Arithmetic;
541
542 case Type::ObjCObject:
543 case Type::ObjCInterface:
544 case Type::ObjCObjectPointer:
545 return STC_ObjectiveC;
546
547 default:
548 return STC_Other;
549 }
550}
551
552/// \brief Get the type that a given expression will have if this declaration
553/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000554QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000555 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
556
557 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
558 return C.getTypeDeclType(Type);
559 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
560 return C.getObjCInterfaceType(Iface);
561
562 QualType T;
563 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000564 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000565 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000566 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000567 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000568 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000569 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
570 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
571 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
572 T = Property->getType();
573 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
574 T = Value->getType();
575 else
576 return QualType();
577
578 return T.getNonReferenceType();
579}
580
581void ResultBuilder::AdjustResultPriorityForPreferredType(Result &R) {
582 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
583 if (T.isNull())
584 return;
585
586 CanQualType TC = SemaRef.Context.getCanonicalType(T);
587 // Check for exactly-matching types (modulo qualifiers).
588 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
589 R.Priority /= CCF_ExactTypeMatch;
590 // Check for nearly-matching types, based on classification of each.
591 else if ((getSimplifiedTypeClass(PreferredType)
592 == getSimplifiedTypeClass(TC)) &&
593 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
594 R.Priority /= CCF_SimilarTypeMatch;
595}
596
Douglas Gregore495b7f2010-01-14 00:20:49 +0000597void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
598 assert(!ShadowMaps.empty() && "Must enter into a results scope");
599
600 if (R.Kind != Result::RK_Declaration) {
601 // For non-declaration results, just add the result.
602 Results.push_back(R);
603 return;
604 }
605
606 // Look through using declarations.
607 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
608 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
609 return;
610 }
611
612 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
613 unsigned IDNS = CanonDecl->getIdentifierNamespace();
614
Douglas Gregor45bcd432010-01-14 03:21:49 +0000615 bool AsNestedNameSpecifier = false;
616 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000617 return;
618
Douglas Gregor86d9a522009-09-21 16:56:56 +0000619 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000620 ShadowMapEntry::iterator I, IEnd;
621 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
622 if (NamePos != SMap.end()) {
623 I = NamePos->second.begin();
624 IEnd = NamePos->second.end();
625 }
626
627 for (; I != IEnd; ++I) {
628 NamedDecl *ND = I->first;
629 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000630 if (ND->getCanonicalDecl() == CanonDecl) {
631 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000632 Results[Index].Declaration = R.Declaration;
633
Douglas Gregor86d9a522009-09-21 16:56:56 +0000634 // We're done.
635 return;
636 }
637 }
638
639 // This is a new declaration in this scope. However, check whether this
640 // declaration name is hidden by a similarly-named declaration in an outer
641 // scope.
642 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
643 --SMEnd;
644 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000645 ShadowMapEntry::iterator I, IEnd;
646 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
647 if (NamePos != SM->end()) {
648 I = NamePos->second.begin();
649 IEnd = NamePos->second.end();
650 }
651 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000652 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000653 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000654 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
655 Decl::IDNS_ObjCProtocol)))
656 continue;
657
658 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000659 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000660 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000661 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000662 continue;
663
664 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000665 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000666 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000667
668 break;
669 }
670 }
671
672 // Make sure that any given declaration only shows up in the result set once.
673 if (!AllDeclsFound.insert(CanonDecl))
674 return;
675
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000676 // If the filter is for nested-name-specifiers, then this result starts a
677 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000678 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000679 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000680 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000681 } else if (!PreferredType.isNull())
682 AdjustResultPriorityForPreferredType(R);
683
Douglas Gregor0563c262009-09-22 23:15:58 +0000684 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000685 if (R.QualifierIsInformative && !R.Qualifier &&
686 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000687 DeclContext *Ctx = R.Declaration->getDeclContext();
688 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
689 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
690 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
691 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
692 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
693 else
694 R.QualifierIsInformative = false;
695 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000696
Douglas Gregor86d9a522009-09-21 16:56:56 +0000697 // Insert this result into the set of results and into the current shadow
698 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000699 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000700 Results.push_back(R);
701}
702
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000703void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000704 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000705 if (R.Kind != Result::RK_Declaration) {
706 // For non-declaration results, just add the result.
707 Results.push_back(R);
708 return;
709 }
710
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000711 // Look through using declarations.
712 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
713 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
714 return;
715 }
716
Douglas Gregor45bcd432010-01-14 03:21:49 +0000717 bool AsNestedNameSpecifier = false;
718 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000719 return;
720
721 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
722 return;
723
724 // Make sure that any given declaration only shows up in the result set once.
725 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
726 return;
727
728 // If the filter is for nested-name-specifiers, then this result starts a
729 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000730 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000731 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000732 R.Priority = CCP_NestedNameSpecifier;
733 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000734 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
735 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
736 ->getLookupContext()))
737 R.QualifierIsInformative = true;
738
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000739 // If this result is supposed to have an informative qualifier, add one.
740 if (R.QualifierIsInformative && !R.Qualifier &&
741 !R.StartsNestedNameSpecifier) {
742 DeclContext *Ctx = R.Declaration->getDeclContext();
743 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
744 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
745 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
746 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000747 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000748 else
749 R.QualifierIsInformative = false;
750 }
751
Douglas Gregor12e13132010-05-26 22:00:08 +0000752 // Adjust the priority if this result comes from a base class.
753 if (InBaseClass)
754 R.Priority += CCD_InBaseClass;
755
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000756 if (!PreferredType.isNull())
757 AdjustResultPriorityForPreferredType(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000758
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000759 // Insert this result into the set of results.
760 Results.push_back(R);
761}
762
Douglas Gregora4477812010-01-14 16:01:26 +0000763void ResultBuilder::AddResult(Result R) {
764 assert(R.Kind != Result::RK_Declaration &&
765 "Declaration results need more context");
766 Results.push_back(R);
767}
768
Douglas Gregor86d9a522009-09-21 16:56:56 +0000769/// \brief Enter into a new scope.
770void ResultBuilder::EnterNewScope() {
771 ShadowMaps.push_back(ShadowMap());
772}
773
774/// \brief Exit from the current scope.
775void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000776 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
777 EEnd = ShadowMaps.back().end();
778 E != EEnd;
779 ++E)
780 E->second.Destroy();
781
Douglas Gregor86d9a522009-09-21 16:56:56 +0000782 ShadowMaps.pop_back();
783}
784
Douglas Gregor791215b2009-09-21 20:51:25 +0000785/// \brief Determines whether this given declaration will be found by
786/// ordinary name lookup.
787bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000788 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
789
Douglas Gregor791215b2009-09-21 20:51:25 +0000790 unsigned IDNS = Decl::IDNS_Ordinary;
791 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000792 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000793 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
794 return true;
795
Douglas Gregor791215b2009-09-21 20:51:25 +0000796 return ND->getIdentifierNamespace() & IDNS;
797}
798
Douglas Gregor01dfea02010-01-10 23:08:15 +0000799/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000800/// ordinary name lookup but is not a type name.
801bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
802 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
803 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
804 return false;
805
806 unsigned IDNS = Decl::IDNS_Ordinary;
807 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000808 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000809 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
810 return true;
811
812 return ND->getIdentifierNamespace() & IDNS;
813}
814
Douglas Gregorf9578432010-07-28 21:50:18 +0000815bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
816 if (!IsOrdinaryNonTypeName(ND))
817 return 0;
818
819 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
820 if (VD->getType()->isIntegralOrEnumerationType())
821 return true;
822
823 return false;
824}
825
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000826/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +0000827/// ordinary name lookup.
828bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000829 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
830
Douglas Gregor01dfea02010-01-10 23:08:15 +0000831 unsigned IDNS = Decl::IDNS_Ordinary;
832 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +0000833 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000834
835 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000836 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
837 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +0000838}
839
Douglas Gregor86d9a522009-09-21 16:56:56 +0000840/// \brief Determines whether the given declaration is suitable as the
841/// start of a C++ nested-name-specifier, e.g., a class or namespace.
842bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
843 // Allow us to find class templates, too.
844 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
845 ND = ClassTemplate->getTemplatedDecl();
846
847 return SemaRef.isAcceptableNestedNameSpecifier(ND);
848}
849
850/// \brief Determines whether the given declaration is an enumeration.
851bool ResultBuilder::IsEnum(NamedDecl *ND) const {
852 return isa<EnumDecl>(ND);
853}
854
855/// \brief Determines whether the given declaration is a class or struct.
856bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
857 // Allow us to find class templates, too.
858 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
859 ND = ClassTemplate->getTemplatedDecl();
860
861 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000862 return RD->getTagKind() == TTK_Class ||
863 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000864
865 return false;
866}
867
868/// \brief Determines whether the given declaration is a union.
869bool ResultBuilder::IsUnion(NamedDecl *ND) const {
870 // Allow us to find class templates, too.
871 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
872 ND = ClassTemplate->getTemplatedDecl();
873
874 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000875 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000876
877 return false;
878}
879
880/// \brief Determines whether the given declaration is a namespace.
881bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
882 return isa<NamespaceDecl>(ND);
883}
884
885/// \brief Determines whether the given declaration is a namespace or
886/// namespace alias.
887bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
888 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
889}
890
Douglas Gregor76282942009-12-11 17:31:05 +0000891/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000892bool ResultBuilder::IsType(NamedDecl *ND) const {
893 return isa<TypeDecl>(ND);
894}
895
Douglas Gregor76282942009-12-11 17:31:05 +0000896/// \brief Determines which members of a class should be visible via
897/// "." or "->". Only value declarations, nested name specifiers, and
898/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000899bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +0000900 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
901 ND = Using->getTargetDecl();
902
Douglas Gregorce821962009-12-11 18:14:22 +0000903 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
904 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000905}
906
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000907static bool isObjCReceiverType(ASTContext &C, QualType T) {
908 T = C.getCanonicalType(T);
909 switch (T->getTypeClass()) {
910 case Type::ObjCObject:
911 case Type::ObjCInterface:
912 case Type::ObjCObjectPointer:
913 return true;
914
915 case Type::Builtin:
916 switch (cast<BuiltinType>(T)->getKind()) {
917 case BuiltinType::ObjCId:
918 case BuiltinType::ObjCClass:
919 case BuiltinType::ObjCSel:
920 return true;
921
922 default:
923 break;
924 }
925 return false;
926
927 default:
928 break;
929 }
930
931 if (!C.getLangOptions().CPlusPlus)
932 return false;
933
934 // FIXME: We could perform more analysis here to determine whether a
935 // particular class type has any conversions to Objective-C types. For now,
936 // just accept all class types.
937 return T->isDependentType() || T->isRecordType();
938}
939
940bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
941 QualType T = getDeclUsageType(SemaRef.Context, ND);
942 if (T.isNull())
943 return false;
944
945 T = SemaRef.Context.getBaseElementType(T);
946 return isObjCReceiverType(SemaRef.Context, T);
947}
948
949
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000950/// \rief Determines whether the given declaration is an Objective-C
951/// instance variable.
952bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
953 return isa<ObjCIvarDecl>(ND);
954}
955
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000956namespace {
957 /// \brief Visible declaration consumer that adds a code-completion result
958 /// for each visible declaration.
959 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
960 ResultBuilder &Results;
961 DeclContext *CurContext;
962
963 public:
964 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
965 : Results(Results), CurContext(CurContext) { }
966
Douglas Gregor0cc84042010-01-14 15:47:35 +0000967 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
968 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000969 }
970 };
971}
972
Douglas Gregor86d9a522009-09-21 16:56:56 +0000973/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +0000974static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +0000975 ResultBuilder &Results) {
976 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor12e13132010-05-26 22:00:08 +0000977 Results.AddResult(Result("short", CCP_Type));
978 Results.AddResult(Result("long", CCP_Type));
979 Results.AddResult(Result("signed", CCP_Type));
980 Results.AddResult(Result("unsigned", CCP_Type));
981 Results.AddResult(Result("void", CCP_Type));
982 Results.AddResult(Result("char", CCP_Type));
983 Results.AddResult(Result("int", CCP_Type));
984 Results.AddResult(Result("float", CCP_Type));
985 Results.AddResult(Result("double", CCP_Type));
986 Results.AddResult(Result("enum", CCP_Type));
987 Results.AddResult(Result("struct", CCP_Type));
988 Results.AddResult(Result("union", CCP_Type));
989 Results.AddResult(Result("const", CCP_Type));
990 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +0000991
Douglas Gregor86d9a522009-09-21 16:56:56 +0000992 if (LangOpts.C99) {
993 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +0000994 Results.AddResult(Result("_Complex", CCP_Type));
995 Results.AddResult(Result("_Imaginary", CCP_Type));
996 Results.AddResult(Result("_Bool", CCP_Type));
997 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +0000998 }
999
1000 if (LangOpts.CPlusPlus) {
1001 // C++-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001002 Results.AddResult(Result("bool", CCP_Type));
1003 Results.AddResult(Result("class", CCP_Type));
1004 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001005
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001006 // typename qualified-id
1007 CodeCompletionString *Pattern = new CodeCompletionString;
1008 Pattern->AddTypedTextChunk("typename");
1009 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1010 Pattern->AddPlaceholderChunk("qualifier");
1011 Pattern->AddTextChunk("::");
1012 Pattern->AddPlaceholderChunk("name");
1013 Results.AddResult(Result(Pattern));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001014
Douglas Gregor86d9a522009-09-21 16:56:56 +00001015 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001016 Results.AddResult(Result("auto", CCP_Type));
1017 Results.AddResult(Result("char16_t", CCP_Type));
1018 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001019
1020 CodeCompletionString *Pattern = new CodeCompletionString;
1021 Pattern->AddTypedTextChunk("decltype");
1022 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1023 Pattern->AddPlaceholderChunk("expression");
1024 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1025 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001026 }
1027 }
1028
1029 // GNU extensions
1030 if (LangOpts.GNUMode) {
1031 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001032 // Results.AddResult(Result("_Decimal32"));
1033 // Results.AddResult(Result("_Decimal64"));
1034 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001035
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001036 CodeCompletionString *Pattern = new CodeCompletionString;
1037 Pattern->AddTypedTextChunk("typeof");
1038 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1039 Pattern->AddPlaceholderChunk("expression");
1040 Results.AddResult(Result(Pattern));
1041
1042 Pattern = new CodeCompletionString;
1043 Pattern->AddTypedTextChunk("typeof");
1044 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1045 Pattern->AddPlaceholderChunk("type");
1046 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1047 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001048 }
1049}
1050
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001051static void AddStorageSpecifiers(Action::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001052 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001053 ResultBuilder &Results) {
1054 typedef CodeCompleteConsumer::Result Result;
1055 // Note: we don't suggest either "auto" or "register", because both
1056 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1057 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001058 Results.AddResult(Result("extern"));
1059 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001060}
1061
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001062static void AddFunctionSpecifiers(Action::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001063 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001064 ResultBuilder &Results) {
1065 typedef CodeCompleteConsumer::Result Result;
1066 switch (CCC) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001067 case Action::PCC_Class:
1068 case Action::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001069 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001070 Results.AddResult(Result("explicit"));
1071 Results.AddResult(Result("friend"));
1072 Results.AddResult(Result("mutable"));
1073 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001074 }
1075 // Fall through
1076
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001077 case Action::PCC_ObjCInterface:
1078 case Action::PCC_ObjCImplementation:
1079 case Action::PCC_Namespace:
1080 case Action::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001081 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001082 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001083 break;
1084
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001085 case Action::PCC_ObjCInstanceVariableList:
1086 case Action::PCC_Expression:
1087 case Action::PCC_Statement:
1088 case Action::PCC_ForInit:
1089 case Action::PCC_Condition:
1090 case Action::PCC_RecoveryInFunction:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001091 break;
1092 }
1093}
1094
Douglas Gregorbca403c2010-01-13 23:51:12 +00001095static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1096static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1097static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001098 ResultBuilder &Results,
1099 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001100static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001101 ResultBuilder &Results,
1102 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001103static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001104 ResultBuilder &Results,
1105 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001106static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001107
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001108static void AddTypedefResult(ResultBuilder &Results) {
1109 CodeCompletionString *Pattern = new CodeCompletionString;
1110 Pattern->AddTypedTextChunk("typedef");
1111 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1112 Pattern->AddPlaceholderChunk("type");
1113 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1114 Pattern->AddPlaceholderChunk("name");
1115 Results.AddResult(CodeCompleteConsumer::Result(Pattern));
1116}
1117
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001118static bool WantTypesInContext(Action::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001119 const LangOptions &LangOpts) {
1120 if (LangOpts.CPlusPlus)
1121 return true;
1122
1123 switch (CCC) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001124 case Action::PCC_Namespace:
1125 case Action::PCC_Class:
1126 case Action::PCC_ObjCInstanceVariableList:
1127 case Action::PCC_Template:
1128 case Action::PCC_MemberTemplate:
1129 case Action::PCC_Statement:
1130 case Action::PCC_RecoveryInFunction:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001131 return true;
1132
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001133 case Action::PCC_ObjCInterface:
1134 case Action::PCC_ObjCImplementation:
1135 case Action::PCC_Expression:
1136 case Action::PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001137 return false;
1138
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001139 case Action::PCC_ForInit:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001140 return LangOpts.ObjC1 || LangOpts.C99;
1141 }
1142
1143 return false;
1144}
1145
Douglas Gregor01dfea02010-01-10 23:08:15 +00001146/// \brief Add language constructs that show up for "ordinary" names.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001147static void AddOrdinaryNameResults(Action::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001148 Scope *S,
1149 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001150 ResultBuilder &Results) {
1151 typedef CodeCompleteConsumer::Result Result;
1152 switch (CCC) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001153 case Action::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001154 if (SemaRef.getLangOptions().CPlusPlus) {
1155 CodeCompletionString *Pattern = 0;
1156
1157 if (Results.includeCodePatterns()) {
1158 // namespace <identifier> { declarations }
1159 CodeCompletionString *Pattern = new CodeCompletionString;
1160 Pattern->AddTypedTextChunk("namespace");
1161 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1162 Pattern->AddPlaceholderChunk("identifier");
1163 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1164 Pattern->AddPlaceholderChunk("declarations");
1165 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1166 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1167 Results.AddResult(Result(Pattern));
1168 }
1169
Douglas Gregor01dfea02010-01-10 23:08:15 +00001170 // namespace identifier = identifier ;
1171 Pattern = new CodeCompletionString;
1172 Pattern->AddTypedTextChunk("namespace");
1173 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001174 Pattern->AddPlaceholderChunk("name");
Douglas Gregor01dfea02010-01-10 23:08:15 +00001175 Pattern->AddChunk(CodeCompletionString::CK_Equal);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001176 Pattern->AddPlaceholderChunk("namespace");
Douglas Gregora4477812010-01-14 16:01:26 +00001177 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001178
1179 // Using directives
1180 Pattern = new CodeCompletionString;
1181 Pattern->AddTypedTextChunk("using");
1182 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1183 Pattern->AddTextChunk("namespace");
1184 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1185 Pattern->AddPlaceholderChunk("identifier");
Douglas Gregora4477812010-01-14 16:01:26 +00001186 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001187
1188 // asm(string-literal)
1189 Pattern = new CodeCompletionString;
1190 Pattern->AddTypedTextChunk("asm");
1191 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1192 Pattern->AddPlaceholderChunk("string-literal");
1193 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001194 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001195
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001196 if (Results.includeCodePatterns()) {
1197 // Explicit template instantiation
1198 Pattern = new CodeCompletionString;
1199 Pattern->AddTypedTextChunk("template");
1200 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1201 Pattern->AddPlaceholderChunk("declaration");
1202 Results.AddResult(Result(Pattern));
1203 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001204 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001205
1206 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001207 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001208
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001209 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001210 // Fall through
1211
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001212 case Action::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001213 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001214 // Using declaration
1215 CodeCompletionString *Pattern = new CodeCompletionString;
1216 Pattern->AddTypedTextChunk("using");
1217 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001218 Pattern->AddPlaceholderChunk("qualifier");
1219 Pattern->AddTextChunk("::");
1220 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001221 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001222
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001223 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001224 if (SemaRef.CurContext->isDependentContext()) {
1225 Pattern = new CodeCompletionString;
1226 Pattern->AddTypedTextChunk("using");
1227 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1228 Pattern->AddTextChunk("typename");
1229 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001230 Pattern->AddPlaceholderChunk("qualifier");
1231 Pattern->AddTextChunk("::");
1232 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001233 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001234 }
1235
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001236 if (CCC == Action::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001237 AddTypedefResult(Results);
1238
Douglas Gregor01dfea02010-01-10 23:08:15 +00001239 // public:
1240 Pattern = new CodeCompletionString;
1241 Pattern->AddTypedTextChunk("public");
1242 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001243 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001244
1245 // protected:
1246 Pattern = new CodeCompletionString;
1247 Pattern->AddTypedTextChunk("protected");
1248 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001249 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001250
1251 // private:
1252 Pattern = new CodeCompletionString;
1253 Pattern->AddTypedTextChunk("private");
1254 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001255 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001256 }
1257 }
1258 // Fall through
1259
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001260 case Action::PCC_Template:
1261 case Action::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001262 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001263 // template < parameters >
1264 CodeCompletionString *Pattern = new CodeCompletionString;
1265 Pattern->AddTypedTextChunk("template");
1266 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1267 Pattern->AddPlaceholderChunk("parameters");
1268 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregora4477812010-01-14 16:01:26 +00001269 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001270 }
1271
Douglas Gregorbca403c2010-01-13 23:51:12 +00001272 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1273 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001274 break;
1275
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001276 case Action::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001277 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1278 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1279 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001280 break;
1281
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001282 case Action::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001283 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1284 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1285 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001286 break;
1287
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001288 case Action::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001289 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001290 break;
1291
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001292 case Action::PCC_RecoveryInFunction:
1293 case Action::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001294 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001295
1296 CodeCompletionString *Pattern = 0;
Douglas Gregord8e8a582010-05-25 21:41:55 +00001297 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001298 Pattern = new CodeCompletionString;
1299 Pattern->AddTypedTextChunk("try");
1300 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1301 Pattern->AddPlaceholderChunk("statements");
1302 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1303 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1304 Pattern->AddTextChunk("catch");
1305 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1306 Pattern->AddPlaceholderChunk("declaration");
1307 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1308 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1309 Pattern->AddPlaceholderChunk("statements");
1310 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1311 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001312 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001313 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001314 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001315 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001316
Douglas Gregord8e8a582010-05-25 21:41:55 +00001317 if (Results.includeCodePatterns()) {
1318 // if (condition) { statements }
1319 Pattern = new CodeCompletionString;
1320 Pattern->AddTypedTextChunk("if");
1321 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1322 if (SemaRef.getLangOptions().CPlusPlus)
1323 Pattern->AddPlaceholderChunk("condition");
1324 else
1325 Pattern->AddPlaceholderChunk("expression");
1326 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1327 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1328 Pattern->AddPlaceholderChunk("statements");
1329 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1330 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1331 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001332
Douglas Gregord8e8a582010-05-25 21:41:55 +00001333 // switch (condition) { }
1334 Pattern = new CodeCompletionString;
1335 Pattern->AddTypedTextChunk("switch");
1336 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1337 if (SemaRef.getLangOptions().CPlusPlus)
1338 Pattern->AddPlaceholderChunk("condition");
1339 else
1340 Pattern->AddPlaceholderChunk("expression");
1341 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1342 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1343 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1344 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1345 Results.AddResult(Result(Pattern));
1346 }
1347
Douglas Gregor01dfea02010-01-10 23:08:15 +00001348 // Switch-specific statements.
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001349 if (!SemaRef.getSwitchStack().empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001350 // case expression:
1351 Pattern = new CodeCompletionString;
1352 Pattern->AddTypedTextChunk("case");
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001353 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001354 Pattern->AddPlaceholderChunk("expression");
1355 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001356 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001357
1358 // default:
1359 Pattern = new CodeCompletionString;
1360 Pattern->AddTypedTextChunk("default");
1361 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001362 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001363 }
1364
Douglas Gregord8e8a582010-05-25 21:41:55 +00001365 if (Results.includeCodePatterns()) {
1366 /// while (condition) { statements }
1367 Pattern = new CodeCompletionString;
1368 Pattern->AddTypedTextChunk("while");
1369 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1370 if (SemaRef.getLangOptions().CPlusPlus)
1371 Pattern->AddPlaceholderChunk("condition");
1372 else
1373 Pattern->AddPlaceholderChunk("expression");
1374 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1375 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1376 Pattern->AddPlaceholderChunk("statements");
1377 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1378 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1379 Results.AddResult(Result(Pattern));
1380
1381 // do { statements } while ( expression );
1382 Pattern = new CodeCompletionString;
1383 Pattern->AddTypedTextChunk("do");
1384 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1385 Pattern->AddPlaceholderChunk("statements");
1386 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1387 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1388 Pattern->AddTextChunk("while");
1389 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001390 Pattern->AddPlaceholderChunk("expression");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001391 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1392 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001393
Douglas Gregord8e8a582010-05-25 21:41:55 +00001394 // for ( for-init-statement ; condition ; expression ) { statements }
1395 Pattern = new CodeCompletionString;
1396 Pattern->AddTypedTextChunk("for");
1397 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1398 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1399 Pattern->AddPlaceholderChunk("init-statement");
1400 else
1401 Pattern->AddPlaceholderChunk("init-expression");
1402 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1403 Pattern->AddPlaceholderChunk("condition");
1404 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1405 Pattern->AddPlaceholderChunk("inc-expression");
1406 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1407 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1408 Pattern->AddPlaceholderChunk("statements");
1409 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1410 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1411 Results.AddResult(Result(Pattern));
1412 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001413
1414 if (S->getContinueParent()) {
1415 // continue ;
1416 Pattern = new CodeCompletionString;
1417 Pattern->AddTypedTextChunk("continue");
Douglas Gregora4477812010-01-14 16:01:26 +00001418 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001419 }
1420
1421 if (S->getBreakParent()) {
1422 // break ;
1423 Pattern = new CodeCompletionString;
1424 Pattern->AddTypedTextChunk("break");
Douglas Gregora4477812010-01-14 16:01:26 +00001425 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001426 }
1427
1428 // "return expression ;" or "return ;", depending on whether we
1429 // know the function is void or not.
1430 bool isVoid = false;
1431 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1432 isVoid = Function->getResultType()->isVoidType();
1433 else if (ObjCMethodDecl *Method
1434 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1435 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001436 else if (SemaRef.getCurBlock() &&
1437 !SemaRef.getCurBlock()->ReturnType.isNull())
1438 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor01dfea02010-01-10 23:08:15 +00001439 Pattern = new CodeCompletionString;
1440 Pattern->AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001441 if (!isVoid) {
1442 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001443 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001444 }
Douglas Gregora4477812010-01-14 16:01:26 +00001445 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001446
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001447 // goto identifier ;
1448 Pattern = new CodeCompletionString;
1449 Pattern->AddTypedTextChunk("goto");
1450 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1451 Pattern->AddPlaceholderChunk("label");
1452 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001453
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001454 // Using directives
1455 Pattern = new CodeCompletionString;
1456 Pattern->AddTypedTextChunk("using");
1457 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1458 Pattern->AddTextChunk("namespace");
1459 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1460 Pattern->AddPlaceholderChunk("identifier");
1461 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001462 }
1463
1464 // Fall through (for statement expressions).
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001465 case Action::PCC_ForInit:
1466 case Action::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001467 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001468 // Fall through: conditions and statements can have expressions.
1469
Douglas Gregore6b1bb62010-08-11 21:23:17 +00001470 case Action::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001471 CodeCompletionString *Pattern = 0;
1472 if (SemaRef.getLangOptions().CPlusPlus) {
1473 // 'this', if we're in a non-static member function.
1474 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1475 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001476 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001477
1478 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001479 Results.AddResult(Result("true"));
1480 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001481
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001482 // dynamic_cast < type-id > ( expression )
1483 Pattern = new CodeCompletionString;
1484 Pattern->AddTypedTextChunk("dynamic_cast");
1485 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1486 Pattern->AddPlaceholderChunk("type");
1487 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1488 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1489 Pattern->AddPlaceholderChunk("expression");
1490 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1491 Results.AddResult(Result(Pattern));
1492
1493 // static_cast < type-id > ( expression )
1494 Pattern = new CodeCompletionString;
1495 Pattern->AddTypedTextChunk("static_cast");
1496 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1497 Pattern->AddPlaceholderChunk("type");
1498 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1499 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1500 Pattern->AddPlaceholderChunk("expression");
1501 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1502 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001503
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001504 // reinterpret_cast < type-id > ( expression )
1505 Pattern = new CodeCompletionString;
1506 Pattern->AddTypedTextChunk("reinterpret_cast");
1507 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1508 Pattern->AddPlaceholderChunk("type");
1509 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1510 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1511 Pattern->AddPlaceholderChunk("expression");
1512 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1513 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001514
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001515 // const_cast < type-id > ( expression )
1516 Pattern = new CodeCompletionString;
1517 Pattern->AddTypedTextChunk("const_cast");
1518 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1519 Pattern->AddPlaceholderChunk("type");
1520 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1521 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1522 Pattern->AddPlaceholderChunk("expression");
1523 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1524 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001525
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001526 // typeid ( expression-or-type )
1527 Pattern = new CodeCompletionString;
1528 Pattern->AddTypedTextChunk("typeid");
1529 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1530 Pattern->AddPlaceholderChunk("expression-or-type");
1531 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1532 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001533
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001534 // new T ( ... )
1535 Pattern = new CodeCompletionString;
1536 Pattern->AddTypedTextChunk("new");
1537 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1538 Pattern->AddPlaceholderChunk("type");
1539 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1540 Pattern->AddPlaceholderChunk("expressions");
1541 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1542 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001543
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001544 // new T [ ] ( ... )
1545 Pattern = new CodeCompletionString;
1546 Pattern->AddTypedTextChunk("new");
1547 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1548 Pattern->AddPlaceholderChunk("type");
1549 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1550 Pattern->AddPlaceholderChunk("size");
1551 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1552 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1553 Pattern->AddPlaceholderChunk("expressions");
1554 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1555 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001556
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001557 // delete expression
1558 Pattern = new CodeCompletionString;
1559 Pattern->AddTypedTextChunk("delete");
1560 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1561 Pattern->AddPlaceholderChunk("expression");
1562 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001563
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001564 // delete [] expression
1565 Pattern = new CodeCompletionString;
1566 Pattern->AddTypedTextChunk("delete");
1567 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1568 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1569 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1570 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1571 Pattern->AddPlaceholderChunk("expression");
1572 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001573
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001574 // throw expression
1575 Pattern = new CodeCompletionString;
1576 Pattern->AddTypedTextChunk("throw");
1577 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1578 Pattern->AddPlaceholderChunk("expression");
1579 Results.AddResult(Result(Pattern));
Douglas Gregor12e13132010-05-26 22:00:08 +00001580
1581 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001582 }
1583
1584 if (SemaRef.getLangOptions().ObjC1) {
1585 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001586 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1587 // The interface can be NULL.
1588 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1589 if (ID->getSuperClass())
1590 Results.AddResult(Result("super"));
1591 }
1592
Douglas Gregorbca403c2010-01-13 23:51:12 +00001593 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001594 }
1595
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001596 // sizeof expression
1597 Pattern = new CodeCompletionString;
1598 Pattern->AddTypedTextChunk("sizeof");
1599 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1600 Pattern->AddPlaceholderChunk("expression-or-type");
1601 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1602 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001603 break;
1604 }
1605 }
1606
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001607 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1608 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001609
1610 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregora4477812010-01-14 16:01:26 +00001611 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001612}
1613
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001614/// \brief If the given declaration has an associated type, add it as a result
1615/// type chunk.
1616static void AddResultTypeChunk(ASTContext &Context,
1617 NamedDecl *ND,
1618 CodeCompletionString *Result) {
1619 if (!ND)
1620 return;
1621
1622 // Determine the type of the declaration (if it has a type).
1623 QualType T;
1624 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1625 T = Function->getResultType();
1626 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1627 T = Method->getResultType();
1628 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1629 T = FunTmpl->getTemplatedDecl()->getResultType();
1630 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1631 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1632 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1633 /* Do nothing: ignore unresolved using declarations*/
1634 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1635 T = Value->getType();
1636 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1637 T = Property->getType();
1638
1639 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1640 return;
1641
Douglas Gregor84139d62010-04-05 21:25:31 +00001642 PrintingPolicy Policy(Context.PrintingPolicy);
1643 Policy.AnonymousTagLocations = false;
1644
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001645 std::string TypeStr;
Douglas Gregor84139d62010-04-05 21:25:31 +00001646 T.getAsStringInternal(TypeStr, Policy);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001647 Result->AddResultTypeChunk(TypeStr);
1648}
1649
Douglas Gregor86d9a522009-09-21 16:56:56 +00001650/// \brief Add function parameter chunks to the given code completion string.
1651static void AddFunctionParameterChunks(ASTContext &Context,
1652 FunctionDecl *Function,
1653 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001654 typedef CodeCompletionString::Chunk Chunk;
1655
Douglas Gregor86d9a522009-09-21 16:56:56 +00001656 CodeCompletionString *CCStr = Result;
1657
1658 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1659 ParmVarDecl *Param = Function->getParamDecl(P);
1660
1661 if (Param->hasDefaultArg()) {
1662 // When we see an optional default argument, put that argument and
1663 // the remaining default arguments into a new, optional string.
1664 CodeCompletionString *Opt = new CodeCompletionString;
1665 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1666 CCStr = Opt;
1667 }
1668
1669 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001670 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001671
1672 // Format the placeholder string.
1673 std::string PlaceholderStr;
1674 if (Param->getIdentifier())
1675 PlaceholderStr = Param->getIdentifier()->getName();
1676
1677 Param->getType().getAsStringInternal(PlaceholderStr,
1678 Context.PrintingPolicy);
1679
1680 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001681 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001682 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00001683
1684 if (const FunctionProtoType *Proto
1685 = Function->getType()->getAs<FunctionProtoType>())
1686 if (Proto->isVariadic())
1687 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor86d9a522009-09-21 16:56:56 +00001688}
1689
1690/// \brief Add template parameter chunks to the given code completion string.
1691static void AddTemplateParameterChunks(ASTContext &Context,
1692 TemplateDecl *Template,
1693 CodeCompletionString *Result,
1694 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001695 typedef CodeCompletionString::Chunk Chunk;
1696
Douglas Gregor86d9a522009-09-21 16:56:56 +00001697 CodeCompletionString *CCStr = Result;
1698 bool FirstParameter = true;
1699
1700 TemplateParameterList *Params = Template->getTemplateParameters();
1701 TemplateParameterList::iterator PEnd = Params->end();
1702 if (MaxParameters)
1703 PEnd = Params->begin() + MaxParameters;
1704 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1705 bool HasDefaultArg = false;
1706 std::string PlaceholderStr;
1707 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1708 if (TTP->wasDeclaredWithTypename())
1709 PlaceholderStr = "typename";
1710 else
1711 PlaceholderStr = "class";
1712
1713 if (TTP->getIdentifier()) {
1714 PlaceholderStr += ' ';
1715 PlaceholderStr += TTP->getIdentifier()->getName();
1716 }
1717
1718 HasDefaultArg = TTP->hasDefaultArgument();
1719 } else if (NonTypeTemplateParmDecl *NTTP
1720 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1721 if (NTTP->getIdentifier())
1722 PlaceholderStr = NTTP->getIdentifier()->getName();
1723 NTTP->getType().getAsStringInternal(PlaceholderStr,
1724 Context.PrintingPolicy);
1725 HasDefaultArg = NTTP->hasDefaultArgument();
1726 } else {
1727 assert(isa<TemplateTemplateParmDecl>(*P));
1728 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1729
1730 // Since putting the template argument list into the placeholder would
1731 // be very, very long, we just use an abbreviation.
1732 PlaceholderStr = "template<...> class";
1733 if (TTP->getIdentifier()) {
1734 PlaceholderStr += ' ';
1735 PlaceholderStr += TTP->getIdentifier()->getName();
1736 }
1737
1738 HasDefaultArg = TTP->hasDefaultArgument();
1739 }
1740
1741 if (HasDefaultArg) {
1742 // When we see an optional default argument, put that argument and
1743 // the remaining default arguments into a new, optional string.
1744 CodeCompletionString *Opt = new CodeCompletionString;
1745 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1746 CCStr = Opt;
1747 }
1748
1749 if (FirstParameter)
1750 FirstParameter = false;
1751 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001752 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001753
1754 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001755 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001756 }
1757}
1758
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001759/// \brief Add a qualifier to the given code-completion string, if the
1760/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00001761static void
1762AddQualifierToCompletionString(CodeCompletionString *Result,
1763 NestedNameSpecifier *Qualifier,
1764 bool QualifierIsInformative,
1765 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001766 if (!Qualifier)
1767 return;
1768
1769 std::string PrintedNNS;
1770 {
1771 llvm::raw_string_ostream OS(PrintedNNS);
1772 Qualifier->print(OS, Context.PrintingPolicy);
1773 }
Douglas Gregor0563c262009-09-22 23:15:58 +00001774 if (QualifierIsInformative)
Benjamin Kramer660cc182009-11-29 20:18:50 +00001775 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor0563c262009-09-22 23:15:58 +00001776 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00001777 Result->AddTextChunk(PrintedNNS);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001778}
1779
Douglas Gregora61a8792009-12-11 18:44:16 +00001780static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1781 FunctionDecl *Function) {
1782 const FunctionProtoType *Proto
1783 = Function->getType()->getAs<FunctionProtoType>();
1784 if (!Proto || !Proto->getTypeQuals())
1785 return;
1786
1787 std::string QualsStr;
1788 if (Proto->getTypeQuals() & Qualifiers::Const)
1789 QualsStr += " const";
1790 if (Proto->getTypeQuals() & Qualifiers::Volatile)
1791 QualsStr += " volatile";
1792 if (Proto->getTypeQuals() & Qualifiers::Restrict)
1793 QualsStr += " restrict";
1794 Result->AddInformativeChunk(QualsStr);
1795}
1796
Douglas Gregor86d9a522009-09-21 16:56:56 +00001797/// \brief If possible, create a new code completion string for the given
1798/// result.
1799///
1800/// \returns Either a new, heap-allocated code completion string describing
1801/// how to use this result, or NULL to indicate that the string or name of the
1802/// result is all that is needed.
1803CodeCompletionString *
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001804CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S,
1805 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001806 typedef CodeCompletionString::Chunk Chunk;
1807
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001808 if (Kind == RK_Pattern)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001809 return Pattern->Clone(Result);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001810
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001811 if (!Result)
1812 Result = new CodeCompletionString;
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001813
1814 if (Kind == RK_Keyword) {
1815 Result->AddTypedTextChunk(Keyword);
1816 return Result;
1817 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001818
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001819 if (Kind == RK_Macro) {
1820 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001821 assert(MI && "Not a macro?");
1822
1823 Result->AddTypedTextChunk(Macro->getName());
1824
1825 if (!MI->isFunctionLike())
1826 return Result;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001827
1828 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001829 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001830 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
1831 A != AEnd; ++A) {
1832 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001833 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001834
1835 if (!MI->isVariadic() || A != AEnd - 1) {
1836 // Non-variadic argument.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001837 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001838 continue;
1839 }
1840
1841 // Variadic argument; cope with the different between GNU and C99
1842 // variadic macros, providing a single placeholder for the rest of the
1843 // arguments.
1844 if ((*A)->isStr("__VA_ARGS__"))
1845 Result->AddPlaceholderChunk("...");
1846 else {
1847 std::string Arg = (*A)->getName();
1848 Arg += "...";
Benjamin Kramer660cc182009-11-29 20:18:50 +00001849 Result->AddPlaceholderChunk(Arg);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001850 }
1851 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001852 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00001853 return Result;
1854 }
1855
Douglas Gregord8e8a582010-05-25 21:41:55 +00001856 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00001857 NamedDecl *ND = Declaration;
1858
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001859 if (StartsNestedNameSpecifier) {
Benjamin Kramer660cc182009-11-29 20:18:50 +00001860 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001861 Result->AddTextChunk("::");
1862 return Result;
1863 }
1864
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001865 AddResultTypeChunk(S.Context, ND, Result);
1866
Douglas Gregor86d9a522009-09-21 16:56:56 +00001867 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001868 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1869 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00001870 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001871 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001872 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001873 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00001874 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001875 return Result;
1876 }
1877
1878 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001879 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1880 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001881 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramer660cc182009-11-29 20:18:50 +00001882 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001883
1884 // Figure out which template parameters are deduced (or have default
1885 // arguments).
1886 llvm::SmallVector<bool, 16> Deduced;
1887 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
1888 unsigned LastDeducibleArgument;
1889 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
1890 --LastDeducibleArgument) {
1891 if (!Deduced[LastDeducibleArgument - 1]) {
1892 // C++0x: Figure out if the template argument has a default. If so,
1893 // the user doesn't need to type this argument.
1894 // FIXME: We need to abstract template parameters better!
1895 bool HasDefaultArg = false;
1896 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
1897 LastDeducibleArgument - 1);
1898 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1899 HasDefaultArg = TTP->hasDefaultArgument();
1900 else if (NonTypeTemplateParmDecl *NTTP
1901 = dyn_cast<NonTypeTemplateParmDecl>(Param))
1902 HasDefaultArg = NTTP->hasDefaultArgument();
1903 else {
1904 assert(isa<TemplateTemplateParmDecl>(Param));
1905 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001906 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00001907 }
1908
1909 if (!HasDefaultArg)
1910 break;
1911 }
1912 }
1913
1914 if (LastDeducibleArgument) {
1915 // Some of the function template arguments cannot be deduced from a
1916 // function call, so we introduce an explicit template argument list
1917 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001918 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001919 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
1920 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001921 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001922 }
1923
1924 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001925 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001926 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001927 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00001928 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001929 return Result;
1930 }
1931
1932 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00001933 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1934 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00001935 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001936 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001937 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001938 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001939 return Result;
1940 }
1941
Douglas Gregor9630eb62009-11-17 16:44:22 +00001942 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00001943 Selector Sel = Method->getSelector();
1944 if (Sel.isUnarySelector()) {
1945 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
1946 return Result;
1947 }
1948
Douglas Gregord3c68542009-11-19 01:08:35 +00001949 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
1950 SelName += ':';
1951 if (StartParameter == 0)
1952 Result->AddTypedTextChunk(SelName);
1953 else {
1954 Result->AddInformativeChunk(SelName);
1955
1956 // If there is only one parameter, and we're past it, add an empty
1957 // typed-text chunk since there is nothing to type.
1958 if (Method->param_size() == 1)
1959 Result->AddTypedTextChunk("");
1960 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00001961 unsigned Idx = 0;
1962 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
1963 PEnd = Method->param_end();
1964 P != PEnd; (void)++P, ++Idx) {
1965 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00001966 std::string Keyword;
1967 if (Idx > StartParameter)
Douglas Gregor834389b2010-01-12 06:38:28 +00001968 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001969 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
1970 Keyword += II->getName().str();
1971 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00001972 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregord3c68542009-11-19 01:08:35 +00001973 Result->AddInformativeChunk(Keyword);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00001974 else if (Idx == StartParameter)
Douglas Gregord3c68542009-11-19 01:08:35 +00001975 Result->AddTypedTextChunk(Keyword);
1976 else
1977 Result->AddTextChunk(Keyword);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001978 }
Douglas Gregord3c68542009-11-19 01:08:35 +00001979
1980 // If we're before the starting parameter, skip the placeholder.
1981 if (Idx < StartParameter)
1982 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00001983
1984 std::string Arg;
1985 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
1986 Arg = "(" + Arg + ")";
1987 if (IdentifierInfo *II = (*P)->getIdentifier())
1988 Arg += II->getName().str();
Douglas Gregor1f5537a2010-07-08 23:20:03 +00001989 if (DeclaringEntity)
1990 Result->AddTextChunk(Arg);
1991 else if (AllParametersAreInformative)
Douglas Gregor4ad96852009-11-19 07:41:15 +00001992 Result->AddInformativeChunk(Arg);
1993 else
1994 Result->AddPlaceholderChunk(Arg);
Douglas Gregor9630eb62009-11-17 16:44:22 +00001995 }
1996
Douglas Gregor2a17af02009-12-23 00:21:46 +00001997 if (Method->isVariadic()) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00001998 if (DeclaringEntity)
1999 Result->AddTextChunk(", ...");
2000 else if (AllParametersAreInformative)
Douglas Gregor2a17af02009-12-23 00:21:46 +00002001 Result->AddInformativeChunk(", ...");
2002 else
2003 Result->AddPlaceholderChunk(", ...");
2004 }
2005
Douglas Gregor9630eb62009-11-17 16:44:22 +00002006 return Result;
2007 }
2008
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002009 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002010 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2011 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002012
2013 Result->AddTypedTextChunk(ND->getNameAsString());
2014 return Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002015}
2016
Douglas Gregor86d802e2009-09-23 00:34:09 +00002017CodeCompletionString *
2018CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2019 unsigned CurrentArg,
2020 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002021 typedef CodeCompletionString::Chunk Chunk;
2022
Douglas Gregor86d802e2009-09-23 00:34:09 +00002023 CodeCompletionString *Result = new CodeCompletionString;
2024 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002025 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002026 const FunctionProtoType *Proto
2027 = dyn_cast<FunctionProtoType>(getFunctionType());
2028 if (!FDecl && !Proto) {
2029 // Function without a prototype. Just give the return type and a
2030 // highlighted ellipsis.
2031 const FunctionType *FT = getFunctionType();
2032 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002033 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002034 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2035 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2036 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002037 return Result;
2038 }
2039
2040 if (FDecl)
Benjamin Kramer660cc182009-11-29 20:18:50 +00002041 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregor86d802e2009-09-23 00:34:09 +00002042 else
2043 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002044 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002045
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002046 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002047 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2048 for (unsigned I = 0; I != NumParams; ++I) {
2049 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002050 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002051
2052 std::string ArgString;
2053 QualType ArgType;
2054
2055 if (FDecl) {
2056 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2057 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2058 } else {
2059 ArgType = Proto->getArgType(I);
2060 }
2061
2062 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2063
2064 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002065 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramer660cc182009-11-29 20:18:50 +00002066 ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002067 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00002068 Result->AddTextChunk(ArgString);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002069 }
2070
2071 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002072 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002073 if (CurrentArg < NumParams)
2074 Result->AddTextChunk("...");
2075 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002076 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002077 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002078 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002079
2080 return Result;
2081}
2082
Douglas Gregor86d9a522009-09-21 16:56:56 +00002083namespace {
2084 struct SortCodeCompleteResult {
2085 typedef CodeCompleteConsumer::Result Result;
2086
Douglas Gregor6a684032009-09-28 03:51:44 +00002087 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregor2b0cc122009-12-05 09:08:56 +00002088 Selector XSel = X.getObjCSelector();
2089 Selector YSel = Y.getObjCSelector();
2090 if (!XSel.isNull() && !YSel.isNull()) {
2091 // We are comparing two selectors.
2092 unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
2093 if (N == 0)
2094 ++N;
2095 for (unsigned I = 0; I != N; ++I) {
2096 IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
2097 IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
2098 if (!XId || !YId)
2099 return XId && !YId;
2100
2101 switch (XId->getName().compare_lower(YId->getName())) {
2102 case -1: return true;
2103 case 1: return false;
2104 default: break;
2105 }
2106 }
2107
2108 return XSel.getNumArgs() < YSel.getNumArgs();
2109 }
2110
2111 // For non-selectors, order by kind.
2112 if (X.getNameKind() != Y.getNameKind())
Douglas Gregor6a684032009-09-28 03:51:44 +00002113 return X.getNameKind() < Y.getNameKind();
2114
Douglas Gregor2b0cc122009-12-05 09:08:56 +00002115 // Order identifiers by comparison of their lowercased names.
2116 if (IdentifierInfo *XId = X.getAsIdentifierInfo())
2117 return XId->getName().compare_lower(
2118 Y.getAsIdentifierInfo()->getName()) < 0;
2119
2120 // Order overloaded operators by the order in which they appear
2121 // in our list of operators.
2122 if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
2123 return XOp < Y.getCXXOverloadedOperator();
2124
2125 // Order C++0x user-defined literal operators lexically by their
2126 // lowercased suffixes.
2127 if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
2128 return XLit->getName().compare_lower(
2129 Y.getCXXLiteralIdentifier()->getName()) < 0;
2130
2131 // The only stable ordering we have is to turn the name into a
2132 // string and then compare the lower-case strings. This is
2133 // inefficient, but thankfully does not happen too often.
Benjamin Kramer0e7049f2009-12-05 10:22:15 +00002134 return llvm::StringRef(X.getAsString()).compare_lower(
2135 Y.getAsString()) < 0;
Douglas Gregor6a684032009-09-28 03:51:44 +00002136 }
2137
Douglas Gregorab0b4f12010-01-13 23:24:38 +00002138 /// \brief Retrieve the name that should be used to order a result.
2139 ///
2140 /// If the name needs to be constructed as a string, that string will be
2141 /// saved into Saved and the returned StringRef will refer to it.
2142 static llvm::StringRef getOrderedName(const Result &R,
2143 std::string &Saved) {
2144 switch (R.Kind) {
2145 case Result::RK_Keyword:
2146 return R.Keyword;
2147
2148 case Result::RK_Pattern:
2149 return R.Pattern->getTypedText();
2150
2151 case Result::RK_Macro:
2152 return R.Macro->getName();
2153
2154 case Result::RK_Declaration:
2155 // Handle declarations below.
2156 break;
Douglas Gregor54f01612009-11-19 00:01:57 +00002157 }
Douglas Gregorab0b4f12010-01-13 23:24:38 +00002158
2159 DeclarationName Name = R.Declaration->getDeclName();
Douglas Gregor54f01612009-11-19 00:01:57 +00002160
Douglas Gregorab0b4f12010-01-13 23:24:38 +00002161 // If the name is a simple identifier (by far the common case), or a
2162 // zero-argument selector, just return a reference to that identifier.
2163 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
2164 return Id->getName();
2165 if (Name.isObjCZeroArgSelector())
2166 if (IdentifierInfo *Id
2167 = Name.getObjCSelector().getIdentifierInfoForSlot(0))
2168 return Id->getName();
2169
2170 Saved = Name.getAsString();
2171 return Saved;
2172 }
2173
2174 bool operator()(const Result &X, const Result &Y) const {
2175 std::string XSaved, YSaved;
2176 llvm::StringRef XStr = getOrderedName(X, XSaved);
2177 llvm::StringRef YStr = getOrderedName(Y, YSaved);
2178 int cmp = XStr.compare_lower(YStr);
2179 if (cmp)
2180 return cmp < 0;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002181
2182 // Non-hidden names precede hidden names.
2183 if (X.Hidden != Y.Hidden)
2184 return !X.Hidden;
2185
Douglas Gregoreb5758b2009-09-23 22:26:46 +00002186 // Non-nested-name-specifiers precede nested-name-specifiers.
2187 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
2188 return !X.StartsNestedNameSpecifier;
2189
Douglas Gregor86d9a522009-09-21 16:56:56 +00002190 return false;
2191 }
2192 };
2193}
2194
Douglas Gregor1827e102010-08-16 16:18:59 +00002195unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName,
2196 bool PreferredTypeIsPointer) {
2197 unsigned Priority = CCP_Macro;
2198
2199 // Treat the "nil" and "NULL" macros as null pointer constants.
2200 if (MacroName.equals("nil") || MacroName.equals("NULL")) {
2201 Priority = CCP_Constant;
2202 if (PreferredTypeIsPointer)
2203 Priority = Priority / CCF_SimilarTypeMatch;
2204 }
2205
2206 return Priority;
2207}
2208
Douglas Gregor590c7d52010-07-08 20:55:51 +00002209static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2210 bool TargetTypeIsPointer = false) {
2211 typedef CodeCompleteConsumer::Result Result;
2212
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002213 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002214 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2215 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002216 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002217 Results.AddResult(Result(M->first,
2218 getMacroUsagePriority(M->first->getName(),
2219 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002220 }
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002221 Results.ExitScope();
2222}
2223
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002224static void HandleCodeCompleteResults(Sema *S,
2225 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002226 CodeCompletionContext Context,
2227 CodeCompleteConsumer::Result *Results,
2228 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002229 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
2230
2231 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002232 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00002233
2234 for (unsigned I = 0; I != NumResults; ++I)
2235 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002236}
2237
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002238static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2239 Sema::ParserCompletionContext PCC) {
2240 switch (PCC) {
2241 case Action::PCC_Namespace:
2242 return CodeCompletionContext::CCC_TopLevel;
2243
2244 case Action::PCC_Class:
2245 return CodeCompletionContext::CCC_ClassStructUnion;
2246
2247 case Action::PCC_ObjCInterface:
2248 return CodeCompletionContext::CCC_ObjCInterface;
2249
2250 case Action::PCC_ObjCImplementation:
2251 return CodeCompletionContext::CCC_ObjCImplementation;
2252
2253 case Action::PCC_ObjCInstanceVariableList:
2254 return CodeCompletionContext::CCC_ObjCIvarList;
2255
2256 case Action::PCC_Template:
2257 case Action::PCC_MemberTemplate:
2258 case Action::PCC_RecoveryInFunction:
2259 return CodeCompletionContext::CCC_Other;
2260
2261 case Action::PCC_Expression:
2262 case Action::PCC_ForInit:
2263 case Action::PCC_Condition:
2264 return CodeCompletionContext::CCC_Expression;
2265
2266 case Action::PCC_Statement:
2267 return CodeCompletionContext::CCC_Statement;
2268 }
2269
2270 return CodeCompletionContext::CCC_Other;
2271}
2272
Douglas Gregor01dfea02010-01-10 23:08:15 +00002273void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002274 ParserCompletionContext CompletionContext) {
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002275 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002276 ResultBuilder Results(*this);
2277
2278 // Determine how to filter results, e.g., so that the names of
2279 // values (functions, enumerators, function templates, etc.) are
2280 // only allowed where we can have an expression.
2281 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002282 case PCC_Namespace:
2283 case PCC_Class:
2284 case PCC_ObjCInterface:
2285 case PCC_ObjCImplementation:
2286 case PCC_ObjCInstanceVariableList:
2287 case PCC_Template:
2288 case PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002289 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2290 break;
2291
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002292 case PCC_Expression:
2293 case PCC_Statement:
2294 case PCC_ForInit:
2295 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002296 if (WantTypesInContext(CompletionContext, getLangOptions()))
2297 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2298 else
2299 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002300 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002301
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002302 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002303 // Unfiltered
2304 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002305 }
2306
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002307 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002308 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2309 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002310
2311 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00002312 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002313 Results.ExitScope();
2314
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002315 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002316 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002317 HandleCodeCompleteResults(this, CodeCompleter,
2318 mapCodeCompletionContext(*this, CompletionContext),
2319 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002320}
2321
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002322/// \brief Perform code-completion in an expression context when we know what
2323/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00002324///
2325/// \param IntegralConstantExpression Only permit integral constant
2326/// expressions.
2327void Sema::CodeCompleteExpression(Scope *S, QualType T,
2328 bool IntegralConstantExpression) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002329 typedef CodeCompleteConsumer::Result Result;
2330 ResultBuilder Results(*this);
2331
Douglas Gregorf9578432010-07-28 21:50:18 +00002332 if (IntegralConstantExpression)
2333 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002334 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002335 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2336 else
2337 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
2338 Results.setPreferredType(T.getNonReferenceType());
2339
2340 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002341 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2342 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002343
2344 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002345 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002346 Results.ExitScope();
2347
Douglas Gregor590c7d52010-07-08 20:55:51 +00002348 bool PreferredTypeIsPointer = false;
2349 if (!T.isNull())
2350 PreferredTypeIsPointer = T->isAnyPointerType() ||
2351 T->isMemberPointerType() || T->isBlockPointerType();
2352
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002353 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00002354 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002355 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor1827e102010-08-16 16:18:59 +00002356 CodeCompletionContext(CodeCompletionContext::CCC_Expression, T),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002357 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002358}
2359
2360
Douglas Gregor95ac6552009-11-18 01:29:26 +00002361static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00002362 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00002363 DeclContext *CurContext,
2364 ResultBuilder &Results) {
2365 typedef CodeCompleteConsumer::Result Result;
2366
2367 // Add properties in this container.
2368 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2369 PEnd = Container->prop_end();
2370 P != PEnd;
2371 ++P)
2372 Results.MaybeAddResult(Result(*P, 0), CurContext);
2373
2374 // Add properties in referenced protocols.
2375 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2376 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2377 PEnd = Protocol->protocol_end();
2378 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002379 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002380 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00002381 if (AllowCategories) {
2382 // Look through categories.
2383 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2384 Category; Category = Category->getNextClassCategory())
2385 AddObjCProperties(Category, AllowCategories, CurContext, Results);
2386 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002387
2388 // Look through protocols.
2389 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2390 E = IFace->protocol_end();
2391 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002392 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002393
2394 // Look in the superclass.
2395 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00002396 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2397 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002398 } else if (const ObjCCategoryDecl *Category
2399 = dyn_cast<ObjCCategoryDecl>(Container)) {
2400 // Look through protocols.
2401 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
2402 PEnd = Category->protocol_end();
2403 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002404 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002405 }
2406}
2407
Douglas Gregor81b747b2009-09-17 21:32:03 +00002408void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2409 SourceLocation OpLoc,
2410 bool IsArrow) {
2411 if (!BaseE || !CodeCompleter)
2412 return;
2413
Douglas Gregor86d9a522009-09-21 16:56:56 +00002414 typedef CodeCompleteConsumer::Result Result;
2415
Douglas Gregor81b747b2009-09-17 21:32:03 +00002416 Expr *Base = static_cast<Expr *>(BaseE);
2417 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002418
2419 if (IsArrow) {
2420 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2421 BaseType = Ptr->getPointeeType();
2422 else if (BaseType->isObjCObjectPointerType())
2423 /*Do nothing*/ ;
2424 else
2425 return;
2426 }
2427
Douglas Gregoreb5758b2009-09-23 22:26:46 +00002428 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002429 Results.EnterNewScope();
2430 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
2431 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00002432 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00002433 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002434 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
2435 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002436
Douglas Gregor95ac6552009-11-18 01:29:26 +00002437 if (getLangOptions().CPlusPlus) {
2438 if (!Results.empty()) {
2439 // The "template" keyword can follow "->" or "." in the grammar.
2440 // However, we only want to suggest the template keyword if something
2441 // is dependent.
2442 bool IsDependent = BaseType->isDependentType();
2443 if (!IsDependent) {
2444 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2445 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2446 IsDependent = Ctx->isDependentContext();
2447 break;
2448 }
2449 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002450
Douglas Gregor95ac6552009-11-18 01:29:26 +00002451 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00002452 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002453 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002454 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002455 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2456 // Objective-C property reference.
2457
2458 // Add property results based on our interface.
2459 const ObjCObjectPointerType *ObjCPtr
2460 = BaseType->getAsObjCInterfacePointerType();
2461 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00002462 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002463
2464 // Add properties from the protocols in a qualified interface.
2465 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2466 E = ObjCPtr->qual_end();
2467 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002468 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002469 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00002470 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00002471 // Objective-C instance variable access.
2472 ObjCInterfaceDecl *Class = 0;
2473 if (const ObjCObjectPointerType *ObjCPtr
2474 = BaseType->getAs<ObjCObjectPointerType>())
2475 Class = ObjCPtr->getInterfaceDecl();
2476 else
John McCallc12c5bb2010-05-15 11:32:37 +00002477 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00002478
2479 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00002480 if (Class) {
2481 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2482 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00002483 LookupVisibleDecls(Class, LookupMemberName, Consumer,
2484 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00002485 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002486 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002487
2488 // FIXME: How do we cope with isa?
2489
2490 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002491
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002492 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002493 HandleCodeCompleteResults(this, CodeCompleter,
2494 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
2495 BaseType),
2496 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002497}
2498
Douglas Gregor374929f2009-09-18 15:37:17 +00002499void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2500 if (!CodeCompleter)
2501 return;
2502
Douglas Gregor86d9a522009-09-21 16:56:56 +00002503 typedef CodeCompleteConsumer::Result Result;
2504 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002505 enum CodeCompletionContext::Kind ContextKind
2506 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00002507 switch ((DeclSpec::TST)TagSpec) {
2508 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002509 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002510 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002511 break;
2512
2513 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002514 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002515 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002516 break;
2517
2518 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00002519 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002520 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002521 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002522 break;
2523
2524 default:
2525 assert(false && "Unknown type specifier kind in CodeCompleteTag");
2526 return;
2527 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002528
John McCall0d6b1642010-04-23 18:46:30 +00002529 ResultBuilder Results(*this);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002530 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00002531
2532 // First pass: look for tags.
2533 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00002534 LookupVisibleDecls(S, LookupTagName, Consumer,
2535 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00002536
Douglas Gregor8071e422010-08-15 06:18:01 +00002537 if (CodeCompleter->includeGlobals()) {
2538 // Second pass: look for nested name specifiers.
2539 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
2540 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
2541 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002542
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002543 HandleCodeCompleteResults(this, CodeCompleter, ContextKind,
2544 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00002545}
2546
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002547void Sema::CodeCompleteCase(Scope *S) {
2548 if (getSwitchStack().empty() || !CodeCompleter)
2549 return;
2550
2551 SwitchStmt *Switch = getSwitchStack().back();
Douglas Gregorf9578432010-07-28 21:50:18 +00002552 if (!Switch->getCond()->getType()->isEnumeralType()) {
2553 CodeCompleteExpression(S, Switch->getCond()->getType(), true);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002554 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00002555 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002556
2557 // Code-complete the cases of a switch statement over an enumeration type
2558 // by providing the list of
2559 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2560
2561 // Determine which enumerators we have already seen in the switch statement.
2562 // FIXME: Ideally, we would also be able to look *past* the code-completion
2563 // token, in case we are code-completing in the middle of the switch and not
2564 // at the end. However, we aren't able to do so at the moment.
2565 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002566 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002567 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2568 SC = SC->getNextSwitchCase()) {
2569 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2570 if (!Case)
2571 continue;
2572
2573 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2574 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2575 if (EnumConstantDecl *Enumerator
2576 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2577 // We look into the AST of the case statement to determine which
2578 // enumerator was named. Alternatively, we could compute the value of
2579 // the integral constant expression, then compare it against the
2580 // values of each enumerator. However, value-based approach would not
2581 // work as well with C++ templates where enumerators declared within a
2582 // template are type- and value-dependent.
2583 EnumeratorsSeen.insert(Enumerator);
2584
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002585 // If this is a qualified-id, keep track of the nested-name-specifier
2586 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002587 //
2588 // switch (TagD.getKind()) {
2589 // case TagDecl::TK_enum:
2590 // break;
2591 // case XXX
2592 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002593 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002594 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2595 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002596 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002597 }
2598 }
2599
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002600 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2601 // If there are no prior enumerators in C++, check whether we have to
2602 // qualify the names of the enumerators that we suggest, because they
2603 // may not be visible in this scope.
2604 Qualifier = getRequiredQualification(Context, CurContext,
2605 Enum->getDeclContext());
2606
2607 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2608 }
2609
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002610 // Add any enumerators that have not yet been mentioned.
2611 ResultBuilder Results(*this);
2612 Results.EnterNewScope();
2613 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2614 EEnd = Enum->enumerator_end();
2615 E != EEnd; ++E) {
2616 if (EnumeratorsSeen.count(*E))
2617 continue;
2618
Douglas Gregor608300b2010-01-14 16:14:35 +00002619 Results.AddResult(CodeCompleteConsumer::Result(*E, Qualifier),
2620 CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002621 }
2622 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00002623
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002624 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002625 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002626 HandleCodeCompleteResults(this, CodeCompleter,
2627 CodeCompletionContext::CCC_Expression,
2628 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002629}
2630
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002631namespace {
2632 struct IsBetterOverloadCandidate {
2633 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00002634 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002635
2636 public:
John McCall5769d612010-02-08 23:07:23 +00002637 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
2638 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002639
2640 bool
2641 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall5769d612010-02-08 23:07:23 +00002642 return S.isBetterOverloadCandidate(X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002643 }
2644 };
2645}
2646
Douglas Gregord28dcd72010-05-30 06:10:08 +00002647static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
2648 if (NumArgs && !Args)
2649 return true;
2650
2651 for (unsigned I = 0; I != NumArgs; ++I)
2652 if (!Args[I])
2653 return true;
2654
2655 return false;
2656}
2657
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002658void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2659 ExprTy **ArgsIn, unsigned NumArgs) {
2660 if (!CodeCompleter)
2661 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002662
2663 // When we're code-completing for a call, we fall back to ordinary
2664 // name code-completion whenever we can't produce specific
2665 // results. We may want to revisit this strategy in the future,
2666 // e.g., by merging the two kinds of results.
2667
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002668 Expr *Fn = (Expr *)FnIn;
2669 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002670
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002671 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00002672 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00002673 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002674 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002675 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002676 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002677
John McCall3b4294e2009-12-16 12:17:52 +00002678 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00002679 SourceLocation Loc = Fn->getExprLoc();
2680 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00002681
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002682 // FIXME: What if we're calling something that isn't a function declaration?
2683 // FIXME: What if we're calling a pseudo-destructor?
2684 // FIXME: What if we're calling a member function?
2685
Douglas Gregorc0265402010-01-21 15:46:19 +00002686 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
2687 llvm::SmallVector<ResultCandidate, 8> Results;
2688
John McCall3b4294e2009-12-16 12:17:52 +00002689 Expr *NakedFn = Fn->IgnoreParenCasts();
2690 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
2691 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
2692 /*PartialOverloading=*/ true);
2693 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
2694 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00002695 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00002696 if (!getLangOptions().CPlusPlus ||
2697 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00002698 Results.push_back(ResultCandidate(FDecl));
2699 else
John McCall86820f52010-01-26 01:37:31 +00002700 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00002701 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
2702 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00002703 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00002704 }
John McCall3b4294e2009-12-16 12:17:52 +00002705 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002706
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002707 QualType ParamType;
2708
Douglas Gregorc0265402010-01-21 15:46:19 +00002709 if (!CandidateSet.empty()) {
2710 // Sort the overload candidate set by placing the best overloads first.
2711 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00002712 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002713
Douglas Gregorc0265402010-01-21 15:46:19 +00002714 // Add the remaining viable overload candidates as code-completion reslults.
2715 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2716 CandEnd = CandidateSet.end();
2717 Cand != CandEnd; ++Cand) {
2718 if (Cand->Viable)
2719 Results.push_back(ResultCandidate(Cand->Function));
2720 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002721
2722 // From the viable candidates, try to determine the type of this parameter.
2723 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
2724 if (const FunctionType *FType = Results[I].getFunctionType())
2725 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
2726 if (NumArgs < Proto->getNumArgs()) {
2727 if (ParamType.isNull())
2728 ParamType = Proto->getArgType(NumArgs);
2729 else if (!Context.hasSameUnqualifiedType(
2730 ParamType.getNonReferenceType(),
2731 Proto->getArgType(NumArgs).getNonReferenceType())) {
2732 ParamType = QualType();
2733 break;
2734 }
2735 }
2736 }
2737 } else {
2738 // Try to determine the parameter type from the type of the expression
2739 // being called.
2740 QualType FunctionType = Fn->getType();
2741 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
2742 FunctionType = Ptr->getPointeeType();
2743 else if (const BlockPointerType *BlockPtr
2744 = FunctionType->getAs<BlockPointerType>())
2745 FunctionType = BlockPtr->getPointeeType();
2746 else if (const MemberPointerType *MemPtr
2747 = FunctionType->getAs<MemberPointerType>())
2748 FunctionType = MemPtr->getPointeeType();
2749
2750 if (const FunctionProtoType *Proto
2751 = FunctionType->getAs<FunctionProtoType>()) {
2752 if (NumArgs < Proto->getNumArgs())
2753 ParamType = Proto->getArgType(NumArgs);
2754 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002755 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00002756
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002757 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002758 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002759 else
2760 CodeCompleteExpression(S, ParamType);
2761
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00002762 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00002763 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
2764 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002765}
2766
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002767void Sema::CodeCompleteInitializer(Scope *S, DeclPtrTy D) {
2768 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D.getAs<Decl>());
2769 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002770 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002771 return;
2772 }
2773
2774 CodeCompleteExpression(S, VD->getType());
2775}
2776
2777void Sema::CodeCompleteReturn(Scope *S) {
2778 QualType ResultType;
2779 if (isa<BlockDecl>(CurContext)) {
2780 if (BlockScopeInfo *BSI = getCurBlock())
2781 ResultType = BSI->ReturnType;
2782 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
2783 ResultType = Function->getResultType();
2784 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
2785 ResultType = Method->getResultType();
2786
2787 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002788 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002789 else
2790 CodeCompleteExpression(S, ResultType);
2791}
2792
2793void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
2794 if (LHS)
2795 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
2796 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002797 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002798}
2799
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002800void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00002801 bool EnteringContext) {
2802 if (!SS.getScopeRep() || !CodeCompleter)
2803 return;
2804
Douglas Gregor86d9a522009-09-21 16:56:56 +00002805 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
2806 if (!Ctx)
2807 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00002808
2809 // Try to instantiate any non-dependent declaration contexts before
2810 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00002811 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00002812 return;
2813
Douglas Gregor86d9a522009-09-21 16:56:56 +00002814 ResultBuilder Results(*this);
Douglas Gregordef91072010-01-14 03:35:48 +00002815 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2816 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002817
2818 // The "template" keyword can follow "::" in the grammar, but only
2819 // put it into the grammar if the nested-name-specifier is dependent.
2820 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
2821 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00002822 Results.AddResult("template");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002823
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002824 HandleCodeCompleteResults(this, CodeCompleter,
2825 CodeCompletionContext::CCC_Other,
2826 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002827}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002828
2829void Sema::CodeCompleteUsing(Scope *S) {
2830 if (!CodeCompleter)
2831 return;
2832
Douglas Gregor86d9a522009-09-21 16:56:56 +00002833 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002834 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002835
2836 // If we aren't in class scope, we could see the "namespace" keyword.
2837 if (!S->isClassScope())
Douglas Gregora4477812010-01-14 16:01:26 +00002838 Results.AddResult(CodeCompleteConsumer::Result("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002839
2840 // After "using", we can see anything that would start a
2841 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002842 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002843 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2844 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002845 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002846
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002847 HandleCodeCompleteResults(this, CodeCompleter,
2848 CodeCompletionContext::CCC_Other,
2849 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002850}
2851
2852void Sema::CodeCompleteUsingDirective(Scope *S) {
2853 if (!CodeCompleter)
2854 return;
2855
Douglas Gregor86d9a522009-09-21 16:56:56 +00002856 // After "using namespace", we expect to see a namespace name or namespace
2857 // alias.
2858 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002859 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002860 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002861 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2862 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002863 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002864 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00002865 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002866 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002867}
2868
2869void Sema::CodeCompleteNamespaceDecl(Scope *S) {
2870 if (!CodeCompleter)
2871 return;
2872
Douglas Gregor86d9a522009-09-21 16:56:56 +00002873 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
2874 DeclContext *Ctx = (DeclContext *)S->getEntity();
2875 if (!S->getParent())
2876 Ctx = Context.getTranslationUnitDecl();
2877
2878 if (Ctx && Ctx->isFileContext()) {
2879 // We only want to see those namespaces that have already been defined
2880 // within this scope, because its likely that the user is creating an
2881 // extended namespace declaration. Keep track of the most recent
2882 // definition of each namespace.
2883 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
2884 for (DeclContext::specific_decl_iterator<NamespaceDecl>
2885 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
2886 NS != NSEnd; ++NS)
2887 OrigToLatest[NS->getOriginalNamespace()] = *NS;
2888
2889 // Add the most recent definition (or extended definition) of each
2890 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002891 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002892 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
2893 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
2894 NS != NSEnd; ++NS)
Douglas Gregor608300b2010-01-14 16:14:35 +00002895 Results.AddResult(CodeCompleteConsumer::Result(NS->second, 0),
2896 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002897 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002898 }
2899
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002900 HandleCodeCompleteResults(this, CodeCompleter,
2901 CodeCompletionContext::CCC_Other,
2902 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002903}
2904
2905void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
2906 if (!CodeCompleter)
2907 return;
2908
Douglas Gregor86d9a522009-09-21 16:56:56 +00002909 // After "namespace", we expect to see a namespace or alias.
2910 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002911 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002912 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2913 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002914 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00002915 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002916 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002917}
2918
Douglas Gregored8d3222009-09-18 20:05:18 +00002919void Sema::CodeCompleteOperatorName(Scope *S) {
2920 if (!CodeCompleter)
2921 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002922
2923 typedef CodeCompleteConsumer::Result Result;
2924 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002925 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00002926
Douglas Gregor86d9a522009-09-21 16:56:56 +00002927 // Add the names of overloadable operators.
2928#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2929 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00002930 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002931#include "clang/Basic/OperatorKinds.def"
2932
2933 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00002934 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002935 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002936 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2937 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00002938
2939 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00002940 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00002941 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002942
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002943 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00002944 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002945 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00002946}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00002947
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002948// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
2949// true or false.
2950#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00002951static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002952 ResultBuilder &Results,
2953 bool NeedAt) {
2954 typedef CodeCompleteConsumer::Result Result;
2955 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00002956 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002957
2958 CodeCompletionString *Pattern = 0;
2959 if (LangOpts.ObjC2) {
2960 // @dynamic
2961 Pattern = new CodeCompletionString;
2962 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
2963 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2964 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00002965 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002966
2967 // @synthesize
2968 Pattern = new CodeCompletionString;
2969 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
2970 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2971 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00002972 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002973 }
2974}
2975
Douglas Gregorbca403c2010-01-13 23:51:12 +00002976static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002977 ResultBuilder &Results,
2978 bool NeedAt) {
2979 typedef CodeCompleteConsumer::Result Result;
2980
2981 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00002982 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002983
2984 if (LangOpts.ObjC2) {
2985 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00002986 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002987
2988 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00002989 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002990
2991 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00002992 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002993 }
2994}
2995
Douglas Gregorbca403c2010-01-13 23:51:12 +00002996static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00002997 typedef CodeCompleteConsumer::Result Result;
2998 CodeCompletionString *Pattern = 0;
2999
3000 // @class name ;
3001 Pattern = new CodeCompletionString;
3002 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3003 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003004 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00003005 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003006
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003007 if (Results.includeCodePatterns()) {
3008 // @interface name
3009 // FIXME: Could introduce the whole pattern, including superclasses and
3010 // such.
3011 Pattern = new CodeCompletionString;
3012 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
3013 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3014 Pattern->AddPlaceholderChunk("class");
3015 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003016
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003017 // @protocol name
3018 Pattern = new CodeCompletionString;
3019 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3020 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3021 Pattern->AddPlaceholderChunk("protocol");
3022 Results.AddResult(Result(Pattern));
3023
3024 // @implementation name
3025 Pattern = new CodeCompletionString;
3026 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
3027 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3028 Pattern->AddPlaceholderChunk("class");
3029 Results.AddResult(Result(Pattern));
3030 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003031
3032 // @compatibility_alias name
3033 Pattern = new CodeCompletionString;
3034 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
3035 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3036 Pattern->AddPlaceholderChunk("alias");
3037 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3038 Pattern->AddPlaceholderChunk("class");
Douglas Gregora4477812010-01-14 16:01:26 +00003039 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003040}
3041
Douglas Gregorc464ae82009-12-07 09:27:33 +00003042void Sema::CodeCompleteObjCAtDirective(Scope *S, DeclPtrTy ObjCImpDecl,
3043 bool InInterface) {
3044 typedef CodeCompleteConsumer::Result Result;
3045 ResultBuilder Results(*this);
3046 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003047 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003048 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003049 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003050 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003051 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00003052 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003053 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003054 HandleCodeCompleteResults(this, CodeCompleter,
3055 CodeCompletionContext::CCC_Other,
3056 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00003057}
3058
Douglas Gregorbca403c2010-01-13 23:51:12 +00003059static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003060 typedef CodeCompleteConsumer::Result Result;
3061 CodeCompletionString *Pattern = 0;
3062
3063 // @encode ( type-name )
3064 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003065 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003066 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3067 Pattern->AddPlaceholderChunk("type-name");
3068 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003069 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003070
3071 // @protocol ( protocol-name )
3072 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003073 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003074 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3075 Pattern->AddPlaceholderChunk("protocol-name");
3076 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003077 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003078
3079 // @selector ( selector )
3080 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003081 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003082 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3083 Pattern->AddPlaceholderChunk("selector");
3084 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003085 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003086}
3087
Douglas Gregorbca403c2010-01-13 23:51:12 +00003088static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003089 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003090 CodeCompletionString *Pattern = 0;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003091
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003092 if (Results.includeCodePatterns()) {
3093 // @try { statements } @catch ( declaration ) { statements } @finally
3094 // { statements }
3095 Pattern = new CodeCompletionString;
3096 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
3097 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3098 Pattern->AddPlaceholderChunk("statements");
3099 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3100 Pattern->AddTextChunk("@catch");
3101 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3102 Pattern->AddPlaceholderChunk("parameter");
3103 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3104 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3105 Pattern->AddPlaceholderChunk("statements");
3106 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3107 Pattern->AddTextChunk("@finally");
3108 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3109 Pattern->AddPlaceholderChunk("statements");
3110 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3111 Results.AddResult(Result(Pattern));
3112 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003113
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003114 // @throw
3115 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003116 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
Douglas Gregor834389b2010-01-12 06:38:28 +00003117 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003118 Pattern->AddPlaceholderChunk("expression");
Douglas Gregora4477812010-01-14 16:01:26 +00003119 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003120
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003121 if (Results.includeCodePatterns()) {
3122 // @synchronized ( expression ) { statements }
3123 Pattern = new CodeCompletionString;
3124 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3125 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3126 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3127 Pattern->AddPlaceholderChunk("expression");
3128 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3129 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3130 Pattern->AddPlaceholderChunk("statements");
3131 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3132 Results.AddResult(Result(Pattern));
3133 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003134}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003135
Douglas Gregorbca403c2010-01-13 23:51:12 +00003136static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003137 ResultBuilder &Results,
3138 bool NeedAt) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003139 typedef CodeCompleteConsumer::Result Result;
Douglas Gregora4477812010-01-14 16:01:26 +00003140 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3141 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3142 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003143 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00003144 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003145}
3146
3147void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
3148 ResultBuilder Results(*this);
3149 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003150 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003151 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003152 HandleCodeCompleteResults(this, CodeCompleter,
3153 CodeCompletionContext::CCC_Other,
3154 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003155}
3156
3157void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003158 ResultBuilder Results(*this);
3159 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003160 AddObjCStatementResults(Results, false);
3161 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003162 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003163 HandleCodeCompleteResults(this, CodeCompleter,
3164 CodeCompletionContext::CCC_Other,
3165 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003166}
3167
3168void Sema::CodeCompleteObjCAtExpression(Scope *S) {
3169 ResultBuilder Results(*this);
3170 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003171 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003172 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003173 HandleCodeCompleteResults(this, CodeCompleter,
3174 CodeCompletionContext::CCC_Other,
3175 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003176}
3177
Douglas Gregor988358f2009-11-19 00:14:45 +00003178/// \brief Determine whether the addition of the given flag to an Objective-C
3179/// property's attributes will cause a conflict.
3180static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3181 // Check if we've already added this flag.
3182 if (Attributes & NewFlag)
3183 return true;
3184
3185 Attributes |= NewFlag;
3186
3187 // Check for collisions with "readonly".
3188 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3189 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3190 ObjCDeclSpec::DQ_PR_assign |
3191 ObjCDeclSpec::DQ_PR_copy |
3192 ObjCDeclSpec::DQ_PR_retain)))
3193 return true;
3194
3195 // Check for more than one of { assign, copy, retain }.
3196 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3197 ObjCDeclSpec::DQ_PR_copy |
3198 ObjCDeclSpec::DQ_PR_retain);
3199 if (AssignCopyRetMask &&
3200 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3201 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3202 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3203 return true;
3204
3205 return false;
3206}
3207
Douglas Gregora93b1082009-11-18 23:08:07 +00003208void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00003209 if (!CodeCompleter)
3210 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00003211
Steve Naroffece8e712009-10-08 21:55:05 +00003212 unsigned Attributes = ODS.getPropertyAttributes();
3213
3214 typedef CodeCompleteConsumer::Result Result;
3215 ResultBuilder Results(*this);
3216 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00003217 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
Douglas Gregora4477812010-01-14 16:01:26 +00003218 Results.AddResult(CodeCompleteConsumer::Result("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003219 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
Douglas Gregora4477812010-01-14 16:01:26 +00003220 Results.AddResult(CodeCompleteConsumer::Result("assign"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003221 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregora4477812010-01-14 16:01:26 +00003222 Results.AddResult(CodeCompleteConsumer::Result("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003223 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
Douglas Gregora4477812010-01-14 16:01:26 +00003224 Results.AddResult(CodeCompleteConsumer::Result("retain"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003225 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
Douglas Gregora4477812010-01-14 16:01:26 +00003226 Results.AddResult(CodeCompleteConsumer::Result("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003227 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
Douglas Gregora4477812010-01-14 16:01:26 +00003228 Results.AddResult(CodeCompleteConsumer::Result("nonatomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003229 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003230 CodeCompletionString *Setter = new CodeCompletionString;
3231 Setter->AddTypedTextChunk("setter");
3232 Setter->AddTextChunk(" = ");
3233 Setter->AddPlaceholderChunk("method");
Douglas Gregora4477812010-01-14 16:01:26 +00003234 Results.AddResult(CodeCompleteConsumer::Result(Setter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003235 }
Douglas Gregor988358f2009-11-19 00:14:45 +00003236 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003237 CodeCompletionString *Getter = new CodeCompletionString;
3238 Getter->AddTypedTextChunk("getter");
3239 Getter->AddTextChunk(" = ");
3240 Getter->AddPlaceholderChunk("method");
Douglas Gregora4477812010-01-14 16:01:26 +00003241 Results.AddResult(CodeCompleteConsumer::Result(Getter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003242 }
Steve Naroffece8e712009-10-08 21:55:05 +00003243 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003244 HandleCodeCompleteResults(this, CodeCompleter,
3245 CodeCompletionContext::CCC_Other,
3246 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00003247}
Steve Naroffc4df6d22009-11-07 02:08:14 +00003248
Douglas Gregor4ad96852009-11-19 07:41:15 +00003249/// \brief Descripts the kind of Objective-C method that we want to find
3250/// via code completion.
3251enum ObjCMethodKind {
3252 MK_Any, //< Any kind of method, provided it means other specified criteria.
3253 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3254 MK_OneArgSelector //< One-argument selector.
3255};
3256
3257static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
3258 ObjCMethodKind WantKind,
3259 IdentifierInfo **SelIdents,
3260 unsigned NumSelIdents) {
3261 Selector Sel = Method->getSelector();
3262 if (NumSelIdents > Sel.getNumArgs())
3263 return false;
3264
3265 switch (WantKind) {
3266 case MK_Any: break;
3267 case MK_ZeroArgSelector: return Sel.isUnarySelector();
3268 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
3269 }
3270
3271 for (unsigned I = 0; I != NumSelIdents; ++I)
3272 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
3273 return false;
3274
3275 return true;
3276}
3277
Douglas Gregor36ecb042009-11-17 23:22:23 +00003278/// \brief Add all of the Objective-C methods in the given Objective-C
3279/// container to the set of results.
3280///
3281/// The container will be a class, protocol, category, or implementation of
3282/// any of the above. This mether will recurse to include methods from
3283/// the superclasses of classes along with their categories, protocols, and
3284/// implementations.
3285///
3286/// \param Container the container in which we'll look to find methods.
3287///
3288/// \param WantInstance whether to add instance methods (only); if false, this
3289/// routine will add factory methods (only).
3290///
3291/// \param CurContext the context in which we're performing the lookup that
3292/// finds methods.
3293///
3294/// \param Results the structure into which we'll add results.
3295static void AddObjCMethods(ObjCContainerDecl *Container,
3296 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003297 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00003298 IdentifierInfo **SelIdents,
3299 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00003300 DeclContext *CurContext,
3301 ResultBuilder &Results) {
3302 typedef CodeCompleteConsumer::Result Result;
3303 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3304 MEnd = Container->meth_end();
3305 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00003306 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3307 // Check whether the selector identifiers we've been given are a
3308 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00003309 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00003310 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003311
Douglas Gregord3c68542009-11-19 01:08:35 +00003312 Result R = Result(*M, 0);
3313 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003314 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregord3c68542009-11-19 01:08:35 +00003315 Results.MaybeAddResult(R, CurContext);
3316 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00003317 }
3318
3319 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
3320 if (!IFace)
3321 return;
3322
3323 // Add methods in protocols.
3324 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
3325 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3326 E = Protocols.end();
3327 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003328 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregord3c68542009-11-19 01:08:35 +00003329 CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003330
3331 // Add methods in categories.
3332 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
3333 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00003334 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
3335 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003336
3337 // Add a categories protocol methods.
3338 const ObjCList<ObjCProtocolDecl> &Protocols
3339 = CatDecl->getReferencedProtocols();
3340 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3341 E = Protocols.end();
3342 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003343 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
3344 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003345
3346 // Add methods in category implementations.
3347 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003348 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3349 NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003350 }
3351
3352 // Add methods in superclass.
3353 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003354 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
3355 SelIdents, NumSelIdents, CurContext, Results);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003356
3357 // Add methods in our implementation, if any.
3358 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003359 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3360 NumSelIdents, CurContext, Results);
3361}
3362
3363
3364void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
3365 DeclPtrTy *Methods,
3366 unsigned NumMethods) {
3367 typedef CodeCompleteConsumer::Result Result;
3368
3369 // Try to find the interface where getters might live.
3370 ObjCInterfaceDecl *Class
3371 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
3372 if (!Class) {
3373 if (ObjCCategoryDecl *Category
3374 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
3375 Class = Category->getClassInterface();
3376
3377 if (!Class)
3378 return;
3379 }
3380
3381 // Find all of the potential getters.
3382 ResultBuilder Results(*this);
3383 Results.EnterNewScope();
3384
3385 // FIXME: We need to do this because Objective-C methods don't get
3386 // pushed into DeclContexts early enough. Argh!
3387 for (unsigned I = 0; I != NumMethods; ++I) {
3388 if (ObjCMethodDecl *Method
3389 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3390 if (Method->isInstanceMethod() &&
3391 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
3392 Result R = Result(Method, 0);
3393 R.AllParametersAreInformative = true;
3394 Results.MaybeAddResult(R, CurContext);
3395 }
3396 }
3397
3398 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
3399 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003400 HandleCodeCompleteResults(this, CodeCompleter,
3401 CodeCompletionContext::CCC_Other,
3402 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00003403}
3404
3405void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
3406 DeclPtrTy *Methods,
3407 unsigned NumMethods) {
3408 typedef CodeCompleteConsumer::Result Result;
3409
3410 // Try to find the interface where setters might live.
3411 ObjCInterfaceDecl *Class
3412 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
3413 if (!Class) {
3414 if (ObjCCategoryDecl *Category
3415 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
3416 Class = Category->getClassInterface();
3417
3418 if (!Class)
3419 return;
3420 }
3421
3422 // Find all of the potential getters.
3423 ResultBuilder Results(*this);
3424 Results.EnterNewScope();
3425
3426 // FIXME: We need to do this because Objective-C methods don't get
3427 // pushed into DeclContexts early enough. Argh!
3428 for (unsigned I = 0; I != NumMethods; ++I) {
3429 if (ObjCMethodDecl *Method
3430 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3431 if (Method->isInstanceMethod() &&
3432 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
3433 Result R = Result(Method, 0);
3434 R.AllParametersAreInformative = true;
3435 Results.MaybeAddResult(R, CurContext);
3436 }
3437 }
3438
3439 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
3440
3441 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003442 HandleCodeCompleteResults(this, CodeCompleter,
3443 CodeCompletionContext::CCC_Other,
3444 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00003445}
3446
Douglas Gregor22f56992010-04-06 19:22:33 +00003447/// \brief When we have an expression with type "id", we may assume
3448/// that it has some more-specific class type based on knowledge of
3449/// common uses of Objective-C. This routine returns that class type,
3450/// or NULL if no better result could be determined.
3451static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
3452 ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E);
3453 if (!Msg)
3454 return 0;
3455
3456 Selector Sel = Msg->getSelector();
3457 if (Sel.isNull())
3458 return 0;
3459
3460 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
3461 if (!Id)
3462 return 0;
3463
3464 ObjCMethodDecl *Method = Msg->getMethodDecl();
3465 if (!Method)
3466 return 0;
3467
3468 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00003469 ObjCInterfaceDecl *IFace = 0;
3470 switch (Msg->getReceiverKind()) {
3471 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00003472 if (const ObjCObjectType *ObjType
3473 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
3474 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00003475 break;
3476
3477 case ObjCMessageExpr::Instance: {
3478 QualType T = Msg->getInstanceReceiver()->getType();
3479 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
3480 IFace = Ptr->getInterfaceDecl();
3481 break;
3482 }
3483
3484 case ObjCMessageExpr::SuperInstance:
3485 case ObjCMessageExpr::SuperClass:
3486 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00003487 }
3488
3489 if (!IFace)
3490 return 0;
3491
3492 ObjCInterfaceDecl *Super = IFace->getSuperClass();
3493 if (Method->isInstanceMethod())
3494 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3495 .Case("retain", IFace)
3496 .Case("autorelease", IFace)
3497 .Case("copy", IFace)
3498 .Case("copyWithZone", IFace)
3499 .Case("mutableCopy", IFace)
3500 .Case("mutableCopyWithZone", IFace)
3501 .Case("awakeFromCoder", IFace)
3502 .Case("replacementObjectFromCoder", IFace)
3503 .Case("class", IFace)
3504 .Case("classForCoder", IFace)
3505 .Case("superclass", Super)
3506 .Default(0);
3507
3508 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3509 .Case("new", IFace)
3510 .Case("alloc", IFace)
3511 .Case("allocWithZone", IFace)
3512 .Case("class", IFace)
3513 .Case("superclass", Super)
3514 .Default(0);
3515}
3516
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003517void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
3518 typedef CodeCompleteConsumer::Result Result;
3519 ResultBuilder Results(*this);
3520
3521 // Find anything that looks like it could be a message receiver.
3522 Results.setFilter(&ResultBuilder::IsObjCMessageReceiver);
3523 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3524 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00003525 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3526 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003527
3528 // If we are in an Objective-C method inside a class that has a superclass,
3529 // add "super" as an option.
3530 if (ObjCMethodDecl *Method = getCurMethodDecl())
3531 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
3532 if (Iface->getSuperClass())
3533 Results.AddResult(Result("super"));
3534
3535 Results.ExitScope();
3536
3537 if (CodeCompleter->includeMacros())
3538 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003539 HandleCodeCompleteResults(this, CodeCompleter,
3540 CodeCompletionContext::CCC_ObjCMessageReceiver,
3541 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003542
3543}
3544
Douglas Gregor2725ca82010-04-21 19:57:20 +00003545void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
3546 IdentifierInfo **SelIdents,
3547 unsigned NumSelIdents) {
3548 ObjCInterfaceDecl *CDecl = 0;
3549 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3550 // Figure out which interface we're in.
3551 CDecl = CurMethod->getClassInterface();
3552 if (!CDecl)
3553 return;
3554
3555 // Find the superclass of this class.
3556 CDecl = CDecl->getSuperClass();
3557 if (!CDecl)
3558 return;
3559
3560 if (CurMethod->isInstanceMethod()) {
3561 // We are inside an instance method, which means that the message
3562 // send [super ...] is actually calling an instance method on the
3563 // current object. Build the super expression and handle this like
3564 // an instance method.
3565 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
3566 SuperTy = Context.getObjCObjectPointerType(SuperTy);
3567 OwningExprResult Super
3568 = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
3569 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
3570 SelIdents, NumSelIdents);
3571 }
3572
3573 // Fall through to send to the superclass in CDecl.
3574 } else {
3575 // "super" may be the name of a type or variable. Figure out which
3576 // it is.
3577 IdentifierInfo *Super = &Context.Idents.get("super");
3578 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
3579 LookupOrdinaryName);
3580 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
3581 // "super" names an interface. Use it.
3582 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00003583 if (const ObjCObjectType *Iface
3584 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
3585 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00003586 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
3587 // "super" names an unresolved type; we can't be more specific.
3588 } else {
3589 // Assume that "super" names some kind of value and parse that way.
3590 CXXScopeSpec SS;
3591 UnqualifiedId id;
3592 id.setIdentifier(Super, SuperLoc);
3593 OwningExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
3594 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
3595 SelIdents, NumSelIdents);
3596 }
3597
3598 // Fall through
3599 }
3600
3601 TypeTy *Receiver = 0;
3602 if (CDecl)
3603 Receiver = Context.getObjCInterfaceType(CDecl).getAsOpaquePtr();
3604 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
3605 NumSelIdents);
3606}
3607
3608void Sema::CodeCompleteObjCClassMessage(Scope *S, TypeTy *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00003609 IdentifierInfo **SelIdents,
3610 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00003611 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00003612 ObjCInterfaceDecl *CDecl = 0;
3613
Douglas Gregor24a069f2009-11-17 17:59:40 +00003614 // If the given name refers to an interface type, retrieve the
3615 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00003616 if (Receiver) {
3617 QualType T = GetTypeFromParser(Receiver, 0);
3618 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00003619 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
3620 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00003621 }
3622
Douglas Gregor36ecb042009-11-17 23:22:23 +00003623 // Add all of the factory methods in this Objective-C class, its protocols,
3624 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00003625 ResultBuilder Results(*this);
3626 Results.EnterNewScope();
Douglas Gregor13438f92010-04-06 16:40:00 +00003627
3628 if (CDecl)
3629 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
3630 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00003631 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00003632 // We're messaging "id" as a type; provide all class/factory methods.
3633
Douglas Gregor719770d2010-04-06 17:30:22 +00003634 // If we have an external source, load the entire class method
3635 // pool from the PCH file.
3636 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00003637 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3638 I != N; ++I) {
3639 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00003640 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00003641 continue;
3642
Sebastian Redldb9d2142010-08-02 23:18:59 +00003643 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00003644 }
3645 }
3646
Sebastian Redldb9d2142010-08-02 23:18:59 +00003647 for (GlobalMethodPool::iterator M = MethodPool.begin(),
3648 MEnd = MethodPool.end();
3649 M != MEnd; ++M) {
3650 for (ObjCMethodList *MethList = &M->second.second;
3651 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00003652 MethList = MethList->Next) {
3653 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3654 NumSelIdents))
3655 continue;
3656
3657 Result R(MethList->Method, 0);
3658 R.StartParameter = NumSelIdents;
3659 R.AllParametersAreInformative = false;
3660 Results.MaybeAddResult(R, CurContext);
3661 }
3662 }
3663 }
3664
Steve Naroffc4df6d22009-11-07 02:08:14 +00003665 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003666 HandleCodeCompleteResults(this, CodeCompleter,
3667 CodeCompletionContext::CCC_Other,
3668 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00003669}
3670
Douglas Gregord3c68542009-11-19 01:08:35 +00003671void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
3672 IdentifierInfo **SelIdents,
3673 unsigned NumSelIdents) {
Steve Naroffc4df6d22009-11-07 02:08:14 +00003674 typedef CodeCompleteConsumer::Result Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00003675
3676 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00003677
Douglas Gregor36ecb042009-11-17 23:22:23 +00003678 // If necessary, apply function/array conversion to the receiver.
3679 // C99 6.7.5.3p[7,8].
Douglas Gregora873dfc2010-02-03 00:27:59 +00003680 DefaultFunctionArrayLvalueConversion(RecExpr);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003681 QualType ReceiverType = RecExpr->getType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00003682
Douglas Gregor36ecb042009-11-17 23:22:23 +00003683 // Build the set of methods we can see.
3684 ResultBuilder Results(*this);
3685 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00003686
3687 // If we're messaging an expression with type "id" or "Class", check
3688 // whether we know something special about the receiver that allows
3689 // us to assume a more-specific receiver type.
3690 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
3691 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
3692 ReceiverType = Context.getObjCObjectPointerType(
3693 Context.getObjCInterfaceType(IFace));
Douglas Gregor36ecb042009-11-17 23:22:23 +00003694
Douglas Gregorf74a4192009-11-18 00:06:18 +00003695 // Handle messages to Class. This really isn't a message to an instance
3696 // method, so we treat it the same way we would treat a message send to a
3697 // class method.
3698 if (ReceiverType->isObjCClassType() ||
3699 ReceiverType->isObjCQualifiedClassType()) {
3700 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3701 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003702 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
3703 CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003704 }
3705 }
3706 // Handle messages to a qualified ID ("id<foo>").
3707 else if (const ObjCObjectPointerType *QualID
3708 = ReceiverType->getAsObjCQualifiedIdType()) {
3709 // Search protocols for instance methods.
3710 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
3711 E = QualID->qual_end();
3712 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003713 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3714 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003715 }
3716 // Handle messages to a pointer to interface type.
3717 else if (const ObjCObjectPointerType *IFacePtr
3718 = ReceiverType->getAsObjCInterfacePointerType()) {
3719 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00003720 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
3721 NumSelIdents, CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003722
3723 // Search protocols for instance methods.
3724 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
3725 E = IFacePtr->qual_end();
3726 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003727 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3728 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00003729 }
Douglas Gregor13438f92010-04-06 16:40:00 +00003730 // Handle messages to "id".
3731 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003732 // We're messaging "id", so provide all instance methods we know
3733 // about as code-completion results.
3734
3735 // If we have an external source, load the entire class method
3736 // pool from the PCH file.
3737 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00003738 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3739 I != N; ++I) {
3740 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00003741 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00003742 continue;
3743
Sebastian Redldb9d2142010-08-02 23:18:59 +00003744 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00003745 }
3746 }
3747
Sebastian Redldb9d2142010-08-02 23:18:59 +00003748 for (GlobalMethodPool::iterator M = MethodPool.begin(),
3749 MEnd = MethodPool.end();
3750 M != MEnd; ++M) {
3751 for (ObjCMethodList *MethList = &M->second.first;
3752 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00003753 MethList = MethList->Next) {
3754 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3755 NumSelIdents))
3756 continue;
3757
3758 Result R(MethList->Method, 0);
3759 R.StartParameter = NumSelIdents;
3760 R.AllParametersAreInformative = false;
3761 Results.MaybeAddResult(R, CurContext);
3762 }
3763 }
3764 }
3765
Steve Naroffc4df6d22009-11-07 02:08:14 +00003766 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003767 HandleCodeCompleteResults(this, CodeCompleter,
3768 CodeCompletionContext::CCC_Other,
3769 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00003770}
Douglas Gregor55385fe2009-11-18 04:19:12 +00003771
3772/// \brief Add all of the protocol declarations that we find in the given
3773/// (translation unit) context.
3774static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00003775 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00003776 ResultBuilder &Results) {
3777 typedef CodeCompleteConsumer::Result Result;
3778
3779 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3780 DEnd = Ctx->decls_end();
3781 D != DEnd; ++D) {
3782 // Record any protocols we find.
3783 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00003784 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00003785 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003786
3787 // Record any forward-declared protocols we find.
3788 if (ObjCForwardProtocolDecl *Forward
3789 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
3790 for (ObjCForwardProtocolDecl::protocol_iterator
3791 P = Forward->protocol_begin(),
3792 PEnd = Forward->protocol_end();
3793 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00003794 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00003795 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003796 }
3797 }
3798}
3799
3800void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
3801 unsigned NumProtocols) {
3802 ResultBuilder Results(*this);
3803 Results.EnterNewScope();
3804
3805 // Tell the result set to ignore all of the protocols we have
3806 // already seen.
3807 for (unsigned I = 0; I != NumProtocols; ++I)
Douglas Gregorc83c6872010-04-15 22:33:43 +00003808 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
3809 Protocols[I].second))
Douglas Gregor55385fe2009-11-18 04:19:12 +00003810 Results.Ignore(Protocol);
3811
3812 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00003813 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
3814 Results);
3815
3816 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003817 HandleCodeCompleteResults(this, CodeCompleter,
3818 CodeCompletionContext::CCC_ObjCProtocolName,
3819 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00003820}
3821
3822void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
3823 ResultBuilder Results(*this);
3824 Results.EnterNewScope();
3825
3826 // Add all protocols.
3827 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
3828 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00003829
3830 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003831 HandleCodeCompleteResults(this, CodeCompleter,
3832 CodeCompletionContext::CCC_ObjCProtocolName,
3833 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00003834}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003835
3836/// \brief Add all of the Objective-C interface declarations that we find in
3837/// the given (translation unit) context.
3838static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
3839 bool OnlyForwardDeclarations,
3840 bool OnlyUnimplemented,
3841 ResultBuilder &Results) {
3842 typedef CodeCompleteConsumer::Result Result;
3843
3844 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3845 DEnd = Ctx->decls_end();
3846 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003847 // Record any interfaces we find.
3848 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
3849 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
3850 (!OnlyUnimplemented || !Class->getImplementation()))
3851 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003852
3853 // Record any forward-declared interfaces we find.
3854 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
3855 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003856 C != CEnd; ++C)
3857 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
3858 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
3859 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00003860 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003861 }
3862 }
3863}
3864
3865void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
3866 ResultBuilder Results(*this);
3867 Results.EnterNewScope();
3868
3869 // Add all classes.
3870 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
3871 false, Results);
3872
3873 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003874 HandleCodeCompleteResults(this, CodeCompleter,
3875 CodeCompletionContext::CCC_Other,
3876 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003877}
3878
Douglas Gregorc83c6872010-04-15 22:33:43 +00003879void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
3880 SourceLocation ClassNameLoc) {
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003881 ResultBuilder Results(*this);
3882 Results.EnterNewScope();
3883
3884 // Make sure that we ignore the class we're currently defining.
3885 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00003886 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003887 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003888 Results.Ignore(CurClass);
3889
3890 // Add all classes.
3891 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3892 false, Results);
3893
3894 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003895 HandleCodeCompleteResults(this, CodeCompleter,
3896 CodeCompletionContext::CCC_Other,
3897 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003898}
3899
3900void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
3901 ResultBuilder Results(*this);
3902 Results.EnterNewScope();
3903
3904 // Add all unimplemented classes.
3905 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3906 true, Results);
3907
3908 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003909 HandleCodeCompleteResults(this, CodeCompleter,
3910 CodeCompletionContext::CCC_Other,
3911 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00003912}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003913
3914void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00003915 IdentifierInfo *ClassName,
3916 SourceLocation ClassNameLoc) {
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003917 typedef CodeCompleteConsumer::Result Result;
3918
3919 ResultBuilder Results(*this);
3920
3921 // Ignore any categories we find that have already been implemented by this
3922 // interface.
3923 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3924 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00003925 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003926 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
3927 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3928 Category = Category->getNextClassCategory())
3929 CategoryNames.insert(Category->getIdentifier());
3930
3931 // Add all of the categories we know about.
3932 Results.EnterNewScope();
3933 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3934 for (DeclContext::decl_iterator D = TU->decls_begin(),
3935 DEnd = TU->decls_end();
3936 D != DEnd; ++D)
3937 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
3938 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003939 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003940 Results.ExitScope();
3941
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003942 HandleCodeCompleteResults(this, CodeCompleter,
3943 CodeCompletionContext::CCC_Other,
3944 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003945}
3946
3947void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00003948 IdentifierInfo *ClassName,
3949 SourceLocation ClassNameLoc) {
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003950 typedef CodeCompleteConsumer::Result Result;
3951
3952 // Find the corresponding interface. If we couldn't find the interface, the
3953 // program itself is ill-formed. However, we'll try to be helpful still by
3954 // providing the list of all of the categories we know about.
3955 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00003956 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003957 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
3958 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00003959 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003960
3961 ResultBuilder Results(*this);
3962
3963 // Add all of the categories that have have corresponding interface
3964 // declarations in this class and any of its superclasses, except for
3965 // already-implemented categories in the class itself.
3966 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3967 Results.EnterNewScope();
3968 bool IgnoreImplemented = true;
3969 while (Class) {
3970 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3971 Category = Category->getNextClassCategory())
3972 if ((!IgnoreImplemented || !Category->getImplementation()) &&
3973 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00003974 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003975
3976 Class = Class->getSuperClass();
3977 IgnoreImplemented = false;
3978 }
3979 Results.ExitScope();
3980
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003981 HandleCodeCompleteResults(this, CodeCompleter,
3982 CodeCompletionContext::CCC_Other,
3983 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00003984}
Douglas Gregor322328b2009-11-18 22:32:06 +00003985
Douglas Gregor424b2a52009-11-18 22:56:13 +00003986void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
Douglas Gregor322328b2009-11-18 22:32:06 +00003987 typedef CodeCompleteConsumer::Result Result;
3988 ResultBuilder Results(*this);
3989
3990 // Figure out where this @synthesize lives.
3991 ObjCContainerDecl *Container
3992 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3993 if (!Container ||
3994 (!isa<ObjCImplementationDecl>(Container) &&
3995 !isa<ObjCCategoryImplDecl>(Container)))
3996 return;
3997
3998 // Ignore any properties that have already been implemented.
3999 for (DeclContext::decl_iterator D = Container->decls_begin(),
4000 DEnd = Container->decls_end();
4001 D != DEnd; ++D)
4002 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
4003 Results.Ignore(PropertyImpl->getPropertyDecl());
4004
4005 // Add any properties that we find.
4006 Results.EnterNewScope();
4007 if (ObjCImplementationDecl *ClassImpl
4008 = dyn_cast<ObjCImplementationDecl>(Container))
4009 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
4010 Results);
4011 else
4012 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
4013 false, CurContext, Results);
4014 Results.ExitScope();
4015
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004016 HandleCodeCompleteResults(this, CodeCompleter,
4017 CodeCompletionContext::CCC_Other,
4018 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00004019}
4020
4021void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
4022 IdentifierInfo *PropertyName,
4023 DeclPtrTy ObjCImpDecl) {
4024 typedef CodeCompleteConsumer::Result Result;
4025 ResultBuilder Results(*this);
4026
4027 // Figure out where this @synthesize lives.
4028 ObjCContainerDecl *Container
4029 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
4030 if (!Container ||
4031 (!isa<ObjCImplementationDecl>(Container) &&
4032 !isa<ObjCCategoryImplDecl>(Container)))
4033 return;
4034
4035 // Figure out which interface we're looking into.
4036 ObjCInterfaceDecl *Class = 0;
4037 if (ObjCImplementationDecl *ClassImpl
4038 = dyn_cast<ObjCImplementationDecl>(Container))
4039 Class = ClassImpl->getClassInterface();
4040 else
4041 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
4042 ->getClassInterface();
4043
4044 // Add all of the instance variables in this class and its superclasses.
4045 Results.EnterNewScope();
4046 for(; Class; Class = Class->getSuperClass()) {
4047 // FIXME: We could screen the type of each ivar for compatibility with
4048 // the property, but is that being too paternal?
4049 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
4050 IVarEnd = Class->ivar_end();
4051 IVar != IVarEnd; ++IVar)
Douglas Gregor608300b2010-01-14 16:14:35 +00004052 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor322328b2009-11-18 22:32:06 +00004053 }
4054 Results.ExitScope();
4055
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004056 HandleCodeCompleteResults(this, CodeCompleter,
4057 CodeCompletionContext::CCC_Other,
4058 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00004059}
Douglas Gregore8f5a172010-04-07 00:21:17 +00004060
4061typedef llvm::DenseMap<Selector, ObjCMethodDecl *> KnownMethodsMap;
4062
4063/// \brief Find all of the methods that reside in the given container
4064/// (and its superclasses, protocols, etc.) that meet the given
4065/// criteria. Insert those methods into the map of known methods,
4066/// indexed by selector so they can be easily found.
4067static void FindImplementableMethods(ASTContext &Context,
4068 ObjCContainerDecl *Container,
4069 bool WantInstanceMethods,
4070 QualType ReturnType,
4071 bool IsInImplementation,
4072 KnownMethodsMap &KnownMethods) {
4073 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
4074 // Recurse into protocols.
4075 const ObjCList<ObjCProtocolDecl> &Protocols
4076 = IFace->getReferencedProtocols();
4077 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4078 E = Protocols.end();
4079 I != E; ++I)
4080 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
4081 IsInImplementation, KnownMethods);
4082
4083 // If we're not in the implementation of a class, also visit the
4084 // superclass.
4085 if (!IsInImplementation && IFace->getSuperClass())
4086 FindImplementableMethods(Context, IFace->getSuperClass(),
4087 WantInstanceMethods, ReturnType,
4088 IsInImplementation, KnownMethods);
4089
4090 // Add methods from any class extensions (but not from categories;
4091 // those should go into category implementations).
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00004092 for (const ObjCCategoryDecl *Cat = IFace->getFirstClassExtension(); Cat;
4093 Cat = Cat->getNextClassExtension())
4094 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
4095 WantInstanceMethods, ReturnType,
Douglas Gregore8f5a172010-04-07 00:21:17 +00004096 IsInImplementation, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004097 }
4098
4099 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4100 // Recurse into protocols.
4101 const ObjCList<ObjCProtocolDecl> &Protocols
4102 = Category->getReferencedProtocols();
4103 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4104 E = Protocols.end();
4105 I != E; ++I)
4106 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
4107 IsInImplementation, KnownMethods);
4108 }
4109
4110 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4111 // Recurse into protocols.
4112 const ObjCList<ObjCProtocolDecl> &Protocols
4113 = Protocol->getReferencedProtocols();
4114 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4115 E = Protocols.end();
4116 I != E; ++I)
4117 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
4118 IsInImplementation, KnownMethods);
4119 }
4120
4121 // Add methods in this container. This operation occurs last because
4122 // we want the methods from this container to override any methods
4123 // we've previously seen with the same selector.
4124 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4125 MEnd = Container->meth_end();
4126 M != MEnd; ++M) {
4127 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4128 if (!ReturnType.isNull() &&
4129 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
4130 continue;
4131
4132 KnownMethods[(*M)->getSelector()] = *M;
4133 }
4134 }
4135}
4136
4137void Sema::CodeCompleteObjCMethodDecl(Scope *S,
4138 bool IsInstanceMethod,
4139 TypeTy *ReturnTy,
4140 DeclPtrTy IDecl) {
4141 // Determine the return type of the method we're declaring, if
4142 // provided.
4143 QualType ReturnType = GetTypeFromParser(ReturnTy);
4144
4145 // Determine where we should start searching for methods, and where we
4146 ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
4147 bool IsInImplementation = false;
4148 if (Decl *D = IDecl.getAs<Decl>()) {
4149 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
4150 SearchDecl = Impl->getClassInterface();
4151 CurrentDecl = Impl;
4152 IsInImplementation = true;
4153 } else if (ObjCCategoryImplDecl *CatImpl
4154 = dyn_cast<ObjCCategoryImplDecl>(D)) {
4155 SearchDecl = CatImpl->getCategoryDecl();
4156 CurrentDecl = CatImpl;
4157 IsInImplementation = true;
4158 } else {
4159 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
4160 CurrentDecl = SearchDecl;
4161 }
4162 }
4163
4164 if (!SearchDecl && S) {
4165 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
4166 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
4167 CurrentDecl = SearchDecl;
4168 }
4169 }
4170
4171 if (!SearchDecl || !CurrentDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004172 HandleCodeCompleteResults(this, CodeCompleter,
4173 CodeCompletionContext::CCC_Other,
4174 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004175 return;
4176 }
4177
4178 // Find all of the methods that we could declare/implement here.
4179 KnownMethodsMap KnownMethods;
4180 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
4181 ReturnType, IsInImplementation, KnownMethods);
4182
4183 // Erase any methods that have already been declared or
4184 // implemented here.
4185 for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
4186 MEnd = CurrentDecl->meth_end();
4187 M != MEnd; ++M) {
4188 if ((*M)->isInstanceMethod() != IsInstanceMethod)
4189 continue;
4190
4191 KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
4192 if (Pos != KnownMethods.end())
4193 KnownMethods.erase(Pos);
4194 }
4195
4196 // Add declarations or definitions for each of the known methods.
4197 typedef CodeCompleteConsumer::Result Result;
4198 ResultBuilder Results(*this);
4199 Results.EnterNewScope();
4200 PrintingPolicy Policy(Context.PrintingPolicy);
4201 Policy.AnonymousTagLocations = false;
4202 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
4203 MEnd = KnownMethods.end();
4204 M != MEnd; ++M) {
4205 ObjCMethodDecl *Method = M->second;
4206 CodeCompletionString *Pattern = new CodeCompletionString;
4207
4208 // If the result type was not already provided, add it to the
4209 // pattern as (type).
4210 if (ReturnType.isNull()) {
4211 std::string TypeStr;
4212 Method->getResultType().getAsStringInternal(TypeStr, Policy);
4213 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4214 Pattern->AddTextChunk(TypeStr);
4215 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4216 }
4217
4218 Selector Sel = Method->getSelector();
4219
4220 // Add the first part of the selector to the pattern.
4221 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4222
4223 // Add parameters to the pattern.
4224 unsigned I = 0;
4225 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4226 PEnd = Method->param_end();
4227 P != PEnd; (void)++P, ++I) {
4228 // Add the part of the selector name.
4229 if (I == 0)
4230 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4231 else if (I < Sel.getNumArgs()) {
4232 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4233 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(1)->getName());
4234 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4235 } else
4236 break;
4237
4238 // Add the parameter type.
4239 std::string TypeStr;
4240 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
4241 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4242 Pattern->AddTextChunk(TypeStr);
4243 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4244
4245 if (IdentifierInfo *Id = (*P)->getIdentifier())
4246 Pattern->AddTextChunk(Id->getName());
4247 }
4248
4249 if (Method->isVariadic()) {
4250 if (Method->param_size() > 0)
4251 Pattern->AddChunk(CodeCompletionString::CK_Comma);
4252 Pattern->AddTextChunk("...");
4253 }
4254
Douglas Gregor447107d2010-05-28 00:57:46 +00004255 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004256 // We will be defining the method here, so add a compound statement.
4257 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4258 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
4259 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4260 if (!Method->getResultType()->isVoidType()) {
4261 // If the result type is not void, add a return clause.
4262 Pattern->AddTextChunk("return");
4263 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4264 Pattern->AddPlaceholderChunk("expression");
4265 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
4266 } else
4267 Pattern->AddPlaceholderChunk("statements");
4268
4269 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4270 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
4271 }
4272
4273 Results.AddResult(Result(Pattern));
4274 }
4275
4276 Results.ExitScope();
4277
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004278 HandleCodeCompleteResults(this, CodeCompleter,
4279 CodeCompletionContext::CCC_Other,
4280 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00004281}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004282
4283void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
4284 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00004285 bool AtParameterName,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004286 TypeTy *ReturnTy,
4287 IdentifierInfo **SelIdents,
4288 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004289 // If we have an external source, load the entire class method
4290 // pool from the PCH file.
4291 if (ExternalSource) {
4292 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4293 I != N; ++I) {
4294 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00004295 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004296 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00004297
4298 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004299 }
4300 }
4301
4302 // Build the set of methods we can see.
4303 typedef CodeCompleteConsumer::Result Result;
4304 ResultBuilder Results(*this);
4305
4306 if (ReturnTy)
4307 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00004308
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004309 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00004310 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4311 MEnd = MethodPool.end();
4312 M != MEnd; ++M) {
4313 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
4314 &M->second.second;
4315 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004316 MethList = MethList->Next) {
4317 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4318 NumSelIdents))
4319 continue;
4320
Douglas Gregor40ed9a12010-07-08 23:37:41 +00004321 if (AtParameterName) {
4322 // Suggest parameter names we've seen before.
4323 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
4324 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
4325 if (Param->getIdentifier()) {
4326 CodeCompletionString *Pattern = new CodeCompletionString;
4327 Pattern->AddTypedTextChunk(Param->getIdentifier()->getName());
4328 Results.AddResult(Pattern);
4329 }
4330 }
4331
4332 continue;
4333 }
4334
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004335 Result R(MethList->Method, 0);
4336 R.StartParameter = NumSelIdents;
4337 R.AllParametersAreInformative = false;
4338 R.DeclaringEntity = true;
4339 Results.MaybeAddResult(R, CurContext);
4340 }
4341 }
4342
4343 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004344 HandleCodeCompleteResults(this, CodeCompleter,
4345 CodeCompletionContext::CCC_Other,
4346 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004347}
Douglas Gregor87c08a52010-08-13 22:48:40 +00004348
4349void Sema::GatherGlobalCodeCompletions(
4350 llvm::SmallVectorImpl<CodeCompleteConsumer::Result> &Results) {
4351 ResultBuilder Builder(*this);
4352
Douglas Gregor8071e422010-08-15 06:18:01 +00004353 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
4354 CodeCompletionDeclConsumer Consumer(Builder,
4355 Context.getTranslationUnitDecl());
4356 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
4357 Consumer);
4358 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00004359
4360 if (!CodeCompleter || CodeCompleter->includeMacros())
4361 AddMacroResults(PP, Builder);
4362
4363 Results.clear();
4364 Results.insert(Results.end(),
4365 Builder.data(), Builder.data() + Builder.size());
4366}