blob: 57ec3297dc0d57bfb008eca910bd6cae333d64df [file] [log] [blame]
Douglas Gregor81b747b2009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
John McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
John McCall120d63c2010-08-24 20:38:10 +000015#include "clang/Sema/Overload.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000016#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregor719770d2010-04-06 17:30:22 +000017#include "clang/Sema/ExternalSemaSource.h"
John McCall5f1e0942010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000023#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000026#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000027#include "llvm/ADT/StringSwitch.h"
Douglas Gregor458433d2010-08-26 15:07:07 +000028#include "llvm/ADT/Twine.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000029#include <list>
30#include <map>
31#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000032
33using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000034using namespace sema;
Douglas Gregor81b747b2009-09-17 21:32:03 +000035
Douglas Gregor86d9a522009-09-21 16:56:56 +000036namespace {
37 /// \brief A container of code-completion results.
38 class ResultBuilder {
39 public:
40 /// \brief The type of a name-lookup filter, which can be provided to the
41 /// name-lookup routines to specify which declarations should be included in
42 /// the result set (when it returns true) and which declarations should be
43 /// filtered out (returns false).
44 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
45
John McCall0a2c5e22010-08-25 06:19:51 +000046 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +000047
48 private:
49 /// \brief The actual results we have found.
50 std::vector<Result> Results;
51
52 /// \brief A record of all of the declarations we have found and placed
53 /// into the result set, used to ensure that no declaration ever gets into
54 /// the result set twice.
55 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
56
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000057 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
58
59 /// \brief An entry in the shadow map, which is optimized to store
60 /// a single (declaration, index) mapping (the common case) but
61 /// can also store a list of (declaration, index) mappings.
62 class ShadowMapEntry {
63 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
64
65 /// \brief Contains either the solitary NamedDecl * or a vector
66 /// of (declaration, index) pairs.
67 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
68
69 /// \brief When the entry contains a single declaration, this is
70 /// the index associated with that entry.
71 unsigned SingleDeclIndex;
72
73 public:
74 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
75
76 void Add(NamedDecl *ND, unsigned Index) {
77 if (DeclOrVector.isNull()) {
78 // 0 - > 1 elements: just set the single element information.
79 DeclOrVector = ND;
80 SingleDeclIndex = Index;
81 return;
82 }
83
84 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
85 // 1 -> 2 elements: create the vector of results and push in the
86 // existing declaration.
87 DeclIndexPairVector *Vec = new DeclIndexPairVector;
88 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
89 DeclOrVector = Vec;
90 }
91
92 // Add the new element to the end of the vector.
93 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
94 DeclIndexPair(ND, Index));
95 }
96
97 void Destroy() {
98 if (DeclIndexPairVector *Vec
99 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
100 delete Vec;
101 DeclOrVector = ((NamedDecl *)0);
102 }
103 }
104
105 // Iteration.
106 class iterator;
107 iterator begin() const;
108 iterator end() const;
109 };
110
Douglas Gregor86d9a522009-09-21 16:56:56 +0000111 /// \brief A mapping from declaration names to the declarations that have
112 /// this name within a particular scope and their index within the list of
113 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000114 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000115
116 /// \brief The semantic analysis object for which results are being
117 /// produced.
118 Sema &SemaRef;
119
120 /// \brief If non-NULL, a filter function used to remove any code-completion
121 /// results that are not desirable.
122 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000123
124 /// \brief Whether we should allow declarations as
125 /// nested-name-specifiers that would otherwise be filtered out.
126 bool AllowNestedNameSpecifiers;
127
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000128 /// \brief If set, the type that we would prefer our resulting value
129 /// declarations to have.
130 ///
131 /// Closely matching the preferred type gives a boost to a result's
132 /// priority.
133 CanQualType PreferredType;
134
Douglas Gregor86d9a522009-09-21 16:56:56 +0000135 /// \brief A list of shadow maps, which is used to model name hiding at
136 /// different levels of, e.g., the inheritance hierarchy.
137 std::list<ShadowMap> ShadowMaps;
138
Douglas Gregor3cdee122010-08-26 16:36:48 +0000139 /// \brief If we're potentially referring to a C++ member function, the set
140 /// of qualifiers applied to the object type.
141 Qualifiers ObjectTypeQualifiers;
142
143 /// \brief Whether the \p ObjectTypeQualifiers field is active.
144 bool HasObjectTypeQualifiers;
145
Douglas Gregor265f7492010-08-27 15:29:55 +0000146 /// \brief The selector that we prefer.
147 Selector PreferredSelector;
148
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000149 void AdjustResultPriorityForPreferredType(Result &R);
150
Douglas Gregor86d9a522009-09-21 16:56:56 +0000151 public:
152 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
Douglas Gregor3cdee122010-08-26 16:36:48 +0000153 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false),
154 HasObjectTypeQualifiers(false) { }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000155
Douglas Gregord8e8a582010-05-25 21:41:55 +0000156 /// \brief Whether we should include code patterns in the completion
157 /// results.
158 bool includeCodePatterns() const {
159 return SemaRef.CodeCompleter &&
160 SemaRef.CodeCompleter->includeCodePatterns();
161 }
162
Douglas Gregor86d9a522009-09-21 16:56:56 +0000163 /// \brief Set the filter used for code-completion results.
164 void setFilter(LookupFilter Filter) {
165 this->Filter = Filter;
166 }
167
168 typedef std::vector<Result>::iterator iterator;
169 iterator begin() { return Results.begin(); }
170 iterator end() { return Results.end(); }
171
172 Result *data() { return Results.empty()? 0 : &Results.front(); }
173 unsigned size() const { return Results.size(); }
174 bool empty() const { return Results.empty(); }
175
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000176 /// \brief Specify the preferred type.
177 void setPreferredType(QualType T) {
178 PreferredType = SemaRef.Context.getCanonicalType(T);
179 }
180
Douglas Gregor3cdee122010-08-26 16:36:48 +0000181 /// \brief Set the cv-qualifiers on the object type, for us in filtering
182 /// calls to member functions.
183 ///
184 /// When there are qualifiers in this set, they will be used to filter
185 /// out member functions that aren't available (because there will be a
186 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
187 /// match.
188 void setObjectTypeQualifiers(Qualifiers Quals) {
189 ObjectTypeQualifiers = Quals;
190 HasObjectTypeQualifiers = true;
191 }
192
Douglas Gregor265f7492010-08-27 15:29:55 +0000193 /// \brief Set the preferred selector.
194 ///
195 /// When an Objective-C method declaration result is added, and that
196 /// method's selector matches this preferred selector, we give that method
197 /// a slight priority boost.
198 void setPreferredSelector(Selector Sel) {
199 PreferredSelector = Sel;
200 }
201
Douglas Gregor45bcd432010-01-14 03:21:49 +0000202 /// \brief Specify whether nested-name-specifiers are allowed.
203 void allowNestedNameSpecifiers(bool Allow = true) {
204 AllowNestedNameSpecifiers = Allow;
205 }
206
Douglas Gregore495b7f2010-01-14 00:20:49 +0000207 /// \brief Determine whether the given declaration is at all interesting
208 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000209 ///
210 /// \param ND the declaration that we are inspecting.
211 ///
212 /// \param AsNestedNameSpecifier will be set true if this declaration is
213 /// only interesting when it is a nested-name-specifier.
214 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000215
216 /// \brief Check whether the result is hidden by the Hiding declaration.
217 ///
218 /// \returns true if the result is hidden and cannot be found, false if
219 /// the hidden result could still be found. When false, \p R may be
220 /// modified to describe how the result can be found (e.g., via extra
221 /// qualification).
222 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
223 NamedDecl *Hiding);
224
Douglas Gregor86d9a522009-09-21 16:56:56 +0000225 /// \brief Add a new result to this result set (if it isn't already in one
226 /// of the shadow maps), or replace an existing result (for, e.g., a
227 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000228 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000229 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000230 ///
231 /// \param R the context in which this result will be named.
232 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000233
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000234 /// \brief Add a new result to this result set, where we already know
235 /// the hiding declation (if any).
236 ///
237 /// \param R the result to add (if it is unique).
238 ///
239 /// \param CurContext the context in which this result will be named.
240 ///
241 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000242 ///
243 /// \param InBaseClass whether the result was found in a base
244 /// class of the searched context.
245 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
246 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000247
Douglas Gregora4477812010-01-14 16:01:26 +0000248 /// \brief Add a new non-declaration result to this result set.
249 void AddResult(Result R);
250
Douglas Gregor86d9a522009-09-21 16:56:56 +0000251 /// \brief Enter into a new scope.
252 void EnterNewScope();
253
254 /// \brief Exit from the current scope.
255 void ExitScope();
256
Douglas Gregor55385fe2009-11-18 04:19:12 +0000257 /// \brief Ignore this declaration, if it is seen again.
258 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
259
Douglas Gregor86d9a522009-09-21 16:56:56 +0000260 /// \name Name lookup predicates
261 ///
262 /// These predicates can be passed to the name lookup functions to filter the
263 /// results of name lookup. All of the predicates have the same type, so that
264 ///
265 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000266 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000267 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000268 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000269 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000270 bool IsNestedNameSpecifier(NamedDecl *ND) const;
271 bool IsEnum(NamedDecl *ND) const;
272 bool IsClassOrStruct(NamedDecl *ND) const;
273 bool IsUnion(NamedDecl *ND) const;
274 bool IsNamespace(NamedDecl *ND) const;
275 bool IsNamespaceOrAlias(NamedDecl *ND) const;
276 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000277 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000278 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000279 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000280 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000281 //@}
282 };
283}
284
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000285class ResultBuilder::ShadowMapEntry::iterator {
286 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
287 unsigned SingleDeclIndex;
288
289public:
290 typedef DeclIndexPair value_type;
291 typedef value_type reference;
292 typedef std::ptrdiff_t difference_type;
293 typedef std::input_iterator_tag iterator_category;
294
295 class pointer {
296 DeclIndexPair Value;
297
298 public:
299 pointer(const DeclIndexPair &Value) : Value(Value) { }
300
301 const DeclIndexPair *operator->() const {
302 return &Value;
303 }
304 };
305
306 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
307
308 iterator(NamedDecl *SingleDecl, unsigned Index)
309 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
310
311 iterator(const DeclIndexPair *Iterator)
312 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
313
314 iterator &operator++() {
315 if (DeclOrIterator.is<NamedDecl *>()) {
316 DeclOrIterator = (NamedDecl *)0;
317 SingleDeclIndex = 0;
318 return *this;
319 }
320
321 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
322 ++I;
323 DeclOrIterator = I;
324 return *this;
325 }
326
327 iterator operator++(int) {
328 iterator tmp(*this);
329 ++(*this);
330 return tmp;
331 }
332
333 reference operator*() const {
334 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
335 return reference(ND, SingleDeclIndex);
336
Douglas Gregord490f952009-12-06 21:27:58 +0000337 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000338 }
339
340 pointer operator->() const {
341 return pointer(**this);
342 }
343
344 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000345 return X.DeclOrIterator.getOpaqueValue()
346 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000347 X.SingleDeclIndex == Y.SingleDeclIndex;
348 }
349
350 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000351 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000352 }
353};
354
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000355ResultBuilder::ShadowMapEntry::iterator
356ResultBuilder::ShadowMapEntry::begin() const {
357 if (DeclOrVector.isNull())
358 return iterator();
359
360 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
361 return iterator(ND, SingleDeclIndex);
362
363 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
364}
365
366ResultBuilder::ShadowMapEntry::iterator
367ResultBuilder::ShadowMapEntry::end() const {
368 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
369 return iterator();
370
371 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
372}
373
Douglas Gregor456c4a12009-09-21 20:12:40 +0000374/// \brief Compute the qualification required to get from the current context
375/// (\p CurContext) to the target context (\p TargetContext).
376///
377/// \param Context the AST context in which the qualification will be used.
378///
379/// \param CurContext the context where an entity is being named, which is
380/// typically based on the current scope.
381///
382/// \param TargetContext the context in which the named entity actually
383/// resides.
384///
385/// \returns a nested name specifier that refers into the target context, or
386/// NULL if no qualification is needed.
387static NestedNameSpecifier *
388getRequiredQualification(ASTContext &Context,
389 DeclContext *CurContext,
390 DeclContext *TargetContext) {
391 llvm::SmallVector<DeclContext *, 4> TargetParents;
392
393 for (DeclContext *CommonAncestor = TargetContext;
394 CommonAncestor && !CommonAncestor->Encloses(CurContext);
395 CommonAncestor = CommonAncestor->getLookupParent()) {
396 if (CommonAncestor->isTransparentContext() ||
397 CommonAncestor->isFunctionOrMethod())
398 continue;
399
400 TargetParents.push_back(CommonAncestor);
401 }
402
403 NestedNameSpecifier *Result = 0;
404 while (!TargetParents.empty()) {
405 DeclContext *Parent = TargetParents.back();
406 TargetParents.pop_back();
407
Douglas Gregorfb629412010-08-23 21:17:50 +0000408 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
409 if (!Namespace->getIdentifier())
410 continue;
411
Douglas Gregor456c4a12009-09-21 20:12:40 +0000412 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000413 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000414 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
415 Result = NestedNameSpecifier::Create(Context, Result,
416 false,
417 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000418 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000419 return Result;
420}
421
Douglas Gregor45bcd432010-01-14 03:21:49 +0000422bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
423 bool &AsNestedNameSpecifier) const {
424 AsNestedNameSpecifier = false;
425
Douglas Gregore495b7f2010-01-14 00:20:49 +0000426 ND = ND->getUnderlyingDecl();
427 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000428
429 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000430 if (!ND->getDeclName())
431 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000432
433 // Friend declarations and declarations introduced due to friends are never
434 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000435 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000436 return false;
437
Douglas Gregor76282942009-12-11 17:31:05 +0000438 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000439 if (isa<ClassTemplateSpecializationDecl>(ND) ||
440 isa<ClassTemplatePartialSpecializationDecl>(ND))
441 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000442
Douglas Gregor76282942009-12-11 17:31:05 +0000443 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000444 if (isa<UsingDecl>(ND))
445 return false;
446
447 // Some declarations have reserved names that we don't want to ever show.
448 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000449 // __va_list_tag is a freak of nature. Find it and skip it.
450 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000451 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000452
Douglas Gregorf52cede2009-10-09 22:16:47 +0000453 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000454 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000455 //
456 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000457 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000458 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000459 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000460 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
461 (ND->getLocation().isInvalid() ||
462 SemaRef.SourceMgr.isInSystemHeader(
463 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000464 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000465 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000466 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000467
Douglas Gregor86d9a522009-09-21 16:56:56 +0000468 // C++ constructors are never found by name lookup.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000469 if (isa<CXXConstructorDecl>(ND))
470 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000471
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000472 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
473 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
474 Filter != &ResultBuilder::IsNamespace &&
475 Filter != &ResultBuilder::IsNamespaceOrAlias))
476 AsNestedNameSpecifier = true;
477
Douglas Gregor86d9a522009-09-21 16:56:56 +0000478 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000479 if (Filter && !(this->*Filter)(ND)) {
480 // Check whether it is interesting as a nested-name-specifier.
481 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
482 IsNestedNameSpecifier(ND) &&
483 (Filter != &ResultBuilder::IsMember ||
484 (isa<CXXRecordDecl>(ND) &&
485 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
486 AsNestedNameSpecifier = true;
487 return true;
488 }
489
Douglas Gregore495b7f2010-01-14 00:20:49 +0000490 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000491 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000492 // ... then it must be interesting!
493 return true;
494}
495
Douglas Gregor6660d842010-01-14 00:41:07 +0000496bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
497 NamedDecl *Hiding) {
498 // In C, there is no way to refer to a hidden name.
499 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
500 // name if we introduce the tag type.
501 if (!SemaRef.getLangOptions().CPlusPlus)
502 return true;
503
504 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext();
505
506 // There is no way to qualify a name declared in a function or method.
507 if (HiddenCtx->isFunctionOrMethod())
508 return true;
509
510 if (HiddenCtx == Hiding->getDeclContext()->getLookupContext())
511 return true;
512
513 // We can refer to the result with the appropriate qualification. Do it.
514 R.Hidden = true;
515 R.QualifierIsInformative = false;
516
517 if (!R.Qualifier)
518 R.Qualifier = getRequiredQualification(SemaRef.Context,
519 CurContext,
520 R.Declaration->getDeclContext());
521 return false;
522}
523
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000524/// \brief A simplified classification of types used to determine whether two
525/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000526SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000527 switch (T->getTypeClass()) {
528 case Type::Builtin:
529 switch (cast<BuiltinType>(T)->getKind()) {
530 case BuiltinType::Void:
531 return STC_Void;
532
533 case BuiltinType::NullPtr:
534 return STC_Pointer;
535
536 case BuiltinType::Overload:
537 case BuiltinType::Dependent:
538 case BuiltinType::UndeducedAuto:
539 return STC_Other;
540
541 case BuiltinType::ObjCId:
542 case BuiltinType::ObjCClass:
543 case BuiltinType::ObjCSel:
544 return STC_ObjectiveC;
545
546 default:
547 return STC_Arithmetic;
548 }
549 return STC_Other;
550
551 case Type::Complex:
552 return STC_Arithmetic;
553
554 case Type::Pointer:
555 return STC_Pointer;
556
557 case Type::BlockPointer:
558 return STC_Block;
559
560 case Type::LValueReference:
561 case Type::RValueReference:
562 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
563
564 case Type::ConstantArray:
565 case Type::IncompleteArray:
566 case Type::VariableArray:
567 case Type::DependentSizedArray:
568 return STC_Array;
569
570 case Type::DependentSizedExtVector:
571 case Type::Vector:
572 case Type::ExtVector:
573 return STC_Arithmetic;
574
575 case Type::FunctionProto:
576 case Type::FunctionNoProto:
577 return STC_Function;
578
579 case Type::Record:
580 return STC_Record;
581
582 case Type::Enum:
583 return STC_Arithmetic;
584
585 case Type::ObjCObject:
586 case Type::ObjCInterface:
587 case Type::ObjCObjectPointer:
588 return STC_ObjectiveC;
589
590 default:
591 return STC_Other;
592 }
593}
594
595/// \brief Get the type that a given expression will have if this declaration
596/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000597QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000598 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
599
600 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
601 return C.getTypeDeclType(Type);
602 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
603 return C.getObjCInterfaceType(Iface);
604
605 QualType T;
606 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000607 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000608 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000609 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000610 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000611 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000612 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
613 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
614 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
615 T = Property->getType();
616 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
617 T = Value->getType();
618 else
619 return QualType();
620
621 return T.getNonReferenceType();
622}
623
624void ResultBuilder::AdjustResultPriorityForPreferredType(Result &R) {
625 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
626 if (T.isNull())
627 return;
628
629 CanQualType TC = SemaRef.Context.getCanonicalType(T);
630 // Check for exactly-matching types (modulo qualifiers).
Douglas Gregoreb0d0142010-08-24 23:58:17 +0000631 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC)) {
632 if (PreferredType->isVoidType())
633 R.Priority += CCD_VoidMatch;
634 else
635 R.Priority /= CCF_ExactTypeMatch;
636 } // Check for nearly-matching types, based on classification of each.
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000637 else if ((getSimplifiedTypeClass(PreferredType)
638 == getSimplifiedTypeClass(TC)) &&
639 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
640 R.Priority /= CCF_SimilarTypeMatch;
641}
642
Douglas Gregore495b7f2010-01-14 00:20:49 +0000643void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
644 assert(!ShadowMaps.empty() && "Must enter into a results scope");
645
646 if (R.Kind != Result::RK_Declaration) {
647 // For non-declaration results, just add the result.
648 Results.push_back(R);
649 return;
650 }
651
652 // Look through using declarations.
653 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
654 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
655 return;
656 }
657
658 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
659 unsigned IDNS = CanonDecl->getIdentifierNamespace();
660
Douglas Gregor45bcd432010-01-14 03:21:49 +0000661 bool AsNestedNameSpecifier = false;
662 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000663 return;
664
Douglas Gregor86d9a522009-09-21 16:56:56 +0000665 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000666 ShadowMapEntry::iterator I, IEnd;
667 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
668 if (NamePos != SMap.end()) {
669 I = NamePos->second.begin();
670 IEnd = NamePos->second.end();
671 }
672
673 for (; I != IEnd; ++I) {
674 NamedDecl *ND = I->first;
675 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000676 if (ND->getCanonicalDecl() == CanonDecl) {
677 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000678 Results[Index].Declaration = R.Declaration;
679
Douglas Gregor86d9a522009-09-21 16:56:56 +0000680 // We're done.
681 return;
682 }
683 }
684
685 // This is a new declaration in this scope. However, check whether this
686 // declaration name is hidden by a similarly-named declaration in an outer
687 // scope.
688 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
689 --SMEnd;
690 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000691 ShadowMapEntry::iterator I, IEnd;
692 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
693 if (NamePos != SM->end()) {
694 I = NamePos->second.begin();
695 IEnd = NamePos->second.end();
696 }
697 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000698 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000699 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000700 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
701 Decl::IDNS_ObjCProtocol)))
702 continue;
703
704 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000705 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000706 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000707 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000708 continue;
709
710 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000711 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000712 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000713
714 break;
715 }
716 }
717
718 // Make sure that any given declaration only shows up in the result set once.
719 if (!AllDeclsFound.insert(CanonDecl))
720 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000721
722 // If this is an Objective-C method declaration whose selector matches our
723 // preferred selector, give it a priority boost.
724 if (!PreferredSelector.isNull())
725 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
726 if (PreferredSelector == Method->getSelector())
727 R.Priority += CCD_SelectorMatch;
728
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000729 // If the filter is for nested-name-specifiers, then this result starts a
730 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000731 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000732 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000733 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000734 } else if (!PreferredType.isNull())
735 AdjustResultPriorityForPreferredType(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000736
Douglas Gregor0563c262009-09-22 23:15:58 +0000737 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000738 if (R.QualifierIsInformative && !R.Qualifier &&
739 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000740 DeclContext *Ctx = R.Declaration->getDeclContext();
741 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
742 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
743 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
744 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
745 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
746 else
747 R.QualifierIsInformative = false;
748 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000749
Douglas Gregor86d9a522009-09-21 16:56:56 +0000750 // Insert this result into the set of results and into the current shadow
751 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000752 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000753 Results.push_back(R);
754}
755
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000756void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000757 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000758 if (R.Kind != Result::RK_Declaration) {
759 // For non-declaration results, just add the result.
760 Results.push_back(R);
761 return;
762 }
763
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000764 // Look through using declarations.
765 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
766 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
767 return;
768 }
769
Douglas Gregor45bcd432010-01-14 03:21:49 +0000770 bool AsNestedNameSpecifier = false;
771 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000772 return;
773
774 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
775 return;
776
777 // Make sure that any given declaration only shows up in the result set once.
778 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
779 return;
780
781 // If the filter is for nested-name-specifiers, then this result starts a
782 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000783 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000784 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000785 R.Priority = CCP_NestedNameSpecifier;
786 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000787 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
788 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
789 ->getLookupContext()))
790 R.QualifierIsInformative = true;
791
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000792 // If this result is supposed to have an informative qualifier, add one.
793 if (R.QualifierIsInformative && !R.Qualifier &&
794 !R.StartsNestedNameSpecifier) {
795 DeclContext *Ctx = R.Declaration->getDeclContext();
796 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
797 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
798 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
799 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000800 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000801 else
802 R.QualifierIsInformative = false;
803 }
804
Douglas Gregor12e13132010-05-26 22:00:08 +0000805 // Adjust the priority if this result comes from a base class.
806 if (InBaseClass)
807 R.Priority += CCD_InBaseClass;
808
Douglas Gregor265f7492010-08-27 15:29:55 +0000809 // If this is an Objective-C method declaration whose selector matches our
810 // preferred selector, give it a priority boost.
811 if (!PreferredSelector.isNull())
812 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
813 if (PreferredSelector == Method->getSelector())
814 R.Priority += CCD_SelectorMatch;
815
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000816 if (!PreferredType.isNull())
817 AdjustResultPriorityForPreferredType(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000818
Douglas Gregor3cdee122010-08-26 16:36:48 +0000819 if (HasObjectTypeQualifiers)
820 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
821 if (Method->isInstance()) {
822 Qualifiers MethodQuals
823 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
824 if (ObjectTypeQualifiers == MethodQuals)
825 R.Priority += CCD_ObjectQualifierMatch;
826 else if (ObjectTypeQualifiers - MethodQuals) {
827 // The method cannot be invoked, because doing so would drop
828 // qualifiers.
829 return;
830 }
831 }
832
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000833 // Insert this result into the set of results.
834 Results.push_back(R);
835}
836
Douglas Gregora4477812010-01-14 16:01:26 +0000837void ResultBuilder::AddResult(Result R) {
838 assert(R.Kind != Result::RK_Declaration &&
839 "Declaration results need more context");
840 Results.push_back(R);
841}
842
Douglas Gregor86d9a522009-09-21 16:56:56 +0000843/// \brief Enter into a new scope.
844void ResultBuilder::EnterNewScope() {
845 ShadowMaps.push_back(ShadowMap());
846}
847
848/// \brief Exit from the current scope.
849void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000850 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
851 EEnd = ShadowMaps.back().end();
852 E != EEnd;
853 ++E)
854 E->second.Destroy();
855
Douglas Gregor86d9a522009-09-21 16:56:56 +0000856 ShadowMaps.pop_back();
857}
858
Douglas Gregor791215b2009-09-21 20:51:25 +0000859/// \brief Determines whether this given declaration will be found by
860/// ordinary name lookup.
861bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000862 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
863
Douglas Gregor791215b2009-09-21 20:51:25 +0000864 unsigned IDNS = Decl::IDNS_Ordinary;
865 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000866 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000867 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
868 return true;
869
Douglas Gregor791215b2009-09-21 20:51:25 +0000870 return ND->getIdentifierNamespace() & IDNS;
871}
872
Douglas Gregor01dfea02010-01-10 23:08:15 +0000873/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000874/// ordinary name lookup but is not a type name.
875bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
876 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
877 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
878 return false;
879
880 unsigned IDNS = Decl::IDNS_Ordinary;
881 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000882 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000883 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
884 return true;
885
886 return ND->getIdentifierNamespace() & IDNS;
887}
888
Douglas Gregorf9578432010-07-28 21:50:18 +0000889bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
890 if (!IsOrdinaryNonTypeName(ND))
891 return 0;
892
893 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
894 if (VD->getType()->isIntegralOrEnumerationType())
895 return true;
896
897 return false;
898}
899
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000900/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +0000901/// ordinary name lookup.
902bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000903 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
904
Douglas Gregor01dfea02010-01-10 23:08:15 +0000905 unsigned IDNS = Decl::IDNS_Ordinary;
906 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +0000907 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000908
909 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000910 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
911 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +0000912}
913
Douglas Gregor86d9a522009-09-21 16:56:56 +0000914/// \brief Determines whether the given declaration is suitable as the
915/// start of a C++ nested-name-specifier, e.g., a class or namespace.
916bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
917 // Allow us to find class templates, too.
918 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
919 ND = ClassTemplate->getTemplatedDecl();
920
921 return SemaRef.isAcceptableNestedNameSpecifier(ND);
922}
923
924/// \brief Determines whether the given declaration is an enumeration.
925bool ResultBuilder::IsEnum(NamedDecl *ND) const {
926 return isa<EnumDecl>(ND);
927}
928
929/// \brief Determines whether the given declaration is a class or struct.
930bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
931 // Allow us to find class templates, too.
932 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
933 ND = ClassTemplate->getTemplatedDecl();
934
935 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000936 return RD->getTagKind() == TTK_Class ||
937 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000938
939 return false;
940}
941
942/// \brief Determines whether the given declaration is a union.
943bool ResultBuilder::IsUnion(NamedDecl *ND) const {
944 // Allow us to find class templates, too.
945 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
946 ND = ClassTemplate->getTemplatedDecl();
947
948 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000949 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000950
951 return false;
952}
953
954/// \brief Determines whether the given declaration is a namespace.
955bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
956 return isa<NamespaceDecl>(ND);
957}
958
959/// \brief Determines whether the given declaration is a namespace or
960/// namespace alias.
961bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
962 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
963}
964
Douglas Gregor76282942009-12-11 17:31:05 +0000965/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000966bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +0000967 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
968 ND = Using->getTargetDecl();
969
970 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000971}
972
Douglas Gregor76282942009-12-11 17:31:05 +0000973/// \brief Determines which members of a class should be visible via
974/// "." or "->". Only value declarations, nested name specifiers, and
975/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000976bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +0000977 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
978 ND = Using->getTargetDecl();
979
Douglas Gregorce821962009-12-11 18:14:22 +0000980 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
981 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000982}
983
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000984static bool isObjCReceiverType(ASTContext &C, QualType T) {
985 T = C.getCanonicalType(T);
986 switch (T->getTypeClass()) {
987 case Type::ObjCObject:
988 case Type::ObjCInterface:
989 case Type::ObjCObjectPointer:
990 return true;
991
992 case Type::Builtin:
993 switch (cast<BuiltinType>(T)->getKind()) {
994 case BuiltinType::ObjCId:
995 case BuiltinType::ObjCClass:
996 case BuiltinType::ObjCSel:
997 return true;
998
999 default:
1000 break;
1001 }
1002 return false;
1003
1004 default:
1005 break;
1006 }
1007
1008 if (!C.getLangOptions().CPlusPlus)
1009 return false;
1010
1011 // FIXME: We could perform more analysis here to determine whether a
1012 // particular class type has any conversions to Objective-C types. For now,
1013 // just accept all class types.
1014 return T->isDependentType() || T->isRecordType();
1015}
1016
1017bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1018 QualType T = getDeclUsageType(SemaRef.Context, ND);
1019 if (T.isNull())
1020 return false;
1021
1022 T = SemaRef.Context.getBaseElementType(T);
1023 return isObjCReceiverType(SemaRef.Context, T);
1024}
1025
Douglas Gregorfb629412010-08-23 21:17:50 +00001026bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1027 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1028 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1029 return false;
1030
1031 QualType T = getDeclUsageType(SemaRef.Context, ND);
1032 if (T.isNull())
1033 return false;
1034
1035 T = SemaRef.Context.getBaseElementType(T);
1036 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1037 T->isObjCIdType() ||
1038 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1039}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001040
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001041/// \rief Determines whether the given declaration is an Objective-C
1042/// instance variable.
1043bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1044 return isa<ObjCIvarDecl>(ND);
1045}
1046
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001047namespace {
1048 /// \brief Visible declaration consumer that adds a code-completion result
1049 /// for each visible declaration.
1050 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1051 ResultBuilder &Results;
1052 DeclContext *CurContext;
1053
1054 public:
1055 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1056 : Results(Results), CurContext(CurContext) { }
1057
Douglas Gregor0cc84042010-01-14 15:47:35 +00001058 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1059 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001060 }
1061 };
1062}
1063
Douglas Gregor86d9a522009-09-21 16:56:56 +00001064/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001065static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001066 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001067 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001068 Results.AddResult(Result("short", CCP_Type));
1069 Results.AddResult(Result("long", CCP_Type));
1070 Results.AddResult(Result("signed", CCP_Type));
1071 Results.AddResult(Result("unsigned", CCP_Type));
1072 Results.AddResult(Result("void", CCP_Type));
1073 Results.AddResult(Result("char", CCP_Type));
1074 Results.AddResult(Result("int", CCP_Type));
1075 Results.AddResult(Result("float", CCP_Type));
1076 Results.AddResult(Result("double", CCP_Type));
1077 Results.AddResult(Result("enum", CCP_Type));
1078 Results.AddResult(Result("struct", CCP_Type));
1079 Results.AddResult(Result("union", CCP_Type));
1080 Results.AddResult(Result("const", CCP_Type));
1081 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001082
Douglas Gregor86d9a522009-09-21 16:56:56 +00001083 if (LangOpts.C99) {
1084 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001085 Results.AddResult(Result("_Complex", CCP_Type));
1086 Results.AddResult(Result("_Imaginary", CCP_Type));
1087 Results.AddResult(Result("_Bool", CCP_Type));
1088 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001089 }
1090
1091 if (LangOpts.CPlusPlus) {
1092 // C++-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001093 Results.AddResult(Result("bool", CCP_Type));
1094 Results.AddResult(Result("class", CCP_Type));
1095 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001096
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001097 // typename qualified-id
1098 CodeCompletionString *Pattern = new CodeCompletionString;
1099 Pattern->AddTypedTextChunk("typename");
1100 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1101 Pattern->AddPlaceholderChunk("qualifier");
1102 Pattern->AddTextChunk("::");
1103 Pattern->AddPlaceholderChunk("name");
1104 Results.AddResult(Result(Pattern));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001105
Douglas Gregor86d9a522009-09-21 16:56:56 +00001106 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001107 Results.AddResult(Result("auto", CCP_Type));
1108 Results.AddResult(Result("char16_t", CCP_Type));
1109 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001110
1111 CodeCompletionString *Pattern = new CodeCompletionString;
1112 Pattern->AddTypedTextChunk("decltype");
1113 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1114 Pattern->AddPlaceholderChunk("expression");
1115 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1116 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001117 }
1118 }
1119
1120 // GNU extensions
1121 if (LangOpts.GNUMode) {
1122 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001123 // Results.AddResult(Result("_Decimal32"));
1124 // Results.AddResult(Result("_Decimal64"));
1125 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001126
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001127 CodeCompletionString *Pattern = new CodeCompletionString;
1128 Pattern->AddTypedTextChunk("typeof");
1129 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1130 Pattern->AddPlaceholderChunk("expression");
1131 Results.AddResult(Result(Pattern));
1132
1133 Pattern = new CodeCompletionString;
1134 Pattern->AddTypedTextChunk("typeof");
1135 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1136 Pattern->AddPlaceholderChunk("type");
1137 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1138 Results.AddResult(Result(Pattern));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001139 }
1140}
1141
John McCallf312b1e2010-08-26 23:41:50 +00001142static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001143 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001144 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001145 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001146 // Note: we don't suggest either "auto" or "register", because both
1147 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1148 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001149 Results.AddResult(Result("extern"));
1150 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001151}
1152
John McCallf312b1e2010-08-26 23:41:50 +00001153static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001154 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001155 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001156 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001157 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001158 case Sema::PCC_Class:
1159 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001160 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001161 Results.AddResult(Result("explicit"));
1162 Results.AddResult(Result("friend"));
1163 Results.AddResult(Result("mutable"));
1164 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001165 }
1166 // Fall through
1167
John McCallf312b1e2010-08-26 23:41:50 +00001168 case Sema::PCC_ObjCInterface:
1169 case Sema::PCC_ObjCImplementation:
1170 case Sema::PCC_Namespace:
1171 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001172 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001173 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001174 break;
1175
John McCallf312b1e2010-08-26 23:41:50 +00001176 case Sema::PCC_ObjCInstanceVariableList:
1177 case Sema::PCC_Expression:
1178 case Sema::PCC_Statement:
1179 case Sema::PCC_ForInit:
1180 case Sema::PCC_Condition:
1181 case Sema::PCC_RecoveryInFunction:
1182 case Sema::PCC_Type:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001183 break;
1184 }
1185}
1186
Douglas Gregorbca403c2010-01-13 23:51:12 +00001187static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1188static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1189static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001190 ResultBuilder &Results,
1191 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001192static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001193 ResultBuilder &Results,
1194 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001195static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001196 ResultBuilder &Results,
1197 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001198static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001199
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001200static void AddTypedefResult(ResultBuilder &Results) {
1201 CodeCompletionString *Pattern = new CodeCompletionString;
1202 Pattern->AddTypedTextChunk("typedef");
1203 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1204 Pattern->AddPlaceholderChunk("type");
1205 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1206 Pattern->AddPlaceholderChunk("name");
John McCall0a2c5e22010-08-25 06:19:51 +00001207 Results.AddResult(CodeCompletionResult(Pattern));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001208}
1209
John McCallf312b1e2010-08-26 23:41:50 +00001210static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001211 const LangOptions &LangOpts) {
1212 if (LangOpts.CPlusPlus)
1213 return true;
1214
1215 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001216 case Sema::PCC_Namespace:
1217 case Sema::PCC_Class:
1218 case Sema::PCC_ObjCInstanceVariableList:
1219 case Sema::PCC_Template:
1220 case Sema::PCC_MemberTemplate:
1221 case Sema::PCC_Statement:
1222 case Sema::PCC_RecoveryInFunction:
1223 case Sema::PCC_Type:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001224 return true;
1225
John McCallf312b1e2010-08-26 23:41:50 +00001226 case Sema::PCC_ObjCInterface:
1227 case Sema::PCC_ObjCImplementation:
1228 case Sema::PCC_Expression:
1229 case Sema::PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001230 return false;
1231
John McCallf312b1e2010-08-26 23:41:50 +00001232 case Sema::PCC_ForInit:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001233 return LangOpts.ObjC1 || LangOpts.C99;
1234 }
1235
1236 return false;
1237}
1238
Douglas Gregor01dfea02010-01-10 23:08:15 +00001239/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001240static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001241 Scope *S,
1242 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001243 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001244 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001245 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001246 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001247 if (SemaRef.getLangOptions().CPlusPlus) {
1248 CodeCompletionString *Pattern = 0;
1249
1250 if (Results.includeCodePatterns()) {
1251 // namespace <identifier> { declarations }
1252 CodeCompletionString *Pattern = new CodeCompletionString;
1253 Pattern->AddTypedTextChunk("namespace");
1254 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1255 Pattern->AddPlaceholderChunk("identifier");
1256 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1257 Pattern->AddPlaceholderChunk("declarations");
1258 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1259 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1260 Results.AddResult(Result(Pattern));
1261 }
1262
Douglas Gregor01dfea02010-01-10 23:08:15 +00001263 // namespace identifier = identifier ;
1264 Pattern = new CodeCompletionString;
1265 Pattern->AddTypedTextChunk("namespace");
1266 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001267 Pattern->AddPlaceholderChunk("name");
Douglas Gregor01dfea02010-01-10 23:08:15 +00001268 Pattern->AddChunk(CodeCompletionString::CK_Equal);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001269 Pattern->AddPlaceholderChunk("namespace");
Douglas Gregora4477812010-01-14 16:01:26 +00001270 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001271
1272 // Using directives
1273 Pattern = new CodeCompletionString;
1274 Pattern->AddTypedTextChunk("using");
1275 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1276 Pattern->AddTextChunk("namespace");
1277 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1278 Pattern->AddPlaceholderChunk("identifier");
Douglas Gregora4477812010-01-14 16:01:26 +00001279 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001280
1281 // asm(string-literal)
1282 Pattern = new CodeCompletionString;
1283 Pattern->AddTypedTextChunk("asm");
1284 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1285 Pattern->AddPlaceholderChunk("string-literal");
1286 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00001287 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001288
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001289 if (Results.includeCodePatterns()) {
1290 // Explicit template instantiation
1291 Pattern = new CodeCompletionString;
1292 Pattern->AddTypedTextChunk("template");
1293 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1294 Pattern->AddPlaceholderChunk("declaration");
1295 Results.AddResult(Result(Pattern));
1296 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001297 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001298
1299 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001300 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001301
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001302 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001303 // Fall through
1304
John McCallf312b1e2010-08-26 23:41:50 +00001305 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001306 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001307 // Using declaration
1308 CodeCompletionString *Pattern = new CodeCompletionString;
1309 Pattern->AddTypedTextChunk("using");
1310 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001311 Pattern->AddPlaceholderChunk("qualifier");
1312 Pattern->AddTextChunk("::");
1313 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001314 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001315
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001316 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001317 if (SemaRef.CurContext->isDependentContext()) {
1318 Pattern = new CodeCompletionString;
1319 Pattern->AddTypedTextChunk("using");
1320 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1321 Pattern->AddTextChunk("typename");
1322 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001323 Pattern->AddPlaceholderChunk("qualifier");
1324 Pattern->AddTextChunk("::");
1325 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00001326 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001327 }
1328
John McCallf312b1e2010-08-26 23:41:50 +00001329 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001330 AddTypedefResult(Results);
1331
Douglas Gregor01dfea02010-01-10 23:08:15 +00001332 // public:
1333 Pattern = new CodeCompletionString;
1334 Pattern->AddTypedTextChunk("public");
1335 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001336 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001337
1338 // protected:
1339 Pattern = new CodeCompletionString;
1340 Pattern->AddTypedTextChunk("protected");
1341 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001342 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001343
1344 // private:
1345 Pattern = new CodeCompletionString;
1346 Pattern->AddTypedTextChunk("private");
1347 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001348 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001349 }
1350 }
1351 // Fall through
1352
John McCallf312b1e2010-08-26 23:41:50 +00001353 case Sema::PCC_Template:
1354 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001355 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001356 // template < parameters >
1357 CodeCompletionString *Pattern = new CodeCompletionString;
1358 Pattern->AddTypedTextChunk("template");
1359 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1360 Pattern->AddPlaceholderChunk("parameters");
1361 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
Douglas Gregora4477812010-01-14 16:01:26 +00001362 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001363 }
1364
Douglas Gregorbca403c2010-01-13 23:51:12 +00001365 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1366 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001367 break;
1368
John McCallf312b1e2010-08-26 23:41:50 +00001369 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001370 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1371 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1372 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001373 break;
1374
John McCallf312b1e2010-08-26 23:41:50 +00001375 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001376 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1377 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1378 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001379 break;
1380
John McCallf312b1e2010-08-26 23:41:50 +00001381 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001382 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001383 break;
1384
John McCallf312b1e2010-08-26 23:41:50 +00001385 case Sema::PCC_RecoveryInFunction:
1386 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001387 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001388
1389 CodeCompletionString *Pattern = 0;
Douglas Gregord8e8a582010-05-25 21:41:55 +00001390 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001391 Pattern = new CodeCompletionString;
1392 Pattern->AddTypedTextChunk("try");
1393 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1394 Pattern->AddPlaceholderChunk("statements");
1395 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1396 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1397 Pattern->AddTextChunk("catch");
1398 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1399 Pattern->AddPlaceholderChunk("declaration");
1400 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1401 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1402 Pattern->AddPlaceholderChunk("statements");
1403 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1404 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregora4477812010-01-14 16:01:26 +00001405 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001406 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001407 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001408 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001409
Douglas Gregord8e8a582010-05-25 21:41:55 +00001410 if (Results.includeCodePatterns()) {
1411 // if (condition) { statements }
1412 Pattern = new CodeCompletionString;
1413 Pattern->AddTypedTextChunk("if");
1414 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1415 if (SemaRef.getLangOptions().CPlusPlus)
1416 Pattern->AddPlaceholderChunk("condition");
1417 else
1418 Pattern->AddPlaceholderChunk("expression");
1419 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1420 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1421 Pattern->AddPlaceholderChunk("statements");
1422 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1423 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1424 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001425
Douglas Gregord8e8a582010-05-25 21:41:55 +00001426 // switch (condition) { }
1427 Pattern = new CodeCompletionString;
1428 Pattern->AddTypedTextChunk("switch");
1429 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1430 if (SemaRef.getLangOptions().CPlusPlus)
1431 Pattern->AddPlaceholderChunk("condition");
1432 else
1433 Pattern->AddPlaceholderChunk("expression");
1434 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1435 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1436 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1437 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1438 Results.AddResult(Result(Pattern));
1439 }
1440
Douglas Gregor01dfea02010-01-10 23:08:15 +00001441 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001442 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001443 // case expression:
1444 Pattern = new CodeCompletionString;
1445 Pattern->AddTypedTextChunk("case");
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001446 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001447 Pattern->AddPlaceholderChunk("expression");
1448 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001449 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001450
1451 // default:
1452 Pattern = new CodeCompletionString;
1453 Pattern->AddTypedTextChunk("default");
1454 Pattern->AddChunk(CodeCompletionString::CK_Colon);
Douglas Gregora4477812010-01-14 16:01:26 +00001455 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001456 }
1457
Douglas Gregord8e8a582010-05-25 21:41:55 +00001458 if (Results.includeCodePatterns()) {
1459 /// while (condition) { statements }
1460 Pattern = new CodeCompletionString;
1461 Pattern->AddTypedTextChunk("while");
1462 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1463 if (SemaRef.getLangOptions().CPlusPlus)
1464 Pattern->AddPlaceholderChunk("condition");
1465 else
1466 Pattern->AddPlaceholderChunk("expression");
1467 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1468 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1469 Pattern->AddPlaceholderChunk("statements");
1470 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1471 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1472 Results.AddResult(Result(Pattern));
1473
1474 // do { statements } while ( expression );
1475 Pattern = new CodeCompletionString;
1476 Pattern->AddTypedTextChunk("do");
1477 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1478 Pattern->AddPlaceholderChunk("statements");
1479 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1480 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1481 Pattern->AddTextChunk("while");
1482 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001483 Pattern->AddPlaceholderChunk("expression");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001484 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1485 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001486
Douglas Gregord8e8a582010-05-25 21:41:55 +00001487 // for ( for-init-statement ; condition ; expression ) { statements }
1488 Pattern = new CodeCompletionString;
1489 Pattern->AddTypedTextChunk("for");
1490 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1491 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1492 Pattern->AddPlaceholderChunk("init-statement");
1493 else
1494 Pattern->AddPlaceholderChunk("init-expression");
1495 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1496 Pattern->AddPlaceholderChunk("condition");
1497 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1498 Pattern->AddPlaceholderChunk("inc-expression");
1499 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1500 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1501 Pattern->AddPlaceholderChunk("statements");
1502 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1503 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1504 Results.AddResult(Result(Pattern));
1505 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001506
1507 if (S->getContinueParent()) {
1508 // continue ;
1509 Pattern = new CodeCompletionString;
1510 Pattern->AddTypedTextChunk("continue");
Douglas Gregora4477812010-01-14 16:01:26 +00001511 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001512 }
1513
1514 if (S->getBreakParent()) {
1515 // break ;
1516 Pattern = new CodeCompletionString;
1517 Pattern->AddTypedTextChunk("break");
Douglas Gregora4477812010-01-14 16:01:26 +00001518 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001519 }
1520
1521 // "return expression ;" or "return ;", depending on whether we
1522 // know the function is void or not.
1523 bool isVoid = false;
1524 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1525 isVoid = Function->getResultType()->isVoidType();
1526 else if (ObjCMethodDecl *Method
1527 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1528 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001529 else if (SemaRef.getCurBlock() &&
1530 !SemaRef.getCurBlock()->ReturnType.isNull())
1531 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor01dfea02010-01-10 23:08:15 +00001532 Pattern = new CodeCompletionString;
1533 Pattern->AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001534 if (!isVoid) {
1535 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001536 Pattern->AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001537 }
Douglas Gregora4477812010-01-14 16:01:26 +00001538 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001539
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001540 // goto identifier ;
1541 Pattern = new CodeCompletionString;
1542 Pattern->AddTypedTextChunk("goto");
1543 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1544 Pattern->AddPlaceholderChunk("label");
1545 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001546
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001547 // Using directives
1548 Pattern = new CodeCompletionString;
1549 Pattern->AddTypedTextChunk("using");
1550 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1551 Pattern->AddTextChunk("namespace");
1552 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1553 Pattern->AddPlaceholderChunk("identifier");
1554 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001555 }
1556
1557 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001558 case Sema::PCC_ForInit:
1559 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001560 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001561 // Fall through: conditions and statements can have expressions.
1562
John McCallf312b1e2010-08-26 23:41:50 +00001563 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001564 CodeCompletionString *Pattern = 0;
1565 if (SemaRef.getLangOptions().CPlusPlus) {
1566 // 'this', if we're in a non-static member function.
1567 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1568 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001569 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001570
1571 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001572 Results.AddResult(Result("true"));
1573 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001574
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001575 // dynamic_cast < type-id > ( expression )
1576 Pattern = new CodeCompletionString;
1577 Pattern->AddTypedTextChunk("dynamic_cast");
1578 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1579 Pattern->AddPlaceholderChunk("type");
1580 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1581 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1582 Pattern->AddPlaceholderChunk("expression");
1583 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1584 Results.AddResult(Result(Pattern));
1585
1586 // static_cast < type-id > ( expression )
1587 Pattern = new CodeCompletionString;
1588 Pattern->AddTypedTextChunk("static_cast");
1589 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1590 Pattern->AddPlaceholderChunk("type");
1591 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1592 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1593 Pattern->AddPlaceholderChunk("expression");
1594 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1595 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001596
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001597 // reinterpret_cast < type-id > ( expression )
1598 Pattern = new CodeCompletionString;
1599 Pattern->AddTypedTextChunk("reinterpret_cast");
1600 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1601 Pattern->AddPlaceholderChunk("type");
1602 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1603 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1604 Pattern->AddPlaceholderChunk("expression");
1605 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1606 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001607
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001608 // const_cast < type-id > ( expression )
1609 Pattern = new CodeCompletionString;
1610 Pattern->AddTypedTextChunk("const_cast");
1611 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1612 Pattern->AddPlaceholderChunk("type");
1613 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1614 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1615 Pattern->AddPlaceholderChunk("expression");
1616 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1617 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001618
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001619 // typeid ( expression-or-type )
1620 Pattern = new CodeCompletionString;
1621 Pattern->AddTypedTextChunk("typeid");
1622 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1623 Pattern->AddPlaceholderChunk("expression-or-type");
1624 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1625 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001626
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001627 // new T ( ... )
1628 Pattern = new CodeCompletionString;
1629 Pattern->AddTypedTextChunk("new");
1630 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1631 Pattern->AddPlaceholderChunk("type");
1632 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1633 Pattern->AddPlaceholderChunk("expressions");
1634 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1635 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001636
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001637 // new T [ ] ( ... )
1638 Pattern = new CodeCompletionString;
1639 Pattern->AddTypedTextChunk("new");
1640 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1641 Pattern->AddPlaceholderChunk("type");
1642 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1643 Pattern->AddPlaceholderChunk("size");
1644 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1645 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1646 Pattern->AddPlaceholderChunk("expressions");
1647 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1648 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001649
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001650 // delete expression
1651 Pattern = new CodeCompletionString;
1652 Pattern->AddTypedTextChunk("delete");
1653 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1654 Pattern->AddPlaceholderChunk("expression");
1655 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001656
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001657 // delete [] expression
1658 Pattern = new CodeCompletionString;
1659 Pattern->AddTypedTextChunk("delete");
1660 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1661 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1662 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1663 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1664 Pattern->AddPlaceholderChunk("expression");
1665 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001666
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001667 // throw expression
1668 Pattern = new CodeCompletionString;
1669 Pattern->AddTypedTextChunk("throw");
1670 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1671 Pattern->AddPlaceholderChunk("expression");
1672 Results.AddResult(Result(Pattern));
Douglas Gregor12e13132010-05-26 22:00:08 +00001673
1674 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001675 }
1676
1677 if (SemaRef.getLangOptions().ObjC1) {
1678 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001679 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1680 // The interface can be NULL.
1681 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1682 if (ID->getSuperClass())
1683 Results.AddResult(Result("super"));
1684 }
1685
Douglas Gregorbca403c2010-01-13 23:51:12 +00001686 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001687 }
1688
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001689 // sizeof expression
1690 Pattern = new CodeCompletionString;
1691 Pattern->AddTypedTextChunk("sizeof");
1692 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1693 Pattern->AddPlaceholderChunk("expression-or-type");
1694 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1695 Results.AddResult(Result(Pattern));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001696 break;
1697 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001698
John McCallf312b1e2010-08-26 23:41:50 +00001699 case Sema::PCC_Type:
Douglas Gregord32b0222010-08-24 01:06:58 +00001700 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001701 }
1702
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001703 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1704 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001705
John McCallf312b1e2010-08-26 23:41:50 +00001706 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001707 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001708}
1709
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001710/// \brief If the given declaration has an associated type, add it as a result
1711/// type chunk.
1712static void AddResultTypeChunk(ASTContext &Context,
1713 NamedDecl *ND,
1714 CodeCompletionString *Result) {
1715 if (!ND)
1716 return;
1717
1718 // Determine the type of the declaration (if it has a type).
1719 QualType T;
1720 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1721 T = Function->getResultType();
1722 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1723 T = Method->getResultType();
1724 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1725 T = FunTmpl->getTemplatedDecl()->getResultType();
1726 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1727 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1728 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1729 /* Do nothing: ignore unresolved using declarations*/
1730 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1731 T = Value->getType();
1732 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1733 T = Property->getType();
1734
1735 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1736 return;
1737
Douglas Gregor84139d62010-04-05 21:25:31 +00001738 PrintingPolicy Policy(Context.PrintingPolicy);
1739 Policy.AnonymousTagLocations = false;
1740
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001741 std::string TypeStr;
Douglas Gregor84139d62010-04-05 21:25:31 +00001742 T.getAsStringInternal(TypeStr, Policy);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001743 Result->AddResultTypeChunk(TypeStr);
1744}
1745
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001746static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
1747 CodeCompletionString *Result) {
1748 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1749 if (Sentinel->getSentinel() == 0) {
1750 if (Context.getLangOptions().ObjC1 &&
1751 Context.Idents.get("nil").hasMacroDefinition())
1752 Result->AddTextChunk(", nil");
1753 else if (Context.Idents.get("NULL").hasMacroDefinition())
1754 Result->AddTextChunk(", NULL");
1755 else
1756 Result->AddTextChunk(", (void*)0");
1757 }
1758}
1759
Douglas Gregor83482d12010-08-24 16:15:59 +00001760static std::string FormatFunctionParameter(ASTContext &Context,
1761 ParmVarDecl *Param) {
1762 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1763 if (Param->getType()->isDependentType() ||
1764 !Param->getType()->isBlockPointerType()) {
1765 // The argument for a dependent or non-block parameter is a placeholder
1766 // containing that parameter's type.
1767 std::string Result;
1768
1769 if (Param->getIdentifier() && !ObjCMethodParam)
1770 Result = Param->getIdentifier()->getName();
1771
1772 Param->getType().getAsStringInternal(Result,
1773 Context.PrintingPolicy);
1774
1775 if (ObjCMethodParam) {
1776 Result = "(" + Result;
1777 Result += ")";
1778 if (Param->getIdentifier())
1779 Result += Param->getIdentifier()->getName();
1780 }
1781 return Result;
1782 }
1783
1784 // The argument for a block pointer parameter is a block literal with
1785 // the appropriate type.
1786 FunctionProtoTypeLoc *Block = 0;
1787 TypeLoc TL;
1788 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1789 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1790 while (true) {
1791 // Look through typedefs.
1792 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1793 if (TypeSourceInfo *InnerTSInfo
1794 = TypedefTL->getTypedefDecl()->getTypeSourceInfo()) {
1795 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1796 continue;
1797 }
1798 }
1799
1800 // Look through qualified types
1801 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1802 TL = QualifiedTL->getUnqualifiedLoc();
1803 continue;
1804 }
1805
1806 // Try to get the function prototype behind the block pointer type,
1807 // then we're done.
1808 if (BlockPointerTypeLoc *BlockPtr
1809 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
1810 TL = BlockPtr->getPointeeLoc();
1811 Block = dyn_cast<FunctionProtoTypeLoc>(&TL);
1812 }
1813 break;
1814 }
1815 }
1816
1817 if (!Block) {
1818 // We were unable to find a FunctionProtoTypeLoc with parameter names
1819 // for the block; just use the parameter type as a placeholder.
1820 std::string Result;
1821 Param->getType().getUnqualifiedType().
1822 getAsStringInternal(Result, Context.PrintingPolicy);
1823
1824 if (ObjCMethodParam) {
1825 Result = "(" + Result;
1826 Result += ")";
1827 if (Param->getIdentifier())
1828 Result += Param->getIdentifier()->getName();
1829 }
1830
1831 return Result;
1832 }
1833
1834 // We have the function prototype behind the block pointer type, as it was
1835 // written in the source.
1836 std::string Result = "(^)(";
1837 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
1838 if (I)
1839 Result += ", ";
1840 Result += FormatFunctionParameter(Context, Block->getArg(I));
1841 }
1842 if (Block->getTypePtr()->isVariadic()) {
1843 if (Block->getNumArgs() > 0)
1844 Result += ", ...";
1845 else
1846 Result += "...";
1847 } else if (Block->getNumArgs() == 0 && !Context.getLangOptions().CPlusPlus)
1848 Result += "void";
1849
1850 Result += ")";
1851 Block->getTypePtr()->getResultType().getAsStringInternal(Result,
1852 Context.PrintingPolicy);
1853 return Result;
1854}
1855
Douglas Gregor86d9a522009-09-21 16:56:56 +00001856/// \brief Add function parameter chunks to the given code completion string.
1857static void AddFunctionParameterChunks(ASTContext &Context,
1858 FunctionDecl *Function,
1859 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001860 typedef CodeCompletionString::Chunk Chunk;
1861
Douglas Gregor86d9a522009-09-21 16:56:56 +00001862 CodeCompletionString *CCStr = Result;
1863
1864 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1865 ParmVarDecl *Param = Function->getParamDecl(P);
1866
1867 if (Param->hasDefaultArg()) {
1868 // When we see an optional default argument, put that argument and
1869 // the remaining default arguments into a new, optional string.
1870 CodeCompletionString *Opt = new CodeCompletionString;
1871 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1872 CCStr = Opt;
1873 }
1874
1875 if (P != 0)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001876 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001877
1878 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00001879 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
1880
Douglas Gregor86d9a522009-09-21 16:56:56 +00001881 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001882 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001883 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00001884
1885 if (const FunctionProtoType *Proto
1886 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001887 if (Proto->isVariadic()) {
Douglas Gregorb3d45252009-09-22 21:42:17 +00001888 CCStr->AddPlaceholderChunk(", ...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001889
1890 MaybeAddSentinel(Context, Function, CCStr);
1891 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001892}
1893
1894/// \brief Add template parameter chunks to the given code completion string.
1895static void AddTemplateParameterChunks(ASTContext &Context,
1896 TemplateDecl *Template,
1897 CodeCompletionString *Result,
1898 unsigned MaxParameters = 0) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001899 typedef CodeCompletionString::Chunk Chunk;
1900
Douglas Gregor86d9a522009-09-21 16:56:56 +00001901 CodeCompletionString *CCStr = Result;
1902 bool FirstParameter = true;
1903
1904 TemplateParameterList *Params = Template->getTemplateParameters();
1905 TemplateParameterList::iterator PEnd = Params->end();
1906 if (MaxParameters)
1907 PEnd = Params->begin() + MaxParameters;
1908 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1909 bool HasDefaultArg = false;
1910 std::string PlaceholderStr;
1911 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1912 if (TTP->wasDeclaredWithTypename())
1913 PlaceholderStr = "typename";
1914 else
1915 PlaceholderStr = "class";
1916
1917 if (TTP->getIdentifier()) {
1918 PlaceholderStr += ' ';
1919 PlaceholderStr += TTP->getIdentifier()->getName();
1920 }
1921
1922 HasDefaultArg = TTP->hasDefaultArgument();
1923 } else if (NonTypeTemplateParmDecl *NTTP
1924 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1925 if (NTTP->getIdentifier())
1926 PlaceholderStr = NTTP->getIdentifier()->getName();
1927 NTTP->getType().getAsStringInternal(PlaceholderStr,
1928 Context.PrintingPolicy);
1929 HasDefaultArg = NTTP->hasDefaultArgument();
1930 } else {
1931 assert(isa<TemplateTemplateParmDecl>(*P));
1932 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1933
1934 // Since putting the template argument list into the placeholder would
1935 // be very, very long, we just use an abbreviation.
1936 PlaceholderStr = "template<...> class";
1937 if (TTP->getIdentifier()) {
1938 PlaceholderStr += ' ';
1939 PlaceholderStr += TTP->getIdentifier()->getName();
1940 }
1941
1942 HasDefaultArg = TTP->hasDefaultArgument();
1943 }
1944
1945 if (HasDefaultArg) {
1946 // When we see an optional default argument, put that argument and
1947 // the remaining default arguments into a new, optional string.
1948 CodeCompletionString *Opt = new CodeCompletionString;
1949 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1950 CCStr = Opt;
1951 }
1952
1953 if (FirstParameter)
1954 FirstParameter = false;
1955 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001956 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001957
1958 // Add the placeholder string.
Benjamin Kramer660cc182009-11-29 20:18:50 +00001959 CCStr->AddPlaceholderChunk(PlaceholderStr);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001960 }
1961}
1962
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001963/// \brief Add a qualifier to the given code-completion string, if the
1964/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00001965static void
1966AddQualifierToCompletionString(CodeCompletionString *Result,
1967 NestedNameSpecifier *Qualifier,
1968 bool QualifierIsInformative,
1969 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001970 if (!Qualifier)
1971 return;
1972
1973 std::string PrintedNNS;
1974 {
1975 llvm::raw_string_ostream OS(PrintedNNS);
1976 Qualifier->print(OS, Context.PrintingPolicy);
1977 }
Douglas Gregor0563c262009-09-22 23:15:58 +00001978 if (QualifierIsInformative)
Benjamin Kramer660cc182009-11-29 20:18:50 +00001979 Result->AddInformativeChunk(PrintedNNS);
Douglas Gregor0563c262009-09-22 23:15:58 +00001980 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00001981 Result->AddTextChunk(PrintedNNS);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00001982}
1983
Douglas Gregora61a8792009-12-11 18:44:16 +00001984static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1985 FunctionDecl *Function) {
1986 const FunctionProtoType *Proto
1987 = Function->getType()->getAs<FunctionProtoType>();
1988 if (!Proto || !Proto->getTypeQuals())
1989 return;
1990
1991 std::string QualsStr;
1992 if (Proto->getTypeQuals() & Qualifiers::Const)
1993 QualsStr += " const";
1994 if (Proto->getTypeQuals() & Qualifiers::Volatile)
1995 QualsStr += " volatile";
1996 if (Proto->getTypeQuals() & Qualifiers::Restrict)
1997 QualsStr += " restrict";
1998 Result->AddInformativeChunk(QualsStr);
1999}
2000
Douglas Gregor86d9a522009-09-21 16:56:56 +00002001/// \brief If possible, create a new code completion string for the given
2002/// result.
2003///
2004/// \returns Either a new, heap-allocated code completion string describing
2005/// how to use this result, or NULL to indicate that the string or name of the
2006/// result is all that is needed.
2007CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002008CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002009 CodeCompletionString *Result) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002010 typedef CodeCompletionString::Chunk Chunk;
2011
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002012 if (Kind == RK_Pattern)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002013 return Pattern->Clone(Result);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002014
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002015 if (!Result)
2016 Result = new CodeCompletionString;
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002017
2018 if (Kind == RK_Keyword) {
2019 Result->AddTypedTextChunk(Keyword);
2020 return Result;
2021 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002022
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002023 if (Kind == RK_Macro) {
2024 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002025 assert(MI && "Not a macro?");
2026
2027 Result->AddTypedTextChunk(Macro->getName());
2028
2029 if (!MI->isFunctionLike())
2030 return Result;
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002031
2032 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002033 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002034 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2035 A != AEnd; ++A) {
2036 if (A != MI->arg_begin())
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002037 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002038
2039 if (!MI->isVariadic() || A != AEnd - 1) {
2040 // Non-variadic argument.
Benjamin Kramer660cc182009-11-29 20:18:50 +00002041 Result->AddPlaceholderChunk((*A)->getName());
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002042 continue;
2043 }
2044
2045 // Variadic argument; cope with the different between GNU and C99
2046 // variadic macros, providing a single placeholder for the rest of the
2047 // arguments.
2048 if ((*A)->isStr("__VA_ARGS__"))
2049 Result->AddPlaceholderChunk("...");
2050 else {
2051 std::string Arg = (*A)->getName();
2052 Arg += "...";
Benjamin Kramer660cc182009-11-29 20:18:50 +00002053 Result->AddPlaceholderChunk(Arg);
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002054 }
2055 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002056 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002057 return Result;
2058 }
2059
Douglas Gregord8e8a582010-05-25 21:41:55 +00002060 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002061 NamedDecl *ND = Declaration;
2062
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002063 if (StartsNestedNameSpecifier) {
Benjamin Kramer660cc182009-11-29 20:18:50 +00002064 Result->AddTypedTextChunk(ND->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002065 Result->AddTextChunk("::");
2066 return Result;
2067 }
2068
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002069 AddResultTypeChunk(S.Context, ND, Result);
2070
Douglas Gregor86d9a522009-09-21 16:56:56 +00002071 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002072 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2073 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00002074 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002075 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002076 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002077 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002078 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002079 return Result;
2080 }
2081
2082 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002083 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2084 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002085 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Benjamin Kramer660cc182009-11-29 20:18:50 +00002086 Result->AddTypedTextChunk(Function->getNameAsString());
Douglas Gregor86d9a522009-09-21 16:56:56 +00002087
2088 // Figure out which template parameters are deduced (or have default
2089 // arguments).
2090 llvm::SmallVector<bool, 16> Deduced;
2091 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2092 unsigned LastDeducibleArgument;
2093 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2094 --LastDeducibleArgument) {
2095 if (!Deduced[LastDeducibleArgument - 1]) {
2096 // C++0x: Figure out if the template argument has a default. If so,
2097 // the user doesn't need to type this argument.
2098 // FIXME: We need to abstract template parameters better!
2099 bool HasDefaultArg = false;
2100 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2101 LastDeducibleArgument - 1);
2102 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2103 HasDefaultArg = TTP->hasDefaultArgument();
2104 else if (NonTypeTemplateParmDecl *NTTP
2105 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2106 HasDefaultArg = NTTP->hasDefaultArgument();
2107 else {
2108 assert(isa<TemplateTemplateParmDecl>(Param));
2109 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002110 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002111 }
2112
2113 if (!HasDefaultArg)
2114 break;
2115 }
2116 }
2117
2118 if (LastDeducibleArgument) {
2119 // Some of the function template arguments cannot be deduced from a
2120 // function call, so we introduce an explicit template argument list
2121 // containing all of the arguments up to the first deducible argument.
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002122 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002123 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2124 LastDeducibleArgument);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002125 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002126 }
2127
2128 // Add the function parameters
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002129 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002130 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002131 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002132 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002133 return Result;
2134 }
2135
2136 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002137 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2138 S.Context);
Benjamin Kramer660cc182009-11-29 20:18:50 +00002139 Result->AddTypedTextChunk(Template->getNameAsString());
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002140 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002141 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002142 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002143 return Result;
2144 }
2145
Douglas Gregor9630eb62009-11-17 16:44:22 +00002146 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002147 Selector Sel = Method->getSelector();
2148 if (Sel.isUnarySelector()) {
2149 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
2150 return Result;
2151 }
2152
Douglas Gregord3c68542009-11-19 01:08:35 +00002153 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
2154 SelName += ':';
2155 if (StartParameter == 0)
2156 Result->AddTypedTextChunk(SelName);
2157 else {
2158 Result->AddInformativeChunk(SelName);
2159
2160 // If there is only one parameter, and we're past it, add an empty
2161 // typed-text chunk since there is nothing to type.
2162 if (Method->param_size() == 1)
2163 Result->AddTypedTextChunk("");
2164 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002165 unsigned Idx = 0;
2166 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2167 PEnd = Method->param_end();
2168 P != PEnd; (void)++P, ++Idx) {
2169 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002170 std::string Keyword;
2171 if (Idx > StartParameter)
Douglas Gregor834389b2010-01-12 06:38:28 +00002172 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002173 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2174 Keyword += II->getName().str();
2175 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002176 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregord3c68542009-11-19 01:08:35 +00002177 Result->AddInformativeChunk(Keyword);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002178 else if (Idx == StartParameter)
Douglas Gregord3c68542009-11-19 01:08:35 +00002179 Result->AddTypedTextChunk(Keyword);
2180 else
2181 Result->AddTextChunk(Keyword);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002182 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002183
2184 // If we're before the starting parameter, skip the placeholder.
2185 if (Idx < StartParameter)
2186 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002187
2188 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002189
2190 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
2191 Arg = FormatFunctionParameter(S.Context, *P);
2192 else {
2193 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
2194 Arg = "(" + Arg + ")";
2195 if (IdentifierInfo *II = (*P)->getIdentifier())
2196 Arg += II->getName().str();
2197 }
2198
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002199 if (DeclaringEntity)
2200 Result->AddTextChunk(Arg);
2201 else if (AllParametersAreInformative)
Douglas Gregor4ad96852009-11-19 07:41:15 +00002202 Result->AddInformativeChunk(Arg);
2203 else
2204 Result->AddPlaceholderChunk(Arg);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002205 }
2206
Douglas Gregor2a17af02009-12-23 00:21:46 +00002207 if (Method->isVariadic()) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002208 if (DeclaringEntity)
2209 Result->AddTextChunk(", ...");
2210 else if (AllParametersAreInformative)
Douglas Gregor2a17af02009-12-23 00:21:46 +00002211 Result->AddInformativeChunk(", ...");
2212 else
2213 Result->AddPlaceholderChunk(", ...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002214
2215 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002216 }
2217
Douglas Gregor9630eb62009-11-17 16:44:22 +00002218 return Result;
2219 }
2220
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002221 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002222 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2223 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002224
2225 Result->AddTypedTextChunk(ND->getNameAsString());
2226 return Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002227}
2228
Douglas Gregor86d802e2009-09-23 00:34:09 +00002229CodeCompletionString *
2230CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2231 unsigned CurrentArg,
2232 Sema &S) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002233 typedef CodeCompletionString::Chunk Chunk;
2234
Douglas Gregor86d802e2009-09-23 00:34:09 +00002235 CodeCompletionString *Result = new CodeCompletionString;
2236 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002237 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002238 const FunctionProtoType *Proto
2239 = dyn_cast<FunctionProtoType>(getFunctionType());
2240 if (!FDecl && !Proto) {
2241 // Function without a prototype. Just give the return type and a
2242 // highlighted ellipsis.
2243 const FunctionType *FT = getFunctionType();
2244 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002245 FT->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002246 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2247 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2248 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002249 return Result;
2250 }
2251
2252 if (FDecl)
Benjamin Kramer660cc182009-11-29 20:18:50 +00002253 Result->AddTextChunk(FDecl->getNameAsString());
Douglas Gregor86d802e2009-09-23 00:34:09 +00002254 else
2255 Result->AddTextChunk(
Benjamin Kramer660cc182009-11-29 20:18:50 +00002256 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002257
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002258 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002259 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2260 for (unsigned I = 0; I != NumParams; ++I) {
2261 if (I)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002262 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002263
2264 std::string ArgString;
2265 QualType ArgType;
2266
2267 if (FDecl) {
2268 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2269 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2270 } else {
2271 ArgType = Proto->getArgType(I);
2272 }
2273
2274 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2275
2276 if (I == CurrentArg)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002277 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Benjamin Kramer660cc182009-11-29 20:18:50 +00002278 ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002279 else
Benjamin Kramer660cc182009-11-29 20:18:50 +00002280 Result->AddTextChunk(ArgString);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002281 }
2282
2283 if (Proto && Proto->isVariadic()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002284 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002285 if (CurrentArg < NumParams)
2286 Result->AddTextChunk("...");
2287 else
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002288 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002289 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002290 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002291
2292 return Result;
2293}
2294
Douglas Gregor1827e102010-08-16 16:18:59 +00002295unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName,
2296 bool PreferredTypeIsPointer) {
2297 unsigned Priority = CCP_Macro;
2298
2299 // Treat the "nil" and "NULL" macros as null pointer constants.
2300 if (MacroName.equals("nil") || MacroName.equals("NULL")) {
2301 Priority = CCP_Constant;
2302 if (PreferredTypeIsPointer)
2303 Priority = Priority / CCF_SimilarTypeMatch;
2304 }
2305
2306 return Priority;
2307}
2308
Douglas Gregor590c7d52010-07-08 20:55:51 +00002309static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2310 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002311 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002312
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002313 Results.EnterNewScope();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002314 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2315 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002316 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002317 Results.AddResult(Result(M->first,
2318 getMacroUsagePriority(M->first->getName(),
2319 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002320 }
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002321 Results.ExitScope();
2322}
2323
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002324static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2325 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002326 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002327
2328 Results.EnterNewScope();
2329 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2330 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2331 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2332 Results.AddResult(Result("__func__", CCP_Constant));
2333 Results.ExitScope();
2334}
2335
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002336static void HandleCodeCompleteResults(Sema *S,
2337 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002338 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002339 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002340 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002341 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002342 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor54f01612009-11-19 00:01:57 +00002343
2344 for (unsigned I = 0; I != NumResults; ++I)
2345 Results[I].Destroy();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002346}
2347
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002348static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2349 Sema::ParserCompletionContext PCC) {
2350 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002351 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002352 return CodeCompletionContext::CCC_TopLevel;
2353
John McCallf312b1e2010-08-26 23:41:50 +00002354 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002355 return CodeCompletionContext::CCC_ClassStructUnion;
2356
John McCallf312b1e2010-08-26 23:41:50 +00002357 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002358 return CodeCompletionContext::CCC_ObjCInterface;
2359
John McCallf312b1e2010-08-26 23:41:50 +00002360 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002361 return CodeCompletionContext::CCC_ObjCImplementation;
2362
John McCallf312b1e2010-08-26 23:41:50 +00002363 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002364 return CodeCompletionContext::CCC_ObjCIvarList;
2365
John McCallf312b1e2010-08-26 23:41:50 +00002366 case Sema::PCC_Template:
2367 case Sema::PCC_MemberTemplate:
2368 case Sema::PCC_RecoveryInFunction:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002369 return CodeCompletionContext::CCC_Other;
2370
John McCallf312b1e2010-08-26 23:41:50 +00002371 case Sema::PCC_Expression:
2372 case Sema::PCC_ForInit:
2373 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002374 return CodeCompletionContext::CCC_Expression;
2375
John McCallf312b1e2010-08-26 23:41:50 +00002376 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002377 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002378
John McCallf312b1e2010-08-26 23:41:50 +00002379 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002380 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002381 }
2382
2383 return CodeCompletionContext::CCC_Other;
2384}
2385
Douglas Gregor01dfea02010-01-10 23:08:15 +00002386void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002387 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002388 typedef CodeCompletionResult Result;
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002389 ResultBuilder Results(*this);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002390
2391 // Determine how to filter results, e.g., so that the names of
2392 // values (functions, enumerators, function templates, etc.) are
2393 // only allowed where we can have an expression.
2394 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002395 case PCC_Namespace:
2396 case PCC_Class:
2397 case PCC_ObjCInterface:
2398 case PCC_ObjCImplementation:
2399 case PCC_ObjCInstanceVariableList:
2400 case PCC_Template:
2401 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002402 case PCC_Type:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002403 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2404 break;
2405
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002406 case PCC_Statement:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002407 // For statements that are expressions, we prefer to call 'void' functions
2408 // rather than functions that return a result, since then the result would
2409 // be ignored.
2410 Results.setPreferredType(Context.VoidTy);
2411 // Fall through
2412
2413 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002414 case PCC_ForInit:
2415 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002416 if (WantTypesInContext(CompletionContext, getLangOptions()))
2417 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2418 else
2419 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002420 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002421
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002422 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002423 // Unfiltered
2424 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002425 }
2426
Douglas Gregor3cdee122010-08-26 16:36:48 +00002427 // If we are in a C++ non-static member function, check the qualifiers on
2428 // the member function to filter/prioritize the results list.
2429 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2430 if (CurMethod->isInstance())
2431 Results.setObjectTypeQualifiers(
2432 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2433
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002434 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002435 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2436 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002437
2438 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00002439 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002440 Results.ExitScope();
2441
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002442 switch (CompletionContext) {
Douglas Gregor72db1082010-08-24 01:11:00 +00002443 case PCC_Expression:
2444 case PCC_Statement:
2445 case PCC_RecoveryInFunction:
2446 if (S->getFnParent())
2447 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2448 break;
2449
2450 case PCC_Namespace:
2451 case PCC_Class:
2452 case PCC_ObjCInterface:
2453 case PCC_ObjCImplementation:
2454 case PCC_ObjCInstanceVariableList:
2455 case PCC_Template:
2456 case PCC_MemberTemplate:
2457 case PCC_ForInit:
2458 case PCC_Condition:
2459 case PCC_Type:
2460 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002461 }
2462
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002463 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002464 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002465
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002466 HandleCodeCompleteResults(this, CodeCompleter,
2467 mapCodeCompletionContext(*this, CompletionContext),
2468 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002469}
2470
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002471void Sema::CodeCompleteDeclarator(Scope *S,
2472 bool AllowNonIdentifiers,
2473 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00002474 typedef CodeCompletionResult Result;
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002475 ResultBuilder Results(*this);
2476 Results.EnterNewScope();
2477
2478 // Type qualifiers can come after names.
2479 Results.AddResult(Result("const"));
2480 Results.AddResult(Result("volatile"));
2481 if (getLangOptions().C99)
2482 Results.AddResult(Result("restrict"));
2483
2484 if (getLangOptions().CPlusPlus) {
2485 if (AllowNonIdentifiers) {
2486 Results.AddResult(Result("operator"));
2487 }
2488
2489 // Add nested-name-specifiers.
2490 if (AllowNestedNameSpecifiers) {
2491 Results.allowNestedNameSpecifiers();
2492 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2493 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
2494 CodeCompleter->includeGlobals());
2495 }
2496 }
2497 Results.ExitScope();
2498
Douglas Gregor4497dd42010-08-24 04:59:56 +00002499 // Note that we intentionally suppress macro results here, since we do not
2500 // encourage using macros to produce the names of entities.
2501
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002502 HandleCodeCompleteResults(this, CodeCompleter,
2503 AllowNestedNameSpecifiers
2504 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2505 : CodeCompletionContext::CCC_Name,
2506 Results.data(), Results.size());
2507}
2508
Douglas Gregorfb629412010-08-23 21:17:50 +00002509struct Sema::CodeCompleteExpressionData {
2510 CodeCompleteExpressionData(QualType PreferredType = QualType())
2511 : PreferredType(PreferredType), IntegralConstantExpression(false),
2512 ObjCCollection(false) { }
2513
2514 QualType PreferredType;
2515 bool IntegralConstantExpression;
2516 bool ObjCCollection;
2517 llvm::SmallVector<Decl *, 4> IgnoreDecls;
2518};
2519
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002520/// \brief Perform code-completion in an expression context when we know what
2521/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00002522///
2523/// \param IntegralConstantExpression Only permit integral constant
2524/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00002525void Sema::CodeCompleteExpression(Scope *S,
2526 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00002527 typedef CodeCompletionResult Result;
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002528 ResultBuilder Results(*this);
2529
Douglas Gregorfb629412010-08-23 21:17:50 +00002530 if (Data.ObjCCollection)
2531 Results.setFilter(&ResultBuilder::IsObjCCollection);
2532 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00002533 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002534 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002535 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2536 else
2537 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00002538
2539 if (!Data.PreferredType.isNull())
2540 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
2541
2542 // Ignore any declarations that we were told that we don't care about.
2543 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
2544 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002545
2546 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002547 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2548 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002549
2550 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002551 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002552 Results.ExitScope();
2553
Douglas Gregor590c7d52010-07-08 20:55:51 +00002554 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00002555 if (!Data.PreferredType.isNull())
2556 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
2557 || Data.PreferredType->isMemberPointerType()
2558 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002559
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002560 if (S->getFnParent() &&
2561 !Data.ObjCCollection &&
2562 !Data.IntegralConstantExpression)
2563 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2564
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002565 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00002566 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002567 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00002568 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
2569 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002570 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002571}
2572
2573
Douglas Gregor95ac6552009-11-18 01:29:26 +00002574static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00002575 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00002576 DeclContext *CurContext,
2577 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002578 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00002579
2580 // Add properties in this container.
2581 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2582 PEnd = Container->prop_end();
2583 P != PEnd;
2584 ++P)
2585 Results.MaybeAddResult(Result(*P, 0), CurContext);
2586
2587 // Add properties in referenced protocols.
2588 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2589 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2590 PEnd = Protocol->protocol_end();
2591 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002592 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002593 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00002594 if (AllowCategories) {
2595 // Look through categories.
2596 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2597 Category; Category = Category->getNextClassCategory())
2598 AddObjCProperties(Category, AllowCategories, CurContext, Results);
2599 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002600
2601 // Look through protocols.
2602 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
2603 E = IFace->protocol_end();
2604 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002605 AddObjCProperties(*I, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002606
2607 // Look in the superclass.
2608 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00002609 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
2610 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002611 } else if (const ObjCCategoryDecl *Category
2612 = dyn_cast<ObjCCategoryDecl>(Container)) {
2613 // Look through protocols.
2614 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
2615 PEnd = Category->protocol_end();
2616 P != PEnd; ++P)
Douglas Gregor322328b2009-11-18 22:32:06 +00002617 AddObjCProperties(*P, AllowCategories, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002618 }
2619}
2620
Douglas Gregor81b747b2009-09-17 21:32:03 +00002621void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
2622 SourceLocation OpLoc,
2623 bool IsArrow) {
2624 if (!BaseE || !CodeCompleter)
2625 return;
2626
John McCall0a2c5e22010-08-25 06:19:51 +00002627 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002628
Douglas Gregor81b747b2009-09-17 21:32:03 +00002629 Expr *Base = static_cast<Expr *>(BaseE);
2630 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002631
2632 if (IsArrow) {
2633 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2634 BaseType = Ptr->getPointeeType();
2635 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00002636 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002637 else
2638 return;
2639 }
2640
Douglas Gregoreb5758b2009-09-23 22:26:46 +00002641 ResultBuilder Results(*this, &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002642 Results.EnterNewScope();
2643 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00002644 // Indicate that we are performing a member access, and the cv-qualifiers
2645 // for the base object type.
2646 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
2647
Douglas Gregor95ac6552009-11-18 01:29:26 +00002648 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00002649 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00002650 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002651 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
2652 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002653
Douglas Gregor95ac6552009-11-18 01:29:26 +00002654 if (getLangOptions().CPlusPlus) {
2655 if (!Results.empty()) {
2656 // The "template" keyword can follow "->" or "." in the grammar.
2657 // However, we only want to suggest the template keyword if something
2658 // is dependent.
2659 bool IsDependent = BaseType->isDependentType();
2660 if (!IsDependent) {
2661 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2662 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2663 IsDependent = Ctx->isDependentContext();
2664 break;
2665 }
2666 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002667
Douglas Gregor95ac6552009-11-18 01:29:26 +00002668 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00002669 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002670 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002671 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002672 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2673 // Objective-C property reference.
2674
2675 // Add property results based on our interface.
2676 const ObjCObjectPointerType *ObjCPtr
2677 = BaseType->getAsObjCInterfacePointerType();
2678 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor322328b2009-11-18 22:32:06 +00002679 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002680
2681 // Add properties from the protocols in a qualified interface.
2682 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2683 E = ObjCPtr->qual_end();
2684 I != E; ++I)
Douglas Gregor322328b2009-11-18 22:32:06 +00002685 AddObjCProperties(*I, true, CurContext, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00002686 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00002687 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00002688 // Objective-C instance variable access.
2689 ObjCInterfaceDecl *Class = 0;
2690 if (const ObjCObjectPointerType *ObjCPtr
2691 = BaseType->getAs<ObjCObjectPointerType>())
2692 Class = ObjCPtr->getInterfaceDecl();
2693 else
John McCallc12c5bb2010-05-15 11:32:37 +00002694 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00002695
2696 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00002697 if (Class) {
2698 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2699 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00002700 LookupVisibleDecls(Class, LookupMemberName, Consumer,
2701 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00002702 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002703 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00002704
2705 // FIXME: How do we cope with isa?
2706
2707 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002708
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002709 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002710 HandleCodeCompleteResults(this, CodeCompleter,
2711 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
2712 BaseType),
2713 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00002714}
2715
Douglas Gregor374929f2009-09-18 15:37:17 +00002716void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2717 if (!CodeCompleter)
2718 return;
2719
John McCall0a2c5e22010-08-25 06:19:51 +00002720 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002721 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002722 enum CodeCompletionContext::Kind ContextKind
2723 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00002724 switch ((DeclSpec::TST)TagSpec) {
2725 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002726 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002727 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002728 break;
2729
2730 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002731 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002732 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002733 break;
2734
2735 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00002736 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00002737 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002738 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00002739 break;
2740
2741 default:
2742 assert(false && "Unknown type specifier kind in CodeCompleteTag");
2743 return;
2744 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002745
John McCall0d6b1642010-04-23 18:46:30 +00002746 ResultBuilder Results(*this);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00002747 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00002748
2749 // First pass: look for tags.
2750 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00002751 LookupVisibleDecls(S, LookupTagName, Consumer,
2752 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00002753
Douglas Gregor8071e422010-08-15 06:18:01 +00002754 if (CodeCompleter->includeGlobals()) {
2755 // Second pass: look for nested name specifiers.
2756 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
2757 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
2758 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002759
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002760 HandleCodeCompleteResults(this, CodeCompleter, ContextKind,
2761 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00002762}
2763
Douglas Gregor1a480c42010-08-27 17:35:51 +00002764void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
2765 ResultBuilder Results(*this);
2766 Results.EnterNewScope();
2767 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
2768 Results.AddResult("const");
2769 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
2770 Results.AddResult("volatile");
2771 if (getLangOptions().C99 &&
2772 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
2773 Results.AddResult("restrict");
2774 Results.ExitScope();
2775 HandleCodeCompleteResults(this, CodeCompleter,
2776 CodeCompletionContext::CCC_TypeQualifiers,
2777 Results.data(), Results.size());
2778}
2779
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002780void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00002781 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002782 return;
2783
John McCall781472f2010-08-25 08:40:02 +00002784 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregorf9578432010-07-28 21:50:18 +00002785 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregorfb629412010-08-23 21:17:50 +00002786 CodeCompleteExpressionData Data(Switch->getCond()->getType());
2787 Data.IntegralConstantExpression = true;
2788 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002789 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00002790 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002791
2792 // Code-complete the cases of a switch statement over an enumeration type
2793 // by providing the list of
2794 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2795
2796 // Determine which enumerators we have already seen in the switch statement.
2797 // FIXME: Ideally, we would also be able to look *past* the code-completion
2798 // token, in case we are code-completing in the middle of the switch and not
2799 // at the end. However, we aren't able to do so at the moment.
2800 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002801 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002802 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2803 SC = SC->getNextSwitchCase()) {
2804 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2805 if (!Case)
2806 continue;
2807
2808 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2809 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2810 if (EnumConstantDecl *Enumerator
2811 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2812 // We look into the AST of the case statement to determine which
2813 // enumerator was named. Alternatively, we could compute the value of
2814 // the integral constant expression, then compare it against the
2815 // values of each enumerator. However, value-based approach would not
2816 // work as well with C++ templates where enumerators declared within a
2817 // template are type- and value-dependent.
2818 EnumeratorsSeen.insert(Enumerator);
2819
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002820 // If this is a qualified-id, keep track of the nested-name-specifier
2821 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002822 //
2823 // switch (TagD.getKind()) {
2824 // case TagDecl::TK_enum:
2825 // break;
2826 // case XXX
2827 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002828 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002829 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2830 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002831 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002832 }
2833 }
2834
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002835 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2836 // If there are no prior enumerators in C++, check whether we have to
2837 // qualify the names of the enumerators that we suggest, because they
2838 // may not be visible in this scope.
2839 Qualifier = getRequiredQualification(Context, CurContext,
2840 Enum->getDeclContext());
2841
2842 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2843 }
2844
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002845 // Add any enumerators that have not yet been mentioned.
2846 ResultBuilder Results(*this);
2847 Results.EnterNewScope();
2848 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2849 EEnd = Enum->enumerator_end();
2850 E != EEnd; ++E) {
2851 if (EnumeratorsSeen.count(*E))
2852 continue;
2853
John McCall0a2c5e22010-08-25 06:19:51 +00002854 Results.AddResult(CodeCompletionResult(*E, Qualifier),
Douglas Gregor608300b2010-01-14 16:14:35 +00002855 CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002856 }
2857 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00002858
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002859 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002860 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002861 HandleCodeCompleteResults(this, CodeCompleter,
2862 CodeCompletionContext::CCC_Expression,
2863 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00002864}
2865
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002866namespace {
2867 struct IsBetterOverloadCandidate {
2868 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00002869 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002870
2871 public:
John McCall5769d612010-02-08 23:07:23 +00002872 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
2873 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002874
2875 bool
2876 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00002877 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002878 }
2879 };
2880}
2881
Douglas Gregord28dcd72010-05-30 06:10:08 +00002882static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
2883 if (NumArgs && !Args)
2884 return true;
2885
2886 for (unsigned I = 0; I != NumArgs; ++I)
2887 if (!Args[I])
2888 return true;
2889
2890 return false;
2891}
2892
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002893void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2894 ExprTy **ArgsIn, unsigned NumArgs) {
2895 if (!CodeCompleter)
2896 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002897
2898 // When we're code-completing for a call, we fall back to ordinary
2899 // name code-completion whenever we can't produce specific
2900 // results. We may want to revisit this strategy in the future,
2901 // e.g., by merging the two kinds of results.
2902
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002903 Expr *Fn = (Expr *)FnIn;
2904 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002905
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002906 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00002907 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00002908 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002909 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002910 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00002911 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002912
John McCall3b4294e2009-12-16 12:17:52 +00002913 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00002914 SourceLocation Loc = Fn->getExprLoc();
2915 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00002916
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002917 // FIXME: What if we're calling something that isn't a function declaration?
2918 // FIXME: What if we're calling a pseudo-destructor?
2919 // FIXME: What if we're calling a member function?
2920
Douglas Gregorc0265402010-01-21 15:46:19 +00002921 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
2922 llvm::SmallVector<ResultCandidate, 8> Results;
2923
John McCall3b4294e2009-12-16 12:17:52 +00002924 Expr *NakedFn = Fn->IgnoreParenCasts();
2925 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
2926 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
2927 /*PartialOverloading=*/ true);
2928 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
2929 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00002930 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00002931 if (!getLangOptions().CPlusPlus ||
2932 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00002933 Results.push_back(ResultCandidate(FDecl));
2934 else
John McCall86820f52010-01-26 01:37:31 +00002935 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00002936 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
2937 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00002938 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00002939 }
John McCall3b4294e2009-12-16 12:17:52 +00002940 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002941
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002942 QualType ParamType;
2943
Douglas Gregorc0265402010-01-21 15:46:19 +00002944 if (!CandidateSet.empty()) {
2945 // Sort the overload candidate set by placing the best overloads first.
2946 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00002947 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002948
Douglas Gregorc0265402010-01-21 15:46:19 +00002949 // Add the remaining viable overload candidates as code-completion reslults.
2950 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2951 CandEnd = CandidateSet.end();
2952 Cand != CandEnd; ++Cand) {
2953 if (Cand->Viable)
2954 Results.push_back(ResultCandidate(Cand->Function));
2955 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002956
2957 // From the viable candidates, try to determine the type of this parameter.
2958 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
2959 if (const FunctionType *FType = Results[I].getFunctionType())
2960 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
2961 if (NumArgs < Proto->getNumArgs()) {
2962 if (ParamType.isNull())
2963 ParamType = Proto->getArgType(NumArgs);
2964 else if (!Context.hasSameUnqualifiedType(
2965 ParamType.getNonReferenceType(),
2966 Proto->getArgType(NumArgs).getNonReferenceType())) {
2967 ParamType = QualType();
2968 break;
2969 }
2970 }
2971 }
2972 } else {
2973 // Try to determine the parameter type from the type of the expression
2974 // being called.
2975 QualType FunctionType = Fn->getType();
2976 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
2977 FunctionType = Ptr->getPointeeType();
2978 else if (const BlockPointerType *BlockPtr
2979 = FunctionType->getAs<BlockPointerType>())
2980 FunctionType = BlockPtr->getPointeeType();
2981 else if (const MemberPointerType *MemPtr
2982 = FunctionType->getAs<MemberPointerType>())
2983 FunctionType = MemPtr->getPointeeType();
2984
2985 if (const FunctionProtoType *Proto
2986 = FunctionType->getAs<FunctionProtoType>()) {
2987 if (NumArgs < Proto->getNumArgs())
2988 ParamType = Proto->getArgType(NumArgs);
2989 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002990 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00002991
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002992 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002993 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002994 else
2995 CodeCompleteExpression(S, ParamType);
2996
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00002997 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00002998 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
2999 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003000}
3001
John McCalld226f652010-08-21 09:40:31 +00003002void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3003 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003004 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003005 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003006 return;
3007 }
3008
3009 CodeCompleteExpression(S, VD->getType());
3010}
3011
3012void Sema::CodeCompleteReturn(Scope *S) {
3013 QualType ResultType;
3014 if (isa<BlockDecl>(CurContext)) {
3015 if (BlockScopeInfo *BSI = getCurBlock())
3016 ResultType = BSI->ReturnType;
3017 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3018 ResultType = Function->getResultType();
3019 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3020 ResultType = Method->getResultType();
3021
3022 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003023 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003024 else
3025 CodeCompleteExpression(S, ResultType);
3026}
3027
3028void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3029 if (LHS)
3030 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3031 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003032 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003033}
3034
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003035void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003036 bool EnteringContext) {
3037 if (!SS.getScopeRep() || !CodeCompleter)
3038 return;
3039
Douglas Gregor86d9a522009-09-21 16:56:56 +00003040 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3041 if (!Ctx)
3042 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003043
3044 // Try to instantiate any non-dependent declaration contexts before
3045 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003046 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003047 return;
3048
Douglas Gregor86d9a522009-09-21 16:56:56 +00003049 ResultBuilder Results(*this);
Douglas Gregordef91072010-01-14 03:35:48 +00003050 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3051 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
Douglas Gregor86d9a522009-09-21 16:56:56 +00003052
3053 // The "template" keyword can follow "::" in the grammar, but only
3054 // put it into the grammar if the nested-name-specifier is dependent.
3055 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3056 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003057 Results.AddResult("template");
Douglas Gregor86d9a522009-09-21 16:56:56 +00003058
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003059 HandleCodeCompleteResults(this, CodeCompleter,
3060 CodeCompletionContext::CCC_Other,
3061 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003062}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003063
3064void Sema::CodeCompleteUsing(Scope *S) {
3065 if (!CodeCompleter)
3066 return;
3067
Douglas Gregor86d9a522009-09-21 16:56:56 +00003068 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003069 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003070
3071 // If we aren't in class scope, we could see the "namespace" keyword.
3072 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003073 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003074
3075 // After "using", we can see anything that would start a
3076 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003077 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003078 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3079 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003080 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003081
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003082 HandleCodeCompleteResults(this, CodeCompleter,
3083 CodeCompletionContext::CCC_Other,
3084 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003085}
3086
3087void Sema::CodeCompleteUsingDirective(Scope *S) {
3088 if (!CodeCompleter)
3089 return;
3090
Douglas Gregor86d9a522009-09-21 16:56:56 +00003091 // After "using namespace", we expect to see a namespace name or namespace
3092 // alias.
3093 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003094 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003095 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003096 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3097 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003098 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003099 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003100 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003101 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003102}
3103
3104void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3105 if (!CodeCompleter)
3106 return;
3107
Douglas Gregor86d9a522009-09-21 16:56:56 +00003108 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
3109 DeclContext *Ctx = (DeclContext *)S->getEntity();
3110 if (!S->getParent())
3111 Ctx = Context.getTranslationUnitDecl();
3112
3113 if (Ctx && Ctx->isFileContext()) {
3114 // We only want to see those namespaces that have already been defined
3115 // within this scope, because its likely that the user is creating an
3116 // extended namespace declaration. Keep track of the most recent
3117 // definition of each namespace.
3118 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3119 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3120 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3121 NS != NSEnd; ++NS)
3122 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3123
3124 // Add the most recent definition (or extended definition) of each
3125 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003126 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003127 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3128 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3129 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003130 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003131 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003132 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003133 }
3134
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003135 HandleCodeCompleteResults(this, CodeCompleter,
3136 CodeCompletionContext::CCC_Other,
3137 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003138}
3139
3140void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3141 if (!CodeCompleter)
3142 return;
3143
Douglas Gregor86d9a522009-09-21 16:56:56 +00003144 // After "namespace", we expect to see a namespace or alias.
3145 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003146 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003147 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3148 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003149 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003150 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003151 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003152}
3153
Douglas Gregored8d3222009-09-18 20:05:18 +00003154void Sema::CodeCompleteOperatorName(Scope *S) {
3155 if (!CodeCompleter)
3156 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003157
John McCall0a2c5e22010-08-25 06:19:51 +00003158 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003159 ResultBuilder Results(*this, &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003160 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003161
Douglas Gregor86d9a522009-09-21 16:56:56 +00003162 // Add the names of overloadable operators.
3163#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3164 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003165 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003166#include "clang/Basic/OperatorKinds.def"
3167
3168 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003169 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003170 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003171 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3172 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003173
3174 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003175 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003176 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003177
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003178 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003179 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003180 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003181}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003182
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003183// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3184// true or false.
3185#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00003186static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003187 ResultBuilder &Results,
3188 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003189 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003190 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003191 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003192
3193 CodeCompletionString *Pattern = 0;
3194 if (LangOpts.ObjC2) {
3195 // @dynamic
3196 Pattern = new CodeCompletionString;
3197 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3198 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3199 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00003200 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003201
3202 // @synthesize
3203 Pattern = new CodeCompletionString;
3204 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3205 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3206 Pattern->AddPlaceholderChunk("property");
Douglas Gregora4477812010-01-14 16:01:26 +00003207 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003208 }
3209}
3210
Douglas Gregorbca403c2010-01-13 23:51:12 +00003211static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003212 ResultBuilder &Results,
3213 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003214 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003215
3216 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003217 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003218
3219 if (LangOpts.ObjC2) {
3220 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00003221 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003222
3223 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00003224 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003225
3226 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00003227 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003228 }
3229}
3230
Douglas Gregorbca403c2010-01-13 23:51:12 +00003231static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003232 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003233 CodeCompletionString *Pattern = 0;
3234
3235 // @class name ;
3236 Pattern = new CodeCompletionString;
3237 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3238 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003239 Pattern->AddPlaceholderChunk("name");
Douglas Gregora4477812010-01-14 16:01:26 +00003240 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003241
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003242 if (Results.includeCodePatterns()) {
3243 // @interface name
3244 // FIXME: Could introduce the whole pattern, including superclasses and
3245 // such.
3246 Pattern = new CodeCompletionString;
3247 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
3248 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3249 Pattern->AddPlaceholderChunk("class");
3250 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003251
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003252 // @protocol name
3253 Pattern = new CodeCompletionString;
3254 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3255 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3256 Pattern->AddPlaceholderChunk("protocol");
3257 Results.AddResult(Result(Pattern));
3258
3259 // @implementation name
3260 Pattern = new CodeCompletionString;
3261 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
3262 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3263 Pattern->AddPlaceholderChunk("class");
3264 Results.AddResult(Result(Pattern));
3265 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003266
3267 // @compatibility_alias name
3268 Pattern = new CodeCompletionString;
3269 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
3270 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3271 Pattern->AddPlaceholderChunk("alias");
3272 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3273 Pattern->AddPlaceholderChunk("class");
Douglas Gregora4477812010-01-14 16:01:26 +00003274 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003275}
3276
John McCalld226f652010-08-21 09:40:31 +00003277void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorc464ae82009-12-07 09:27:33 +00003278 bool InInterface) {
John McCall0a2c5e22010-08-25 06:19:51 +00003279 typedef CodeCompletionResult Result;
Douglas Gregorc464ae82009-12-07 09:27:33 +00003280 ResultBuilder Results(*this);
3281 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003282 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003283 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003284 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003285 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003286 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00003287 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003288 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003289 HandleCodeCompleteResults(this, CodeCompleter,
3290 CodeCompletionContext::CCC_Other,
3291 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00003292}
3293
Douglas Gregorbca403c2010-01-13 23:51:12 +00003294static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003295 typedef CodeCompletionResult Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003296 CodeCompletionString *Pattern = 0;
3297
3298 // @encode ( type-name )
3299 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003300 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003301 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3302 Pattern->AddPlaceholderChunk("type-name");
3303 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003304 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003305
3306 // @protocol ( protocol-name )
3307 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003308 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003309 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3310 Pattern->AddPlaceholderChunk("protocol-name");
3311 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003312 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003313
3314 // @selector ( selector )
3315 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003316 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003317 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3318 Pattern->AddPlaceholderChunk("selector");
3319 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
Douglas Gregora4477812010-01-14 16:01:26 +00003320 Results.AddResult(Result(Pattern));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003321}
3322
Douglas Gregorbca403c2010-01-13 23:51:12 +00003323static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003324 typedef CodeCompletionResult Result;
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003325 CodeCompletionString *Pattern = 0;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003326
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003327 if (Results.includeCodePatterns()) {
3328 // @try { statements } @catch ( declaration ) { statements } @finally
3329 // { statements }
3330 Pattern = new CodeCompletionString;
3331 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
3332 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3333 Pattern->AddPlaceholderChunk("statements");
3334 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3335 Pattern->AddTextChunk("@catch");
3336 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3337 Pattern->AddPlaceholderChunk("parameter");
3338 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3339 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3340 Pattern->AddPlaceholderChunk("statements");
3341 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3342 Pattern->AddTextChunk("@finally");
3343 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3344 Pattern->AddPlaceholderChunk("statements");
3345 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3346 Results.AddResult(Result(Pattern));
3347 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003348
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003349 // @throw
3350 Pattern = new CodeCompletionString;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003351 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
Douglas Gregor834389b2010-01-12 06:38:28 +00003352 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003353 Pattern->AddPlaceholderChunk("expression");
Douglas Gregora4477812010-01-14 16:01:26 +00003354 Results.AddResult(Result(Pattern));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003355
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003356 if (Results.includeCodePatterns()) {
3357 // @synchronized ( expression ) { statements }
3358 Pattern = new CodeCompletionString;
3359 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3360 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3361 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3362 Pattern->AddPlaceholderChunk("expression");
3363 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3364 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3365 Pattern->AddPlaceholderChunk("statements");
3366 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3367 Results.AddResult(Result(Pattern));
3368 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003369}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003370
Douglas Gregorbca403c2010-01-13 23:51:12 +00003371static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003372 ResultBuilder &Results,
3373 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003374 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00003375 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3376 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3377 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003378 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00003379 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003380}
3381
3382void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
3383 ResultBuilder Results(*this);
3384 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003385 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003386 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003387 HandleCodeCompleteResults(this, CodeCompleter,
3388 CodeCompletionContext::CCC_Other,
3389 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003390}
3391
3392void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003393 ResultBuilder Results(*this);
3394 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003395 AddObjCStatementResults(Results, false);
3396 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003397 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003398 HandleCodeCompleteResults(this, CodeCompleter,
3399 CodeCompletionContext::CCC_Other,
3400 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003401}
3402
3403void Sema::CodeCompleteObjCAtExpression(Scope *S) {
3404 ResultBuilder Results(*this);
3405 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003406 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003407 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003408 HandleCodeCompleteResults(this, CodeCompleter,
3409 CodeCompletionContext::CCC_Other,
3410 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003411}
3412
Douglas Gregor988358f2009-11-19 00:14:45 +00003413/// \brief Determine whether the addition of the given flag to an Objective-C
3414/// property's attributes will cause a conflict.
3415static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3416 // Check if we've already added this flag.
3417 if (Attributes & NewFlag)
3418 return true;
3419
3420 Attributes |= NewFlag;
3421
3422 // Check for collisions with "readonly".
3423 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3424 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3425 ObjCDeclSpec::DQ_PR_assign |
3426 ObjCDeclSpec::DQ_PR_copy |
3427 ObjCDeclSpec::DQ_PR_retain)))
3428 return true;
3429
3430 // Check for more than one of { assign, copy, retain }.
3431 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3432 ObjCDeclSpec::DQ_PR_copy |
3433 ObjCDeclSpec::DQ_PR_retain);
3434 if (AssignCopyRetMask &&
3435 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3436 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3437 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3438 return true;
3439
3440 return false;
3441}
3442
Douglas Gregora93b1082009-11-18 23:08:07 +00003443void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00003444 if (!CodeCompleter)
3445 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00003446
Steve Naroffece8e712009-10-08 21:55:05 +00003447 unsigned Attributes = ODS.getPropertyAttributes();
3448
John McCall0a2c5e22010-08-25 06:19:51 +00003449 typedef CodeCompletionResult Result;
Steve Naroffece8e712009-10-08 21:55:05 +00003450 ResultBuilder Results(*this);
3451 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00003452 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00003453 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003454 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00003455 Results.AddResult(CodeCompletionResult("assign"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003456 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00003457 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003458 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00003459 Results.AddResult(CodeCompletionResult("retain"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003460 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00003461 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003462 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00003463 Results.AddResult(CodeCompletionResult("nonatomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00003464 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003465 CodeCompletionString *Setter = new CodeCompletionString;
3466 Setter->AddTypedTextChunk("setter");
3467 Setter->AddTextChunk(" = ");
3468 Setter->AddPlaceholderChunk("method");
John McCall0a2c5e22010-08-25 06:19:51 +00003469 Results.AddResult(CodeCompletionResult(Setter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003470 }
Douglas Gregor988358f2009-11-19 00:14:45 +00003471 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor54f01612009-11-19 00:01:57 +00003472 CodeCompletionString *Getter = new CodeCompletionString;
3473 Getter->AddTypedTextChunk("getter");
3474 Getter->AddTextChunk(" = ");
3475 Getter->AddPlaceholderChunk("method");
John McCall0a2c5e22010-08-25 06:19:51 +00003476 Results.AddResult(CodeCompletionResult(Getter));
Douglas Gregor54f01612009-11-19 00:01:57 +00003477 }
Steve Naroffece8e712009-10-08 21:55:05 +00003478 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003479 HandleCodeCompleteResults(this, CodeCompleter,
3480 CodeCompletionContext::CCC_Other,
3481 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00003482}
Steve Naroffc4df6d22009-11-07 02:08:14 +00003483
Douglas Gregor4ad96852009-11-19 07:41:15 +00003484/// \brief Descripts the kind of Objective-C method that we want to find
3485/// via code completion.
3486enum ObjCMethodKind {
3487 MK_Any, //< Any kind of method, provided it means other specified criteria.
3488 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
3489 MK_OneArgSelector //< One-argument selector.
3490};
3491
Douglas Gregor458433d2010-08-26 15:07:07 +00003492static bool isAcceptableObjCSelector(Selector Sel,
3493 ObjCMethodKind WantKind,
3494 IdentifierInfo **SelIdents,
3495 unsigned NumSelIdents) {
3496 if (NumSelIdents > Sel.getNumArgs())
3497 return false;
3498
3499 switch (WantKind) {
3500 case MK_Any: break;
3501 case MK_ZeroArgSelector: return Sel.isUnarySelector();
3502 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
3503 }
3504
3505 for (unsigned I = 0; I != NumSelIdents; ++I)
3506 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
3507 return false;
3508
3509 return true;
3510}
3511
Douglas Gregor4ad96852009-11-19 07:41:15 +00003512static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
3513 ObjCMethodKind WantKind,
3514 IdentifierInfo **SelIdents,
3515 unsigned NumSelIdents) {
Douglas Gregor458433d2010-08-26 15:07:07 +00003516 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
3517 NumSelIdents);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003518}
3519
Douglas Gregor36ecb042009-11-17 23:22:23 +00003520/// \brief Add all of the Objective-C methods in the given Objective-C
3521/// container to the set of results.
3522///
3523/// The container will be a class, protocol, category, or implementation of
3524/// any of the above. This mether will recurse to include methods from
3525/// the superclasses of classes along with their categories, protocols, and
3526/// implementations.
3527///
3528/// \param Container the container in which we'll look to find methods.
3529///
3530/// \param WantInstance whether to add instance methods (only); if false, this
3531/// routine will add factory methods (only).
3532///
3533/// \param CurContext the context in which we're performing the lookup that
3534/// finds methods.
3535///
3536/// \param Results the structure into which we'll add results.
3537static void AddObjCMethods(ObjCContainerDecl *Container,
3538 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003539 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00003540 IdentifierInfo **SelIdents,
3541 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00003542 DeclContext *CurContext,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003543 ResultBuilder &Results,
3544 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00003545 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00003546 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3547 MEnd = Container->meth_end();
3548 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00003549 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
3550 // Check whether the selector identifiers we've been given are a
3551 // subset of the identifiers for this particular method.
Douglas Gregor4ad96852009-11-19 07:41:15 +00003552 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
Douglas Gregord3c68542009-11-19 01:08:35 +00003553 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003554
Douglas Gregord3c68542009-11-19 01:08:35 +00003555 Result R = Result(*M, 0);
3556 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003557 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00003558 if (!InOriginalClass)
3559 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00003560 Results.MaybeAddResult(R, CurContext);
3561 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00003562 }
3563
3564 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
3565 if (!IFace)
3566 return;
3567
3568 // Add methods in protocols.
3569 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
3570 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3571 E = Protocols.end();
3572 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003573 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003574 CurContext, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003575
3576 // Add methods in categories.
3577 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
3578 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00003579 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003580 NumSelIdents, CurContext, Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003581
3582 // Add a categories protocol methods.
3583 const ObjCList<ObjCProtocolDecl> &Protocols
3584 = CatDecl->getReferencedProtocols();
3585 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
3586 E = Protocols.end();
3587 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00003588 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003589 NumSelIdents, CurContext, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003590
3591 // Add methods in category implementations.
3592 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003593 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003594 NumSelIdents, CurContext, Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003595 }
3596
3597 // Add methods in superclass.
3598 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003599 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003600 SelIdents, NumSelIdents, CurContext, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00003601
3602 // Add methods in our implementation, if any.
3603 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00003604 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregor408be5a2010-08-25 01:08:01 +00003605 NumSelIdents, CurContext, Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003606}
3607
3608
John McCalld226f652010-08-21 09:40:31 +00003609void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl,
3610 Decl **Methods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003611 unsigned NumMethods) {
John McCall0a2c5e22010-08-25 06:19:51 +00003612 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003613
3614 // Try to find the interface where getters might live.
John McCalld226f652010-08-21 09:40:31 +00003615 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003616 if (!Class) {
3617 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00003618 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003619 Class = Category->getClassInterface();
3620
3621 if (!Class)
3622 return;
3623 }
3624
3625 // Find all of the potential getters.
3626 ResultBuilder Results(*this);
3627 Results.EnterNewScope();
3628
3629 // FIXME: We need to do this because Objective-C methods don't get
3630 // pushed into DeclContexts early enough. Argh!
3631 for (unsigned I = 0; I != NumMethods; ++I) {
3632 if (ObjCMethodDecl *Method
John McCalld226f652010-08-21 09:40:31 +00003633 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003634 if (Method->isInstanceMethod() &&
3635 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
3636 Result R = Result(Method, 0);
3637 R.AllParametersAreInformative = true;
3638 Results.MaybeAddResult(R, CurContext);
3639 }
3640 }
3641
3642 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
3643 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003644 HandleCodeCompleteResults(this, CodeCompleter,
3645 CodeCompletionContext::CCC_Other,
3646 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00003647}
3648
John McCalld226f652010-08-21 09:40:31 +00003649void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl,
3650 Decl **Methods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00003651 unsigned NumMethods) {
John McCall0a2c5e22010-08-25 06:19:51 +00003652 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00003653
3654 // Try to find the interface where setters might live.
3655 ObjCInterfaceDecl *Class
John McCalld226f652010-08-21 09:40:31 +00003656 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00003657 if (!Class) {
3658 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00003659 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003660 Class = Category->getClassInterface();
3661
3662 if (!Class)
3663 return;
3664 }
3665
3666 // Find all of the potential getters.
3667 ResultBuilder Results(*this);
3668 Results.EnterNewScope();
3669
3670 // FIXME: We need to do this because Objective-C methods don't get
3671 // pushed into DeclContexts early enough. Argh!
3672 for (unsigned I = 0; I != NumMethods; ++I) {
3673 if (ObjCMethodDecl *Method
John McCalld226f652010-08-21 09:40:31 +00003674 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
Douglas Gregor4ad96852009-11-19 07:41:15 +00003675 if (Method->isInstanceMethod() &&
3676 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
3677 Result R = Result(Method, 0);
3678 R.AllParametersAreInformative = true;
3679 Results.MaybeAddResult(R, CurContext);
3680 }
3681 }
3682
3683 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
3684
3685 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003686 HandleCodeCompleteResults(this, CodeCompleter,
3687 CodeCompletionContext::CCC_Other,
3688 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00003689}
3690
Douglas Gregord32b0222010-08-24 01:06:58 +00003691void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS) {
John McCall0a2c5e22010-08-25 06:19:51 +00003692 typedef CodeCompletionResult Result;
Douglas Gregord32b0222010-08-24 01:06:58 +00003693 ResultBuilder Results(*this);
3694 Results.EnterNewScope();
3695
3696 // Add context-sensitive, Objective-C parameter-passing keywords.
3697 bool AddedInOut = false;
3698 if ((DS.getObjCDeclQualifier() &
3699 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
3700 Results.AddResult("in");
3701 Results.AddResult("inout");
3702 AddedInOut = true;
3703 }
3704 if ((DS.getObjCDeclQualifier() &
3705 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
3706 Results.AddResult("out");
3707 if (!AddedInOut)
3708 Results.AddResult("inout");
3709 }
3710 if ((DS.getObjCDeclQualifier() &
3711 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
3712 ObjCDeclSpec::DQ_Oneway)) == 0) {
3713 Results.AddResult("bycopy");
3714 Results.AddResult("byref");
3715 Results.AddResult("oneway");
3716 }
3717
3718 // Add various builtin type names and specifiers.
3719 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
3720 Results.ExitScope();
3721
3722 // Add the various type names
3723 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3724 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3725 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3726 CodeCompleter->includeGlobals());
3727
3728 if (CodeCompleter->includeMacros())
3729 AddMacroResults(PP, Results);
3730
3731 HandleCodeCompleteResults(this, CodeCompleter,
3732 CodeCompletionContext::CCC_Type,
3733 Results.data(), Results.size());
3734}
3735
Douglas Gregor22f56992010-04-06 19:22:33 +00003736/// \brief When we have an expression with type "id", we may assume
3737/// that it has some more-specific class type based on knowledge of
3738/// common uses of Objective-C. This routine returns that class type,
3739/// or NULL if no better result could be determined.
3740static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
3741 ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E);
3742 if (!Msg)
3743 return 0;
3744
3745 Selector Sel = Msg->getSelector();
3746 if (Sel.isNull())
3747 return 0;
3748
3749 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
3750 if (!Id)
3751 return 0;
3752
3753 ObjCMethodDecl *Method = Msg->getMethodDecl();
3754 if (!Method)
3755 return 0;
3756
3757 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00003758 ObjCInterfaceDecl *IFace = 0;
3759 switch (Msg->getReceiverKind()) {
3760 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00003761 if (const ObjCObjectType *ObjType
3762 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
3763 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00003764 break;
3765
3766 case ObjCMessageExpr::Instance: {
3767 QualType T = Msg->getInstanceReceiver()->getType();
3768 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
3769 IFace = Ptr->getInterfaceDecl();
3770 break;
3771 }
3772
3773 case ObjCMessageExpr::SuperInstance:
3774 case ObjCMessageExpr::SuperClass:
3775 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00003776 }
3777
3778 if (!IFace)
3779 return 0;
3780
3781 ObjCInterfaceDecl *Super = IFace->getSuperClass();
3782 if (Method->isInstanceMethod())
3783 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3784 .Case("retain", IFace)
3785 .Case("autorelease", IFace)
3786 .Case("copy", IFace)
3787 .Case("copyWithZone", IFace)
3788 .Case("mutableCopy", IFace)
3789 .Case("mutableCopyWithZone", IFace)
3790 .Case("awakeFromCoder", IFace)
3791 .Case("replacementObjectFromCoder", IFace)
3792 .Case("class", IFace)
3793 .Case("classForCoder", IFace)
3794 .Case("superclass", Super)
3795 .Default(0);
3796
3797 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
3798 .Case("new", IFace)
3799 .Case("alloc", IFace)
3800 .Case("allocWithZone", IFace)
3801 .Case("class", IFace)
3802 .Case("superclass", Super)
3803 .Default(0);
3804}
3805
Douglas Gregor03d8aec2010-08-27 15:10:57 +00003806// Add a special completion for a message send to "super", which fills in the
3807// most likely case of forwarding all of our arguments to the superclass
3808// function.
3809///
3810/// \param S The semantic analysis object.
3811///
3812/// \param S NeedSuperKeyword Whether we need to prefix this completion with
3813/// the "super" keyword. Otherwise, we just need to provide the arguments.
3814///
3815/// \param SelIdents The identifiers in the selector that have already been
3816/// provided as arguments for a send to "super".
3817///
3818/// \param NumSelIdents The number of identifiers in \p SelIdents.
3819///
3820/// \param Results The set of results to augment.
3821///
3822/// \returns the Objective-C method declaration that would be invoked by
3823/// this "super" completion. If NULL, no completion was added.
3824static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
3825 IdentifierInfo **SelIdents,
3826 unsigned NumSelIdents,
3827 ResultBuilder &Results) {
3828 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
3829 if (!CurMethod)
3830 return 0;
3831
3832 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
3833 if (!Class)
3834 return 0;
3835
3836 // Try to find a superclass method with the same selector.
3837 ObjCMethodDecl *SuperMethod = 0;
3838 while ((Class = Class->getSuperClass()) && !SuperMethod)
3839 SuperMethod = Class->getMethod(CurMethod->getSelector(),
3840 CurMethod->isInstanceMethod());
3841
3842 if (!SuperMethod)
3843 return 0;
3844
3845 // Check whether the superclass method has the same signature.
3846 if (CurMethod->param_size() != SuperMethod->param_size() ||
3847 CurMethod->isVariadic() != SuperMethod->isVariadic())
3848 return 0;
3849
3850 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
3851 CurPEnd = CurMethod->param_end(),
3852 SuperP = SuperMethod->param_begin();
3853 CurP != CurPEnd; ++CurP, ++SuperP) {
3854 // Make sure the parameter types are compatible.
3855 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
3856 (*SuperP)->getType()))
3857 return 0;
3858
3859 // Make sure we have a parameter name to forward!
3860 if (!(*CurP)->getIdentifier())
3861 return 0;
3862 }
3863
3864 // We have a superclass method. Now, form the send-to-super completion.
3865 CodeCompletionString *Pattern = new CodeCompletionString;
3866
3867 // Give this completion a return type.
3868 AddResultTypeChunk(S.Context, SuperMethod, Pattern);
3869
3870 // If we need the "super" keyword, add it (plus some spacing).
3871 if (NeedSuperKeyword) {
3872 Pattern->AddTypedTextChunk("super");
3873 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3874 }
3875
3876 Selector Sel = CurMethod->getSelector();
3877 if (Sel.isUnarySelector()) {
3878 if (NeedSuperKeyword)
3879 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
3880 else
3881 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
3882 } else {
3883 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
3884 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
3885 if (I > NumSelIdents)
3886 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3887
3888 if (I < NumSelIdents)
3889 Pattern->AddInformativeChunk(
3890 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
3891 else if (NeedSuperKeyword || I > NumSelIdents) {
3892 Pattern->AddTextChunk(
3893 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
3894 Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
3895 } else {
3896 Pattern->AddTypedTextChunk(
3897 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
3898 Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
3899 }
3900 }
3901 }
3902
3903 Results.AddResult(CodeCompletionResult(Pattern, CCP_SuperCompletion,
3904 SuperMethod->isInstanceMethod()
3905 ? CXCursor_ObjCInstanceMethodDecl
3906 : CXCursor_ObjCClassMethodDecl));
3907 return SuperMethod;
3908}
3909
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003910void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00003911 typedef CodeCompletionResult Result;
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003912 ResultBuilder Results(*this);
3913
3914 // Find anything that looks like it could be a message receiver.
3915 Results.setFilter(&ResultBuilder::IsObjCMessageReceiver);
3916 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3917 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00003918 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3919 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003920
3921 // If we are in an Objective-C method inside a class that has a superclass,
3922 // add "super" as an option.
3923 if (ObjCMethodDecl *Method = getCurMethodDecl())
3924 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00003925 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003926 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00003927
3928 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
3929 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003930
3931 Results.ExitScope();
3932
3933 if (CodeCompleter->includeMacros())
3934 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003935 HandleCodeCompleteResults(this, CodeCompleter,
3936 CodeCompletionContext::CCC_ObjCMessageReceiver,
3937 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00003938
3939}
3940
Douglas Gregor2725ca82010-04-21 19:57:20 +00003941void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
3942 IdentifierInfo **SelIdents,
3943 unsigned NumSelIdents) {
3944 ObjCInterfaceDecl *CDecl = 0;
3945 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3946 // Figure out which interface we're in.
3947 CDecl = CurMethod->getClassInterface();
3948 if (!CDecl)
3949 return;
3950
3951 // Find the superclass of this class.
3952 CDecl = CDecl->getSuperClass();
3953 if (!CDecl)
3954 return;
3955
3956 if (CurMethod->isInstanceMethod()) {
3957 // We are inside an instance method, which means that the message
3958 // send [super ...] is actually calling an instance method on the
3959 // current object. Build the super expression and handle this like
3960 // an instance method.
3961 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
3962 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall60d7b3a2010-08-24 06:29:42 +00003963 ExprResult Super
Douglas Gregor2725ca82010-04-21 19:57:20 +00003964 = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
3965 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00003966 SelIdents, NumSelIdents,
3967 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00003968 }
3969
3970 // Fall through to send to the superclass in CDecl.
3971 } else {
3972 // "super" may be the name of a type or variable. Figure out which
3973 // it is.
3974 IdentifierInfo *Super = &Context.Idents.get("super");
3975 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
3976 LookupOrdinaryName);
3977 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
3978 // "super" names an interface. Use it.
3979 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00003980 if (const ObjCObjectType *Iface
3981 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
3982 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00003983 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
3984 // "super" names an unresolved type; we can't be more specific.
3985 } else {
3986 // Assume that "super" names some kind of value and parse that way.
3987 CXXScopeSpec SS;
3988 UnqualifiedId id;
3989 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00003990 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00003991 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
3992 SelIdents, NumSelIdents);
3993 }
3994
3995 // Fall through
3996 }
3997
John McCallb3d87482010-08-24 05:47:05 +00003998 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00003999 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004000 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004001 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004002 NumSelIdents, /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004003}
4004
John McCallb3d87482010-08-24 05:47:05 +00004005void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00004006 IdentifierInfo **SelIdents,
4007 unsigned NumSelIdents) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004008 CodeCompleteObjCClassMessage(S, Receiver, SelIdents, NumSelIdents, false);
4009}
4010
4011void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4012 IdentifierInfo **SelIdents,
4013 unsigned NumSelIdents,
4014 bool IsSuper) {
John McCall0a2c5e22010-08-25 06:19:51 +00004015 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004016 ObjCInterfaceDecl *CDecl = 0;
4017
Douglas Gregor24a069f2009-11-17 17:59:40 +00004018 // If the given name refers to an interface type, retrieve the
4019 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004020 if (Receiver) {
4021 QualType T = GetTypeFromParser(Receiver, 0);
4022 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004023 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4024 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004025 }
4026
Douglas Gregor36ecb042009-11-17 23:22:23 +00004027 // Add all of the factory methods in this Objective-C class, its protocols,
4028 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004029 ResultBuilder Results(*this);
4030 Results.EnterNewScope();
Douglas Gregor13438f92010-04-06 16:40:00 +00004031
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004032 // If this is a send-to-super, try to add the special "super" send
4033 // completion.
4034 if (IsSuper) {
4035 if (ObjCMethodDecl *SuperMethod
4036 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
4037 Results))
4038 Results.Ignore(SuperMethod);
4039 }
4040
Douglas Gregor265f7492010-08-27 15:29:55 +00004041 // If we're inside an Objective-C method definition, prefer its selector to
4042 // others.
4043 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
4044 Results.setPreferredSelector(CurMethod->getSelector());
4045
Douglas Gregor13438f92010-04-06 16:40:00 +00004046 if (CDecl)
4047 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
4048 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004049 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00004050 // We're messaging "id" as a type; provide all class/factory methods.
4051
Douglas Gregor719770d2010-04-06 17:30:22 +00004052 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004053 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00004054 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00004055 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4056 I != N; ++I) {
4057 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00004058 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004059 continue;
4060
Sebastian Redldb9d2142010-08-02 23:18:59 +00004061 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004062 }
4063 }
4064
Sebastian Redldb9d2142010-08-02 23:18:59 +00004065 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4066 MEnd = MethodPool.end();
4067 M != MEnd; ++M) {
4068 for (ObjCMethodList *MethList = &M->second.second;
4069 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004070 MethList = MethList->Next) {
4071 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4072 NumSelIdents))
4073 continue;
4074
4075 Result R(MethList->Method, 0);
4076 R.StartParameter = NumSelIdents;
4077 R.AllParametersAreInformative = false;
4078 Results.MaybeAddResult(R, CurContext);
4079 }
4080 }
4081 }
4082
Steve Naroffc4df6d22009-11-07 02:08:14 +00004083 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004084 HandleCodeCompleteResults(this, CodeCompleter,
4085 CodeCompletionContext::CCC_Other,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004086 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004087}
4088
Douglas Gregord3c68542009-11-19 01:08:35 +00004089void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4090 IdentifierInfo **SelIdents,
4091 unsigned NumSelIdents) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004092 CodeCompleteObjCInstanceMessage(S, Receiver, SelIdents, NumSelIdents, false);
4093}
4094
4095void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4096 IdentifierInfo **SelIdents,
4097 unsigned NumSelIdents,
4098 bool IsSuper) {
John McCall0a2c5e22010-08-25 06:19:51 +00004099 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00004100
4101 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00004102
Douglas Gregor36ecb042009-11-17 23:22:23 +00004103 // If necessary, apply function/array conversion to the receiver.
4104 // C99 6.7.5.3p[7,8].
Douglas Gregora873dfc2010-02-03 00:27:59 +00004105 DefaultFunctionArrayLvalueConversion(RecExpr);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004106 QualType ReceiverType = RecExpr->getType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00004107
Douglas Gregor36ecb042009-11-17 23:22:23 +00004108 // Build the set of methods we can see.
4109 ResultBuilder Results(*this);
4110 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00004111
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004112 // If this is a send-to-super, try to add the special "super" send
4113 // completion.
4114 if (IsSuper) {
4115 if (ObjCMethodDecl *SuperMethod
4116 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
4117 Results))
4118 Results.Ignore(SuperMethod);
4119 }
4120
Douglas Gregor265f7492010-08-27 15:29:55 +00004121 // If we're inside an Objective-C method definition, prefer its selector to
4122 // others.
4123 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
4124 Results.setPreferredSelector(CurMethod->getSelector());
4125
Douglas Gregor22f56992010-04-06 19:22:33 +00004126 // If we're messaging an expression with type "id" or "Class", check
4127 // whether we know something special about the receiver that allows
4128 // us to assume a more-specific receiver type.
4129 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
4130 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
4131 ReceiverType = Context.getObjCObjectPointerType(
4132 Context.getObjCInterfaceType(IFace));
Douglas Gregor36ecb042009-11-17 23:22:23 +00004133
Douglas Gregorf74a4192009-11-18 00:06:18 +00004134 // Handle messages to Class. This really isn't a message to an instance
4135 // method, so we treat it the same way we would treat a message send to a
4136 // class method.
4137 if (ReceiverType->isObjCClassType() ||
4138 ReceiverType->isObjCQualifiedClassType()) {
4139 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4140 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004141 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
4142 CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004143 }
4144 }
4145 // Handle messages to a qualified ID ("id<foo>").
4146 else if (const ObjCObjectPointerType *QualID
4147 = ReceiverType->getAsObjCQualifiedIdType()) {
4148 // Search protocols for instance methods.
4149 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
4150 E = QualID->qual_end();
4151 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004152 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
4153 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004154 }
4155 // Handle messages to a pointer to interface type.
4156 else if (const ObjCObjectPointerType *IFacePtr
4157 = ReceiverType->getAsObjCInterfacePointerType()) {
4158 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00004159 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
4160 NumSelIdents, CurContext, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004161
4162 // Search protocols for instance methods.
4163 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
4164 E = IFacePtr->qual_end();
4165 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004166 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
4167 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004168 }
Douglas Gregor13438f92010-04-06 16:40:00 +00004169 // Handle messages to "id".
4170 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00004171 // We're messaging "id", so provide all instance methods we know
4172 // about as code-completion results.
4173
4174 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004175 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00004176 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00004177 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4178 I != N; ++I) {
4179 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00004180 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004181 continue;
4182
Sebastian Redldb9d2142010-08-02 23:18:59 +00004183 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004184 }
4185 }
4186
Sebastian Redldb9d2142010-08-02 23:18:59 +00004187 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4188 MEnd = MethodPool.end();
4189 M != MEnd; ++M) {
4190 for (ObjCMethodList *MethList = &M->second.first;
4191 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004192 MethList = MethList->Next) {
4193 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4194 NumSelIdents))
4195 continue;
4196
4197 Result R(MethList->Method, 0);
4198 R.StartParameter = NumSelIdents;
4199 R.AllParametersAreInformative = false;
4200 Results.MaybeAddResult(R, CurContext);
4201 }
4202 }
4203 }
4204
Steve Naroffc4df6d22009-11-07 02:08:14 +00004205 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004206 HandleCodeCompleteResults(this, CodeCompleter,
4207 CodeCompletionContext::CCC_Other,
4208 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004209}
Douglas Gregor55385fe2009-11-18 04:19:12 +00004210
Douglas Gregorfb629412010-08-23 21:17:50 +00004211void Sema::CodeCompleteObjCForCollection(Scope *S,
4212 DeclGroupPtrTy IterationVar) {
4213 CodeCompleteExpressionData Data;
4214 Data.ObjCCollection = true;
4215
4216 if (IterationVar.getAsOpaquePtr()) {
4217 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
4218 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
4219 if (*I)
4220 Data.IgnoreDecls.push_back(*I);
4221 }
4222 }
4223
4224 CodeCompleteExpression(S, Data);
4225}
4226
Douglas Gregor458433d2010-08-26 15:07:07 +00004227void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
4228 unsigned NumSelIdents) {
4229 // If we have an external source, load the entire class method
4230 // pool from the AST file.
4231 if (ExternalSource) {
4232 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4233 I != N; ++I) {
4234 Selector Sel = ExternalSource->GetExternalSelector(I);
4235 if (Sel.isNull() || MethodPool.count(Sel))
4236 continue;
4237
4238 ReadMethodPool(Sel);
4239 }
4240 }
4241
4242 ResultBuilder Results(*this);
4243 Results.EnterNewScope();
4244 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4245 MEnd = MethodPool.end();
4246 M != MEnd; ++M) {
4247
4248 Selector Sel = M->first;
4249 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
4250 continue;
4251
4252 CodeCompletionString *Pattern = new CodeCompletionString;
4253 if (Sel.isUnarySelector()) {
4254 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4255 Results.AddResult(Pattern);
4256 continue;
4257 }
4258
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004259 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00004260 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004261 if (I == NumSelIdents) {
4262 if (!Accumulator.empty()) {
4263 Pattern->AddInformativeChunk(Accumulator);
4264 Accumulator.clear();
4265 }
4266 }
4267
4268 Accumulator += Sel.getIdentifierInfoForSlot(I)->getName().str();
4269 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00004270 }
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00004271 Pattern->AddTypedTextChunk(Accumulator);
Douglas Gregor458433d2010-08-26 15:07:07 +00004272 Results.AddResult(Pattern);
4273 }
4274 Results.ExitScope();
4275
4276 HandleCodeCompleteResults(this, CodeCompleter,
4277 CodeCompletionContext::CCC_SelectorName,
4278 Results.data(), Results.size());
4279}
4280
Douglas Gregor55385fe2009-11-18 04:19:12 +00004281/// \brief Add all of the protocol declarations that we find in the given
4282/// (translation unit) context.
4283static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00004284 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00004285 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004286 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00004287
4288 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4289 DEnd = Ctx->decls_end();
4290 D != DEnd; ++D) {
4291 // Record any protocols we find.
4292 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00004293 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00004294 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004295
4296 // Record any forward-declared protocols we find.
4297 if (ObjCForwardProtocolDecl *Forward
4298 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
4299 for (ObjCForwardProtocolDecl::protocol_iterator
4300 P = Forward->protocol_begin(),
4301 PEnd = Forward->protocol_end();
4302 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00004303 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00004304 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004305 }
4306 }
4307}
4308
4309void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
4310 unsigned NumProtocols) {
4311 ResultBuilder Results(*this);
4312 Results.EnterNewScope();
4313
4314 // Tell the result set to ignore all of the protocols we have
4315 // already seen.
4316 for (unsigned I = 0; I != NumProtocols; ++I)
Douglas Gregorc83c6872010-04-15 22:33:43 +00004317 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
4318 Protocols[I].second))
Douglas Gregor55385fe2009-11-18 04:19:12 +00004319 Results.Ignore(Protocol);
4320
4321 // Add all protocols.
Douglas Gregor083128f2009-11-18 04:49:41 +00004322 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
4323 Results);
4324
4325 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004326 HandleCodeCompleteResults(this, CodeCompleter,
4327 CodeCompletionContext::CCC_ObjCProtocolName,
4328 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00004329}
4330
4331void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
4332 ResultBuilder Results(*this);
4333 Results.EnterNewScope();
4334
4335 // Add all protocols.
4336 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
4337 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00004338
4339 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004340 HandleCodeCompleteResults(this, CodeCompleter,
4341 CodeCompletionContext::CCC_ObjCProtocolName,
4342 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00004343}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004344
4345/// \brief Add all of the Objective-C interface declarations that we find in
4346/// the given (translation unit) context.
4347static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
4348 bool OnlyForwardDeclarations,
4349 bool OnlyUnimplemented,
4350 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004351 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004352
4353 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4354 DEnd = Ctx->decls_end();
4355 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00004356 // Record any interfaces we find.
4357 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
4358 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
4359 (!OnlyUnimplemented || !Class->getImplementation()))
4360 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004361
4362 // Record any forward-declared interfaces we find.
4363 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
4364 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00004365 C != CEnd; ++C)
4366 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
4367 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
4368 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00004369 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004370 }
4371 }
4372}
4373
4374void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
4375 ResultBuilder Results(*this);
4376 Results.EnterNewScope();
4377
4378 // Add all classes.
4379 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
4380 false, Results);
4381
4382 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004383 HandleCodeCompleteResults(this, CodeCompleter,
4384 CodeCompletionContext::CCC_Other,
4385 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004386}
4387
Douglas Gregorc83c6872010-04-15 22:33:43 +00004388void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
4389 SourceLocation ClassNameLoc) {
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004390 ResultBuilder Results(*this);
4391 Results.EnterNewScope();
4392
4393 // Make sure that we ignore the class we're currently defining.
4394 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00004395 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004396 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004397 Results.Ignore(CurClass);
4398
4399 // Add all classes.
4400 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
4401 false, Results);
4402
4403 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004404 HandleCodeCompleteResults(this, CodeCompleter,
4405 CodeCompletionContext::CCC_Other,
4406 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004407}
4408
4409void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
4410 ResultBuilder Results(*this);
4411 Results.EnterNewScope();
4412
4413 // Add all unimplemented classes.
4414 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
4415 true, Results);
4416
4417 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004418 HandleCodeCompleteResults(this, CodeCompleter,
4419 CodeCompletionContext::CCC_Other,
4420 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00004421}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004422
4423void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00004424 IdentifierInfo *ClassName,
4425 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00004426 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004427
4428 ResultBuilder Results(*this);
4429
4430 // Ignore any categories we find that have already been implemented by this
4431 // interface.
4432 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
4433 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00004434 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004435 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
4436 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4437 Category = Category->getNextClassCategory())
4438 CategoryNames.insert(Category->getIdentifier());
4439
4440 // Add all of the categories we know about.
4441 Results.EnterNewScope();
4442 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4443 for (DeclContext::decl_iterator D = TU->decls_begin(),
4444 DEnd = TU->decls_end();
4445 D != DEnd; ++D)
4446 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
4447 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00004448 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004449 Results.ExitScope();
4450
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004451 HandleCodeCompleteResults(this, CodeCompleter,
4452 CodeCompletionContext::CCC_Other,
4453 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004454}
4455
4456void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00004457 IdentifierInfo *ClassName,
4458 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00004459 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004460
4461 // Find the corresponding interface. If we couldn't find the interface, the
4462 // program itself is ill-formed. However, we'll try to be helpful still by
4463 // providing the list of all of the categories we know about.
4464 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00004465 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004466 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
4467 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00004468 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004469
4470 ResultBuilder Results(*this);
4471
4472 // Add all of the categories that have have corresponding interface
4473 // declarations in this class and any of its superclasses, except for
4474 // already-implemented categories in the class itself.
4475 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
4476 Results.EnterNewScope();
4477 bool IgnoreImplemented = true;
4478 while (Class) {
4479 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4480 Category = Category->getNextClassCategory())
4481 if ((!IgnoreImplemented || !Category->getImplementation()) &&
4482 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00004483 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004484
4485 Class = Class->getSuperClass();
4486 IgnoreImplemented = false;
4487 }
4488 Results.ExitScope();
4489
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004490 HandleCodeCompleteResults(this, CodeCompleter,
4491 CodeCompletionContext::CCC_Other,
4492 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00004493}
Douglas Gregor322328b2009-11-18 22:32:06 +00004494
John McCalld226f652010-08-21 09:40:31 +00004495void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004496 typedef CodeCompletionResult Result;
Douglas Gregor322328b2009-11-18 22:32:06 +00004497 ResultBuilder Results(*this);
4498
4499 // Figure out where this @synthesize lives.
4500 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00004501 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00004502 if (!Container ||
4503 (!isa<ObjCImplementationDecl>(Container) &&
4504 !isa<ObjCCategoryImplDecl>(Container)))
4505 return;
4506
4507 // Ignore any properties that have already been implemented.
4508 for (DeclContext::decl_iterator D = Container->decls_begin(),
4509 DEnd = Container->decls_end();
4510 D != DEnd; ++D)
4511 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
4512 Results.Ignore(PropertyImpl->getPropertyDecl());
4513
4514 // Add any properties that we find.
4515 Results.EnterNewScope();
4516 if (ObjCImplementationDecl *ClassImpl
4517 = dyn_cast<ObjCImplementationDecl>(Container))
4518 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
4519 Results);
4520 else
4521 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
4522 false, CurContext, Results);
4523 Results.ExitScope();
4524
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004525 HandleCodeCompleteResults(this, CodeCompleter,
4526 CodeCompletionContext::CCC_Other,
4527 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00004528}
4529
4530void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
4531 IdentifierInfo *PropertyName,
John McCalld226f652010-08-21 09:40:31 +00004532 Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004533 typedef CodeCompletionResult Result;
Douglas Gregor322328b2009-11-18 22:32:06 +00004534 ResultBuilder Results(*this);
4535
4536 // Figure out where this @synthesize lives.
4537 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00004538 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00004539 if (!Container ||
4540 (!isa<ObjCImplementationDecl>(Container) &&
4541 !isa<ObjCCategoryImplDecl>(Container)))
4542 return;
4543
4544 // Figure out which interface we're looking into.
4545 ObjCInterfaceDecl *Class = 0;
4546 if (ObjCImplementationDecl *ClassImpl
4547 = dyn_cast<ObjCImplementationDecl>(Container))
4548 Class = ClassImpl->getClassInterface();
4549 else
4550 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
4551 ->getClassInterface();
4552
4553 // Add all of the instance variables in this class and its superclasses.
4554 Results.EnterNewScope();
4555 for(; Class; Class = Class->getSuperClass()) {
4556 // FIXME: We could screen the type of each ivar for compatibility with
4557 // the property, but is that being too paternal?
4558 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
4559 IVarEnd = Class->ivar_end();
4560 IVar != IVarEnd; ++IVar)
Douglas Gregor608300b2010-01-14 16:14:35 +00004561 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor322328b2009-11-18 22:32:06 +00004562 }
4563 Results.ExitScope();
4564
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004565 HandleCodeCompleteResults(this, CodeCompleter,
4566 CodeCompletionContext::CCC_Other,
4567 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00004568}
Douglas Gregore8f5a172010-04-07 00:21:17 +00004569
Douglas Gregor408be5a2010-08-25 01:08:01 +00004570// Mapping from selectors to the methods that implement that selector, along
4571// with the "in original class" flag.
4572typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
4573 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00004574
4575/// \brief Find all of the methods that reside in the given container
4576/// (and its superclasses, protocols, etc.) that meet the given
4577/// criteria. Insert those methods into the map of known methods,
4578/// indexed by selector so they can be easily found.
4579static void FindImplementableMethods(ASTContext &Context,
4580 ObjCContainerDecl *Container,
4581 bool WantInstanceMethods,
4582 QualType ReturnType,
4583 bool IsInImplementation,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004584 KnownMethodsMap &KnownMethods,
4585 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004586 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
4587 // Recurse into protocols.
4588 const ObjCList<ObjCProtocolDecl> &Protocols
4589 = IFace->getReferencedProtocols();
4590 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4591 E = Protocols.end();
4592 I != E; ++I)
4593 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004594 IsInImplementation, KnownMethods,
4595 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004596
4597 // If we're not in the implementation of a class, also visit the
4598 // superclass.
4599 if (!IsInImplementation && IFace->getSuperClass())
4600 FindImplementableMethods(Context, IFace->getSuperClass(),
4601 WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004602 IsInImplementation, KnownMethods,
4603 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004604
4605 // Add methods from any class extensions (but not from categories;
4606 // those should go into category implementations).
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00004607 for (const ObjCCategoryDecl *Cat = IFace->getFirstClassExtension(); Cat;
4608 Cat = Cat->getNextClassExtension())
4609 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
4610 WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004611 IsInImplementation, KnownMethods,
4612 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004613 }
4614
4615 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4616 // Recurse into protocols.
4617 const ObjCList<ObjCProtocolDecl> &Protocols
4618 = Category->getReferencedProtocols();
4619 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4620 E = Protocols.end();
4621 I != E; ++I)
4622 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004623 IsInImplementation, KnownMethods,
4624 InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004625 }
4626
4627 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4628 // Recurse into protocols.
4629 const ObjCList<ObjCProtocolDecl> &Protocols
4630 = Protocol->getReferencedProtocols();
4631 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4632 E = Protocols.end();
4633 I != E; ++I)
4634 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004635 IsInImplementation, KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004636 }
4637
4638 // Add methods in this container. This operation occurs last because
4639 // we want the methods from this container to override any methods
4640 // we've previously seen with the same selector.
4641 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4642 MEnd = Container->meth_end();
4643 M != MEnd; ++M) {
4644 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4645 if (!ReturnType.isNull() &&
4646 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
4647 continue;
4648
Douglas Gregor408be5a2010-08-25 01:08:01 +00004649 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004650 }
4651 }
4652}
4653
4654void Sema::CodeCompleteObjCMethodDecl(Scope *S,
4655 bool IsInstanceMethod,
John McCallb3d87482010-08-24 05:47:05 +00004656 ParsedType ReturnTy,
John McCalld226f652010-08-21 09:40:31 +00004657 Decl *IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004658 // Determine the return type of the method we're declaring, if
4659 // provided.
4660 QualType ReturnType = GetTypeFromParser(ReturnTy);
4661
4662 // Determine where we should start searching for methods, and where we
4663 ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
4664 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00004665 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004666 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
4667 SearchDecl = Impl->getClassInterface();
4668 CurrentDecl = Impl;
4669 IsInImplementation = true;
4670 } else if (ObjCCategoryImplDecl *CatImpl
4671 = dyn_cast<ObjCCategoryImplDecl>(D)) {
4672 SearchDecl = CatImpl->getCategoryDecl();
4673 CurrentDecl = CatImpl;
4674 IsInImplementation = true;
4675 } else {
4676 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
4677 CurrentDecl = SearchDecl;
4678 }
4679 }
4680
4681 if (!SearchDecl && S) {
4682 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
4683 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
4684 CurrentDecl = SearchDecl;
4685 }
4686 }
4687
4688 if (!SearchDecl || !CurrentDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004689 HandleCodeCompleteResults(this, CodeCompleter,
4690 CodeCompletionContext::CCC_Other,
4691 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00004692 return;
4693 }
4694
4695 // Find all of the methods that we could declare/implement here.
4696 KnownMethodsMap KnownMethods;
4697 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
4698 ReturnType, IsInImplementation, KnownMethods);
4699
4700 // Erase any methods that have already been declared or
4701 // implemented here.
4702 for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
4703 MEnd = CurrentDecl->meth_end();
4704 M != MEnd; ++M) {
4705 if ((*M)->isInstanceMethod() != IsInstanceMethod)
4706 continue;
4707
4708 KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
4709 if (Pos != KnownMethods.end())
4710 KnownMethods.erase(Pos);
4711 }
4712
4713 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00004714 typedef CodeCompletionResult Result;
Douglas Gregore8f5a172010-04-07 00:21:17 +00004715 ResultBuilder Results(*this);
4716 Results.EnterNewScope();
4717 PrintingPolicy Policy(Context.PrintingPolicy);
4718 Policy.AnonymousTagLocations = false;
4719 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
4720 MEnd = KnownMethods.end();
4721 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00004722 ObjCMethodDecl *Method = M->second.first;
Douglas Gregore8f5a172010-04-07 00:21:17 +00004723 CodeCompletionString *Pattern = new CodeCompletionString;
4724
4725 // If the result type was not already provided, add it to the
4726 // pattern as (type).
4727 if (ReturnType.isNull()) {
4728 std::string TypeStr;
4729 Method->getResultType().getAsStringInternal(TypeStr, Policy);
4730 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4731 Pattern->AddTextChunk(TypeStr);
4732 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4733 }
4734
4735 Selector Sel = Method->getSelector();
4736
4737 // Add the first part of the selector to the pattern.
4738 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4739
4740 // Add parameters to the pattern.
4741 unsigned I = 0;
4742 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4743 PEnd = Method->param_end();
4744 P != PEnd; (void)++P, ++I) {
4745 // Add the part of the selector name.
4746 if (I == 0)
4747 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4748 else if (I < Sel.getNumArgs()) {
4749 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor47c03a72010-08-17 15:53:35 +00004750 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(I)->getName());
Douglas Gregore8f5a172010-04-07 00:21:17 +00004751 Pattern->AddChunk(CodeCompletionString::CK_Colon);
4752 } else
4753 break;
4754
4755 // Add the parameter type.
4756 std::string TypeStr;
4757 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
4758 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4759 Pattern->AddTextChunk(TypeStr);
4760 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4761
4762 if (IdentifierInfo *Id = (*P)->getIdentifier())
4763 Pattern->AddTextChunk(Id->getName());
4764 }
4765
4766 if (Method->isVariadic()) {
4767 if (Method->param_size() > 0)
4768 Pattern->AddChunk(CodeCompletionString::CK_Comma);
4769 Pattern->AddTextChunk("...");
4770 }
4771
Douglas Gregor447107d2010-05-28 00:57:46 +00004772 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00004773 // We will be defining the method here, so add a compound statement.
4774 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4775 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
4776 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4777 if (!Method->getResultType()->isVoidType()) {
4778 // If the result type is not void, add a return clause.
4779 Pattern->AddTextChunk("return");
4780 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4781 Pattern->AddPlaceholderChunk("expression");
4782 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
4783 } else
4784 Pattern->AddPlaceholderChunk("statements");
4785
4786 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
4787 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
4788 }
4789
Douglas Gregor408be5a2010-08-25 01:08:01 +00004790 unsigned Priority = CCP_CodePattern;
4791 if (!M->second.second)
4792 Priority += CCD_InBaseClass;
4793
4794 Results.AddResult(Result(Pattern, Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00004795 Method->isInstanceMethod()
4796 ? CXCursor_ObjCInstanceMethodDecl
4797 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00004798 }
4799
4800 Results.ExitScope();
4801
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004802 HandleCodeCompleteResults(this, CodeCompleter,
4803 CodeCompletionContext::CCC_Other,
4804 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00004805}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004806
4807void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
4808 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00004809 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00004810 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004811 IdentifierInfo **SelIdents,
4812 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004813 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004814 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004815 if (ExternalSource) {
4816 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4817 I != N; ++I) {
4818 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00004819 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004820 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00004821
4822 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004823 }
4824 }
4825
4826 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00004827 typedef CodeCompletionResult Result;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004828 ResultBuilder Results(*this);
4829
4830 if (ReturnTy)
4831 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00004832
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004833 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00004834 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4835 MEnd = MethodPool.end();
4836 M != MEnd; ++M) {
4837 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
4838 &M->second.second;
4839 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004840 MethList = MethList->Next) {
4841 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4842 NumSelIdents))
4843 continue;
4844
Douglas Gregor40ed9a12010-07-08 23:37:41 +00004845 if (AtParameterName) {
4846 // Suggest parameter names we've seen before.
4847 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
4848 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
4849 if (Param->getIdentifier()) {
4850 CodeCompletionString *Pattern = new CodeCompletionString;
4851 Pattern->AddTypedTextChunk(Param->getIdentifier()->getName());
4852 Results.AddResult(Pattern);
4853 }
4854 }
4855
4856 continue;
4857 }
4858
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004859 Result R(MethList->Method, 0);
4860 R.StartParameter = NumSelIdents;
4861 R.AllParametersAreInformative = false;
4862 R.DeclaringEntity = true;
4863 Results.MaybeAddResult(R, CurContext);
4864 }
4865 }
4866
4867 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004868 HandleCodeCompleteResults(this, CodeCompleter,
4869 CodeCompletionContext::CCC_Other,
4870 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00004871}
Douglas Gregor87c08a52010-08-13 22:48:40 +00004872
Douglas Gregorf29c5232010-08-24 22:20:20 +00004873void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00004874 ResultBuilder Results(*this);
4875 Results.EnterNewScope();
4876
4877 // #if <condition>
4878 CodeCompletionString *Pattern = new CodeCompletionString;
4879 Pattern->AddTypedTextChunk("if");
4880 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4881 Pattern->AddPlaceholderChunk("condition");
4882 Results.AddResult(Pattern);
4883
4884 // #ifdef <macro>
4885 Pattern = new CodeCompletionString;
4886 Pattern->AddTypedTextChunk("ifdef");
4887 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4888 Pattern->AddPlaceholderChunk("macro");
4889 Results.AddResult(Pattern);
4890
4891 // #ifndef <macro>
4892 Pattern = new CodeCompletionString;
4893 Pattern->AddTypedTextChunk("ifndef");
4894 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4895 Pattern->AddPlaceholderChunk("macro");
4896 Results.AddResult(Pattern);
4897
4898 if (InConditional) {
4899 // #elif <condition>
4900 Pattern = new CodeCompletionString;
4901 Pattern->AddTypedTextChunk("elif");
4902 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4903 Pattern->AddPlaceholderChunk("condition");
4904 Results.AddResult(Pattern);
4905
4906 // #else
4907 Pattern = new CodeCompletionString;
4908 Pattern->AddTypedTextChunk("else");
4909 Results.AddResult(Pattern);
4910
4911 // #endif
4912 Pattern = new CodeCompletionString;
4913 Pattern->AddTypedTextChunk("endif");
4914 Results.AddResult(Pattern);
4915 }
4916
4917 // #include "header"
4918 Pattern = new CodeCompletionString;
4919 Pattern->AddTypedTextChunk("include");
4920 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4921 Pattern->AddTextChunk("\"");
4922 Pattern->AddPlaceholderChunk("header");
4923 Pattern->AddTextChunk("\"");
4924 Results.AddResult(Pattern);
4925
4926 // #include <header>
4927 Pattern = new CodeCompletionString;
4928 Pattern->AddTypedTextChunk("include");
4929 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4930 Pattern->AddTextChunk("<");
4931 Pattern->AddPlaceholderChunk("header");
4932 Pattern->AddTextChunk(">");
4933 Results.AddResult(Pattern);
4934
4935 // #define <macro>
4936 Pattern = new CodeCompletionString;
4937 Pattern->AddTypedTextChunk("define");
4938 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4939 Pattern->AddPlaceholderChunk("macro");
4940 Results.AddResult(Pattern);
4941
4942 // #define <macro>(<args>)
4943 Pattern = new CodeCompletionString;
4944 Pattern->AddTypedTextChunk("define");
4945 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4946 Pattern->AddPlaceholderChunk("macro");
4947 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
4948 Pattern->AddPlaceholderChunk("args");
4949 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
4950 Results.AddResult(Pattern);
4951
4952 // #undef <macro>
4953 Pattern = new CodeCompletionString;
4954 Pattern->AddTypedTextChunk("undef");
4955 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4956 Pattern->AddPlaceholderChunk("macro");
4957 Results.AddResult(Pattern);
4958
4959 // #line <number>
4960 Pattern = new CodeCompletionString;
4961 Pattern->AddTypedTextChunk("line");
4962 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4963 Pattern->AddPlaceholderChunk("number");
4964 Results.AddResult(Pattern);
4965
4966 // #line <number> "filename"
4967 Pattern = new CodeCompletionString;
4968 Pattern->AddTypedTextChunk("line");
4969 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4970 Pattern->AddPlaceholderChunk("number");
4971 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4972 Pattern->AddTextChunk("\"");
4973 Pattern->AddPlaceholderChunk("filename");
4974 Pattern->AddTextChunk("\"");
4975 Results.AddResult(Pattern);
4976
4977 // #error <message>
4978 Pattern = new CodeCompletionString;
4979 Pattern->AddTypedTextChunk("error");
4980 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4981 Pattern->AddPlaceholderChunk("message");
4982 Results.AddResult(Pattern);
4983
4984 // #pragma <arguments>
4985 Pattern = new CodeCompletionString;
4986 Pattern->AddTypedTextChunk("pragma");
4987 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4988 Pattern->AddPlaceholderChunk("arguments");
4989 Results.AddResult(Pattern);
4990
4991 if (getLangOptions().ObjC1) {
4992 // #import "header"
4993 Pattern = new CodeCompletionString;
4994 Pattern->AddTypedTextChunk("import");
4995 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4996 Pattern->AddTextChunk("\"");
4997 Pattern->AddPlaceholderChunk("header");
4998 Pattern->AddTextChunk("\"");
4999 Results.AddResult(Pattern);
5000
5001 // #import <header>
5002 Pattern = new CodeCompletionString;
5003 Pattern->AddTypedTextChunk("import");
5004 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5005 Pattern->AddTextChunk("<");
5006 Pattern->AddPlaceholderChunk("header");
5007 Pattern->AddTextChunk(">");
5008 Results.AddResult(Pattern);
5009 }
5010
5011 // #include_next "header"
5012 Pattern = new CodeCompletionString;
5013 Pattern->AddTypedTextChunk("include_next");
5014 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5015 Pattern->AddTextChunk("\"");
5016 Pattern->AddPlaceholderChunk("header");
5017 Pattern->AddTextChunk("\"");
5018 Results.AddResult(Pattern);
5019
5020 // #include_next <header>
5021 Pattern = new CodeCompletionString;
5022 Pattern->AddTypedTextChunk("include_next");
5023 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5024 Pattern->AddTextChunk("<");
5025 Pattern->AddPlaceholderChunk("header");
5026 Pattern->AddTextChunk(">");
5027 Results.AddResult(Pattern);
5028
5029 // #warning <message>
5030 Pattern = new CodeCompletionString;
5031 Pattern->AddTypedTextChunk("warning");
5032 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5033 Pattern->AddPlaceholderChunk("message");
5034 Results.AddResult(Pattern);
5035
5036 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
5037 // completions for them. And __include_macros is a Clang-internal extension
5038 // that we don't want to encourage anyone to use.
5039
5040 // FIXME: we don't support #assert or #unassert, so don't suggest them.
5041 Results.ExitScope();
5042
Douglas Gregorf44e8542010-08-24 19:08:16 +00005043 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00005044 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00005045 Results.data(), Results.size());
5046}
5047
5048void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00005049 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00005050 S->getFnParent()? Sema::PCC_RecoveryInFunction
5051 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00005052}
5053
Douglas Gregorf29c5232010-08-24 22:20:20 +00005054void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor1fbb4472010-08-24 20:21:13 +00005055 ResultBuilder Results(*this);
5056 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
5057 // Add just the names of macros, not their arguments.
5058 Results.EnterNewScope();
5059 for (Preprocessor::macro_iterator M = PP.macro_begin(),
5060 MEnd = PP.macro_end();
5061 M != MEnd; ++M) {
5062 CodeCompletionString *Pattern = new CodeCompletionString;
5063 Pattern->AddTypedTextChunk(M->first->getName());
5064 Results.AddResult(Pattern);
5065 }
5066 Results.ExitScope();
5067 } else if (IsDefinition) {
5068 // FIXME: Can we detect when the user just wrote an include guard above?
5069 }
5070
5071 HandleCodeCompleteResults(this, CodeCompleter,
5072 IsDefinition? CodeCompletionContext::CCC_MacroName
5073 : CodeCompletionContext::CCC_MacroNameUse,
5074 Results.data(), Results.size());
5075}
5076
Douglas Gregorf29c5232010-08-24 22:20:20 +00005077void Sema::CodeCompletePreprocessorExpression() {
5078 ResultBuilder Results(*this);
5079
5080 if (!CodeCompleter || CodeCompleter->includeMacros())
5081 AddMacroResults(PP, Results);
5082
5083 // defined (<macro>)
5084 Results.EnterNewScope();
5085 CodeCompletionString *Pattern = new CodeCompletionString;
5086 Pattern->AddTypedTextChunk("defined");
5087 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5088 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5089 Pattern->AddPlaceholderChunk("macro");
5090 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5091 Results.AddResult(Pattern);
5092 Results.ExitScope();
5093
5094 HandleCodeCompleteResults(this, CodeCompleter,
5095 CodeCompletionContext::CCC_PreprocessorExpression,
5096 Results.data(), Results.size());
5097}
5098
5099void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
5100 IdentifierInfo *Macro,
5101 MacroInfo *MacroInfo,
5102 unsigned Argument) {
5103 // FIXME: In the future, we could provide "overload" results, much like we
5104 // do for function calls.
5105
5106 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00005107 S->getFnParent()? Sema::PCC_RecoveryInFunction
5108 : Sema::PCC_Namespace);
Douglas Gregorf29c5232010-08-24 22:20:20 +00005109}
5110
Douglas Gregor55817af2010-08-25 17:04:25 +00005111void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00005112 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00005113 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00005114 0, 0);
5115}
5116
Douglas Gregor87c08a52010-08-13 22:48:40 +00005117void Sema::GatherGlobalCodeCompletions(
John McCall0a2c5e22010-08-25 06:19:51 +00005118 llvm::SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor87c08a52010-08-13 22:48:40 +00005119 ResultBuilder Builder(*this);
5120
Douglas Gregor8071e422010-08-15 06:18:01 +00005121 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
5122 CodeCompletionDeclConsumer Consumer(Builder,
5123 Context.getTranslationUnitDecl());
5124 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
5125 Consumer);
5126 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00005127
5128 if (!CodeCompleter || CodeCompleter->includeMacros())
5129 AddMacroResults(PP, Builder);
5130
5131 Results.clear();
5132 Results.insert(Results.end(),
5133 Builder.data(), Builder.data() + Builder.size());
5134}