blob: 599a10fd90a5f1c4878a3b1f3b2f2b5485e078d4 [file] [log] [blame]
Douglas Gregor2436e712009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
14#include "clang/Sema/Lookup.h"
Douglas Gregor2436e712009-09-17 21:32:03 +000015#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregord720daf2010-04-06 17:30:22 +000016#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregorf2510672009-09-21 19:57:38 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor8ce33212009-11-17 17:59:40 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregorf329c7c2009-10-30 16:50:04 +000019#include "clang/Lex/MacroInfo.h"
20#include "clang/Lex/Preprocessor.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000021#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregore6688e62009-09-28 03:51:44 +000022#include "llvm/ADT/StringExtras.h"
Douglas Gregor9d2ddb22010-04-06 19:22:33 +000023#include "llvm/ADT/StringSwitch.h"
Douglas Gregor3545ff42009-09-21 16:56:56 +000024#include <list>
25#include <map>
26#include <vector>
Douglas Gregor2436e712009-09-17 21:32:03 +000027
28using namespace clang;
29
Douglas Gregor3545ff42009-09-21 16:56:56 +000030namespace {
31 /// \brief A container of code-completion results.
32 class ResultBuilder {
33 public:
34 /// \brief The type of a name-lookup filter, which can be provided to the
35 /// name-lookup routines to specify which declarations should be included in
36 /// the result set (when it returns true) and which declarations should be
37 /// filtered out (returns false).
38 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
39
40 typedef CodeCompleteConsumer::Result Result;
41
42 private:
43 /// \brief The actual results we have found.
44 std::vector<Result> Results;
45
46 /// \brief A record of all of the declarations we have found and placed
47 /// into the result set, used to ensure that no declaration ever gets into
48 /// the result set twice.
49 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
50
Douglas Gregor05e7ca32009-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 Gregor3545ff42009-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 Gregor05e7ca32009-12-06 20:23:50 +0000108 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor3545ff42009-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 Gregor6ae4c522010-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 Gregor7aa6b222010-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 Gregor3545ff42009-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 Gregor95887f92010-07-08 23:20:03 +0000133 void AdjustResultPriorityForPreferredType(Result &R);
134
Douglas Gregor3545ff42009-09-21 16:56:56 +0000135 public:
136 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000137 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false) { }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000138
Douglas Gregorf64acca2010-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 Gregor3545ff42009-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 Gregor7aa6b222010-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 Gregor6ae4c522010-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 Gregor7c208612010-01-14 00:20:49 +0000169 /// \brief Determine whether the given declaration is at all interesting
170 /// as a code-completion result.
Douglas Gregor6ae4c522010-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 Gregore0717ab2010-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 Gregor3545ff42009-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 Gregor2af2f672009-09-21 20:12:40 +0000190 ///
Douglas Gregorc580c522010-01-14 01:09:38 +0000191 /// \param CurContext the result to add (if it is unique).
Douglas Gregor2af2f672009-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 Gregor3545ff42009-09-21 16:56:56 +0000195
Douglas Gregorc580c522010-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 Gregor09bbc652010-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 Gregorc580c522010-01-14 01:09:38 +0000209
Douglas Gregor78a21012010-01-14 16:01:26 +0000210 /// \brief Add a new non-declaration result to this result set.
211 void AddResult(Result R);
212
Douglas Gregor3545ff42009-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 Gregorbaf69612009-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 Gregor3545ff42009-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 Gregor9d64c5e2009-09-21 20:51:25 +0000228 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor70febae2010-05-28 00:49:12 +0000229 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregor85b50632010-07-28 21:50:18 +0000230 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000231 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor3545ff42009-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 Gregore412a5a2009-09-23 22:26:46 +0000239 bool IsMember(NamedDecl *ND) const;
Douglas Gregor2b8162b2010-01-14 16:08:12 +0000240 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregora817a192010-05-27 23:06:34 +0000241 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000242 //@}
243 };
244}
245
Douglas Gregor05e7ca32009-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 Gregor94bb5e82009-12-06 21:27:58 +0000298 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregor05e7ca32009-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 Gregor94bb5e82009-12-06 21:27:58 +0000306 return X.DeclOrIterator.getOpaqueValue()
307 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000308 X.SingleDeclIndex == Y.SingleDeclIndex;
309 }
310
311 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregor94bb5e82009-12-06 21:27:58 +0000312 return !(X == Y);
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000313 }
314};
315
Douglas Gregor05e7ca32009-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 Gregor2af2f672009-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 Gregor9eb77012009-11-07 00:00:49 +0000375 }
Douglas Gregor2af2f672009-09-21 20:12:40 +0000376 return Result;
377}
378
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000379bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
380 bool &AsNestedNameSpecifier) const {
381 AsNestedNameSpecifier = false;
382
Douglas Gregor7c208612010-01-14 00:20:49 +0000383 ND = ND->getUnderlyingDecl();
384 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregor58acf322009-10-09 22:16:47 +0000385
386 // Skip unnamed entities.
Douglas Gregor7c208612010-01-14 00:20:49 +0000387 if (!ND->getDeclName())
388 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000389
390 // Friend declarations and declarations introduced due to friends are never
391 // added as results.
John McCallbbbbe4e2010-03-11 07:50:04 +0000392 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregor7c208612010-01-14 00:20:49 +0000393 return false;
394
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000395 // Class template (partial) specializations are never added as results.
Douglas Gregor7c208612010-01-14 00:20:49 +0000396 if (isa<ClassTemplateSpecializationDecl>(ND) ||
397 isa<ClassTemplatePartialSpecializationDecl>(ND))
398 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000399
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000400 // Using declarations themselves are never added as results.
Douglas Gregor7c208612010-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 Gregor3545ff42009-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 Gregor7c208612010-01-14 00:20:49 +0000408 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000409
Douglas Gregor58acf322009-10-09 22:16:47 +0000410 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor9f1570d2010-07-14 17:44:04 +0000411 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +0000412 //
413 // FIXME: Add predicate for this.
Douglas Gregor58acf322009-10-09 22:16:47 +0000414 if (Id->getLength() >= 2) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +0000415 const char *Name = Id->getNameStart();
Douglas Gregor58acf322009-10-09 22:16:47 +0000416 if (Name[0] == '_' &&
Douglas Gregor9f1570d2010-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 Gregor7c208612010-01-14 00:20:49 +0000421 return false;
Douglas Gregor58acf322009-10-09 22:16:47 +0000422 }
Douglas Gregor3545ff42009-09-21 16:56:56 +0000423 }
Douglas Gregor7c208612010-01-14 00:20:49 +0000424
Douglas Gregor3545ff42009-09-21 16:56:56 +0000425 // C++ constructors are never found by name lookup.
Douglas Gregor7c208612010-01-14 00:20:49 +0000426 if (isa<CXXConstructorDecl>(ND))
427 return false;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000428
429 // Filter out any unwanted results.
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000430 if (Filter && !(this->*Filter)(ND)) {
431 // Check whether it is interesting as a nested-name-specifier.
432 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
433 IsNestedNameSpecifier(ND) &&
434 (Filter != &ResultBuilder::IsMember ||
435 (isa<CXXRecordDecl>(ND) &&
436 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
437 AsNestedNameSpecifier = true;
438 return true;
439 }
440
Douglas Gregor7c208612010-01-14 00:20:49 +0000441 return false;
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000442 }
John McCalle87beb22010-04-23 18:46:30 +0000443
444 if (Filter == &ResultBuilder::IsNestedNameSpecifier)
445 AsNestedNameSpecifier = true;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000446
Douglas Gregor7c208612010-01-14 00:20:49 +0000447 // ... then it must be interesting!
448 return true;
449}
450
Douglas Gregore0717ab2010-01-14 00:41:07 +0000451bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
452 NamedDecl *Hiding) {
453 // In C, there is no way to refer to a hidden name.
454 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
455 // name if we introduce the tag type.
456 if (!SemaRef.getLangOptions().CPlusPlus)
457 return true;
458
459 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext();
460
461 // There is no way to qualify a name declared in a function or method.
462 if (HiddenCtx->isFunctionOrMethod())
463 return true;
464
465 if (HiddenCtx == Hiding->getDeclContext()->getLookupContext())
466 return true;
467
468 // We can refer to the result with the appropriate qualification. Do it.
469 R.Hidden = true;
470 R.QualifierIsInformative = false;
471
472 if (!R.Qualifier)
473 R.Qualifier = getRequiredQualification(SemaRef.Context,
474 CurContext,
475 R.Declaration->getDeclContext());
476 return false;
477}
478
Douglas Gregor95887f92010-07-08 23:20:03 +0000479enum SimplifiedTypeClass {
480 STC_Arithmetic,
481 STC_Array,
482 STC_Block,
483 STC_Function,
484 STC_ObjectiveC,
485 STC_Other,
486 STC_Pointer,
487 STC_Record,
488 STC_Void
489};
490
491/// \brief A simplified classification of types used to determine whether two
492/// types are "similar enough" when adjusting priorities.
493static SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T) {
494 switch (T->getTypeClass()) {
495 case Type::Builtin:
496 switch (cast<BuiltinType>(T)->getKind()) {
497 case BuiltinType::Void:
498 return STC_Void;
499
500 case BuiltinType::NullPtr:
501 return STC_Pointer;
502
503 case BuiltinType::Overload:
504 case BuiltinType::Dependent:
505 case BuiltinType::UndeducedAuto:
506 return STC_Other;
507
508 case BuiltinType::ObjCId:
509 case BuiltinType::ObjCClass:
510 case BuiltinType::ObjCSel:
511 return STC_ObjectiveC;
512
513 default:
514 return STC_Arithmetic;
515 }
516 return STC_Other;
517
518 case Type::Complex:
519 return STC_Arithmetic;
520
521 case Type::Pointer:
522 return STC_Pointer;
523
524 case Type::BlockPointer:
525 return STC_Block;
526
527 case Type::LValueReference:
528 case Type::RValueReference:
529 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
530
531 case Type::ConstantArray:
532 case Type::IncompleteArray:
533 case Type::VariableArray:
534 case Type::DependentSizedArray:
535 return STC_Array;
536
537 case Type::DependentSizedExtVector:
538 case Type::Vector:
539 case Type::ExtVector:
540 return STC_Arithmetic;
541
542 case Type::FunctionProto:
543 case Type::FunctionNoProto:
544 return STC_Function;
545
546 case Type::Record:
547 return STC_Record;
548
549 case Type::Enum:
550 return STC_Arithmetic;
551
552 case Type::ObjCObject:
553 case Type::ObjCInterface:
554 case Type::ObjCObjectPointer:
555 return STC_ObjectiveC;
556
557 default:
558 return STC_Other;
559 }
560}
561
562/// \brief Get the type that a given expression will have if this declaration
563/// is used as an expression in its "typical" code-completion form.
564static QualType getDeclUsageType(ASTContext &C, NamedDecl *ND) {
565 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
566
567 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
568 return C.getTypeDeclType(Type);
569 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
570 return C.getObjCInterfaceType(Iface);
571
572 QualType T;
573 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000574 T = Function->getCallResultType();
Douglas Gregor95887f92010-07-08 23:20:03 +0000575 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000576 T = Method->getSendResultType();
Douglas Gregor95887f92010-07-08 23:20:03 +0000577 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor603d81b2010-07-13 08:18:22 +0000578 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor95887f92010-07-08 23:20:03 +0000579 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
580 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
581 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
582 T = Property->getType();
583 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
584 T = Value->getType();
585 else
586 return QualType();
587
588 return T.getNonReferenceType();
589}
590
591void ResultBuilder::AdjustResultPriorityForPreferredType(Result &R) {
592 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
593 if (T.isNull())
594 return;
595
596 CanQualType TC = SemaRef.Context.getCanonicalType(T);
597 // Check for exactly-matching types (modulo qualifiers).
598 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
599 R.Priority /= CCF_ExactTypeMatch;
600 // Check for nearly-matching types, based on classification of each.
601 else if ((getSimplifiedTypeClass(PreferredType)
602 == getSimplifiedTypeClass(TC)) &&
603 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
604 R.Priority /= CCF_SimilarTypeMatch;
605}
606
Douglas Gregor7c208612010-01-14 00:20:49 +0000607void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
608 assert(!ShadowMaps.empty() && "Must enter into a results scope");
609
610 if (R.Kind != Result::RK_Declaration) {
611 // For non-declaration results, just add the result.
612 Results.push_back(R);
613 return;
614 }
615
616 // Look through using declarations.
617 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
618 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
619 return;
620 }
621
622 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
623 unsigned IDNS = CanonDecl->getIdentifierNamespace();
624
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000625 bool AsNestedNameSpecifier = false;
626 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor7c208612010-01-14 00:20:49 +0000627 return;
628
Douglas Gregor3545ff42009-09-21 16:56:56 +0000629 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000630 ShadowMapEntry::iterator I, IEnd;
631 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
632 if (NamePos != SMap.end()) {
633 I = NamePos->second.begin();
634 IEnd = NamePos->second.end();
635 }
636
637 for (; I != IEnd; ++I) {
638 NamedDecl *ND = I->first;
639 unsigned Index = I->second;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000640 if (ND->getCanonicalDecl() == CanonDecl) {
641 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000642 Results[Index].Declaration = R.Declaration;
643
Douglas Gregor3545ff42009-09-21 16:56:56 +0000644 // We're done.
645 return;
646 }
647 }
648
649 // This is a new declaration in this scope. However, check whether this
650 // declaration name is hidden by a similarly-named declaration in an outer
651 // scope.
652 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
653 --SMEnd;
654 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000655 ShadowMapEntry::iterator I, IEnd;
656 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
657 if (NamePos != SM->end()) {
658 I = NamePos->second.begin();
659 IEnd = NamePos->second.end();
660 }
661 for (; I != IEnd; ++I) {
Douglas Gregor3545ff42009-09-21 16:56:56 +0000662 // A tag declaration does not hide a non-tag declaration.
John McCalle87beb22010-04-23 18:46:30 +0000663 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor3545ff42009-09-21 16:56:56 +0000664 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
665 Decl::IDNS_ObjCProtocol)))
666 continue;
667
668 // Protocols are in distinct namespaces from everything else.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000669 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000670 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000671 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor3545ff42009-09-21 16:56:56 +0000672 continue;
673
674 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregore0717ab2010-01-14 00:41:07 +0000675 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor3545ff42009-09-21 16:56:56 +0000676 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000677
678 break;
679 }
680 }
681
682 // Make sure that any given declaration only shows up in the result set once.
683 if (!AllDeclsFound.insert(CanonDecl))
684 return;
685
Douglas Gregore412a5a2009-09-23 22:26:46 +0000686 // If the filter is for nested-name-specifiers, then this result starts a
687 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000688 if (AsNestedNameSpecifier) {
Douglas Gregore412a5a2009-09-23 22:26:46 +0000689 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000690 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor95887f92010-07-08 23:20:03 +0000691 } else if (!PreferredType.isNull())
692 AdjustResultPriorityForPreferredType(R);
693
Douglas Gregor5bf52692009-09-22 23:15:58 +0000694 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000695 if (R.QualifierIsInformative && !R.Qualifier &&
696 !R.StartsNestedNameSpecifier) {
Douglas Gregor5bf52692009-09-22 23:15:58 +0000697 DeclContext *Ctx = R.Declaration->getDeclContext();
698 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
699 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
700 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
701 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
702 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
703 else
704 R.QualifierIsInformative = false;
705 }
Douglas Gregore412a5a2009-09-23 22:26:46 +0000706
Douglas Gregor3545ff42009-09-21 16:56:56 +0000707 // Insert this result into the set of results and into the current shadow
708 // map.
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000709 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor3545ff42009-09-21 16:56:56 +0000710 Results.push_back(R);
711}
712
Douglas Gregorc580c522010-01-14 01:09:38 +0000713void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor09bbc652010-01-14 15:47:35 +0000714 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregor78a21012010-01-14 16:01:26 +0000715 if (R.Kind != Result::RK_Declaration) {
716 // For non-declaration results, just add the result.
717 Results.push_back(R);
718 return;
719 }
720
Douglas Gregorc580c522010-01-14 01:09:38 +0000721 // Look through using declarations.
722 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
723 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
724 return;
725 }
726
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000727 bool AsNestedNameSpecifier = false;
728 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregorc580c522010-01-14 01:09:38 +0000729 return;
730
731 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
732 return;
733
734 // Make sure that any given declaration only shows up in the result set once.
735 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
736 return;
737
738 // If the filter is for nested-name-specifiers, then this result starts a
739 // nested-name-specifier.
Douglas Gregora2db7932010-05-26 22:00:08 +0000740 if (AsNestedNameSpecifier) {
Douglas Gregorc580c522010-01-14 01:09:38 +0000741 R.StartsNestedNameSpecifier = true;
Douglas Gregora2db7932010-05-26 22:00:08 +0000742 R.Priority = CCP_NestedNameSpecifier;
743 }
Douglas Gregor09bbc652010-01-14 15:47:35 +0000744 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
745 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
746 ->getLookupContext()))
747 R.QualifierIsInformative = true;
748
Douglas Gregorc580c522010-01-14 01:09:38 +0000749 // If this result is supposed to have an informative qualifier, add one.
750 if (R.QualifierIsInformative && !R.Qualifier &&
751 !R.StartsNestedNameSpecifier) {
752 DeclContext *Ctx = R.Declaration->getDeclContext();
753 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
754 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
755 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
756 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor6ae4c522010-01-14 03:21:49 +0000757 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregorc580c522010-01-14 01:09:38 +0000758 else
759 R.QualifierIsInformative = false;
760 }
761
Douglas Gregora2db7932010-05-26 22:00:08 +0000762 // Adjust the priority if this result comes from a base class.
763 if (InBaseClass)
764 R.Priority += CCD_InBaseClass;
765
Douglas Gregor95887f92010-07-08 23:20:03 +0000766 if (!PreferredType.isNull())
767 AdjustResultPriorityForPreferredType(R);
Douglas Gregor7aa6b222010-05-30 01:49:25 +0000768
Douglas Gregorc580c522010-01-14 01:09:38 +0000769 // Insert this result into the set of results.
770 Results.push_back(R);
771}
772
Douglas Gregor78a21012010-01-14 16:01:26 +0000773void ResultBuilder::AddResult(Result R) {
774 assert(R.Kind != Result::RK_Declaration &&
775 "Declaration results need more context");
776 Results.push_back(R);
777}
778
Douglas Gregor3545ff42009-09-21 16:56:56 +0000779/// \brief Enter into a new scope.
780void ResultBuilder::EnterNewScope() {
781 ShadowMaps.push_back(ShadowMap());
782}
783
784/// \brief Exit from the current scope.
785void ResultBuilder::ExitScope() {
Douglas Gregor05e7ca32009-12-06 20:23:50 +0000786 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
787 EEnd = ShadowMaps.back().end();
788 E != EEnd;
789 ++E)
790 E->second.Destroy();
791
Douglas Gregor3545ff42009-09-21 16:56:56 +0000792 ShadowMaps.pop_back();
793}
794
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000795/// \brief Determines whether this given declaration will be found by
796/// ordinary name lookup.
797bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +0000798 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
799
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000800 unsigned IDNS = Decl::IDNS_Ordinary;
801 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +0000802 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorc580c522010-01-14 01:09:38 +0000803 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
804 return true;
805
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000806 return ND->getIdentifierNamespace() & IDNS;
807}
808
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000809/// \brief Determines whether this given declaration will be found by
Douglas Gregor70febae2010-05-28 00:49:12 +0000810/// ordinary name lookup but is not a type name.
811bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
812 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
813 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
814 return false;
815
816 unsigned IDNS = Decl::IDNS_Ordinary;
817 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9858ed52010-06-15 20:26:51 +0000818 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor70febae2010-05-28 00:49:12 +0000819 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
820 return true;
821
822 return ND->getIdentifierNamespace() & IDNS;
823}
824
Douglas Gregor85b50632010-07-28 21:50:18 +0000825bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
826 if (!IsOrdinaryNonTypeName(ND))
827 return 0;
828
829 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
830 if (VD->getType()->isIntegralOrEnumerationType())
831 return true;
832
833 return false;
834}
835
Douglas Gregor70febae2010-05-28 00:49:12 +0000836/// \brief Determines whether this given declaration will be found by
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000837/// ordinary name lookup.
838bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor70febae2010-05-28 00:49:12 +0000839 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
840
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000841 unsigned IDNS = Decl::IDNS_Ordinary;
842 if (SemaRef.getLangOptions().CPlusPlus)
John McCalle87beb22010-04-23 18:46:30 +0000843 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000844
845 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor70febae2010-05-28 00:49:12 +0000846 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
847 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000848}
849
Douglas Gregor3545ff42009-09-21 16:56:56 +0000850/// \brief Determines whether the given declaration is suitable as the
851/// start of a C++ nested-name-specifier, e.g., a class or namespace.
852bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
853 // Allow us to find class templates, too.
854 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
855 ND = ClassTemplate->getTemplatedDecl();
856
857 return SemaRef.isAcceptableNestedNameSpecifier(ND);
858}
859
860/// \brief Determines whether the given declaration is an enumeration.
861bool ResultBuilder::IsEnum(NamedDecl *ND) const {
862 return isa<EnumDecl>(ND);
863}
864
865/// \brief Determines whether the given declaration is a class or struct.
866bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
867 // Allow us to find class templates, too.
868 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
869 ND = ClassTemplate->getTemplatedDecl();
870
871 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +0000872 return RD->getTagKind() == TTK_Class ||
873 RD->getTagKind() == TTK_Struct;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000874
875 return false;
876}
877
878/// \brief Determines whether the given declaration is a union.
879bool ResultBuilder::IsUnion(NamedDecl *ND) const {
880 // Allow us to find class templates, too.
881 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
882 ND = ClassTemplate->getTemplatedDecl();
883
884 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara6150c882010-05-11 21:36:43 +0000885 return RD->getTagKind() == TTK_Union;
Douglas Gregor3545ff42009-09-21 16:56:56 +0000886
887 return false;
888}
889
890/// \brief Determines whether the given declaration is a namespace.
891bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
892 return isa<NamespaceDecl>(ND);
893}
894
895/// \brief Determines whether the given declaration is a namespace or
896/// namespace alias.
897bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
898 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
899}
900
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000901/// \brief Determines whether the given declaration is a type.
Douglas Gregor3545ff42009-09-21 16:56:56 +0000902bool ResultBuilder::IsType(NamedDecl *ND) const {
903 return isa<TypeDecl>(ND);
904}
905
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000906/// \brief Determines which members of a class should be visible via
907/// "." or "->". Only value declarations, nested name specifiers, and
908/// using declarations thereof should show up.
Douglas Gregore412a5a2009-09-23 22:26:46 +0000909bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor99fe2ad2009-12-11 17:31:05 +0000910 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
911 ND = Using->getTargetDecl();
912
Douglas Gregor70788392009-12-11 18:14:22 +0000913 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
914 isa<ObjCPropertyDecl>(ND);
Douglas Gregore412a5a2009-09-23 22:26:46 +0000915}
916
Douglas Gregora817a192010-05-27 23:06:34 +0000917static bool isObjCReceiverType(ASTContext &C, QualType T) {
918 T = C.getCanonicalType(T);
919 switch (T->getTypeClass()) {
920 case Type::ObjCObject:
921 case Type::ObjCInterface:
922 case Type::ObjCObjectPointer:
923 return true;
924
925 case Type::Builtin:
926 switch (cast<BuiltinType>(T)->getKind()) {
927 case BuiltinType::ObjCId:
928 case BuiltinType::ObjCClass:
929 case BuiltinType::ObjCSel:
930 return true;
931
932 default:
933 break;
934 }
935 return false;
936
937 default:
938 break;
939 }
940
941 if (!C.getLangOptions().CPlusPlus)
942 return false;
943
944 // FIXME: We could perform more analysis here to determine whether a
945 // particular class type has any conversions to Objective-C types. For now,
946 // just accept all class types.
947 return T->isDependentType() || T->isRecordType();
948}
949
950bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
951 QualType T = getDeclUsageType(SemaRef.Context, ND);
952 if (T.isNull())
953 return false;
954
955 T = SemaRef.Context.getBaseElementType(T);
956 return isObjCReceiverType(SemaRef.Context, T);
957}
958
959
Douglas Gregor2b8162b2010-01-14 16:08:12 +0000960/// \rief Determines whether the given declaration is an Objective-C
961/// instance variable.
962bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
963 return isa<ObjCIvarDecl>(ND);
964}
965
Douglas Gregorc580c522010-01-14 01:09:38 +0000966namespace {
967 /// \brief Visible declaration consumer that adds a code-completion result
968 /// for each visible declaration.
969 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
970 ResultBuilder &Results;
971 DeclContext *CurContext;
972
973 public:
974 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
975 : Results(Results), CurContext(CurContext) { }
976
Douglas Gregor09bbc652010-01-14 15:47:35 +0000977 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
978 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregorc580c522010-01-14 01:09:38 +0000979 }
980 };
981}
982
Douglas Gregor3545ff42009-09-21 16:56:56 +0000983/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorf98e6a22010-01-13 23:51:12 +0000984static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor3545ff42009-09-21 16:56:56 +0000985 ResultBuilder &Results) {
986 typedef CodeCompleteConsumer::Result Result;
Douglas Gregora2db7932010-05-26 22:00:08 +0000987 Results.AddResult(Result("short", CCP_Type));
988 Results.AddResult(Result("long", CCP_Type));
989 Results.AddResult(Result("signed", CCP_Type));
990 Results.AddResult(Result("unsigned", CCP_Type));
991 Results.AddResult(Result("void", CCP_Type));
992 Results.AddResult(Result("char", CCP_Type));
993 Results.AddResult(Result("int", CCP_Type));
994 Results.AddResult(Result("float", CCP_Type));
995 Results.AddResult(Result("double", CCP_Type));
996 Results.AddResult(Result("enum", CCP_Type));
997 Results.AddResult(Result("struct", CCP_Type));
998 Results.AddResult(Result("union", CCP_Type));
999 Results.AddResult(Result("const", CCP_Type));
1000 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001001
Douglas Gregor3545ff42009-09-21 16:56:56 +00001002 if (LangOpts.C99) {
1003 // C99-specific
Douglas Gregora2db7932010-05-26 22:00:08 +00001004 Results.AddResult(Result("_Complex", CCP_Type));
1005 Results.AddResult(Result("_Imaginary", CCP_Type));
1006 Results.AddResult(Result("_Bool", CCP_Type));
1007 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001008 }
1009
1010 if (LangOpts.CPlusPlus) {
1011 // C++-specific
Douglas Gregora2db7932010-05-26 22:00:08 +00001012 Results.AddResult(Result("bool", CCP_Type));
1013 Results.AddResult(Result("class", CCP_Type));
1014 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001015
Douglas Gregorf4c33342010-05-28 00:22:41 +00001016 // typename qualified-id
1017 CodeCompletionString *Pattern = new CodeCompletionString;
1018 Pattern->AddTypedTextChunk("typename");
1019 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1020 Pattern->AddPlaceholderChunk("qualifier");
1021 Pattern->AddTextChunk("::");
1022 Pattern->AddPlaceholderChunk("name");
1023 Results.AddResult(Result(Pattern));
Douglas Gregorf64acca2010-05-25 21:41:55 +00001024
Douglas Gregor3545ff42009-09-21 16:56:56 +00001025 if (LangOpts.CPlusPlus0x) {
Douglas Gregora2db7932010-05-26 22:00:08 +00001026 Results.AddResult(Result("auto", CCP_Type));
1027 Results.AddResult(Result("char16_t", CCP_Type));
1028 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorf4c33342010-05-28 00:22:41 +00001029
1030 CodeCompletionString *Pattern = new CodeCompletionString;
1031 Pattern->AddTypedTextChunk("decltype");
1032 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1033 Pattern->AddPlaceholderChunk("expression");
1034 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1035 Results.AddResult(Result(Pattern));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001036 }
1037 }
1038
1039 // GNU extensions
1040 if (LangOpts.GNUMode) {
1041 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregor78a21012010-01-14 16:01:26 +00001042 // Results.AddResult(Result("_Decimal32"));
1043 // Results.AddResult(Result("_Decimal64"));
1044 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001045
Douglas Gregorf4c33342010-05-28 00:22:41 +00001046 CodeCompletionString *Pattern = new CodeCompletionString;
1047 Pattern->AddTypedTextChunk("typeof");
1048 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1049 Pattern->AddPlaceholderChunk("expression");
1050 Results.AddResult(Result(Pattern));
1051
1052 Pattern = new CodeCompletionString;
1053 Pattern->AddTypedTextChunk("typeof");
1054 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1055 Pattern->AddPlaceholderChunk("type");
1056 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1057 Results.AddResult(Result(Pattern));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001058 }
1059}
1060
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001061static void AddStorageSpecifiers(Action::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001062 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001063 ResultBuilder &Results) {
1064 typedef CodeCompleteConsumer::Result Result;
1065 // Note: we don't suggest either "auto" or "register", because both
1066 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1067 // in C++0x as a type specifier.
Douglas Gregor78a21012010-01-14 16:01:26 +00001068 Results.AddResult(Result("extern"));
1069 Results.AddResult(Result("static"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001070}
1071
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001072static void AddFunctionSpecifiers(Action::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001073 const LangOptions &LangOpts,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001074 ResultBuilder &Results) {
1075 typedef CodeCompleteConsumer::Result Result;
1076 switch (CCC) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001077 case Action::PCC_Class:
1078 case Action::PCC_MemberTemplate:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001079 if (LangOpts.CPlusPlus) {
Douglas Gregor78a21012010-01-14 16:01:26 +00001080 Results.AddResult(Result("explicit"));
1081 Results.AddResult(Result("friend"));
1082 Results.AddResult(Result("mutable"));
1083 Results.AddResult(Result("virtual"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001084 }
1085 // Fall through
1086
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001087 case Action::PCC_ObjCInterface:
1088 case Action::PCC_ObjCImplementation:
1089 case Action::PCC_Namespace:
1090 case Action::PCC_Template:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001091 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregor78a21012010-01-14 16:01:26 +00001092 Results.AddResult(Result("inline"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001093 break;
1094
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001095 case Action::PCC_ObjCInstanceVariableList:
1096 case Action::PCC_Expression:
1097 case Action::PCC_Statement:
1098 case Action::PCC_ForInit:
1099 case Action::PCC_Condition:
1100 case Action::PCC_RecoveryInFunction:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001101 break;
1102 }
1103}
1104
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001105static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1106static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1107static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00001108 ResultBuilder &Results,
1109 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001110static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001111 ResultBuilder &Results,
1112 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001113static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00001114 ResultBuilder &Results,
1115 bool NeedAt);
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001116static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorf1934162010-01-13 21:24:21 +00001117
Douglas Gregorf4c33342010-05-28 00:22:41 +00001118static void AddTypedefResult(ResultBuilder &Results) {
1119 CodeCompletionString *Pattern = new CodeCompletionString;
1120 Pattern->AddTypedTextChunk("typedef");
1121 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1122 Pattern->AddPlaceholderChunk("type");
1123 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1124 Pattern->AddPlaceholderChunk("name");
1125 Results.AddResult(CodeCompleteConsumer::Result(Pattern));
1126}
1127
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001128static bool WantTypesInContext(Action::ParserCompletionContext CCC,
Douglas Gregor70febae2010-05-28 00:49:12 +00001129 const LangOptions &LangOpts) {
1130 if (LangOpts.CPlusPlus)
1131 return true;
1132
1133 switch (CCC) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001134 case Action::PCC_Namespace:
1135 case Action::PCC_Class:
1136 case Action::PCC_ObjCInstanceVariableList:
1137 case Action::PCC_Template:
1138 case Action::PCC_MemberTemplate:
1139 case Action::PCC_Statement:
1140 case Action::PCC_RecoveryInFunction:
Douglas Gregor70febae2010-05-28 00:49:12 +00001141 return true;
1142
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001143 case Action::PCC_ObjCInterface:
1144 case Action::PCC_ObjCImplementation:
1145 case Action::PCC_Expression:
1146 case Action::PCC_Condition:
Douglas Gregor70febae2010-05-28 00:49:12 +00001147 return false;
1148
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001149 case Action::PCC_ForInit:
Douglas Gregor70febae2010-05-28 00:49:12 +00001150 return LangOpts.ObjC1 || LangOpts.C99;
1151 }
1152
1153 return false;
1154}
1155
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001156/// \brief Add language constructs that show up for "ordinary" names.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001157static void AddOrdinaryNameResults(Action::ParserCompletionContext CCC,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001158 Scope *S,
1159 Sema &SemaRef,
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001160 ResultBuilder &Results) {
1161 typedef CodeCompleteConsumer::Result Result;
1162 switch (CCC) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001163 case Action::PCC_Namespace:
Douglas Gregorf4c33342010-05-28 00:22:41 +00001164 if (SemaRef.getLangOptions().CPlusPlus) {
1165 CodeCompletionString *Pattern = 0;
1166
1167 if (Results.includeCodePatterns()) {
1168 // namespace <identifier> { declarations }
1169 CodeCompletionString *Pattern = new CodeCompletionString;
1170 Pattern->AddTypedTextChunk("namespace");
1171 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1172 Pattern->AddPlaceholderChunk("identifier");
1173 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1174 Pattern->AddPlaceholderChunk("declarations");
1175 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1176 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1177 Results.AddResult(Result(Pattern));
1178 }
1179
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001180 // namespace identifier = identifier ;
1181 Pattern = new CodeCompletionString;
1182 Pattern->AddTypedTextChunk("namespace");
1183 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorf4c33342010-05-28 00:22:41 +00001184 Pattern->AddPlaceholderChunk("name");
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001185 Pattern->AddChunk(CodeCompletionString::CK_Equal);
Douglas Gregorf4c33342010-05-28 00:22:41 +00001186 Pattern->AddPlaceholderChunk("namespace");
Douglas Gregor78a21012010-01-14 16:01:26 +00001187 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001188
1189 // Using directives
1190 Pattern = new CodeCompletionString;
1191 Pattern->AddTypedTextChunk("using");
1192 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1193 Pattern->AddTextChunk("namespace");
1194 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1195 Pattern->AddPlaceholderChunk("identifier");
Douglas Gregor78a21012010-01-14 16:01:26 +00001196 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001197
1198 // asm(string-literal)
1199 Pattern = new CodeCompletionString;
1200 Pattern->AddTypedTextChunk("asm");
1201 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1202 Pattern->AddPlaceholderChunk("string-literal");
1203 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor78a21012010-01-14 16:01:26 +00001204 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001205
Douglas Gregorf4c33342010-05-28 00:22:41 +00001206 if (Results.includeCodePatterns()) {
1207 // Explicit template instantiation
1208 Pattern = new CodeCompletionString;
1209 Pattern->AddTypedTextChunk("template");
1210 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1211 Pattern->AddPlaceholderChunk("declaration");
1212 Results.AddResult(Result(Pattern));
1213 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001214 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001215
1216 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001217 AddObjCTopLevelResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001218
Douglas Gregorf4c33342010-05-28 00:22:41 +00001219 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001220 // Fall through
1221
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001222 case Action::PCC_Class:
Douglas Gregorf4c33342010-05-28 00:22:41 +00001223 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001224 // Using declaration
1225 CodeCompletionString *Pattern = new CodeCompletionString;
1226 Pattern->AddTypedTextChunk("using");
1227 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorf4c33342010-05-28 00:22:41 +00001228 Pattern->AddPlaceholderChunk("qualifier");
1229 Pattern->AddTextChunk("::");
1230 Pattern->AddPlaceholderChunk("name");
Douglas Gregor78a21012010-01-14 16:01:26 +00001231 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001232
Douglas Gregorf4c33342010-05-28 00:22:41 +00001233 // using typename qualifier::name (only in a dependent context)
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001234 if (SemaRef.CurContext->isDependentContext()) {
1235 Pattern = new CodeCompletionString;
1236 Pattern->AddTypedTextChunk("using");
1237 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1238 Pattern->AddTextChunk("typename");
1239 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorf4c33342010-05-28 00:22:41 +00001240 Pattern->AddPlaceholderChunk("qualifier");
1241 Pattern->AddTextChunk("::");
1242 Pattern->AddPlaceholderChunk("name");
Douglas Gregor78a21012010-01-14 16:01:26 +00001243 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001244 }
1245
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001246 if (CCC == Action::PCC_Class) {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001247 AddTypedefResult(Results);
1248
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001249 // public:
1250 Pattern = new CodeCompletionString;
1251 Pattern->AddTypedTextChunk("public");
1252 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregor78a21012010-01-14 16:01:26 +00001253 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001254
1255 // protected:
1256 Pattern = new CodeCompletionString;
1257 Pattern->AddTypedTextChunk("protected");
1258 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregor78a21012010-01-14 16:01:26 +00001259 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001260
1261 // private:
1262 Pattern = new CodeCompletionString;
1263 Pattern->AddTypedTextChunk("private");
1264 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregor78a21012010-01-14 16:01:26 +00001265 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001266 }
1267 }
1268 // Fall through
1269
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001270 case Action::PCC_Template:
1271 case Action::PCC_MemberTemplate:
Douglas Gregorf64acca2010-05-25 21:41:55 +00001272 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001273 // template < parameters >
1274 CodeCompletionString *Pattern = new CodeCompletionString;
1275 Pattern->AddTypedTextChunk("template");
1276 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1277 Pattern->AddPlaceholderChunk("parameters");
1278 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregor78a21012010-01-14 16:01:26 +00001279 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001280 }
1281
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001282 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1283 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001284 break;
1285
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001286 case Action::PCC_ObjCInterface:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001287 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1288 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1289 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001290 break;
1291
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001292 case Action::PCC_ObjCImplementation:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001293 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1294 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1295 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorf1934162010-01-13 21:24:21 +00001296 break;
1297
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001298 case Action::PCC_ObjCInstanceVariableList:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001299 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregor48d46252010-01-13 21:54:15 +00001300 break;
1301
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001302 case Action::PCC_RecoveryInFunction:
1303 case Action::PCC_Statement: {
Douglas Gregorf4c33342010-05-28 00:22:41 +00001304 AddTypedefResult(Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001305
1306 CodeCompletionString *Pattern = 0;
Douglas Gregorf64acca2010-05-25 21:41:55 +00001307 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001308 Pattern = new CodeCompletionString;
1309 Pattern->AddTypedTextChunk("try");
1310 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1311 Pattern->AddPlaceholderChunk("statements");
1312 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1313 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1314 Pattern->AddTextChunk("catch");
1315 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1316 Pattern->AddPlaceholderChunk("declaration");
1317 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1318 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1319 Pattern->AddPlaceholderChunk("statements");
1320 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1321 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregor78a21012010-01-14 16:01:26 +00001322 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001323 }
Douglas Gregorf1934162010-01-13 21:24:21 +00001324 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001325 AddObjCStatementResults(Results, true);
Douglas Gregorf1934162010-01-13 21:24:21 +00001326
Douglas Gregorf64acca2010-05-25 21:41:55 +00001327 if (Results.includeCodePatterns()) {
1328 // if (condition) { statements }
1329 Pattern = new CodeCompletionString;
1330 Pattern->AddTypedTextChunk("if");
1331 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1332 if (SemaRef.getLangOptions().CPlusPlus)
1333 Pattern->AddPlaceholderChunk("condition");
1334 else
1335 Pattern->AddPlaceholderChunk("expression");
1336 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1337 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1338 Pattern->AddPlaceholderChunk("statements");
1339 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1340 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1341 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001342
Douglas Gregorf64acca2010-05-25 21:41:55 +00001343 // switch (condition) { }
1344 Pattern = new CodeCompletionString;
1345 Pattern->AddTypedTextChunk("switch");
1346 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1347 if (SemaRef.getLangOptions().CPlusPlus)
1348 Pattern->AddPlaceholderChunk("condition");
1349 else
1350 Pattern->AddPlaceholderChunk("expression");
1351 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1352 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1353 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1354 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1355 Results.AddResult(Result(Pattern));
1356 }
1357
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001358 // Switch-specific statements.
Douglas Gregorf4c33342010-05-28 00:22:41 +00001359 if (!SemaRef.getSwitchStack().empty()) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001360 // case expression:
1361 Pattern = new CodeCompletionString;
1362 Pattern->AddTypedTextChunk("case");
Douglas Gregorf4c33342010-05-28 00:22:41 +00001363 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001364 Pattern->AddPlaceholderChunk("expression");
1365 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregor78a21012010-01-14 16:01:26 +00001366 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001367
1368 // default:
1369 Pattern = new CodeCompletionString;
1370 Pattern->AddTypedTextChunk("default");
1371 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregor78a21012010-01-14 16:01:26 +00001372 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001373 }
1374
Douglas Gregorf64acca2010-05-25 21:41:55 +00001375 if (Results.includeCodePatterns()) {
1376 /// while (condition) { statements }
1377 Pattern = new CodeCompletionString;
1378 Pattern->AddTypedTextChunk("while");
1379 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1380 if (SemaRef.getLangOptions().CPlusPlus)
1381 Pattern->AddPlaceholderChunk("condition");
1382 else
1383 Pattern->AddPlaceholderChunk("expression");
1384 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1385 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1386 Pattern->AddPlaceholderChunk("statements");
1387 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1388 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1389 Results.AddResult(Result(Pattern));
1390
1391 // do { statements } while ( expression );
1392 Pattern = new CodeCompletionString;
1393 Pattern->AddTypedTextChunk("do");
1394 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1395 Pattern->AddPlaceholderChunk("statements");
1396 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1397 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1398 Pattern->AddTextChunk("while");
1399 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001400 Pattern->AddPlaceholderChunk("expression");
Douglas Gregorf64acca2010-05-25 21:41:55 +00001401 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1402 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001403
Douglas Gregorf64acca2010-05-25 21:41:55 +00001404 // for ( for-init-statement ; condition ; expression ) { statements }
1405 Pattern = new CodeCompletionString;
1406 Pattern->AddTypedTextChunk("for");
1407 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1408 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1409 Pattern->AddPlaceholderChunk("init-statement");
1410 else
1411 Pattern->AddPlaceholderChunk("init-expression");
1412 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1413 Pattern->AddPlaceholderChunk("condition");
1414 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1415 Pattern->AddPlaceholderChunk("inc-expression");
1416 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1417 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1418 Pattern->AddPlaceholderChunk("statements");
1419 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1420 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1421 Results.AddResult(Result(Pattern));
1422 }
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001423
1424 if (S->getContinueParent()) {
1425 // continue ;
1426 Pattern = new CodeCompletionString;
1427 Pattern->AddTypedTextChunk("continue");
Douglas Gregor78a21012010-01-14 16:01:26 +00001428 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001429 }
1430
1431 if (S->getBreakParent()) {
1432 // break ;
1433 Pattern = new CodeCompletionString;
1434 Pattern->AddTypedTextChunk("break");
Douglas Gregor78a21012010-01-14 16:01:26 +00001435 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001436 }
1437
1438 // "return expression ;" or "return ;", depending on whether we
1439 // know the function is void or not.
1440 bool isVoid = false;
1441 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1442 isVoid = Function->getResultType()->isVoidType();
1443 else if (ObjCMethodDecl *Method
1444 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1445 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001446 else if (SemaRef.getCurBlock() &&
1447 !SemaRef.getCurBlock()->ReturnType.isNull())
1448 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001449 Pattern = new CodeCompletionString;
1450 Pattern->AddTypedTextChunk("return");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001451 if (!isVoid) {
1452 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001453 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor44272ca2010-02-18 04:06:48 +00001454 }
Douglas Gregor78a21012010-01-14 16:01:26 +00001455 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001456
Douglas Gregorf4c33342010-05-28 00:22:41 +00001457 // goto identifier ;
1458 Pattern = new CodeCompletionString;
1459 Pattern->AddTypedTextChunk("goto");
1460 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1461 Pattern->AddPlaceholderChunk("label");
1462 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001463
Douglas Gregorf4c33342010-05-28 00:22:41 +00001464 // Using directives
1465 Pattern = new CodeCompletionString;
1466 Pattern->AddTypedTextChunk("using");
1467 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1468 Pattern->AddTextChunk("namespace");
1469 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1470 Pattern->AddPlaceholderChunk("identifier");
1471 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001472 }
1473
1474 // Fall through (for statement expressions).
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001475 case Action::PCC_ForInit:
1476 case Action::PCC_Condition:
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001477 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001478 // Fall through: conditions and statements can have expressions.
1479
Douglas Gregor00c37ef2010-08-11 21:23:17 +00001480 case Action::PCC_Expression: {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001481 CodeCompletionString *Pattern = 0;
1482 if (SemaRef.getLangOptions().CPlusPlus) {
1483 // 'this', if we're in a non-static member function.
1484 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1485 if (!Method->isStatic())
Douglas Gregor78a21012010-01-14 16:01:26 +00001486 Results.AddResult(Result("this"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001487
1488 // true, false
Douglas Gregor78a21012010-01-14 16:01:26 +00001489 Results.AddResult(Result("true"));
1490 Results.AddResult(Result("false"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001491
Douglas Gregorf4c33342010-05-28 00:22:41 +00001492 // dynamic_cast < type-id > ( expression )
1493 Pattern = new CodeCompletionString;
1494 Pattern->AddTypedTextChunk("dynamic_cast");
1495 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1496 Pattern->AddPlaceholderChunk("type");
1497 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1498 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1499 Pattern->AddPlaceholderChunk("expression");
1500 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1501 Results.AddResult(Result(Pattern));
1502
1503 // static_cast < type-id > ( expression )
1504 Pattern = new CodeCompletionString;
1505 Pattern->AddTypedTextChunk("static_cast");
1506 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1507 Pattern->AddPlaceholderChunk("type");
1508 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1509 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1510 Pattern->AddPlaceholderChunk("expression");
1511 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1512 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001513
Douglas Gregorf4c33342010-05-28 00:22:41 +00001514 // reinterpret_cast < type-id > ( expression )
1515 Pattern = new CodeCompletionString;
1516 Pattern->AddTypedTextChunk("reinterpret_cast");
1517 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1518 Pattern->AddPlaceholderChunk("type");
1519 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1520 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1521 Pattern->AddPlaceholderChunk("expression");
1522 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1523 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001524
Douglas Gregorf4c33342010-05-28 00:22:41 +00001525 // const_cast < type-id > ( expression )
1526 Pattern = new CodeCompletionString;
1527 Pattern->AddTypedTextChunk("const_cast");
1528 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1529 Pattern->AddPlaceholderChunk("type");
1530 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1531 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1532 Pattern->AddPlaceholderChunk("expression");
1533 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1534 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001535
Douglas Gregorf4c33342010-05-28 00:22:41 +00001536 // typeid ( expression-or-type )
1537 Pattern = new CodeCompletionString;
1538 Pattern->AddTypedTextChunk("typeid");
1539 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1540 Pattern->AddPlaceholderChunk("expression-or-type");
1541 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1542 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001543
Douglas Gregorf4c33342010-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_LeftParen);
1550 Pattern->AddPlaceholderChunk("expressions");
1551 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1552 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001553
Douglas Gregorf4c33342010-05-28 00:22:41 +00001554 // new T [ ] ( ... )
1555 Pattern = new CodeCompletionString;
1556 Pattern->AddTypedTextChunk("new");
1557 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1558 Pattern->AddPlaceholderChunk("type");
1559 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1560 Pattern->AddPlaceholderChunk("size");
1561 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1562 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1563 Pattern->AddPlaceholderChunk("expressions");
1564 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1565 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001566
Douglas Gregorf4c33342010-05-28 00:22:41 +00001567 // delete expression
1568 Pattern = new CodeCompletionString;
1569 Pattern->AddTypedTextChunk("delete");
1570 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1571 Pattern->AddPlaceholderChunk("expression");
1572 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001573
Douglas Gregorf4c33342010-05-28 00:22:41 +00001574 // delete [] expression
1575 Pattern = new CodeCompletionString;
1576 Pattern->AddTypedTextChunk("delete");
1577 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1578 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1579 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1580 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1581 Pattern->AddPlaceholderChunk("expression");
1582 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001583
Douglas Gregorf4c33342010-05-28 00:22:41 +00001584 // throw expression
1585 Pattern = new CodeCompletionString;
1586 Pattern->AddTypedTextChunk("throw");
1587 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1588 Pattern->AddPlaceholderChunk("expression");
1589 Results.AddResult(Result(Pattern));
Douglas Gregora2db7932010-05-26 22:00:08 +00001590
1591 // FIXME: Rethrow?
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001592 }
1593
1594 if (SemaRef.getLangOptions().ObjC1) {
1595 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek305a0a72010-05-31 21:43:10 +00001596 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1597 // The interface can be NULL.
1598 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1599 if (ID->getSuperClass())
1600 Results.AddResult(Result("super"));
1601 }
1602
Douglas Gregorf98e6a22010-01-13 23:51:12 +00001603 AddObjCExpressionResults(Results, true);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001604 }
1605
Douglas Gregorf4c33342010-05-28 00:22:41 +00001606 // sizeof expression
1607 Pattern = new CodeCompletionString;
1608 Pattern->AddTypedTextChunk("sizeof");
1609 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1610 Pattern->AddPlaceholderChunk("expression-or-type");
1611 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1612 Results.AddResult(Result(Pattern));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001613 break;
1614 }
1615 }
1616
Douglas Gregor70febae2010-05-28 00:49:12 +00001617 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1618 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001619
1620 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor78a21012010-01-14 16:01:26 +00001621 Results.AddResult(Result("operator"));
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001622}
1623
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001624/// \brief If the given declaration has an associated type, add it as a result
1625/// type chunk.
1626static void AddResultTypeChunk(ASTContext &Context,
1627 NamedDecl *ND,
1628 CodeCompletionString *Result) {
1629 if (!ND)
1630 return;
1631
1632 // Determine the type of the declaration (if it has a type).
1633 QualType T;
1634 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1635 T = Function->getResultType();
1636 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1637 T = Method->getResultType();
1638 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1639 T = FunTmpl->getTemplatedDecl()->getResultType();
1640 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1641 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1642 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1643 /* Do nothing: ignore unresolved using declarations*/
1644 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1645 T = Value->getType();
1646 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1647 T = Property->getType();
1648
1649 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1650 return;
1651
Douglas Gregorcf04b022010-04-05 21:25:31 +00001652 PrintingPolicy Policy(Context.PrintingPolicy);
1653 Policy.AnonymousTagLocations = false;
1654
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001655 std::string TypeStr;
Douglas Gregorcf04b022010-04-05 21:25:31 +00001656 T.getAsStringInternal(TypeStr, Policy);
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001657 Result->AddResultTypeChunk(TypeStr);
1658}
1659
Douglas Gregor3545ff42009-09-21 16:56:56 +00001660/// \brief Add function parameter chunks to the given code completion string.
1661static void AddFunctionParameterChunks(ASTContext &Context,
1662 FunctionDecl *Function,
1663 CodeCompletionString *Result) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001664 typedef CodeCompletionString::Chunk Chunk;
1665
Douglas Gregor3545ff42009-09-21 16:56:56 +00001666 CodeCompletionString *CCStr = Result;
1667
1668 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1669 ParmVarDecl *Param = Function->getParamDecl(P);
1670
1671 if (Param->hasDefaultArg()) {
1672 // When we see an optional default argument, put that argument and
1673 // the remaining default arguments into a new, optional string.
1674 CodeCompletionString *Opt = new CodeCompletionString;
1675 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1676 CCStr = Opt;
1677 }
1678
1679 if (P != 0)
Douglas Gregor9eb77012009-11-07 00:00:49 +00001680 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001681
1682 // Format the placeholder string.
1683 std::string PlaceholderStr;
1684 if (Param->getIdentifier())
1685 PlaceholderStr = Param->getIdentifier()->getName();
1686
1687 Param->getType().getAsStringInternal(PlaceholderStr,
1688 Context.PrintingPolicy);
1689
1690 // Add the placeholder string.
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001691 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001692 }
Douglas Gregorba449032009-09-22 21:42:17 +00001693
1694 if (const FunctionProtoType *Proto
1695 = Function->getType()->getAs<FunctionProtoType>())
1696 if (Proto->isVariadic())
1697 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregor3545ff42009-09-21 16:56:56 +00001698}
1699
1700/// \brief Add template parameter chunks to the given code completion string.
1701static void AddTemplateParameterChunks(ASTContext &Context,
1702 TemplateDecl *Template,
1703 CodeCompletionString *Result,
1704 unsigned MaxParameters = 0) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001705 typedef CodeCompletionString::Chunk Chunk;
1706
Douglas Gregor3545ff42009-09-21 16:56:56 +00001707 CodeCompletionString *CCStr = Result;
1708 bool FirstParameter = true;
1709
1710 TemplateParameterList *Params = Template->getTemplateParameters();
1711 TemplateParameterList::iterator PEnd = Params->end();
1712 if (MaxParameters)
1713 PEnd = Params->begin() + MaxParameters;
1714 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1715 bool HasDefaultArg = false;
1716 std::string PlaceholderStr;
1717 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1718 if (TTP->wasDeclaredWithTypename())
1719 PlaceholderStr = "typename";
1720 else
1721 PlaceholderStr = "class";
1722
1723 if (TTP->getIdentifier()) {
1724 PlaceholderStr += ' ';
1725 PlaceholderStr += TTP->getIdentifier()->getName();
1726 }
1727
1728 HasDefaultArg = TTP->hasDefaultArgument();
1729 } else if (NonTypeTemplateParmDecl *NTTP
1730 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1731 if (NTTP->getIdentifier())
1732 PlaceholderStr = NTTP->getIdentifier()->getName();
1733 NTTP->getType().getAsStringInternal(PlaceholderStr,
1734 Context.PrintingPolicy);
1735 HasDefaultArg = NTTP->hasDefaultArgument();
1736 } else {
1737 assert(isa<TemplateTemplateParmDecl>(*P));
1738 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1739
1740 // Since putting the template argument list into the placeholder would
1741 // be very, very long, we just use an abbreviation.
1742 PlaceholderStr = "template<...> class";
1743 if (TTP->getIdentifier()) {
1744 PlaceholderStr += ' ';
1745 PlaceholderStr += TTP->getIdentifier()->getName();
1746 }
1747
1748 HasDefaultArg = TTP->hasDefaultArgument();
1749 }
1750
1751 if (HasDefaultArg) {
1752 // When we see an optional default argument, put that argument and
1753 // the remaining default arguments into a new, optional string.
1754 CodeCompletionString *Opt = new CodeCompletionString;
1755 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1756 CCStr = Opt;
1757 }
1758
1759 if (FirstParameter)
1760 FirstParameter = false;
1761 else
Douglas Gregor9eb77012009-11-07 00:00:49 +00001762 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001763
1764 // Add the placeholder string.
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001765 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001766 }
1767}
1768
Douglas Gregorf2510672009-09-21 19:57:38 +00001769/// \brief Add a qualifier to the given code-completion string, if the
1770/// provided nested-name-specifier is non-NULL.
Douglas Gregor0f622362009-12-11 18:44:16 +00001771static void
1772AddQualifierToCompletionString(CodeCompletionString *Result,
1773 NestedNameSpecifier *Qualifier,
1774 bool QualifierIsInformative,
1775 ASTContext &Context) {
Douglas Gregorf2510672009-09-21 19:57:38 +00001776 if (!Qualifier)
1777 return;
1778
1779 std::string PrintedNNS;
1780 {
1781 llvm::raw_string_ostream OS(PrintedNNS);
1782 Qualifier->print(OS, Context.PrintingPolicy);
1783 }
Douglas Gregor5bf52692009-09-22 23:15:58 +00001784 if (QualifierIsInformative)
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001785 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor5bf52692009-09-22 23:15:58 +00001786 else
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001787 Result->AddTextChunk(PrintedNNS);
Douglas Gregorf2510672009-09-21 19:57:38 +00001788}
1789
Douglas Gregor0f622362009-12-11 18:44:16 +00001790static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1791 FunctionDecl *Function) {
1792 const FunctionProtoType *Proto
1793 = Function->getType()->getAs<FunctionProtoType>();
1794 if (!Proto || !Proto->getTypeQuals())
1795 return;
1796
1797 std::string QualsStr;
1798 if (Proto->getTypeQuals() & Qualifiers::Const)
1799 QualsStr += " const";
1800 if (Proto->getTypeQuals() & Qualifiers::Volatile)
1801 QualsStr += " volatile";
1802 if (Proto->getTypeQuals() & Qualifiers::Restrict)
1803 QualsStr += " restrict";
1804 Result->AddInformativeChunk(QualsStr);
1805}
1806
Douglas Gregor3545ff42009-09-21 16:56:56 +00001807/// \brief If possible, create a new code completion string for the given
1808/// result.
1809///
1810/// \returns Either a new, heap-allocated code completion string describing
1811/// how to use this result, or NULL to indicate that the string or name of the
1812/// result is all that is needed.
1813CodeCompletionString *
Douglas Gregor8e984da2010-08-04 16:47:14 +00001814CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S,
1815 CodeCompletionString *Result) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001816 typedef CodeCompletionString::Chunk Chunk;
1817
Douglas Gregorf09935f2009-12-01 05:55:20 +00001818 if (Kind == RK_Pattern)
Douglas Gregor8e984da2010-08-04 16:47:14 +00001819 return Pattern->Clone(Result);
Douglas Gregorf09935f2009-12-01 05:55:20 +00001820
Douglas Gregor8e984da2010-08-04 16:47:14 +00001821 if (!Result)
1822 Result = new CodeCompletionString;
Douglas Gregorf09935f2009-12-01 05:55:20 +00001823
1824 if (Kind == RK_Keyword) {
1825 Result->AddTypedTextChunk(Keyword);
1826 return Result;
1827 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001828
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001829 if (Kind == RK_Macro) {
1830 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregorf09935f2009-12-01 05:55:20 +00001831 assert(MI && "Not a macro?");
1832
1833 Result->AddTypedTextChunk(Macro->getName());
1834
1835 if (!MI->isFunctionLike())
1836 return Result;
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001837
1838 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor9eb77012009-11-07 00:00:49 +00001839 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001840 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
1841 A != AEnd; ++A) {
1842 if (A != MI->arg_begin())
Douglas Gregor9eb77012009-11-07 00:00:49 +00001843 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001844
1845 if (!MI->isVariadic() || A != AEnd - 1) {
1846 // Non-variadic argument.
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001847 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001848 continue;
1849 }
1850
1851 // Variadic argument; cope with the different between GNU and C99
1852 // variadic macros, providing a single placeholder for the rest of the
1853 // arguments.
1854 if ((*A)->isStr("__VA_ARGS__"))
1855 Result->AddPlaceholderChunk("...");
1856 else {
1857 std::string Arg = (*A)->getName();
1858 Arg += "...";
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001859 Result->AddPlaceholderChunk(Arg);
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001860 }
1861 }
Douglas Gregor9eb77012009-11-07 00:00:49 +00001862 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf329c7c2009-10-30 16:50:04 +00001863 return Result;
1864 }
1865
Douglas Gregorf64acca2010-05-25 21:41:55 +00001866 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor3545ff42009-09-21 16:56:56 +00001867 NamedDecl *ND = Declaration;
1868
Douglas Gregor9eb77012009-11-07 00:00:49 +00001869 if (StartsNestedNameSpecifier) {
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001870 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor9eb77012009-11-07 00:00:49 +00001871 Result->AddTextChunk("::");
1872 return Result;
1873 }
1874
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001875 AddResultTypeChunk(S.Context, ND, Result);
1876
Douglas Gregor3545ff42009-09-21 16:56:56 +00001877 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00001878 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1879 S.Context);
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001880 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor9eb77012009-11-07 00:00:49 +00001881 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001882 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001883 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor0f622362009-12-11 18:44:16 +00001884 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001885 return Result;
1886 }
1887
1888 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00001889 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1890 S.Context);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001891 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001892 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor3545ff42009-09-21 16:56:56 +00001893
1894 // Figure out which template parameters are deduced (or have default
1895 // arguments).
1896 llvm::SmallVector<bool, 16> Deduced;
1897 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
1898 unsigned LastDeducibleArgument;
1899 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
1900 --LastDeducibleArgument) {
1901 if (!Deduced[LastDeducibleArgument - 1]) {
1902 // C++0x: Figure out if the template argument has a default. If so,
1903 // the user doesn't need to type this argument.
1904 // FIXME: We need to abstract template parameters better!
1905 bool HasDefaultArg = false;
1906 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
1907 LastDeducibleArgument - 1);
1908 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1909 HasDefaultArg = TTP->hasDefaultArgument();
1910 else if (NonTypeTemplateParmDecl *NTTP
1911 = dyn_cast<NonTypeTemplateParmDecl>(Param))
1912 HasDefaultArg = NTTP->hasDefaultArgument();
1913 else {
1914 assert(isa<TemplateTemplateParmDecl>(Param));
1915 HasDefaultArg
Douglas Gregor9eb77012009-11-07 00:00:49 +00001916 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor3545ff42009-09-21 16:56:56 +00001917 }
1918
1919 if (!HasDefaultArg)
1920 break;
1921 }
1922 }
1923
1924 if (LastDeducibleArgument) {
1925 // Some of the function template arguments cannot be deduced from a
1926 // function call, so we introduce an explicit template argument list
1927 // containing all of the arguments up to the first deducible argument.
Douglas Gregor9eb77012009-11-07 00:00:49 +00001928 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001929 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
1930 LastDeducibleArgument);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001931 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001932 }
1933
1934 // Add the function parameters
Douglas Gregor9eb77012009-11-07 00:00:49 +00001935 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001936 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001937 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor0f622362009-12-11 18:44:16 +00001938 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor3545ff42009-09-21 16:56:56 +00001939 return Result;
1940 }
1941
1942 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor5bf52692009-09-22 23:15:58 +00001943 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1944 S.Context);
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00001945 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor9eb77012009-11-07 00:00:49 +00001946 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001947 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001948 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor3545ff42009-09-21 16:56:56 +00001949 return Result;
1950 }
1951
Douglas Gregord3c5d792009-11-17 16:44:22 +00001952 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregord3c5d792009-11-17 16:44:22 +00001953 Selector Sel = Method->getSelector();
1954 if (Sel.isUnarySelector()) {
1955 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
1956 return Result;
1957 }
1958
Douglas Gregor1b605f72009-11-19 01:08:35 +00001959 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
1960 SelName += ':';
1961 if (StartParameter == 0)
1962 Result->AddTypedTextChunk(SelName);
1963 else {
1964 Result->AddInformativeChunk(SelName);
1965
1966 // If there is only one parameter, and we're past it, add an empty
1967 // typed-text chunk since there is nothing to type.
1968 if (Method->param_size() == 1)
1969 Result->AddTypedTextChunk("");
1970 }
Douglas Gregord3c5d792009-11-17 16:44:22 +00001971 unsigned Idx = 0;
1972 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
1973 PEnd = Method->param_end();
1974 P != PEnd; (void)++P, ++Idx) {
1975 if (Idx > 0) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00001976 std::string Keyword;
1977 if (Idx > StartParameter)
Douglas Gregor6a803932010-01-12 06:38:28 +00001978 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregord3c5d792009-11-17 16:44:22 +00001979 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
1980 Keyword += II->getName().str();
1981 Keyword += ":";
Douglas Gregor95887f92010-07-08 23:20:03 +00001982 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregor1b605f72009-11-19 01:08:35 +00001983 Result->AddInformativeChunk(Keyword);
Douglas Gregor95887f92010-07-08 23:20:03 +00001984 else if (Idx == StartParameter)
Douglas Gregor1b605f72009-11-19 01:08:35 +00001985 Result->AddTypedTextChunk(Keyword);
1986 else
1987 Result->AddTextChunk(Keyword);
Douglas Gregord3c5d792009-11-17 16:44:22 +00001988 }
Douglas Gregor1b605f72009-11-19 01:08:35 +00001989
1990 // If we're before the starting parameter, skip the placeholder.
1991 if (Idx < StartParameter)
1992 continue;
Douglas Gregord3c5d792009-11-17 16:44:22 +00001993
1994 std::string Arg;
1995 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
1996 Arg = "(" + Arg + ")";
1997 if (IdentifierInfo *II = (*P)->getIdentifier())
1998 Arg += II->getName().str();
Douglas Gregor95887f92010-07-08 23:20:03 +00001999 if (DeclaringEntity)
2000 Result->AddTextChunk(Arg);
2001 else if (AllParametersAreInformative)
Douglas Gregorc8537c52009-11-19 07:41:15 +00002002 Result->AddInformativeChunk(Arg);
2003 else
2004 Result->AddPlaceholderChunk(Arg);
Douglas Gregord3c5d792009-11-17 16:44:22 +00002005 }
2006
Douglas Gregor04c5f972009-12-23 00:21:46 +00002007 if (Method->isVariadic()) {
Douglas Gregor95887f92010-07-08 23:20:03 +00002008 if (DeclaringEntity)
2009 Result->AddTextChunk(", ...");
2010 else if (AllParametersAreInformative)
Douglas Gregor04c5f972009-12-23 00:21:46 +00002011 Result->AddInformativeChunk(", ...");
2012 else
2013 Result->AddPlaceholderChunk(", ...");
2014 }
2015
Douglas Gregord3c5d792009-11-17 16:44:22 +00002016 return Result;
2017 }
2018
Douglas Gregorf09935f2009-12-01 05:55:20 +00002019 if (Qualifier)
Douglas Gregor5bf52692009-09-22 23:15:58 +00002020 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2021 S.Context);
Douglas Gregorf09935f2009-12-01 05:55:20 +00002022
2023 Result->AddTypedTextChunk(ND->getNameAsString());
2024 return Result;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002025}
2026
Douglas Gregorf0f51982009-09-23 00:34:09 +00002027CodeCompletionString *
2028CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2029 unsigned CurrentArg,
2030 Sema &S) const {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002031 typedef CodeCompletionString::Chunk Chunk;
2032
Douglas Gregorf0f51982009-09-23 00:34:09 +00002033 CodeCompletionString *Result = new CodeCompletionString;
2034 FunctionDecl *FDecl = getFunction();
Douglas Gregorb3fa9192009-12-18 18:53:37 +00002035 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002036 const FunctionProtoType *Proto
2037 = dyn_cast<FunctionProtoType>(getFunctionType());
2038 if (!FDecl && !Proto) {
2039 // Function without a prototype. Just give the return type and a
2040 // highlighted ellipsis.
2041 const FunctionType *FT = getFunctionType();
2042 Result->AddTextChunk(
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002043 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor9eb77012009-11-07 00:00:49 +00002044 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2045 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2046 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002047 return Result;
2048 }
2049
2050 if (FDecl)
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002051 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregorf0f51982009-09-23 00:34:09 +00002052 else
2053 Result->AddTextChunk(
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002054 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002055
Douglas Gregor9eb77012009-11-07 00:00:49 +00002056 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002057 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2058 for (unsigned I = 0; I != NumParams; ++I) {
2059 if (I)
Douglas Gregor9eb77012009-11-07 00:00:49 +00002060 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002061
2062 std::string ArgString;
2063 QualType ArgType;
2064
2065 if (FDecl) {
2066 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2067 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2068 } else {
2069 ArgType = Proto->getArgType(I);
2070 }
2071
2072 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2073
2074 if (I == CurrentArg)
Douglas Gregor9eb77012009-11-07 00:00:49 +00002075 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002076 ArgString));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002077 else
Benjamin Kramerb33a97c2009-11-29 20:18:50 +00002078 Result->AddTextChunk(ArgString);
Douglas Gregorf0f51982009-09-23 00:34:09 +00002079 }
2080
2081 if (Proto && Proto->isVariadic()) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002082 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002083 if (CurrentArg < NumParams)
2084 Result->AddTextChunk("...");
2085 else
Douglas Gregor9eb77012009-11-07 00:00:49 +00002086 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002087 }
Douglas Gregor9eb77012009-11-07 00:00:49 +00002088 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregorf0f51982009-09-23 00:34:09 +00002089
2090 return Result;
2091}
2092
Douglas Gregor3545ff42009-09-21 16:56:56 +00002093namespace {
2094 struct SortCodeCompleteResult {
2095 typedef CodeCompleteConsumer::Result Result;
2096
Douglas Gregore6688e62009-09-28 03:51:44 +00002097 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
Douglas Gregor249d6822009-12-05 09:08:56 +00002098 Selector XSel = X.getObjCSelector();
2099 Selector YSel = Y.getObjCSelector();
2100 if (!XSel.isNull() && !YSel.isNull()) {
2101 // We are comparing two selectors.
2102 unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
2103 if (N == 0)
2104 ++N;
2105 for (unsigned I = 0; I != N; ++I) {
2106 IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
2107 IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
2108 if (!XId || !YId)
2109 return XId && !YId;
2110
2111 switch (XId->getName().compare_lower(YId->getName())) {
2112 case -1: return true;
2113 case 1: return false;
2114 default: break;
2115 }
2116 }
2117
2118 return XSel.getNumArgs() < YSel.getNumArgs();
2119 }
2120
2121 // For non-selectors, order by kind.
2122 if (X.getNameKind() != Y.getNameKind())
Douglas Gregore6688e62009-09-28 03:51:44 +00002123 return X.getNameKind() < Y.getNameKind();
2124
Douglas Gregor249d6822009-12-05 09:08:56 +00002125 // Order identifiers by comparison of their lowercased names.
2126 if (IdentifierInfo *XId = X.getAsIdentifierInfo())
2127 return XId->getName().compare_lower(
2128 Y.getAsIdentifierInfo()->getName()) < 0;
2129
2130 // Order overloaded operators by the order in which they appear
2131 // in our list of operators.
2132 if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
2133 return XOp < Y.getCXXOverloadedOperator();
2134
2135 // Order C++0x user-defined literal operators lexically by their
2136 // lowercased suffixes.
2137 if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
2138 return XLit->getName().compare_lower(
2139 Y.getCXXLiteralIdentifier()->getName()) < 0;
2140
2141 // The only stable ordering we have is to turn the name into a
2142 // string and then compare the lower-case strings. This is
2143 // inefficient, but thankfully does not happen too often.
Benjamin Kramer4053e5d2009-12-05 10:22:15 +00002144 return llvm::StringRef(X.getAsString()).compare_lower(
2145 Y.getAsString()) < 0;
Douglas Gregore6688e62009-09-28 03:51:44 +00002146 }
2147
Douglas Gregor52ce62f2010-01-13 23:24:38 +00002148 /// \brief Retrieve the name that should be used to order a result.
2149 ///
2150 /// If the name needs to be constructed as a string, that string will be
2151 /// saved into Saved and the returned StringRef will refer to it.
2152 static llvm::StringRef getOrderedName(const Result &R,
2153 std::string &Saved) {
2154 switch (R.Kind) {
2155 case Result::RK_Keyword:
2156 return R.Keyword;
2157
2158 case Result::RK_Pattern:
2159 return R.Pattern->getTypedText();
2160
2161 case Result::RK_Macro:
2162 return R.Macro->getName();
2163
2164 case Result::RK_Declaration:
2165 // Handle declarations below.
2166 break;
Douglas Gregor45f83ee2009-11-19 00:01:57 +00002167 }
Douglas Gregor52ce62f2010-01-13 23:24:38 +00002168
2169 DeclarationName Name = R.Declaration->getDeclName();
Douglas Gregor45f83ee2009-11-19 00:01:57 +00002170
Douglas Gregor52ce62f2010-01-13 23:24:38 +00002171 // If the name is a simple identifier (by far the common case), or a
2172 // zero-argument selector, just return a reference to that identifier.
2173 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
2174 return Id->getName();
2175 if (Name.isObjCZeroArgSelector())
2176 if (IdentifierInfo *Id
2177 = Name.getObjCSelector().getIdentifierInfoForSlot(0))
2178 return Id->getName();
2179
2180 Saved = Name.getAsString();
2181 return Saved;
2182 }
2183
2184 bool operator()(const Result &X, const Result &Y) const {
2185 std::string XSaved, YSaved;
2186 llvm::StringRef XStr = getOrderedName(X, XSaved);
2187 llvm::StringRef YStr = getOrderedName(Y, YSaved);
2188 int cmp = XStr.compare_lower(YStr);
2189 if (cmp)
2190 return cmp < 0;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002191
2192 // Non-hidden names precede hidden names.
2193 if (X.Hidden != Y.Hidden)
2194 return !X.Hidden;
2195
Douglas Gregore412a5a2009-09-23 22:26:46 +00002196 // Non-nested-name-specifiers precede nested-name-specifiers.
2197 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
2198 return !X.StartsNestedNameSpecifier;
2199
Douglas Gregor3545ff42009-09-21 16:56:56 +00002200 return false;
2201 }
2202 };
2203}
2204
Douglas Gregor55b037b2010-07-08 20:55:51 +00002205static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2206 bool TargetTypeIsPointer = false) {
2207 typedef CodeCompleteConsumer::Result Result;
2208
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002209 Results.EnterNewScope();
Douglas Gregor9eb77012009-11-07 00:00:49 +00002210 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2211 MEnd = PP.macro_end();
Douglas Gregor55b037b2010-07-08 20:55:51 +00002212 M != MEnd; ++M) {
2213 unsigned Priority = CCP_Macro;
2214
2215 // Treat the "nil" and "NULL" macros as null pointer constants.
2216 if (M->first->isStr("nil") || M->first->isStr("NULL")) {
2217 Priority = CCP_Constant;
2218 if (TargetTypeIsPointer)
2219 Priority = Priority / CCF_SimilarTypeMatch;
2220 }
2221
2222 Results.AddResult(Result(M->first, Priority));
2223 }
Douglas Gregorf329c7c2009-10-30 16:50:04 +00002224 Results.ExitScope();
2225}
2226
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002227static void HandleCodeCompleteResults(Sema *S,
2228 CodeCompleteConsumer *CodeCompleter,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002229 CodeCompletionContext Context,
2230 CodeCompleteConsumer::Result *Results,
2231 unsigned NumResults) {
Douglas Gregor3545ff42009-09-21 16:56:56 +00002232 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
2233
2234 if (CodeCompleter)
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002235 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor45f83ee2009-11-19 00:01:57 +00002236
2237 for (unsigned I = 0; I != NumResults; ++I)
2238 Results[I].Destroy();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002239}
2240
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002241static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2242 Sema::ParserCompletionContext PCC) {
2243 switch (PCC) {
2244 case Action::PCC_Namespace:
2245 return CodeCompletionContext::CCC_TopLevel;
2246
2247 case Action::PCC_Class:
2248 return CodeCompletionContext::CCC_ClassStructUnion;
2249
2250 case Action::PCC_ObjCInterface:
2251 return CodeCompletionContext::CCC_ObjCInterface;
2252
2253 case Action::PCC_ObjCImplementation:
2254 return CodeCompletionContext::CCC_ObjCImplementation;
2255
2256 case Action::PCC_ObjCInstanceVariableList:
2257 return CodeCompletionContext::CCC_ObjCIvarList;
2258
2259 case Action::PCC_Template:
2260 case Action::PCC_MemberTemplate:
2261 case Action::PCC_RecoveryInFunction:
2262 return CodeCompletionContext::CCC_Other;
2263
2264 case Action::PCC_Expression:
2265 case Action::PCC_ForInit:
2266 case Action::PCC_Condition:
2267 return CodeCompletionContext::CCC_Expression;
2268
2269 case Action::PCC_Statement:
2270 return CodeCompletionContext::CCC_Statement;
2271 }
2272
2273 return CodeCompletionContext::CCC_Other;
2274}
2275
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002276void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002277 ParserCompletionContext CompletionContext) {
Douglas Gregor92253692009-12-07 09:54:55 +00002278 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002279 ResultBuilder Results(*this);
2280
2281 // Determine how to filter results, e.g., so that the names of
2282 // values (functions, enumerators, function templates, etc.) are
2283 // only allowed where we can have an expression.
2284 switch (CompletionContext) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002285 case PCC_Namespace:
2286 case PCC_Class:
2287 case PCC_ObjCInterface:
2288 case PCC_ObjCImplementation:
2289 case PCC_ObjCInstanceVariableList:
2290 case PCC_Template:
2291 case PCC_MemberTemplate:
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002292 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2293 break;
2294
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002295 case PCC_Expression:
2296 case PCC_Statement:
2297 case PCC_ForInit:
2298 case PCC_Condition:
Douglas Gregor70febae2010-05-28 00:49:12 +00002299 if (WantTypesInContext(CompletionContext, getLangOptions()))
2300 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2301 else
2302 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002303 break;
Douglas Gregor6da3db42010-05-25 05:58:43 +00002304
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002305 case PCC_RecoveryInFunction:
Douglas Gregor6da3db42010-05-25 05:58:43 +00002306 // Unfiltered
2307 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00002308 }
2309
Douglas Gregorc580c522010-01-14 01:09:38 +00002310 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00002311 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2312 CodeCompleter->includeGlobals());
Douglas Gregor92253692009-12-07 09:54:55 +00002313
2314 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002315 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor92253692009-12-07 09:54:55 +00002316 Results.ExitScope();
2317
Douglas Gregor9eb77012009-11-07 00:00:49 +00002318 if (CodeCompleter->includeMacros())
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002319 AddMacroResults(PP, Results);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002320 HandleCodeCompleteResults(this, CodeCompleter,
2321 mapCodeCompletionContext(*this, CompletionContext),
2322 Results.data(),Results.size());
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00002323}
2324
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002325/// \brief Perform code-completion in an expression context when we know what
2326/// type we're looking for.
Douglas Gregor85b50632010-07-28 21:50:18 +00002327///
2328/// \param IntegralConstantExpression Only permit integral constant
2329/// expressions.
2330void Sema::CodeCompleteExpression(Scope *S, QualType T,
2331 bool IntegralConstantExpression) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002332 typedef CodeCompleteConsumer::Result Result;
2333 ResultBuilder Results(*this);
2334
Douglas Gregor85b50632010-07-28 21:50:18 +00002335 if (IntegralConstantExpression)
2336 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002337 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002338 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2339 else
2340 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
2341 Results.setPreferredType(T.getNonReferenceType());
2342
2343 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00002344 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2345 CodeCompleter->includeGlobals());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002346
2347 Results.EnterNewScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002348 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002349 Results.ExitScope();
2350
Douglas Gregor55b037b2010-07-08 20:55:51 +00002351 bool PreferredTypeIsPointer = false;
2352 if (!T.isNull())
2353 PreferredTypeIsPointer = T->isAnyPointerType() ||
2354 T->isMemberPointerType() || T->isBlockPointerType();
2355
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002356 if (CodeCompleter->includeMacros())
Douglas Gregor55b037b2010-07-08 20:55:51 +00002357 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002358 HandleCodeCompleteResults(this, CodeCompleter,
2359 CodeCompletionContext::CCC_Expression,
2360 Results.data(),Results.size());
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002361}
2362
2363
Douglas Gregor9291bad2009-11-18 01:29:26 +00002364static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor5d649882009-11-18 22:32:06 +00002365 bool AllowCategories,
Douglas Gregor9291bad2009-11-18 01:29:26 +00002366 DeclContext *CurContext,
2367 ResultBuilder &Results) {
2368 typedef CodeCompleteConsumer::Result Result;
2369
2370 // Add properties in this container.
2371 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2372 PEnd = Container->prop_end();
2373 P != PEnd;
2374 ++P)
2375 Results.MaybeAddResult(Result(*P, 0), CurContext);
2376
2377 // Add properties in referenced protocols.
2378 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2379 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2380 PEnd = Protocol->protocol_end();
2381 P != PEnd; ++P)
Douglas Gregor5d649882009-11-18 22:32:06 +00002382 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002383 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor5d649882009-11-18 22:32:06 +00002384 if (AllowCategories) {
2385 // Look through categories.
2386 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2387 Category; Category = Category->getNextClassCategory())
2388 AddObjCProperties(Category, AllowCategories, CurContext, Results);
2389 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00002390
2391 // Look through protocols.
2392 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2393 E = IFace->protocol_end();
2394 I != E; ++I)
Douglas Gregor5d649882009-11-18 22:32:06 +00002395 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002396
2397 // Look in the superclass.
2398 if (IFace->getSuperClass())
Douglas Gregor5d649882009-11-18 22:32:06 +00002399 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2400 Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002401 } else if (const ObjCCategoryDecl *Category
2402 = dyn_cast<ObjCCategoryDecl>(Container)) {
2403 // Look through protocols.
2404 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
2405 PEnd = Category->protocol_end();
2406 P != PEnd; ++P)
Douglas Gregor5d649882009-11-18 22:32:06 +00002407 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002408 }
2409}
2410
Douglas Gregor2436e712009-09-17 21:32:03 +00002411void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2412 SourceLocation OpLoc,
2413 bool IsArrow) {
2414 if (!BaseE || !CodeCompleter)
2415 return;
2416
Douglas Gregor3545ff42009-09-21 16:56:56 +00002417 typedef CodeCompleteConsumer::Result Result;
2418
Douglas Gregor2436e712009-09-17 21:32:03 +00002419 Expr *Base = static_cast<Expr *>(BaseE);
2420 QualType BaseType = Base->getType();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002421
2422 if (IsArrow) {
2423 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2424 BaseType = Ptr->getPointeeType();
2425 else if (BaseType->isObjCObjectPointerType())
2426 /*Do nothing*/ ;
2427 else
2428 return;
2429 }
2430
Douglas Gregore412a5a2009-09-23 22:26:46 +00002431 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002432 Results.EnterNewScope();
2433 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
2434 // Access to a C/C++ class, struct, or union.
Douglas Gregor6ae4c522010-01-14 03:21:49 +00002435 Results.allowNestedNameSpecifiers();
Douglas Gregor09bbc652010-01-14 15:47:35 +00002436 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00002437 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
2438 CodeCompleter->includeGlobals());
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002439
Douglas Gregor9291bad2009-11-18 01:29:26 +00002440 if (getLangOptions().CPlusPlus) {
2441 if (!Results.empty()) {
2442 // The "template" keyword can follow "->" or "." in the grammar.
2443 // However, we only want to suggest the template keyword if something
2444 // is dependent.
2445 bool IsDependent = BaseType->isDependentType();
2446 if (!IsDependent) {
2447 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2448 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2449 IsDependent = Ctx->isDependentContext();
2450 break;
2451 }
2452 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002453
Douglas Gregor9291bad2009-11-18 01:29:26 +00002454 if (IsDependent)
Douglas Gregor78a21012010-01-14 16:01:26 +00002455 Results.AddResult(Result("template"));
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002456 }
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002457 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00002458 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2459 // Objective-C property reference.
2460
2461 // Add property results based on our interface.
2462 const ObjCObjectPointerType *ObjCPtr
2463 = BaseType->getAsObjCInterfacePointerType();
2464 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor5d649882009-11-18 22:32:06 +00002465 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002466
2467 // Add properties from the protocols in a qualified interface.
2468 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2469 E = ObjCPtr->qual_end();
2470 I != E; ++I)
Douglas Gregor5d649882009-11-18 22:32:06 +00002471 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor9291bad2009-11-18 01:29:26 +00002472 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00002473 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor9291bad2009-11-18 01:29:26 +00002474 // Objective-C instance variable access.
2475 ObjCInterfaceDecl *Class = 0;
2476 if (const ObjCObjectPointerType *ObjCPtr
2477 = BaseType->getAs<ObjCObjectPointerType>())
2478 Class = ObjCPtr->getInterfaceDecl();
2479 else
John McCall8b07ec22010-05-15 11:32:37 +00002480 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9291bad2009-11-18 01:29:26 +00002481
2482 // Add all ivars from this class and its superclasses.
Douglas Gregor2b8162b2010-01-14 16:08:12 +00002483 if (Class) {
2484 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2485 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor39982192010-08-15 06:18:01 +00002486 LookupVisibleDecls(Class, LookupMemberName, Consumer,
2487 CodeCompleter->includeGlobals());
Douglas Gregor9291bad2009-11-18 01:29:26 +00002488 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002489 }
Douglas Gregor9291bad2009-11-18 01:29:26 +00002490
2491 // FIXME: How do we cope with isa?
2492
2493 Results.ExitScope();
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002494
Daniel Dunbar242ea9a2009-11-13 08:58:20 +00002495 // Hand off the results found for code completion.
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002496 HandleCodeCompleteResults(this, CodeCompleter,
2497 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
2498 BaseType),
2499 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00002500}
2501
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002502void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2503 if (!CodeCompleter)
2504 return;
2505
Douglas Gregor3545ff42009-09-21 16:56:56 +00002506 typedef CodeCompleteConsumer::Result Result;
2507 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002508 enum CodeCompletionContext::Kind ContextKind
2509 = CodeCompletionContext::CCC_Other;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002510 switch ((DeclSpec::TST)TagSpec) {
2511 case DeclSpec::TST_enum:
Douglas Gregor3545ff42009-09-21 16:56:56 +00002512 Filter = &ResultBuilder::IsEnum;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002513 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002514 break;
2515
2516 case DeclSpec::TST_union:
Douglas Gregor3545ff42009-09-21 16:56:56 +00002517 Filter = &ResultBuilder::IsUnion;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002518 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002519 break;
2520
2521 case DeclSpec::TST_struct:
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002522 case DeclSpec::TST_class:
Douglas Gregor3545ff42009-09-21 16:56:56 +00002523 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002524 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002525 break;
2526
2527 default:
2528 assert(false && "Unknown type specifier kind in CodeCompleteTag");
2529 return;
2530 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002531
John McCalle87beb22010-04-23 18:46:30 +00002532 ResultBuilder Results(*this);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002533 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCalle87beb22010-04-23 18:46:30 +00002534
2535 // First pass: look for tags.
2536 Results.setFilter(Filter);
Douglas Gregor39982192010-08-15 06:18:01 +00002537 LookupVisibleDecls(S, LookupTagName, Consumer,
2538 CodeCompleter->includeGlobals());
John McCalle87beb22010-04-23 18:46:30 +00002539
Douglas Gregor39982192010-08-15 06:18:01 +00002540 if (CodeCompleter->includeGlobals()) {
2541 // Second pass: look for nested name specifiers.
2542 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
2543 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
2544 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002545
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002546 HandleCodeCompleteResults(this, CodeCompleter, ContextKind,
2547 Results.data(),Results.size());
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00002548}
2549
Douglas Gregord328d572009-09-21 18:10:23 +00002550void Sema::CodeCompleteCase(Scope *S) {
2551 if (getSwitchStack().empty() || !CodeCompleter)
2552 return;
2553
2554 SwitchStmt *Switch = getSwitchStack().back();
Douglas Gregor85b50632010-07-28 21:50:18 +00002555 if (!Switch->getCond()->getType()->isEnumeralType()) {
2556 CodeCompleteExpression(S, Switch->getCond()->getType(), true);
Douglas Gregord328d572009-09-21 18:10:23 +00002557 return;
Douglas Gregor85b50632010-07-28 21:50:18 +00002558 }
Douglas Gregord328d572009-09-21 18:10:23 +00002559
2560 // Code-complete the cases of a switch statement over an enumeration type
2561 // by providing the list of
2562 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2563
2564 // Determine which enumerators we have already seen in the switch statement.
2565 // FIXME: Ideally, we would also be able to look *past* the code-completion
2566 // token, in case we are code-completing in the middle of the switch and not
2567 // at the end. However, we aren't able to do so at the moment.
2568 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorf2510672009-09-21 19:57:38 +00002569 NestedNameSpecifier *Qualifier = 0;
Douglas Gregord328d572009-09-21 18:10:23 +00002570 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2571 SC = SC->getNextSwitchCase()) {
2572 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2573 if (!Case)
2574 continue;
2575
2576 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2577 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2578 if (EnumConstantDecl *Enumerator
2579 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2580 // We look into the AST of the case statement to determine which
2581 // enumerator was named. Alternatively, we could compute the value of
2582 // the integral constant expression, then compare it against the
2583 // values of each enumerator. However, value-based approach would not
2584 // work as well with C++ templates where enumerators declared within a
2585 // template are type- and value-dependent.
2586 EnumeratorsSeen.insert(Enumerator);
2587
Douglas Gregorf2510672009-09-21 19:57:38 +00002588 // If this is a qualified-id, keep track of the nested-name-specifier
2589 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregord328d572009-09-21 18:10:23 +00002590 //
2591 // switch (TagD.getKind()) {
2592 // case TagDecl::TK_enum:
2593 // break;
2594 // case XXX
2595 //
Douglas Gregorf2510672009-09-21 19:57:38 +00002596 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregord328d572009-09-21 18:10:23 +00002597 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2598 // TK_struct, and TK_class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002599 Qualifier = DRE->getQualifier();
Douglas Gregord328d572009-09-21 18:10:23 +00002600 }
2601 }
2602
Douglas Gregorf2510672009-09-21 19:57:38 +00002603 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2604 // If there are no prior enumerators in C++, check whether we have to
2605 // qualify the names of the enumerators that we suggest, because they
2606 // may not be visible in this scope.
2607 Qualifier = getRequiredQualification(Context, CurContext,
2608 Enum->getDeclContext());
2609
2610 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2611 }
2612
Douglas Gregord328d572009-09-21 18:10:23 +00002613 // Add any enumerators that have not yet been mentioned.
2614 ResultBuilder Results(*this);
2615 Results.EnterNewScope();
2616 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2617 EEnd = Enum->enumerator_end();
2618 E != EEnd; ++E) {
2619 if (EnumeratorsSeen.count(*E))
2620 continue;
2621
Douglas Gregorfc59ce12010-01-14 16:14:35 +00002622 Results.AddResult(CodeCompleteConsumer::Result(*E, Qualifier),
2623 CurContext, 0, false);
Douglas Gregord328d572009-09-21 18:10:23 +00002624 }
2625 Results.ExitScope();
Douglas Gregor285560922010-04-06 20:02:15 +00002626
Douglas Gregor9eb77012009-11-07 00:00:49 +00002627 if (CodeCompleter->includeMacros())
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002628 AddMacroResults(PP, Results);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002629 HandleCodeCompleteResults(this, CodeCompleter,
2630 CodeCompletionContext::CCC_Expression,
2631 Results.data(),Results.size());
Douglas Gregord328d572009-09-21 18:10:23 +00002632}
2633
Douglas Gregorcabea402009-09-22 15:41:20 +00002634namespace {
2635 struct IsBetterOverloadCandidate {
2636 Sema &S;
John McCallbc077cf2010-02-08 23:07:23 +00002637 SourceLocation Loc;
Douglas Gregorcabea402009-09-22 15:41:20 +00002638
2639 public:
John McCallbc077cf2010-02-08 23:07:23 +00002640 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
2641 : S(S), Loc(Loc) { }
Douglas Gregorcabea402009-09-22 15:41:20 +00002642
2643 bool
2644 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCallbc077cf2010-02-08 23:07:23 +00002645 return S.isBetterOverloadCandidate(X, Y, Loc);
Douglas Gregorcabea402009-09-22 15:41:20 +00002646 }
2647 };
2648}
2649
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00002650static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
2651 if (NumArgs && !Args)
2652 return true;
2653
2654 for (unsigned I = 0; I != NumArgs; ++I)
2655 if (!Args[I])
2656 return true;
2657
2658 return false;
2659}
2660
Douglas Gregorcabea402009-09-22 15:41:20 +00002661void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2662 ExprTy **ArgsIn, unsigned NumArgs) {
2663 if (!CodeCompleter)
2664 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00002665
2666 // When we're code-completing for a call, we fall back to ordinary
2667 // name code-completion whenever we can't produce specific
2668 // results. We may want to revisit this strategy in the future,
2669 // e.g., by merging the two kinds of results.
2670
Douglas Gregorcabea402009-09-22 15:41:20 +00002671 Expr *Fn = (Expr *)FnIn;
2672 Expr **Args = (Expr **)ArgsIn;
Douglas Gregor3ef59522009-12-11 19:06:04 +00002673
Douglas Gregorcabea402009-09-22 15:41:20 +00002674 // Ignore type-dependent call expressions entirely.
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00002675 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregor3ef59522009-12-11 19:06:04 +00002676 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002677 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregorcabea402009-09-22 15:41:20 +00002678 return;
Douglas Gregor3ef59522009-12-11 19:06:04 +00002679 }
Douglas Gregorcabea402009-09-22 15:41:20 +00002680
John McCall57500772009-12-16 12:17:52 +00002681 // Build an overload candidate set based on the functions we find.
John McCallbc077cf2010-02-08 23:07:23 +00002682 SourceLocation Loc = Fn->getExprLoc();
2683 OverloadCandidateSet CandidateSet(Loc);
John McCall57500772009-12-16 12:17:52 +00002684
Douglas Gregorcabea402009-09-22 15:41:20 +00002685 // FIXME: What if we're calling something that isn't a function declaration?
2686 // FIXME: What if we're calling a pseudo-destructor?
2687 // FIXME: What if we're calling a member function?
2688
Douglas Gregorff59f672010-01-21 15:46:19 +00002689 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
2690 llvm::SmallVector<ResultCandidate, 8> Results;
2691
John McCall57500772009-12-16 12:17:52 +00002692 Expr *NakedFn = Fn->IgnoreParenCasts();
2693 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
2694 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
2695 /*PartialOverloading=*/ true);
2696 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
2697 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorff59f672010-01-21 15:46:19 +00002698 if (FDecl) {
Douglas Gregor6ed3eb82010-05-30 06:10:08 +00002699 if (!getLangOptions().CPlusPlus ||
2700 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorff59f672010-01-21 15:46:19 +00002701 Results.push_back(ResultCandidate(FDecl));
2702 else
John McCallb89836b2010-01-26 01:37:31 +00002703 // FIXME: access?
John McCalla0296f72010-03-19 07:35:19 +00002704 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
2705 Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00002706 false, /*PartialOverloading*/true);
Douglas Gregorff59f672010-01-21 15:46:19 +00002707 }
John McCall57500772009-12-16 12:17:52 +00002708 }
Douglas Gregorcabea402009-09-22 15:41:20 +00002709
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002710 QualType ParamType;
2711
Douglas Gregorff59f672010-01-21 15:46:19 +00002712 if (!CandidateSet.empty()) {
2713 // Sort the overload candidate set by placing the best overloads first.
2714 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCallbc077cf2010-02-08 23:07:23 +00002715 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregorcabea402009-09-22 15:41:20 +00002716
Douglas Gregorff59f672010-01-21 15:46:19 +00002717 // Add the remaining viable overload candidates as code-completion reslults.
2718 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2719 CandEnd = CandidateSet.end();
2720 Cand != CandEnd; ++Cand) {
2721 if (Cand->Viable)
2722 Results.push_back(ResultCandidate(Cand->Function));
2723 }
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002724
2725 // From the viable candidates, try to determine the type of this parameter.
2726 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
2727 if (const FunctionType *FType = Results[I].getFunctionType())
2728 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
2729 if (NumArgs < Proto->getNumArgs()) {
2730 if (ParamType.isNull())
2731 ParamType = Proto->getArgType(NumArgs);
2732 else if (!Context.hasSameUnqualifiedType(
2733 ParamType.getNonReferenceType(),
2734 Proto->getArgType(NumArgs).getNonReferenceType())) {
2735 ParamType = QualType();
2736 break;
2737 }
2738 }
2739 }
2740 } else {
2741 // Try to determine the parameter type from the type of the expression
2742 // being called.
2743 QualType FunctionType = Fn->getType();
2744 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
2745 FunctionType = Ptr->getPointeeType();
2746 else if (const BlockPointerType *BlockPtr
2747 = FunctionType->getAs<BlockPointerType>())
2748 FunctionType = BlockPtr->getPointeeType();
2749 else if (const MemberPointerType *MemPtr
2750 = FunctionType->getAs<MemberPointerType>())
2751 FunctionType = MemPtr->getPointeeType();
2752
2753 if (const FunctionProtoType *Proto
2754 = FunctionType->getAs<FunctionProtoType>()) {
2755 if (NumArgs < Proto->getNumArgs())
2756 ParamType = Proto->getArgType(NumArgs);
2757 }
Douglas Gregorcabea402009-09-22 15:41:20 +00002758 }
Douglas Gregor3ef59522009-12-11 19:06:04 +00002759
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002760 if (ParamType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002761 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002762 else
2763 CodeCompleteExpression(S, ParamType);
2764
Douglas Gregorc01890e2010-04-06 20:19:47 +00002765 if (!Results.empty())
Douglas Gregor3ef59522009-12-11 19:06:04 +00002766 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
2767 Results.size());
Douglas Gregorcabea402009-09-22 15:41:20 +00002768}
2769
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002770void Sema::CodeCompleteInitializer(Scope *S, DeclPtrTy D) {
2771 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D.getAs<Decl>());
2772 if (!VD) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002773 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002774 return;
2775 }
2776
2777 CodeCompleteExpression(S, VD->getType());
2778}
2779
2780void Sema::CodeCompleteReturn(Scope *S) {
2781 QualType ResultType;
2782 if (isa<BlockDecl>(CurContext)) {
2783 if (BlockScopeInfo *BSI = getCurBlock())
2784 ResultType = BSI->ReturnType;
2785 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
2786 ResultType = Function->getResultType();
2787 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
2788 ResultType = Method->getResultType();
2789
2790 if (ResultType.isNull())
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002791 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002792 else
2793 CodeCompleteExpression(S, ResultType);
2794}
2795
2796void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
2797 if (LHS)
2798 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
2799 else
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002800 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002801}
2802
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002803void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor2436e712009-09-17 21:32:03 +00002804 bool EnteringContext) {
2805 if (!SS.getScopeRep() || !CodeCompleter)
2806 return;
2807
Douglas Gregor3545ff42009-09-21 16:56:56 +00002808 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
2809 if (!Ctx)
2810 return;
Douglas Gregor800f2f02009-12-11 18:28:39 +00002811
2812 // Try to instantiate any non-dependent declaration contexts before
2813 // we look in them.
John McCall0b66eb32010-05-01 00:40:08 +00002814 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregor800f2f02009-12-11 18:28:39 +00002815 return;
2816
Douglas Gregor3545ff42009-09-21 16:56:56 +00002817 ResultBuilder Results(*this);
Douglas Gregor200c99d2010-01-14 03:35:48 +00002818 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2819 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
Douglas Gregor3545ff42009-09-21 16:56:56 +00002820
2821 // The "template" keyword can follow "::" in the grammar, but only
2822 // put it into the grammar if the nested-name-specifier is dependent.
2823 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
2824 if (!Results.empty() && NNS->isDependent())
Douglas Gregor78a21012010-01-14 16:01:26 +00002825 Results.AddResult("template");
Douglas Gregor3545ff42009-09-21 16:56:56 +00002826
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002827 HandleCodeCompleteResults(this, CodeCompleter,
2828 CodeCompletionContext::CCC_Other,
2829 Results.data(),Results.size());
Douglas Gregor2436e712009-09-17 21:32:03 +00002830}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002831
2832void Sema::CodeCompleteUsing(Scope *S) {
2833 if (!CodeCompleter)
2834 return;
2835
Douglas Gregor3545ff42009-09-21 16:56:56 +00002836 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002837 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002838
2839 // If we aren't in class scope, we could see the "namespace" keyword.
2840 if (!S->isClassScope())
Douglas Gregor78a21012010-01-14 16:01:26 +00002841 Results.AddResult(CodeCompleteConsumer::Result("namespace"));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002842
2843 // After "using", we can see anything that would start a
2844 // nested-name-specifier.
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002845 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00002846 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2847 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00002848 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002849
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002850 HandleCodeCompleteResults(this, CodeCompleter,
2851 CodeCompletionContext::CCC_Other,
2852 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002853}
2854
2855void Sema::CodeCompleteUsingDirective(Scope *S) {
2856 if (!CodeCompleter)
2857 return;
2858
Douglas Gregor3545ff42009-09-21 16:56:56 +00002859 // After "using namespace", we expect to see a namespace name or namespace
2860 // alias.
2861 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002862 Results.EnterNewScope();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002863 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00002864 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2865 CodeCompleter->includeGlobals());
Douglas Gregor64b12b52009-09-22 23:31:26 +00002866 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002867 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00002868 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002869 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002870}
2871
2872void Sema::CodeCompleteNamespaceDecl(Scope *S) {
2873 if (!CodeCompleter)
2874 return;
2875
Douglas Gregor3545ff42009-09-21 16:56:56 +00002876 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
2877 DeclContext *Ctx = (DeclContext *)S->getEntity();
2878 if (!S->getParent())
2879 Ctx = Context.getTranslationUnitDecl();
2880
2881 if (Ctx && Ctx->isFileContext()) {
2882 // We only want to see those namespaces that have already been defined
2883 // within this scope, because its likely that the user is creating an
2884 // extended namespace declaration. Keep track of the most recent
2885 // definition of each namespace.
2886 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
2887 for (DeclContext::specific_decl_iterator<NamespaceDecl>
2888 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
2889 NS != NSEnd; ++NS)
2890 OrigToLatest[NS->getOriginalNamespace()] = *NS;
2891
2892 // Add the most recent definition (or extended definition) of each
2893 // namespace to the list of results.
Douglas Gregor64b12b52009-09-22 23:31:26 +00002894 Results.EnterNewScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002895 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
2896 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
2897 NS != NSEnd; ++NS)
Douglas Gregorfc59ce12010-01-14 16:14:35 +00002898 Results.AddResult(CodeCompleteConsumer::Result(NS->second, 0),
2899 CurContext, 0, false);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002900 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002901 }
2902
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002903 HandleCodeCompleteResults(this, CodeCompleter,
2904 CodeCompletionContext::CCC_Other,
2905 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002906}
2907
2908void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
2909 if (!CodeCompleter)
2910 return;
2911
Douglas Gregor3545ff42009-09-21 16:56:56 +00002912 // After "namespace", we expect to see a namespace or alias.
2913 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002914 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00002915 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2916 CodeCompleter->includeGlobals());
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002917 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00002918 CodeCompletionContext::CCC_Namespace,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002919 Results.data(),Results.size());
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002920}
2921
Douglas Gregorc811ede2009-09-18 20:05:18 +00002922void Sema::CodeCompleteOperatorName(Scope *S) {
2923 if (!CodeCompleter)
2924 return;
Douglas Gregor3545ff42009-09-21 16:56:56 +00002925
2926 typedef CodeCompleteConsumer::Result Result;
2927 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002928 Results.EnterNewScope();
Douglas Gregorc811ede2009-09-18 20:05:18 +00002929
Douglas Gregor3545ff42009-09-21 16:56:56 +00002930 // Add the names of overloadable operators.
2931#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2932 if (std::strcmp(Spelling, "?")) \
Douglas Gregor78a21012010-01-14 16:01:26 +00002933 Results.AddResult(Result(Spelling));
Douglas Gregor3545ff42009-09-21 16:56:56 +00002934#include "clang/Basic/OperatorKinds.def"
2935
2936 // Add any type names visible from the current scope
Douglas Gregor6ae4c522010-01-14 03:21:49 +00002937 Results.allowNestedNameSpecifiers();
Douglas Gregora6e2edc2010-01-14 03:27:13 +00002938 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor39982192010-08-15 06:18:01 +00002939 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2940 CodeCompleter->includeGlobals());
Douglas Gregor3545ff42009-09-21 16:56:56 +00002941
2942 // Add any type specifiers
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002943 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor64b12b52009-09-22 23:31:26 +00002944 Results.ExitScope();
Douglas Gregor3545ff42009-09-21 16:56:56 +00002945
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002946 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor39982192010-08-15 06:18:01 +00002947 CodeCompletionContext::CCC_Type,
Douglas Gregor00c37ef2010-08-11 21:23:17 +00002948 Results.data(),Results.size());
Douglas Gregorc811ede2009-09-18 20:05:18 +00002949}
Douglas Gregor7e90c6d2009-09-18 19:03:04 +00002950
Douglas Gregorf1934162010-01-13 21:24:21 +00002951// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
2952// true or false.
2953#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002954static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00002955 ResultBuilder &Results,
2956 bool NeedAt) {
2957 typedef CodeCompleteConsumer::Result Result;
2958 // Since we have an implementation, we can end it.
Douglas Gregor78a21012010-01-14 16:01:26 +00002959 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002960
2961 CodeCompletionString *Pattern = 0;
2962 if (LangOpts.ObjC2) {
2963 // @dynamic
2964 Pattern = new CodeCompletionString;
2965 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
2966 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2967 Pattern->AddPlaceholderChunk("property");
Douglas Gregor78a21012010-01-14 16:01:26 +00002968 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002969
2970 // @synthesize
2971 Pattern = new CodeCompletionString;
2972 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
2973 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2974 Pattern->AddPlaceholderChunk("property");
Douglas Gregor78a21012010-01-14 16:01:26 +00002975 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00002976 }
2977}
2978
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002979static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorf1934162010-01-13 21:24:21 +00002980 ResultBuilder &Results,
2981 bool NeedAt) {
2982 typedef CodeCompleteConsumer::Result Result;
2983
2984 // Since we have an interface or protocol, we can end it.
Douglas Gregor78a21012010-01-14 16:01:26 +00002985 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002986
2987 if (LangOpts.ObjC2) {
2988 // @property
Douglas Gregor78a21012010-01-14 16:01:26 +00002989 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002990
2991 // @required
Douglas Gregor78a21012010-01-14 16:01:26 +00002992 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002993
2994 // @optional
Douglas Gregor78a21012010-01-14 16:01:26 +00002995 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorf1934162010-01-13 21:24:21 +00002996 }
2997}
2998
Douglas Gregorf98e6a22010-01-13 23:51:12 +00002999static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregorf1934162010-01-13 21:24:21 +00003000 typedef CodeCompleteConsumer::Result Result;
3001 CodeCompletionString *Pattern = 0;
3002
3003 // @class name ;
3004 Pattern = new CodeCompletionString;
3005 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3006 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorf4c33342010-05-28 00:22:41 +00003007 Pattern->AddPlaceholderChunk("name");
Douglas Gregor78a21012010-01-14 16:01:26 +00003008 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00003009
Douglas Gregorf4c33342010-05-28 00:22:41 +00003010 if (Results.includeCodePatterns()) {
3011 // @interface name
3012 // FIXME: Could introduce the whole pattern, including superclasses and
3013 // such.
3014 Pattern = new CodeCompletionString;
3015 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
3016 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3017 Pattern->AddPlaceholderChunk("class");
3018 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00003019
Douglas Gregorf4c33342010-05-28 00:22:41 +00003020 // @protocol name
3021 Pattern = new CodeCompletionString;
3022 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3023 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3024 Pattern->AddPlaceholderChunk("protocol");
3025 Results.AddResult(Result(Pattern));
3026
3027 // @implementation name
3028 Pattern = new CodeCompletionString;
3029 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
3030 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3031 Pattern->AddPlaceholderChunk("class");
3032 Results.AddResult(Result(Pattern));
3033 }
Douglas Gregorf1934162010-01-13 21:24:21 +00003034
3035 // @compatibility_alias name
3036 Pattern = new CodeCompletionString;
3037 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
3038 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3039 Pattern->AddPlaceholderChunk("alias");
3040 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3041 Pattern->AddPlaceholderChunk("class");
Douglas Gregor78a21012010-01-14 16:01:26 +00003042 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00003043}
3044
Douglas Gregorf48706c2009-12-07 09:27:33 +00003045void Sema::CodeCompleteObjCAtDirective(Scope *S, DeclPtrTy ObjCImpDecl,
3046 bool InInterface) {
3047 typedef CodeCompleteConsumer::Result Result;
3048 ResultBuilder Results(*this);
3049 Results.EnterNewScope();
Douglas Gregorf1934162010-01-13 21:24:21 +00003050 if (ObjCImpDecl)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003051 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00003052 else if (InInterface)
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003053 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorf1934162010-01-13 21:24:21 +00003054 else
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003055 AddObjCTopLevelResults(Results, false);
Douglas Gregorf48706c2009-12-07 09:27:33 +00003056 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003057 HandleCodeCompleteResults(this, CodeCompleter,
3058 CodeCompletionContext::CCC_Other,
3059 Results.data(),Results.size());
Douglas Gregorf48706c2009-12-07 09:27:33 +00003060}
3061
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003062static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003063 typedef CodeCompleteConsumer::Result Result;
3064 CodeCompletionString *Pattern = 0;
3065
3066 // @encode ( type-name )
3067 Pattern = new CodeCompletionString;
Douglas Gregorf1934162010-01-13 21:24:21 +00003068 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003069 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3070 Pattern->AddPlaceholderChunk("type-name");
3071 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor78a21012010-01-14 16:01:26 +00003072 Results.AddResult(Result(Pattern));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003073
3074 // @protocol ( protocol-name )
3075 Pattern = new CodeCompletionString;
Douglas Gregorf1934162010-01-13 21:24:21 +00003076 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003077 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3078 Pattern->AddPlaceholderChunk("protocol-name");
3079 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor78a21012010-01-14 16:01:26 +00003080 Results.AddResult(Result(Pattern));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003081
3082 // @selector ( selector )
3083 Pattern = new CodeCompletionString;
Douglas Gregorf1934162010-01-13 21:24:21 +00003084 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003085 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3086 Pattern->AddPlaceholderChunk("selector");
3087 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregor78a21012010-01-14 16:01:26 +00003088 Results.AddResult(Result(Pattern));
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003089}
3090
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003091static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003092 typedef CodeCompleteConsumer::Result Result;
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003093 CodeCompletionString *Pattern = 0;
Douglas Gregorf1934162010-01-13 21:24:21 +00003094
Douglas Gregorf4c33342010-05-28 00:22:41 +00003095 if (Results.includeCodePatterns()) {
3096 // @try { statements } @catch ( declaration ) { statements } @finally
3097 // { statements }
3098 Pattern = new CodeCompletionString;
3099 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
3100 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3101 Pattern->AddPlaceholderChunk("statements");
3102 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3103 Pattern->AddTextChunk("@catch");
3104 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3105 Pattern->AddPlaceholderChunk("parameter");
3106 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3107 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3108 Pattern->AddPlaceholderChunk("statements");
3109 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3110 Pattern->AddTextChunk("@finally");
3111 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3112 Pattern->AddPlaceholderChunk("statements");
3113 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3114 Results.AddResult(Result(Pattern));
3115 }
Douglas Gregorf1934162010-01-13 21:24:21 +00003116
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003117 // @throw
3118 Pattern = new CodeCompletionString;
Douglas Gregorf1934162010-01-13 21:24:21 +00003119 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
Douglas Gregor6a803932010-01-12 06:38:28 +00003120 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003121 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor78a21012010-01-14 16:01:26 +00003122 Results.AddResult(Result(Pattern));
Douglas Gregorf1934162010-01-13 21:24:21 +00003123
Douglas Gregorf4c33342010-05-28 00:22:41 +00003124 if (Results.includeCodePatterns()) {
3125 // @synchronized ( expression ) { statements }
3126 Pattern = new CodeCompletionString;
3127 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3128 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3129 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3130 Pattern->AddPlaceholderChunk("expression");
3131 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3132 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3133 Pattern->AddPlaceholderChunk("statements");
3134 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3135 Results.AddResult(Result(Pattern));
3136 }
Douglas Gregorf1934162010-01-13 21:24:21 +00003137}
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003138
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003139static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregor48d46252010-01-13 21:54:15 +00003140 ResultBuilder &Results,
3141 bool NeedAt) {
Douglas Gregorf1934162010-01-13 21:24:21 +00003142 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor78a21012010-01-14 16:01:26 +00003143 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3144 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3145 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregor48d46252010-01-13 21:54:15 +00003146 if (LangOpts.ObjC2)
Douglas Gregor78a21012010-01-14 16:01:26 +00003147 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregor48d46252010-01-13 21:54:15 +00003148}
3149
3150void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
3151 ResultBuilder Results(*this);
3152 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003153 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregor48d46252010-01-13 21:54:15 +00003154 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003155 HandleCodeCompleteResults(this, CodeCompleter,
3156 CodeCompletionContext::CCC_Other,
3157 Results.data(),Results.size());
Douglas Gregor48d46252010-01-13 21:54:15 +00003158}
3159
3160void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorf1934162010-01-13 21:24:21 +00003161 ResultBuilder Results(*this);
3162 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003163 AddObjCStatementResults(Results, false);
3164 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003165 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003166 HandleCodeCompleteResults(this, CodeCompleter,
3167 CodeCompletionContext::CCC_Other,
3168 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003169}
3170
3171void Sema::CodeCompleteObjCAtExpression(Scope *S) {
3172 ResultBuilder Results(*this);
3173 Results.EnterNewScope();
Douglas Gregorf98e6a22010-01-13 23:51:12 +00003174 AddObjCExpressionResults(Results, false);
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003175 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003176 HandleCodeCompleteResults(this, CodeCompleter,
3177 CodeCompletionContext::CCC_Other,
3178 Results.data(),Results.size());
Douglas Gregorbc7c5e42009-12-07 09:51:25 +00003179}
3180
Douglas Gregore6078da2009-11-19 00:14:45 +00003181/// \brief Determine whether the addition of the given flag to an Objective-C
3182/// property's attributes will cause a conflict.
3183static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3184 // Check if we've already added this flag.
3185 if (Attributes & NewFlag)
3186 return true;
3187
3188 Attributes |= NewFlag;
3189
3190 // Check for collisions with "readonly".
3191 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3192 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3193 ObjCDeclSpec::DQ_PR_assign |
3194 ObjCDeclSpec::DQ_PR_copy |
3195 ObjCDeclSpec::DQ_PR_retain)))
3196 return true;
3197
3198 // Check for more than one of { assign, copy, retain }.
3199 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3200 ObjCDeclSpec::DQ_PR_copy |
3201 ObjCDeclSpec::DQ_PR_retain);
3202 if (AssignCopyRetMask &&
3203 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3204 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3205 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3206 return true;
3207
3208 return false;
3209}
3210
Douglas Gregor36029f42009-11-18 23:08:07 +00003211void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroff936354c2009-10-08 21:55:05 +00003212 if (!CodeCompleter)
3213 return;
Douglas Gregor1b605f72009-11-19 01:08:35 +00003214
Steve Naroff936354c2009-10-08 21:55:05 +00003215 unsigned Attributes = ODS.getPropertyAttributes();
3216
3217 typedef CodeCompleteConsumer::Result Result;
3218 ResultBuilder Results(*this);
3219 Results.EnterNewScope();
Douglas Gregore6078da2009-11-19 00:14:45 +00003220 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
Douglas Gregor78a21012010-01-14 16:01:26 +00003221 Results.AddResult(CodeCompleteConsumer::Result("readonly"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003222 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
Douglas Gregor78a21012010-01-14 16:01:26 +00003223 Results.AddResult(CodeCompleteConsumer::Result("assign"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003224 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
Douglas Gregor78a21012010-01-14 16:01:26 +00003225 Results.AddResult(CodeCompleteConsumer::Result("readwrite"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003226 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
Douglas Gregor78a21012010-01-14 16:01:26 +00003227 Results.AddResult(CodeCompleteConsumer::Result("retain"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003228 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
Douglas Gregor78a21012010-01-14 16:01:26 +00003229 Results.AddResult(CodeCompleteConsumer::Result("copy"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003230 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
Douglas Gregor78a21012010-01-14 16:01:26 +00003231 Results.AddResult(CodeCompleteConsumer::Result("nonatomic"));
Douglas Gregore6078da2009-11-19 00:14:45 +00003232 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor45f83ee2009-11-19 00:01:57 +00003233 CodeCompletionString *Setter = new CodeCompletionString;
3234 Setter->AddTypedTextChunk("setter");
3235 Setter->AddTextChunk(" = ");
3236 Setter->AddPlaceholderChunk("method");
Douglas Gregor78a21012010-01-14 16:01:26 +00003237 Results.AddResult(CodeCompleteConsumer::Result(Setter));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00003238 }
Douglas Gregore6078da2009-11-19 00:14:45 +00003239 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor45f83ee2009-11-19 00:01:57 +00003240 CodeCompletionString *Getter = new CodeCompletionString;
3241 Getter->AddTypedTextChunk("getter");
3242 Getter->AddTextChunk(" = ");
3243 Getter->AddPlaceholderChunk("method");
Douglas Gregor78a21012010-01-14 16:01:26 +00003244 Results.AddResult(CodeCompleteConsumer::Result(Getter));
Douglas Gregor45f83ee2009-11-19 00:01:57 +00003245 }
Steve Naroff936354c2009-10-08 21:55:05 +00003246 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003247 HandleCodeCompleteResults(this, CodeCompleter,
3248 CodeCompletionContext::CCC_Other,
3249 Results.data(),Results.size());
Steve Naroff936354c2009-10-08 21:55:05 +00003250}
Steve Naroffeae65032009-11-07 02:08:14 +00003251
Douglas Gregorc8537c52009-11-19 07:41:15 +00003252/// \brief Descripts the kind of Objective-C method that we want to find
3253/// via code completion.
3254enum ObjCMethodKind {
3255 MK_Any, //< Any kind of method, provided it means other specified criteria.
3256 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3257 MK_OneArgSelector //< One-argument selector.
3258};
3259
3260static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
3261 ObjCMethodKind WantKind,
3262 IdentifierInfo **SelIdents,
3263 unsigned NumSelIdents) {
3264 Selector Sel = Method->getSelector();
3265 if (NumSelIdents > Sel.getNumArgs())
3266 return false;
3267
3268 switch (WantKind) {
3269 case MK_Any: break;
3270 case MK_ZeroArgSelector: return Sel.isUnarySelector();
3271 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
3272 }
3273
3274 for (unsigned I = 0; I != NumSelIdents; ++I)
3275 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
3276 return false;
3277
3278 return true;
3279}
3280
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003281/// \brief Add all of the Objective-C methods in the given Objective-C
3282/// container to the set of results.
3283///
3284/// The container will be a class, protocol, category, or implementation of
3285/// any of the above. This mether will recurse to include methods from
3286/// the superclasses of classes along with their categories, protocols, and
3287/// implementations.
3288///
3289/// \param Container the container in which we'll look to find methods.
3290///
3291/// \param WantInstance whether to add instance methods (only); if false, this
3292/// routine will add factory methods (only).
3293///
3294/// \param CurContext the context in which we're performing the lookup that
3295/// finds methods.
3296///
3297/// \param Results the structure into which we'll add results.
3298static void AddObjCMethods(ObjCContainerDecl *Container,
3299 bool WantInstanceMethods,
Douglas Gregorc8537c52009-11-19 07:41:15 +00003300 ObjCMethodKind WantKind,
Douglas Gregor1b605f72009-11-19 01:08:35 +00003301 IdentifierInfo **SelIdents,
3302 unsigned NumSelIdents,
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003303 DeclContext *CurContext,
3304 ResultBuilder &Results) {
3305 typedef CodeCompleteConsumer::Result Result;
3306 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3307 MEnd = Container->meth_end();
3308 M != MEnd; ++M) {
Douglas Gregor1b605f72009-11-19 01:08:35 +00003309 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3310 // Check whether the selector identifiers we've been given are a
3311 // subset of the identifiers for this particular method.
Douglas Gregorc8537c52009-11-19 07:41:15 +00003312 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregor1b605f72009-11-19 01:08:35 +00003313 continue;
Douglas Gregorc8537c52009-11-19 07:41:15 +00003314
Douglas Gregor1b605f72009-11-19 01:08:35 +00003315 Result R = Result(*M, 0);
3316 R.StartParameter = NumSelIdents;
Douglas Gregorc8537c52009-11-19 07:41:15 +00003317 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor1b605f72009-11-19 01:08:35 +00003318 Results.MaybeAddResult(R, CurContext);
3319 }
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003320 }
3321
3322 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
3323 if (!IFace)
3324 return;
3325
3326 // Add methods in protocols.
3327 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
3328 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3329 E = Protocols.end();
3330 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00003331 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregor1b605f72009-11-19 01:08:35 +00003332 CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003333
3334 // Add methods in categories.
3335 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
3336 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregorc8537c52009-11-19 07:41:15 +00003337 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
3338 NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003339
3340 // Add a categories protocol methods.
3341 const ObjCList<ObjCProtocolDecl> &Protocols
3342 = CatDecl->getReferencedProtocols();
3343 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3344 E = Protocols.end();
3345 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00003346 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
3347 NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003348
3349 // Add methods in category implementations.
3350 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00003351 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3352 NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003353 }
3354
3355 // Add methods in superclass.
3356 if (IFace->getSuperClass())
Douglas Gregorc8537c52009-11-19 07:41:15 +00003357 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
3358 SelIdents, NumSelIdents, CurContext, Results);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003359
3360 // Add methods in our implementation, if any.
3361 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregorc8537c52009-11-19 07:41:15 +00003362 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
3363 NumSelIdents, CurContext, Results);
3364}
3365
3366
3367void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
3368 DeclPtrTy *Methods,
3369 unsigned NumMethods) {
3370 typedef CodeCompleteConsumer::Result Result;
3371
3372 // Try to find the interface where getters might live.
3373 ObjCInterfaceDecl *Class
3374 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
3375 if (!Class) {
3376 if (ObjCCategoryDecl *Category
3377 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
3378 Class = Category->getClassInterface();
3379
3380 if (!Class)
3381 return;
3382 }
3383
3384 // Find all of the potential getters.
3385 ResultBuilder Results(*this);
3386 Results.EnterNewScope();
3387
3388 // FIXME: We need to do this because Objective-C methods don't get
3389 // pushed into DeclContexts early enough. Argh!
3390 for (unsigned I = 0; I != NumMethods; ++I) {
3391 if (ObjCMethodDecl *Method
3392 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3393 if (Method->isInstanceMethod() &&
3394 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
3395 Result R = Result(Method, 0);
3396 R.AllParametersAreInformative = true;
3397 Results.MaybeAddResult(R, CurContext);
3398 }
3399 }
3400
3401 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
3402 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003403 HandleCodeCompleteResults(this, CodeCompleter,
3404 CodeCompletionContext::CCC_Other,
3405 Results.data(),Results.size());
Douglas Gregorc8537c52009-11-19 07:41:15 +00003406}
3407
3408void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
3409 DeclPtrTy *Methods,
3410 unsigned NumMethods) {
3411 typedef CodeCompleteConsumer::Result Result;
3412
3413 // Try to find the interface where setters might live.
3414 ObjCInterfaceDecl *Class
3415 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
3416 if (!Class) {
3417 if (ObjCCategoryDecl *Category
3418 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
3419 Class = Category->getClassInterface();
3420
3421 if (!Class)
3422 return;
3423 }
3424
3425 // Find all of the potential getters.
3426 ResultBuilder Results(*this);
3427 Results.EnterNewScope();
3428
3429 // FIXME: We need to do this because Objective-C methods don't get
3430 // pushed into DeclContexts early enough. Argh!
3431 for (unsigned I = 0; I != NumMethods; ++I) {
3432 if (ObjCMethodDecl *Method
3433 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
3434 if (Method->isInstanceMethod() &&
3435 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
3436 Result R = Result(Method, 0);
3437 R.AllParametersAreInformative = true;
3438 Results.MaybeAddResult(R, CurContext);
3439 }
3440 }
3441
3442 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
3443
3444 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003445 HandleCodeCompleteResults(this, CodeCompleter,
3446 CodeCompletionContext::CCC_Other,
3447 Results.data(),Results.size());
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003448}
3449
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00003450/// \brief When we have an expression with type "id", we may assume
3451/// that it has some more-specific class type based on knowledge of
3452/// common uses of Objective-C. This routine returns that class type,
3453/// or NULL if no better result could be determined.
3454static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
3455 ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E);
3456 if (!Msg)
3457 return 0;
3458
3459 Selector Sel = Msg->getSelector();
3460 if (Sel.isNull())
3461 return 0;
3462
3463 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
3464 if (!Id)
3465 return 0;
3466
3467 ObjCMethodDecl *Method = Msg->getMethodDecl();
3468 if (!Method)
3469 return 0;
3470
3471 // Determine the class that we're sending the message to.
Douglas Gregor9a129192010-04-21 00:45:42 +00003472 ObjCInterfaceDecl *IFace = 0;
3473 switch (Msg->getReceiverKind()) {
3474 case ObjCMessageExpr::Class:
John McCall8b07ec22010-05-15 11:32:37 +00003475 if (const ObjCObjectType *ObjType
3476 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
3477 IFace = ObjType->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00003478 break;
3479
3480 case ObjCMessageExpr::Instance: {
3481 QualType T = Msg->getInstanceReceiver()->getType();
3482 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
3483 IFace = Ptr->getInterfaceDecl();
3484 break;
3485 }
3486
3487 case ObjCMessageExpr::SuperInstance:
3488 case ObjCMessageExpr::SuperClass:
3489 break;
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00003490 }
3491
3492 if (!IFace)
3493 return 0;
3494
3495 ObjCInterfaceDecl *Super = IFace->getSuperClass();
3496 if (Method->isInstanceMethod())
3497 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3498 .Case("retain", IFace)
3499 .Case("autorelease", IFace)
3500 .Case("copy", IFace)
3501 .Case("copyWithZone", IFace)
3502 .Case("mutableCopy", IFace)
3503 .Case("mutableCopyWithZone", IFace)
3504 .Case("awakeFromCoder", IFace)
3505 .Case("replacementObjectFromCoder", IFace)
3506 .Case("class", IFace)
3507 .Case("classForCoder", IFace)
3508 .Case("superclass", Super)
3509 .Default(0);
3510
3511 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3512 .Case("new", IFace)
3513 .Case("alloc", IFace)
3514 .Case("allocWithZone", IFace)
3515 .Case("class", IFace)
3516 .Case("superclass", Super)
3517 .Default(0);
3518}
3519
Douglas Gregora817a192010-05-27 23:06:34 +00003520void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
3521 typedef CodeCompleteConsumer::Result Result;
3522 ResultBuilder Results(*this);
3523
3524 // Find anything that looks like it could be a message receiver.
3525 Results.setFilter(&ResultBuilder::IsObjCMessageReceiver);
3526 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3527 Results.EnterNewScope();
Douglas Gregor39982192010-08-15 06:18:01 +00003528 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3529 CodeCompleter->includeGlobals());
Douglas Gregora817a192010-05-27 23:06:34 +00003530
3531 // If we are in an Objective-C method inside a class that has a superclass,
3532 // add "super" as an option.
3533 if (ObjCMethodDecl *Method = getCurMethodDecl())
3534 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
3535 if (Iface->getSuperClass())
3536 Results.AddResult(Result("super"));
3537
3538 Results.ExitScope();
3539
3540 if (CodeCompleter->includeMacros())
3541 AddMacroResults(PP, Results);
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003542 HandleCodeCompleteResults(this, CodeCompleter,
3543 CodeCompletionContext::CCC_ObjCMessageReceiver,
3544 Results.data(), Results.size());
Douglas Gregora817a192010-05-27 23:06:34 +00003545
3546}
3547
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003548void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
3549 IdentifierInfo **SelIdents,
3550 unsigned NumSelIdents) {
3551 ObjCInterfaceDecl *CDecl = 0;
3552 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3553 // Figure out which interface we're in.
3554 CDecl = CurMethod->getClassInterface();
3555 if (!CDecl)
3556 return;
3557
3558 // Find the superclass of this class.
3559 CDecl = CDecl->getSuperClass();
3560 if (!CDecl)
3561 return;
3562
3563 if (CurMethod->isInstanceMethod()) {
3564 // We are inside an instance method, which means that the message
3565 // send [super ...] is actually calling an instance method on the
3566 // current object. Build the super expression and handle this like
3567 // an instance method.
3568 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
3569 SuperTy = Context.getObjCObjectPointerType(SuperTy);
3570 OwningExprResult Super
3571 = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
3572 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
3573 SelIdents, NumSelIdents);
3574 }
3575
3576 // Fall through to send to the superclass in CDecl.
3577 } else {
3578 // "super" may be the name of a type or variable. Figure out which
3579 // it is.
3580 IdentifierInfo *Super = &Context.Idents.get("super");
3581 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
3582 LookupOrdinaryName);
3583 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
3584 // "super" names an interface. Use it.
3585 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCall8b07ec22010-05-15 11:32:37 +00003586 if (const ObjCObjectType *Iface
3587 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
3588 CDecl = Iface->getInterface();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003589 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
3590 // "super" names an unresolved type; we can't be more specific.
3591 } else {
3592 // Assume that "super" names some kind of value and parse that way.
3593 CXXScopeSpec SS;
3594 UnqualifiedId id;
3595 id.setIdentifier(Super, SuperLoc);
3596 OwningExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
3597 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
3598 SelIdents, NumSelIdents);
3599 }
3600
3601 // Fall through
3602 }
3603
3604 TypeTy *Receiver = 0;
3605 if (CDecl)
3606 Receiver = Context.getObjCInterfaceType(CDecl).getAsOpaquePtr();
3607 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
3608 NumSelIdents);
3609}
3610
3611void Sema::CodeCompleteObjCClassMessage(Scope *S, TypeTy *Receiver,
Douglas Gregor1b605f72009-11-19 01:08:35 +00003612 IdentifierInfo **SelIdents,
3613 unsigned NumSelIdents) {
Steve Naroffeae65032009-11-07 02:08:14 +00003614 typedef CodeCompleteConsumer::Result Result;
Douglas Gregor8ce33212009-11-17 17:59:40 +00003615 ObjCInterfaceDecl *CDecl = 0;
3616
Douglas Gregor8ce33212009-11-17 17:59:40 +00003617 // If the given name refers to an interface type, retrieve the
3618 // corresponding declaration.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003619 if (Receiver) {
3620 QualType T = GetTypeFromParser(Receiver, 0);
3621 if (!T.isNull())
John McCall8b07ec22010-05-15 11:32:37 +00003622 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
3623 CDecl = Interface->getInterface();
Douglas Gregor8ce33212009-11-17 17:59:40 +00003624 }
3625
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003626 // Add all of the factory methods in this Objective-C class, its protocols,
3627 // superclasses, categories, implementation, etc.
Steve Naroffeae65032009-11-07 02:08:14 +00003628 ResultBuilder Results(*this);
3629 Results.EnterNewScope();
Douglas Gregor6285f752010-04-06 16:40:00 +00003630
3631 if (CDecl)
3632 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
3633 Results);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003634 else {
Douglas Gregor6285f752010-04-06 16:40:00 +00003635 // We're messaging "id" as a type; provide all class/factory methods.
3636
Douglas Gregord720daf2010-04-06 17:30:22 +00003637 // If we have an external source, load the entire class method
3638 // pool from the PCH file.
3639 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00003640 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3641 I != N; ++I) {
3642 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00003643 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00003644 continue;
3645
Sebastian Redl75d8a322010-08-02 23:18:59 +00003646 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00003647 }
3648 }
3649
Sebastian Redl75d8a322010-08-02 23:18:59 +00003650 for (GlobalMethodPool::iterator M = MethodPool.begin(),
3651 MEnd = MethodPool.end();
3652 M != MEnd; ++M) {
3653 for (ObjCMethodList *MethList = &M->second.second;
3654 MethList && MethList->Method;
Douglas Gregor6285f752010-04-06 16:40:00 +00003655 MethList = MethList->Next) {
3656 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3657 NumSelIdents))
3658 continue;
3659
3660 Result R(MethList->Method, 0);
3661 R.StartParameter = NumSelIdents;
3662 R.AllParametersAreInformative = false;
3663 Results.MaybeAddResult(R, CurContext);
3664 }
3665 }
3666 }
3667
Steve Naroffeae65032009-11-07 02:08:14 +00003668 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003669 HandleCodeCompleteResults(this, CodeCompleter,
3670 CodeCompletionContext::CCC_Other,
3671 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00003672}
3673
Douglas Gregor1b605f72009-11-19 01:08:35 +00003674void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
3675 IdentifierInfo **SelIdents,
3676 unsigned NumSelIdents) {
Steve Naroffeae65032009-11-07 02:08:14 +00003677 typedef CodeCompleteConsumer::Result Result;
Steve Naroffeae65032009-11-07 02:08:14 +00003678
3679 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffeae65032009-11-07 02:08:14 +00003680
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003681 // If necessary, apply function/array conversion to the receiver.
3682 // C99 6.7.5.3p[7,8].
Douglas Gregorb92a1562010-02-03 00:27:59 +00003683 DefaultFunctionArrayLvalueConversion(RecExpr);
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003684 QualType ReceiverType = RecExpr->getType();
Steve Naroffeae65032009-11-07 02:08:14 +00003685
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003686 // Build the set of methods we can see.
3687 ResultBuilder Results(*this);
3688 Results.EnterNewScope();
Douglas Gregor9d2ddb22010-04-06 19:22:33 +00003689
3690 // If we're messaging an expression with type "id" or "Class", check
3691 // whether we know something special about the receiver that allows
3692 // us to assume a more-specific receiver type.
3693 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
3694 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
3695 ReceiverType = Context.getObjCObjectPointerType(
3696 Context.getObjCInterfaceType(IFace));
Douglas Gregorbab2b3c2009-11-17 23:22:23 +00003697
Douglas Gregora3329fa2009-11-18 00:06:18 +00003698 // Handle messages to Class. This really isn't a message to an instance
3699 // method, so we treat it the same way we would treat a message send to a
3700 // class method.
3701 if (ReceiverType->isObjCClassType() ||
3702 ReceiverType->isObjCQualifiedClassType()) {
3703 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3704 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregorc8537c52009-11-19 07:41:15 +00003705 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
3706 CurContext, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00003707 }
3708 }
3709 // Handle messages to a qualified ID ("id<foo>").
3710 else if (const ObjCObjectPointerType *QualID
3711 = ReceiverType->getAsObjCQualifiedIdType()) {
3712 // Search protocols for instance methods.
3713 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
3714 E = QualID->qual_end();
3715 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00003716 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3717 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00003718 }
3719 // Handle messages to a pointer to interface type.
3720 else if (const ObjCObjectPointerType *IFacePtr
3721 = ReceiverType->getAsObjCInterfacePointerType()) {
3722 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregorc8537c52009-11-19 07:41:15 +00003723 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
3724 NumSelIdents, CurContext, Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00003725
3726 // Search protocols for instance methods.
3727 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
3728 E = IFacePtr->qual_end();
3729 I != E; ++I)
Douglas Gregorc8537c52009-11-19 07:41:15 +00003730 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3731 Results);
Douglas Gregora3329fa2009-11-18 00:06:18 +00003732 }
Douglas Gregor6285f752010-04-06 16:40:00 +00003733 // Handle messages to "id".
3734 else if (ReceiverType->isObjCIdType()) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003735 // We're messaging "id", so provide all instance methods we know
3736 // about as code-completion results.
3737
3738 // If we have an external source, load the entire class method
3739 // pool from the PCH file.
3740 if (ExternalSource) {
John McCall75b960e2010-06-01 09:23:16 +00003741 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
3742 I != N; ++I) {
3743 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00003744 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregord720daf2010-04-06 17:30:22 +00003745 continue;
3746
Sebastian Redl75d8a322010-08-02 23:18:59 +00003747 ReadMethodPool(Sel);
Douglas Gregord720daf2010-04-06 17:30:22 +00003748 }
3749 }
3750
Sebastian Redl75d8a322010-08-02 23:18:59 +00003751 for (GlobalMethodPool::iterator M = MethodPool.begin(),
3752 MEnd = MethodPool.end();
3753 M != MEnd; ++M) {
3754 for (ObjCMethodList *MethList = &M->second.first;
3755 MethList && MethList->Method;
Douglas Gregor6285f752010-04-06 16:40:00 +00003756 MethList = MethList->Next) {
3757 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
3758 NumSelIdents))
3759 continue;
3760
3761 Result R(MethList->Method, 0);
3762 R.StartParameter = NumSelIdents;
3763 R.AllParametersAreInformative = false;
3764 Results.MaybeAddResult(R, CurContext);
3765 }
3766 }
3767 }
3768
Steve Naroffeae65032009-11-07 02:08:14 +00003769 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003770 HandleCodeCompleteResults(this, CodeCompleter,
3771 CodeCompletionContext::CCC_Other,
3772 Results.data(),Results.size());
Steve Naroffeae65032009-11-07 02:08:14 +00003773}
Douglas Gregorbaf69612009-11-18 04:19:12 +00003774
3775/// \brief Add all of the protocol declarations that we find in the given
3776/// (translation unit) context.
3777static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor5b4671c2009-11-18 04:49:41 +00003778 bool OnlyForwardDeclarations,
Douglas Gregorbaf69612009-11-18 04:19:12 +00003779 ResultBuilder &Results) {
3780 typedef CodeCompleteConsumer::Result Result;
3781
3782 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3783 DEnd = Ctx->decls_end();
3784 D != DEnd; ++D) {
3785 // Record any protocols we find.
3786 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor5b4671c2009-11-18 04:49:41 +00003787 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003788 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00003789
3790 // Record any forward-declared protocols we find.
3791 if (ObjCForwardProtocolDecl *Forward
3792 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
3793 for (ObjCForwardProtocolDecl::protocol_iterator
3794 P = Forward->protocol_begin(),
3795 PEnd = Forward->protocol_end();
3796 P != PEnd; ++P)
Douglas Gregor5b4671c2009-11-18 04:49:41 +00003797 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003798 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregorbaf69612009-11-18 04:19:12 +00003799 }
3800 }
3801}
3802
3803void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
3804 unsigned NumProtocols) {
3805 ResultBuilder Results(*this);
3806 Results.EnterNewScope();
3807
3808 // Tell the result set to ignore all of the protocols we have
3809 // already seen.
3810 for (unsigned I = 0; I != NumProtocols; ++I)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003811 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
3812 Protocols[I].second))
Douglas Gregorbaf69612009-11-18 04:19:12 +00003813 Results.Ignore(Protocol);
3814
3815 // Add all protocols.
Douglas Gregor5b4671c2009-11-18 04:49:41 +00003816 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
3817 Results);
3818
3819 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003820 HandleCodeCompleteResults(this, CodeCompleter,
3821 CodeCompletionContext::CCC_ObjCProtocolName,
3822 Results.data(),Results.size());
Douglas Gregor5b4671c2009-11-18 04:49:41 +00003823}
3824
3825void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
3826 ResultBuilder Results(*this);
3827 Results.EnterNewScope();
3828
3829 // Add all protocols.
3830 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
3831 Results);
Douglas Gregorbaf69612009-11-18 04:19:12 +00003832
3833 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003834 HandleCodeCompleteResults(this, CodeCompleter,
3835 CodeCompletionContext::CCC_ObjCProtocolName,
3836 Results.data(),Results.size());
Douglas Gregorbaf69612009-11-18 04:19:12 +00003837}
Douglas Gregor49c22a72009-11-18 16:26:39 +00003838
3839/// \brief Add all of the Objective-C interface declarations that we find in
3840/// the given (translation unit) context.
3841static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
3842 bool OnlyForwardDeclarations,
3843 bool OnlyUnimplemented,
3844 ResultBuilder &Results) {
3845 typedef CodeCompleteConsumer::Result Result;
3846
3847 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3848 DEnd = Ctx->decls_end();
3849 D != DEnd; ++D) {
Douglas Gregor1c283312010-08-11 12:19:30 +00003850 // Record any interfaces we find.
3851 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
3852 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
3853 (!OnlyUnimplemented || !Class->getImplementation()))
3854 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00003855
3856 // Record any forward-declared interfaces we find.
3857 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
3858 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregor1c283312010-08-11 12:19:30 +00003859 C != CEnd; ++C)
3860 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
3861 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
3862 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003863 0, false);
Douglas Gregor49c22a72009-11-18 16:26:39 +00003864 }
3865 }
3866}
3867
3868void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
3869 ResultBuilder Results(*this);
3870 Results.EnterNewScope();
3871
3872 // Add all classes.
3873 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
3874 false, Results);
3875
3876 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003877 HandleCodeCompleteResults(this, CodeCompleter,
3878 CodeCompletionContext::CCC_Other,
3879 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00003880}
3881
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003882void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
3883 SourceLocation ClassNameLoc) {
Douglas Gregor49c22a72009-11-18 16:26:39 +00003884 ResultBuilder Results(*this);
3885 Results.EnterNewScope();
3886
3887 // Make sure that we ignore the class we're currently defining.
3888 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003889 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003890 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor49c22a72009-11-18 16:26:39 +00003891 Results.Ignore(CurClass);
3892
3893 // Add all classes.
3894 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3895 false, Results);
3896
3897 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003898 HandleCodeCompleteResults(this, CodeCompleter,
3899 CodeCompletionContext::CCC_Other,
3900 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00003901}
3902
3903void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
3904 ResultBuilder Results(*this);
3905 Results.EnterNewScope();
3906
3907 // Add all unimplemented classes.
3908 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3909 true, Results);
3910
3911 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003912 HandleCodeCompleteResults(this, CodeCompleter,
3913 CodeCompletionContext::CCC_Other,
3914 Results.data(),Results.size());
Douglas Gregor49c22a72009-11-18 16:26:39 +00003915}
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003916
3917void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003918 IdentifierInfo *ClassName,
3919 SourceLocation ClassNameLoc) {
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003920 typedef CodeCompleteConsumer::Result Result;
3921
3922 ResultBuilder Results(*this);
3923
3924 // Ignore any categories we find that have already been implemented by this
3925 // interface.
3926 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3927 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003928 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003929 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
3930 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3931 Category = Category->getNextClassCategory())
3932 CategoryNames.insert(Category->getIdentifier());
3933
3934 // Add all of the categories we know about.
3935 Results.EnterNewScope();
3936 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3937 for (DeclContext::decl_iterator D = TU->decls_begin(),
3938 DEnd = TU->decls_end();
3939 D != DEnd; ++D)
3940 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
3941 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003942 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003943 Results.ExitScope();
3944
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003945 HandleCodeCompleteResults(this, CodeCompleter,
3946 CodeCompletionContext::CCC_Other,
3947 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003948}
3949
3950void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003951 IdentifierInfo *ClassName,
3952 SourceLocation ClassNameLoc) {
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003953 typedef CodeCompleteConsumer::Result Result;
3954
3955 // Find the corresponding interface. If we couldn't find the interface, the
3956 // program itself is ill-formed. However, we'll try to be helpful still by
3957 // providing the list of all of the categories we know about.
3958 NamedDecl *CurClass
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003959 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003960 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
3961 if (!Class)
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003962 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003963
3964 ResultBuilder Results(*this);
3965
3966 // Add all of the categories that have have corresponding interface
3967 // declarations in this class and any of its superclasses, except for
3968 // already-implemented categories in the class itself.
3969 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3970 Results.EnterNewScope();
3971 bool IgnoreImplemented = true;
3972 while (Class) {
3973 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3974 Category = Category->getNextClassCategory())
3975 if ((!IgnoreImplemented || !Category->getImplementation()) &&
3976 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregorfc59ce12010-01-14 16:14:35 +00003977 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003978
3979 Class = Class->getSuperClass();
3980 IgnoreImplemented = false;
3981 }
3982 Results.ExitScope();
3983
Douglas Gregor00c37ef2010-08-11 21:23:17 +00003984 HandleCodeCompleteResults(this, CodeCompleter,
3985 CodeCompletionContext::CCC_Other,
3986 Results.data(),Results.size());
Douglas Gregor5d34fd32009-11-18 19:08:43 +00003987}
Douglas Gregor5d649882009-11-18 22:32:06 +00003988
Douglas Gregor52e78bd2009-11-18 22:56:13 +00003989void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
Douglas Gregor5d649882009-11-18 22:32:06 +00003990 typedef CodeCompleteConsumer::Result Result;
3991 ResultBuilder Results(*this);
3992
3993 // Figure out where this @synthesize lives.
3994 ObjCContainerDecl *Container
3995 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3996 if (!Container ||
3997 (!isa<ObjCImplementationDecl>(Container) &&
3998 !isa<ObjCCategoryImplDecl>(Container)))
3999 return;
4000
4001 // Ignore any properties that have already been implemented.
4002 for (DeclContext::decl_iterator D = Container->decls_begin(),
4003 DEnd = Container->decls_end();
4004 D != DEnd; ++D)
4005 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
4006 Results.Ignore(PropertyImpl->getPropertyDecl());
4007
4008 // Add any properties that we find.
4009 Results.EnterNewScope();
4010 if (ObjCImplementationDecl *ClassImpl
4011 = dyn_cast<ObjCImplementationDecl>(Container))
4012 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
4013 Results);
4014 else
4015 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
4016 false, CurContext, Results);
4017 Results.ExitScope();
4018
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004019 HandleCodeCompleteResults(this, CodeCompleter,
4020 CodeCompletionContext::CCC_Other,
4021 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00004022}
4023
4024void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
4025 IdentifierInfo *PropertyName,
4026 DeclPtrTy ObjCImpDecl) {
4027 typedef CodeCompleteConsumer::Result Result;
4028 ResultBuilder Results(*this);
4029
4030 // Figure out where this @synthesize lives.
4031 ObjCContainerDecl *Container
4032 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
4033 if (!Container ||
4034 (!isa<ObjCImplementationDecl>(Container) &&
4035 !isa<ObjCCategoryImplDecl>(Container)))
4036 return;
4037
4038 // Figure out which interface we're looking into.
4039 ObjCInterfaceDecl *Class = 0;
4040 if (ObjCImplementationDecl *ClassImpl
4041 = dyn_cast<ObjCImplementationDecl>(Container))
4042 Class = ClassImpl->getClassInterface();
4043 else
4044 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
4045 ->getClassInterface();
4046
4047 // Add all of the instance variables in this class and its superclasses.
4048 Results.EnterNewScope();
4049 for(; Class; Class = Class->getSuperClass()) {
4050 // FIXME: We could screen the type of each ivar for compatibility with
4051 // the property, but is that being too paternal?
4052 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
4053 IVarEnd = Class->ivar_end();
4054 IVar != IVarEnd; ++IVar)
Douglas Gregorfc59ce12010-01-14 16:14:35 +00004055 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor5d649882009-11-18 22:32:06 +00004056 }
4057 Results.ExitScope();
4058
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004059 HandleCodeCompleteResults(this, CodeCompleter,
4060 CodeCompletionContext::CCC_Other,
4061 Results.data(),Results.size());
Douglas Gregor5d649882009-11-18 22:32:06 +00004062}
Douglas Gregor636a61e2010-04-07 00:21:17 +00004063
4064typedef llvm::DenseMap<Selector, ObjCMethodDecl *> KnownMethodsMap;
4065
4066/// \brief Find all of the methods that reside in the given container
4067/// (and its superclasses, protocols, etc.) that meet the given
4068/// criteria. Insert those methods into the map of known methods,
4069/// indexed by selector so they can be easily found.
4070static void FindImplementableMethods(ASTContext &Context,
4071 ObjCContainerDecl *Container,
4072 bool WantInstanceMethods,
4073 QualType ReturnType,
4074 bool IsInImplementation,
4075 KnownMethodsMap &KnownMethods) {
4076 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
4077 // Recurse into protocols.
4078 const ObjCList<ObjCProtocolDecl> &Protocols
4079 = IFace->getReferencedProtocols();
4080 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4081 E = Protocols.end();
4082 I != E; ++I)
4083 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
4084 IsInImplementation, KnownMethods);
4085
4086 // If we're not in the implementation of a class, also visit the
4087 // superclass.
4088 if (!IsInImplementation && IFace->getSuperClass())
4089 FindImplementableMethods(Context, IFace->getSuperClass(),
4090 WantInstanceMethods, ReturnType,
4091 IsInImplementation, KnownMethods);
4092
4093 // Add methods from any class extensions (but not from categories;
4094 // those should go into category implementations).
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00004095 for (const ObjCCategoryDecl *Cat = IFace->getFirstClassExtension(); Cat;
4096 Cat = Cat->getNextClassExtension())
4097 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
4098 WantInstanceMethods, ReturnType,
Douglas Gregor636a61e2010-04-07 00:21:17 +00004099 IsInImplementation, KnownMethods);
Douglas Gregor636a61e2010-04-07 00:21:17 +00004100 }
4101
4102 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4103 // Recurse into protocols.
4104 const ObjCList<ObjCProtocolDecl> &Protocols
4105 = Category->getReferencedProtocols();
4106 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4107 E = Protocols.end();
4108 I != E; ++I)
4109 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
4110 IsInImplementation, KnownMethods);
4111 }
4112
4113 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4114 // Recurse into protocols.
4115 const ObjCList<ObjCProtocolDecl> &Protocols
4116 = Protocol->getReferencedProtocols();
4117 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4118 E = Protocols.end();
4119 I != E; ++I)
4120 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
4121 IsInImplementation, KnownMethods);
4122 }
4123
4124 // Add methods in this container. This operation occurs last because
4125 // we want the methods from this container to override any methods
4126 // we've previously seen with the same selector.
4127 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4128 MEnd = Container->meth_end();
4129 M != MEnd; ++M) {
4130 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4131 if (!ReturnType.isNull() &&
4132 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
4133 continue;
4134
4135 KnownMethods[(*M)->getSelector()] = *M;
4136 }
4137 }
4138}
4139
4140void Sema::CodeCompleteObjCMethodDecl(Scope *S,
4141 bool IsInstanceMethod,
4142 TypeTy *ReturnTy,
4143 DeclPtrTy IDecl) {
4144 // Determine the return type of the method we're declaring, if
4145 // provided.
4146 QualType ReturnType = GetTypeFromParser(ReturnTy);
4147
4148 // Determine where we should start searching for methods, and where we
4149 ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
4150 bool IsInImplementation = false;
4151 if (Decl *D = IDecl.getAs<Decl>()) {
4152 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
4153 SearchDecl = Impl->getClassInterface();
4154 CurrentDecl = Impl;
4155 IsInImplementation = true;
4156 } else if (ObjCCategoryImplDecl *CatImpl
4157 = dyn_cast<ObjCCategoryImplDecl>(D)) {
4158 SearchDecl = CatImpl->getCategoryDecl();
4159 CurrentDecl = CatImpl;
4160 IsInImplementation = true;
4161 } else {
4162 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
4163 CurrentDecl = SearchDecl;
4164 }
4165 }
4166
4167 if (!SearchDecl && S) {
4168 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
4169 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
4170 CurrentDecl = SearchDecl;
4171 }
4172 }
4173
4174 if (!SearchDecl || !CurrentDecl) {
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004175 HandleCodeCompleteResults(this, CodeCompleter,
4176 CodeCompletionContext::CCC_Other,
4177 0, 0);
Douglas Gregor636a61e2010-04-07 00:21:17 +00004178 return;
4179 }
4180
4181 // Find all of the methods that we could declare/implement here.
4182 KnownMethodsMap KnownMethods;
4183 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
4184 ReturnType, IsInImplementation, KnownMethods);
4185
4186 // Erase any methods that have already been declared or
4187 // implemented here.
4188 for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
4189 MEnd = CurrentDecl->meth_end();
4190 M != MEnd; ++M) {
4191 if ((*M)->isInstanceMethod() != IsInstanceMethod)
4192 continue;
4193
4194 KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
4195 if (Pos != KnownMethods.end())
4196 KnownMethods.erase(Pos);
4197 }
4198
4199 // Add declarations or definitions for each of the known methods.
4200 typedef CodeCompleteConsumer::Result Result;
4201 ResultBuilder Results(*this);
4202 Results.EnterNewScope();
4203 PrintingPolicy Policy(Context.PrintingPolicy);
4204 Policy.AnonymousTagLocations = false;
4205 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
4206 MEnd = KnownMethods.end();
4207 M != MEnd; ++M) {
4208 ObjCMethodDecl *Method = M->second;
4209 CodeCompletionString *Pattern = new CodeCompletionString;
4210
4211 // If the result type was not already provided, add it to the
4212 // pattern as (type).
4213 if (ReturnType.isNull()) {
4214 std::string TypeStr;
4215 Method->getResultType().getAsStringInternal(TypeStr, Policy);
4216 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4217 Pattern->AddTextChunk(TypeStr);
4218 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4219 }
4220
4221 Selector Sel = Method->getSelector();
4222
4223 // Add the first part of the selector to the pattern.
4224 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4225
4226 // Add parameters to the pattern.
4227 unsigned I = 0;
4228 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4229 PEnd = Method->param_end();
4230 P != PEnd; (void)++P, ++I) {
4231 // Add the part of the selector name.
4232 if (I == 0)
4233 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4234 else if (I < Sel.getNumArgs()) {
4235 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4236 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(1)->getName());
4237 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4238 } else
4239 break;
4240
4241 // Add the parameter type.
4242 std::string TypeStr;
4243 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
4244 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4245 Pattern->AddTextChunk(TypeStr);
4246 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4247
4248 if (IdentifierInfo *Id = (*P)->getIdentifier())
4249 Pattern->AddTextChunk(Id->getName());
4250 }
4251
4252 if (Method->isVariadic()) {
4253 if (Method->param_size() > 0)
4254 Pattern->AddChunk(CodeCompletionString::CK_Comma);
4255 Pattern->AddTextChunk("...");
4256 }
4257
Douglas Gregord37c59d2010-05-28 00:57:46 +00004258 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregor636a61e2010-04-07 00:21:17 +00004259 // We will be defining the method here, so add a compound statement.
4260 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4261 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
4262 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4263 if (!Method->getResultType()->isVoidType()) {
4264 // If the result type is not void, add a return clause.
4265 Pattern->AddTextChunk("return");
4266 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4267 Pattern->AddPlaceholderChunk("expression");
4268 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
4269 } else
4270 Pattern->AddPlaceholderChunk("statements");
4271
4272 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4273 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
4274 }
4275
4276 Results.AddResult(Result(Pattern));
4277 }
4278
4279 Results.ExitScope();
4280
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004281 HandleCodeCompleteResults(this, CodeCompleter,
4282 CodeCompletionContext::CCC_Other,
4283 Results.data(),Results.size());
Douglas Gregor636a61e2010-04-07 00:21:17 +00004284}
Douglas Gregor95887f92010-07-08 23:20:03 +00004285
4286void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
4287 bool IsInstanceMethod,
Douglas Gregor45879692010-07-08 23:37:41 +00004288 bool AtParameterName,
Douglas Gregor95887f92010-07-08 23:20:03 +00004289 TypeTy *ReturnTy,
4290 IdentifierInfo **SelIdents,
4291 unsigned NumSelIdents) {
Douglas Gregor95887f92010-07-08 23:20:03 +00004292 // If we have an external source, load the entire class method
4293 // pool from the PCH file.
4294 if (ExternalSource) {
4295 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4296 I != N; ++I) {
4297 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redl75d8a322010-08-02 23:18:59 +00004298 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor95887f92010-07-08 23:20:03 +00004299 continue;
Sebastian Redl75d8a322010-08-02 23:18:59 +00004300
4301 ReadMethodPool(Sel);
Douglas Gregor95887f92010-07-08 23:20:03 +00004302 }
4303 }
4304
4305 // Build the set of methods we can see.
4306 typedef CodeCompleteConsumer::Result Result;
4307 ResultBuilder Results(*this);
4308
4309 if (ReturnTy)
4310 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redl75d8a322010-08-02 23:18:59 +00004311
Douglas Gregor95887f92010-07-08 23:20:03 +00004312 Results.EnterNewScope();
Sebastian Redl75d8a322010-08-02 23:18:59 +00004313 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4314 MEnd = MethodPool.end();
4315 M != MEnd; ++M) {
4316 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
4317 &M->second.second;
4318 MethList && MethList->Method;
Douglas Gregor95887f92010-07-08 23:20:03 +00004319 MethList = MethList->Next) {
4320 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4321 NumSelIdents))
4322 continue;
4323
Douglas Gregor45879692010-07-08 23:37:41 +00004324 if (AtParameterName) {
4325 // Suggest parameter names we've seen before.
4326 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
4327 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
4328 if (Param->getIdentifier()) {
4329 CodeCompletionString *Pattern = new CodeCompletionString;
4330 Pattern->AddTypedTextChunk(Param->getIdentifier()->getName());
4331 Results.AddResult(Pattern);
4332 }
4333 }
4334
4335 continue;
4336 }
4337
Douglas Gregor95887f92010-07-08 23:20:03 +00004338 Result R(MethList->Method, 0);
4339 R.StartParameter = NumSelIdents;
4340 R.AllParametersAreInformative = false;
4341 R.DeclaringEntity = true;
4342 Results.MaybeAddResult(R, CurContext);
4343 }
4344 }
4345
4346 Results.ExitScope();
Douglas Gregor00c37ef2010-08-11 21:23:17 +00004347 HandleCodeCompleteResults(this, CodeCompleter,
4348 CodeCompletionContext::CCC_Other,
4349 Results.data(),Results.size());
Douglas Gregor95887f92010-07-08 23:20:03 +00004350}
Douglas Gregorb14904c2010-08-13 22:48:40 +00004351
4352void Sema::GatherGlobalCodeCompletions(
4353 llvm::SmallVectorImpl<CodeCompleteConsumer::Result> &Results) {
4354 ResultBuilder Builder(*this);
4355
Douglas Gregor39982192010-08-15 06:18:01 +00004356 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
4357 CodeCompletionDeclConsumer Consumer(Builder,
4358 Context.getTranslationUnitDecl());
4359 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
4360 Consumer);
4361 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00004362
4363 if (!CodeCompleter || CodeCompleter->includeMacros())
4364 AddMacroResults(PP, Builder);
4365
4366 Results.clear();
4367 Results.insert(Results.end(),
4368 Builder.data(), Builder.data() + Builder.size());
4369}