blob: f964ec14836d6453a5c7ded17ace83e6ce64c5e2 [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 Gregord36adf52010-09-16 16:06:31 +000025#include "llvm/ADT/DenseSet.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000026#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000027#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000028#include "llvm/ADT/StringSwitch.h"
Douglas Gregor458433d2010-08-26 15:07:07 +000029#include "llvm/ADT/Twine.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000030#include <list>
31#include <map>
32#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000033
34using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000035using namespace sema;
Douglas Gregor81b747b2009-09-17 21:32:03 +000036
Douglas Gregor86d9a522009-09-21 16:56:56 +000037namespace {
38 /// \brief A container of code-completion results.
39 class ResultBuilder {
40 public:
41 /// \brief The type of a name-lookup filter, which can be provided to the
42 /// name-lookup routines to specify which declarations should be included in
43 /// the result set (when it returns true) and which declarations should be
44 /// filtered out (returns false).
45 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
46
John McCall0a2c5e22010-08-25 06:19:51 +000047 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +000048
49 private:
50 /// \brief The actual results we have found.
51 std::vector<Result> Results;
52
53 /// \brief A record of all of the declarations we have found and placed
54 /// into the result set, used to ensure that no declaration ever gets into
55 /// the result set twice.
56 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
57
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000058 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
59
60 /// \brief An entry in the shadow map, which is optimized to store
61 /// a single (declaration, index) mapping (the common case) but
62 /// can also store a list of (declaration, index) mappings.
63 class ShadowMapEntry {
Chris Lattner5f9e2722011-07-23 10:55:15 +000064 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000065
66 /// \brief Contains either the solitary NamedDecl * or a vector
67 /// of (declaration, index) pairs.
68 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
69
70 /// \brief When the entry contains a single declaration, this is
71 /// the index associated with that entry.
72 unsigned SingleDeclIndex;
73
74 public:
75 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
76
77 void Add(NamedDecl *ND, unsigned Index) {
78 if (DeclOrVector.isNull()) {
79 // 0 - > 1 elements: just set the single element information.
80 DeclOrVector = ND;
81 SingleDeclIndex = Index;
82 return;
83 }
84
85 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
86 // 1 -> 2 elements: create the vector of results and push in the
87 // existing declaration.
88 DeclIndexPairVector *Vec = new DeclIndexPairVector;
89 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
90 DeclOrVector = Vec;
91 }
92
93 // Add the new element to the end of the vector.
94 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
95 DeclIndexPair(ND, Index));
96 }
97
98 void Destroy() {
99 if (DeclIndexPairVector *Vec
100 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
101 delete Vec;
102 DeclOrVector = ((NamedDecl *)0);
103 }
104 }
105
106 // Iteration.
107 class iterator;
108 iterator begin() const;
109 iterator end() const;
110 };
111
Douglas Gregor86d9a522009-09-21 16:56:56 +0000112 /// \brief A mapping from declaration names to the declarations that have
113 /// this name within a particular scope and their index within the list of
114 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000115 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000116
117 /// \brief The semantic analysis object for which results are being
118 /// produced.
119 Sema &SemaRef;
Douglas Gregor218937c2011-02-01 19:23:04 +0000120
121 /// \brief The allocator used to allocate new code-completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000122 CodeCompletionAllocator &Allocator;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000123
124 /// \brief If non-NULL, a filter function used to remove any code-completion
125 /// results that are not desirable.
126 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000127
128 /// \brief Whether we should allow declarations as
129 /// nested-name-specifiers that would otherwise be filtered out.
130 bool AllowNestedNameSpecifiers;
131
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000132 /// \brief If set, the type that we would prefer our resulting value
133 /// declarations to have.
134 ///
135 /// Closely matching the preferred type gives a boost to a result's
136 /// priority.
137 CanQualType PreferredType;
138
Douglas Gregor86d9a522009-09-21 16:56:56 +0000139 /// \brief A list of shadow maps, which is used to model name hiding at
140 /// different levels of, e.g., the inheritance hierarchy.
141 std::list<ShadowMap> ShadowMaps;
142
Douglas Gregor3cdee122010-08-26 16:36:48 +0000143 /// \brief If we're potentially referring to a C++ member function, the set
144 /// of qualifiers applied to the object type.
145 Qualifiers ObjectTypeQualifiers;
146
147 /// \brief Whether the \p ObjectTypeQualifiers field is active.
148 bool HasObjectTypeQualifiers;
149
Douglas Gregor265f7492010-08-27 15:29:55 +0000150 /// \brief The selector that we prefer.
151 Selector PreferredSelector;
152
Douglas Gregorca45da02010-11-02 20:36:02 +0000153 /// \brief The completion context in which we are gathering results.
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000154 CodeCompletionContext CompletionContext;
155
Douglas Gregorca45da02010-11-02 20:36:02 +0000156 /// \brief If we are in an instance method definition, the @implementation
157 /// object.
158 ObjCImplementationDecl *ObjCImplementation;
159
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000160 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000161
Douglas Gregor6f942b22010-09-21 16:06:22 +0000162 void MaybeAddConstructorResults(Result R);
163
Douglas Gregor86d9a522009-09-21 16:56:56 +0000164 public:
Douglas Gregordae68752011-02-01 22:57:45 +0000165 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Douglas Gregor52779fb2010-09-23 23:01:17 +0000166 const CodeCompletionContext &CompletionContext,
167 LookupFilter Filter = 0)
Douglas Gregor218937c2011-02-01 19:23:04 +0000168 : SemaRef(SemaRef), Allocator(Allocator), Filter(Filter),
169 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregorca45da02010-11-02 20:36:02 +0000170 CompletionContext(CompletionContext),
171 ObjCImplementation(0)
172 {
173 // If this is an Objective-C instance method definition, dig out the
174 // corresponding implementation.
175 switch (CompletionContext.getKind()) {
176 case CodeCompletionContext::CCC_Expression:
177 case CodeCompletionContext::CCC_ObjCMessageReceiver:
178 case CodeCompletionContext::CCC_ParenthesizedExpression:
179 case CodeCompletionContext::CCC_Statement:
180 case CodeCompletionContext::CCC_Recovery:
181 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
182 if (Method->isInstanceMethod())
183 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
184 ObjCImplementation = Interface->getImplementation();
185 break;
186
187 default:
188 break;
189 }
190 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000191
Douglas Gregord8e8a582010-05-25 21:41:55 +0000192 /// \brief Whether we should include code patterns in the completion
193 /// results.
194 bool includeCodePatterns() const {
195 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000196 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000197 }
198
Douglas Gregor86d9a522009-09-21 16:56:56 +0000199 /// \brief Set the filter used for code-completion results.
200 void setFilter(LookupFilter Filter) {
201 this->Filter = Filter;
202 }
203
Douglas Gregor86d9a522009-09-21 16:56:56 +0000204 Result *data() { return Results.empty()? 0 : &Results.front(); }
205 unsigned size() const { return Results.size(); }
206 bool empty() const { return Results.empty(); }
207
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000208 /// \brief Specify the preferred type.
209 void setPreferredType(QualType T) {
210 PreferredType = SemaRef.Context.getCanonicalType(T);
211 }
212
Douglas Gregor3cdee122010-08-26 16:36:48 +0000213 /// \brief Set the cv-qualifiers on the object type, for us in filtering
214 /// calls to member functions.
215 ///
216 /// When there are qualifiers in this set, they will be used to filter
217 /// out member functions that aren't available (because there will be a
218 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
219 /// match.
220 void setObjectTypeQualifiers(Qualifiers Quals) {
221 ObjectTypeQualifiers = Quals;
222 HasObjectTypeQualifiers = true;
223 }
224
Douglas Gregor265f7492010-08-27 15:29:55 +0000225 /// \brief Set the preferred selector.
226 ///
227 /// When an Objective-C method declaration result is added, and that
228 /// method's selector matches this preferred selector, we give that method
229 /// a slight priority boost.
230 void setPreferredSelector(Selector Sel) {
231 PreferredSelector = Sel;
232 }
Douglas Gregorca45da02010-11-02 20:36:02 +0000233
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000234 /// \brief Retrieve the code-completion context for which results are
235 /// being collected.
236 const CodeCompletionContext &getCompletionContext() const {
237 return CompletionContext;
238 }
239
Douglas Gregor45bcd432010-01-14 03:21:49 +0000240 /// \brief Specify whether nested-name-specifiers are allowed.
241 void allowNestedNameSpecifiers(bool Allow = true) {
242 AllowNestedNameSpecifiers = Allow;
243 }
244
Douglas Gregorb9d77572010-09-21 00:03:25 +0000245 /// \brief Return the semantic analysis object for which we are collecting
246 /// code completion results.
247 Sema &getSema() const { return SemaRef; }
248
Douglas Gregor218937c2011-02-01 19:23:04 +0000249 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000250 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Douglas Gregor218937c2011-02-01 19:23:04 +0000251
Douglas Gregore495b7f2010-01-14 00:20:49 +0000252 /// \brief Determine whether the given declaration is at all interesting
253 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000254 ///
255 /// \param ND the declaration that we are inspecting.
256 ///
257 /// \param AsNestedNameSpecifier will be set true if this declaration is
258 /// only interesting when it is a nested-name-specifier.
259 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000260
261 /// \brief Check whether the result is hidden by the Hiding declaration.
262 ///
263 /// \returns true if the result is hidden and cannot be found, false if
264 /// the hidden result could still be found. When false, \p R may be
265 /// modified to describe how the result can be found (e.g., via extra
266 /// qualification).
267 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
268 NamedDecl *Hiding);
269
Douglas Gregor86d9a522009-09-21 16:56:56 +0000270 /// \brief Add a new result to this result set (if it isn't already in one
271 /// of the shadow maps), or replace an existing result (for, e.g., a
272 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000273 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000274 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000275 ///
276 /// \param R the context in which this result will be named.
277 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000278
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000279 /// \brief Add a new result to this result set, where we already know
280 /// the hiding declation (if any).
281 ///
282 /// \param R the result to add (if it is unique).
283 ///
284 /// \param CurContext the context in which this result will be named.
285 ///
286 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000287 ///
288 /// \param InBaseClass whether the result was found in a base
289 /// class of the searched context.
290 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
291 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000292
Douglas Gregora4477812010-01-14 16:01:26 +0000293 /// \brief Add a new non-declaration result to this result set.
294 void AddResult(Result R);
295
Douglas Gregor86d9a522009-09-21 16:56:56 +0000296 /// \brief Enter into a new scope.
297 void EnterNewScope();
298
299 /// \brief Exit from the current scope.
300 void ExitScope();
301
Douglas Gregor55385fe2009-11-18 04:19:12 +0000302 /// \brief Ignore this declaration, if it is seen again.
303 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
304
Douglas Gregor86d9a522009-09-21 16:56:56 +0000305 /// \name Name lookup predicates
306 ///
307 /// These predicates can be passed to the name lookup functions to filter the
308 /// results of name lookup. All of the predicates have the same type, so that
309 ///
310 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000311 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000312 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000313 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000314 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000315 bool IsNestedNameSpecifier(NamedDecl *ND) const;
316 bool IsEnum(NamedDecl *ND) const;
317 bool IsClassOrStruct(NamedDecl *ND) const;
318 bool IsUnion(NamedDecl *ND) const;
319 bool IsNamespace(NamedDecl *ND) const;
320 bool IsNamespaceOrAlias(NamedDecl *ND) const;
321 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000322 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000323 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000324 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000325 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000326 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000327 //@}
328 };
329}
330
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000331class ResultBuilder::ShadowMapEntry::iterator {
332 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
333 unsigned SingleDeclIndex;
334
335public:
336 typedef DeclIndexPair value_type;
337 typedef value_type reference;
338 typedef std::ptrdiff_t difference_type;
339 typedef std::input_iterator_tag iterator_category;
340
341 class pointer {
342 DeclIndexPair Value;
343
344 public:
345 pointer(const DeclIndexPair &Value) : Value(Value) { }
346
347 const DeclIndexPair *operator->() const {
348 return &Value;
349 }
350 };
351
352 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
353
354 iterator(NamedDecl *SingleDecl, unsigned Index)
355 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
356
357 iterator(const DeclIndexPair *Iterator)
358 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
359
360 iterator &operator++() {
361 if (DeclOrIterator.is<NamedDecl *>()) {
362 DeclOrIterator = (NamedDecl *)0;
363 SingleDeclIndex = 0;
364 return *this;
365 }
366
367 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
368 ++I;
369 DeclOrIterator = I;
370 return *this;
371 }
372
Chris Lattner66392d42010-09-04 18:12:20 +0000373 /*iterator operator++(int) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000374 iterator tmp(*this);
375 ++(*this);
376 return tmp;
Chris Lattner66392d42010-09-04 18:12:20 +0000377 }*/
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000378
379 reference operator*() const {
380 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
381 return reference(ND, SingleDeclIndex);
382
Douglas Gregord490f952009-12-06 21:27:58 +0000383 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000384 }
385
386 pointer operator->() const {
387 return pointer(**this);
388 }
389
390 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000391 return X.DeclOrIterator.getOpaqueValue()
392 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000393 X.SingleDeclIndex == Y.SingleDeclIndex;
394 }
395
396 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000397 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000398 }
399};
400
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000401ResultBuilder::ShadowMapEntry::iterator
402ResultBuilder::ShadowMapEntry::begin() const {
403 if (DeclOrVector.isNull())
404 return iterator();
405
406 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
407 return iterator(ND, SingleDeclIndex);
408
409 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
410}
411
412ResultBuilder::ShadowMapEntry::iterator
413ResultBuilder::ShadowMapEntry::end() const {
414 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
415 return iterator();
416
417 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
418}
419
Douglas Gregor456c4a12009-09-21 20:12:40 +0000420/// \brief Compute the qualification required to get from the current context
421/// (\p CurContext) to the target context (\p TargetContext).
422///
423/// \param Context the AST context in which the qualification will be used.
424///
425/// \param CurContext the context where an entity is being named, which is
426/// typically based on the current scope.
427///
428/// \param TargetContext the context in which the named entity actually
429/// resides.
430///
431/// \returns a nested name specifier that refers into the target context, or
432/// NULL if no qualification is needed.
433static NestedNameSpecifier *
434getRequiredQualification(ASTContext &Context,
435 DeclContext *CurContext,
436 DeclContext *TargetContext) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000437 SmallVector<DeclContext *, 4> TargetParents;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000438
439 for (DeclContext *CommonAncestor = TargetContext;
440 CommonAncestor && !CommonAncestor->Encloses(CurContext);
441 CommonAncestor = CommonAncestor->getLookupParent()) {
442 if (CommonAncestor->isTransparentContext() ||
443 CommonAncestor->isFunctionOrMethod())
444 continue;
445
446 TargetParents.push_back(CommonAncestor);
447 }
448
449 NestedNameSpecifier *Result = 0;
450 while (!TargetParents.empty()) {
451 DeclContext *Parent = TargetParents.back();
452 TargetParents.pop_back();
453
Douglas Gregorfb629412010-08-23 21:17:50 +0000454 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
455 if (!Namespace->getIdentifier())
456 continue;
457
Douglas Gregor456c4a12009-09-21 20:12:40 +0000458 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000459 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000460 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
461 Result = NestedNameSpecifier::Create(Context, Result,
462 false,
463 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000464 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000465 return Result;
466}
467
Douglas Gregor45bcd432010-01-14 03:21:49 +0000468bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
469 bool &AsNestedNameSpecifier) const {
470 AsNestedNameSpecifier = false;
471
Douglas Gregore495b7f2010-01-14 00:20:49 +0000472 ND = ND->getUnderlyingDecl();
473 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000474
475 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000476 if (!ND->getDeclName())
477 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000478
479 // Friend declarations and declarations introduced due to friends are never
480 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000481 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000482 return false;
483
Douglas Gregor76282942009-12-11 17:31:05 +0000484 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000485 if (isa<ClassTemplateSpecializationDecl>(ND) ||
486 isa<ClassTemplatePartialSpecializationDecl>(ND))
487 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000488
Douglas Gregor76282942009-12-11 17:31:05 +0000489 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000490 if (isa<UsingDecl>(ND))
491 return false;
492
493 // Some declarations have reserved names that we don't want to ever show.
494 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000495 // __va_list_tag is a freak of nature. Find it and skip it.
496 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000497 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000498
Douglas Gregorf52cede2009-10-09 22:16:47 +0000499 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000500 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000501 //
502 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000503 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000504 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000505 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000506 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
507 (ND->getLocation().isInvalid() ||
508 SemaRef.SourceMgr.isInSystemHeader(
509 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000510 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000511 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000512 }
Douglas Gregor6f942b22010-09-21 16:06:22 +0000513
Douglas Gregor9b0ba872010-11-09 03:59:40 +0000514 // Skip out-of-line declarations and definitions.
515 // NOTE: Unless it's an Objective-C property, method, or ivar, where
516 // the contexts can be messy.
517 if (!ND->getDeclContext()->Equals(ND->getLexicalDeclContext()) &&
518 !(isa<ObjCPropertyDecl>(ND) || isa<ObjCIvarDecl>(ND) ||
519 isa<ObjCMethodDecl>(ND)))
520 return false;
521
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000522 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
523 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
524 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor52779fb2010-09-23 23:01:17 +0000525 Filter != &ResultBuilder::IsNamespaceOrAlias &&
526 Filter != 0))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000527 AsNestedNameSpecifier = true;
528
Douglas Gregor86d9a522009-09-21 16:56:56 +0000529 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000530 if (Filter && !(this->*Filter)(ND)) {
531 // Check whether it is interesting as a nested-name-specifier.
532 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
533 IsNestedNameSpecifier(ND) &&
534 (Filter != &ResultBuilder::IsMember ||
535 (isa<CXXRecordDecl>(ND) &&
536 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
537 AsNestedNameSpecifier = true;
538 return true;
539 }
540
Douglas Gregore495b7f2010-01-14 00:20:49 +0000541 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000542 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000543 // ... then it must be interesting!
544 return true;
545}
546
Douglas Gregor6660d842010-01-14 00:41:07 +0000547bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
548 NamedDecl *Hiding) {
549 // In C, there is no way to refer to a hidden name.
550 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
551 // name if we introduce the tag type.
552 if (!SemaRef.getLangOptions().CPlusPlus)
553 return true;
554
Sebastian Redl7a126a42010-08-31 00:36:30 +0000555 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregor6660d842010-01-14 00:41:07 +0000556
557 // There is no way to qualify a name declared in a function or method.
558 if (HiddenCtx->isFunctionOrMethod())
559 return true;
560
Sebastian Redl7a126a42010-08-31 00:36:30 +0000561 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregor6660d842010-01-14 00:41:07 +0000562 return true;
563
564 // We can refer to the result with the appropriate qualification. Do it.
565 R.Hidden = true;
566 R.QualifierIsInformative = false;
567
568 if (!R.Qualifier)
569 R.Qualifier = getRequiredQualification(SemaRef.Context,
570 CurContext,
571 R.Declaration->getDeclContext());
572 return false;
573}
574
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000575/// \brief A simplified classification of types used to determine whether two
576/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000577SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000578 switch (T->getTypeClass()) {
579 case Type::Builtin:
580 switch (cast<BuiltinType>(T)->getKind()) {
581 case BuiltinType::Void:
582 return STC_Void;
583
584 case BuiltinType::NullPtr:
585 return STC_Pointer;
586
587 case BuiltinType::Overload:
588 case BuiltinType::Dependent:
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000589 return STC_Other;
590
591 case BuiltinType::ObjCId:
592 case BuiltinType::ObjCClass:
593 case BuiltinType::ObjCSel:
594 return STC_ObjectiveC;
595
596 default:
597 return STC_Arithmetic;
598 }
599 return STC_Other;
600
601 case Type::Complex:
602 return STC_Arithmetic;
603
604 case Type::Pointer:
605 return STC_Pointer;
606
607 case Type::BlockPointer:
608 return STC_Block;
609
610 case Type::LValueReference:
611 case Type::RValueReference:
612 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
613
614 case Type::ConstantArray:
615 case Type::IncompleteArray:
616 case Type::VariableArray:
617 case Type::DependentSizedArray:
618 return STC_Array;
619
620 case Type::DependentSizedExtVector:
621 case Type::Vector:
622 case Type::ExtVector:
623 return STC_Arithmetic;
624
625 case Type::FunctionProto:
626 case Type::FunctionNoProto:
627 return STC_Function;
628
629 case Type::Record:
630 return STC_Record;
631
632 case Type::Enum:
633 return STC_Arithmetic;
634
635 case Type::ObjCObject:
636 case Type::ObjCInterface:
637 case Type::ObjCObjectPointer:
638 return STC_ObjectiveC;
639
640 default:
641 return STC_Other;
642 }
643}
644
645/// \brief Get the type that a given expression will have if this declaration
646/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000647QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000648 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
649
650 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
651 return C.getTypeDeclType(Type);
652 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
653 return C.getObjCInterfaceType(Iface);
654
655 QualType T;
656 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000657 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000658 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000659 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000660 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000661 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000662 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
663 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
664 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
665 T = Property->getType();
666 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
667 T = Value->getType();
668 else
669 return QualType();
Douglas Gregor3e64d562011-04-14 20:33:34 +0000670
671 // Dig through references, function pointers, and block pointers to
672 // get down to the likely type of an expression when the entity is
673 // used.
674 do {
675 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
676 T = Ref->getPointeeType();
677 continue;
678 }
679
680 if (const PointerType *Pointer = T->getAs<PointerType>()) {
681 if (Pointer->getPointeeType()->isFunctionType()) {
682 T = Pointer->getPointeeType();
683 continue;
684 }
685
686 break;
687 }
688
689 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
690 T = Block->getPointeeType();
691 continue;
692 }
693
694 if (const FunctionType *Function = T->getAs<FunctionType>()) {
695 T = Function->getResultType();
696 continue;
697 }
698
699 break;
700 } while (true);
701
702 return T;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000703}
704
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000705void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
706 // If this is an Objective-C method declaration whose selector matches our
707 // preferred selector, give it a priority boost.
708 if (!PreferredSelector.isNull())
709 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
710 if (PreferredSelector == Method->getSelector())
711 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000712
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000713 // If we have a preferred type, adjust the priority for results with exactly-
714 // matching or nearly-matching types.
715 if (!PreferredType.isNull()) {
716 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
717 if (!T.isNull()) {
718 CanQualType TC = SemaRef.Context.getCanonicalType(T);
719 // Check for exactly-matching types (modulo qualifiers).
720 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
721 R.Priority /= CCF_ExactTypeMatch;
722 // Check for nearly-matching types, based on classification of each.
723 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000724 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000725 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
726 R.Priority /= CCF_SimilarTypeMatch;
727 }
728 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000729}
730
Douglas Gregor6f942b22010-09-21 16:06:22 +0000731void ResultBuilder::MaybeAddConstructorResults(Result R) {
732 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
733 !CompletionContext.wantConstructorResults())
734 return;
735
736 ASTContext &Context = SemaRef.Context;
737 NamedDecl *D = R.Declaration;
738 CXXRecordDecl *Record = 0;
739 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
740 Record = ClassTemplate->getTemplatedDecl();
741 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
742 // Skip specializations and partial specializations.
743 if (isa<ClassTemplateSpecializationDecl>(Record))
744 return;
745 } else {
746 // There are no constructors here.
747 return;
748 }
749
750 Record = Record->getDefinition();
751 if (!Record)
752 return;
753
754
755 QualType RecordTy = Context.getTypeDeclType(Record);
756 DeclarationName ConstructorName
757 = Context.DeclarationNames.getCXXConstructorName(
758 Context.getCanonicalType(RecordTy));
759 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
760 Ctors.first != Ctors.second; ++Ctors.first) {
761 R.Declaration = *Ctors.first;
762 R.CursorKind = getCursorKindForDecl(R.Declaration);
763 Results.push_back(R);
764 }
765}
766
Douglas Gregore495b7f2010-01-14 00:20:49 +0000767void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
768 assert(!ShadowMaps.empty() && "Must enter into a results scope");
769
770 if (R.Kind != Result::RK_Declaration) {
771 // For non-declaration results, just add the result.
772 Results.push_back(R);
773 return;
774 }
775
776 // Look through using declarations.
777 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
778 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
779 return;
780 }
781
782 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
783 unsigned IDNS = CanonDecl->getIdentifierNamespace();
784
Douglas Gregor45bcd432010-01-14 03:21:49 +0000785 bool AsNestedNameSpecifier = false;
786 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000787 return;
788
Douglas Gregor6f942b22010-09-21 16:06:22 +0000789 // C++ constructors are never found by name lookup.
790 if (isa<CXXConstructorDecl>(R.Declaration))
791 return;
792
Douglas Gregor86d9a522009-09-21 16:56:56 +0000793 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000794 ShadowMapEntry::iterator I, IEnd;
795 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
796 if (NamePos != SMap.end()) {
797 I = NamePos->second.begin();
798 IEnd = NamePos->second.end();
799 }
800
801 for (; I != IEnd; ++I) {
802 NamedDecl *ND = I->first;
803 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000804 if (ND->getCanonicalDecl() == CanonDecl) {
805 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000806 Results[Index].Declaration = R.Declaration;
807
Douglas Gregor86d9a522009-09-21 16:56:56 +0000808 // We're done.
809 return;
810 }
811 }
812
813 // This is a new declaration in this scope. However, check whether this
814 // declaration name is hidden by a similarly-named declaration in an outer
815 // scope.
816 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
817 --SMEnd;
818 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000819 ShadowMapEntry::iterator I, IEnd;
820 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
821 if (NamePos != SM->end()) {
822 I = NamePos->second.begin();
823 IEnd = NamePos->second.end();
824 }
825 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000826 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000827 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000828 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
829 Decl::IDNS_ObjCProtocol)))
830 continue;
831
832 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000833 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000834 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000835 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000836 continue;
837
838 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000839 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000840 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000841
842 break;
843 }
844 }
845
846 // Make sure that any given declaration only shows up in the result set once.
847 if (!AllDeclsFound.insert(CanonDecl))
848 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000849
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000850 // If the filter is for nested-name-specifiers, then this result starts a
851 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000852 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000853 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000854 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000855 } else
856 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000857
Douglas Gregor0563c262009-09-22 23:15:58 +0000858 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000859 if (R.QualifierIsInformative && !R.Qualifier &&
860 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000861 DeclContext *Ctx = R.Declaration->getDeclContext();
862 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
863 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
864 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
865 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
866 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
867 else
868 R.QualifierIsInformative = false;
869 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000870
Douglas Gregor86d9a522009-09-21 16:56:56 +0000871 // Insert this result into the set of results and into the current shadow
872 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000873 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000874 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000875
876 if (!AsNestedNameSpecifier)
877 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000878}
879
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000880void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000881 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000882 if (R.Kind != Result::RK_Declaration) {
883 // For non-declaration results, just add the result.
884 Results.push_back(R);
885 return;
886 }
887
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000888 // Look through using declarations.
889 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
890 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
891 return;
892 }
893
Douglas Gregor45bcd432010-01-14 03:21:49 +0000894 bool AsNestedNameSpecifier = false;
895 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000896 return;
897
Douglas Gregor6f942b22010-09-21 16:06:22 +0000898 // C++ constructors are never found by name lookup.
899 if (isa<CXXConstructorDecl>(R.Declaration))
900 return;
901
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000902 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
903 return;
904
905 // Make sure that any given declaration only shows up in the result set once.
906 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
907 return;
908
909 // If the filter is for nested-name-specifiers, then this result starts a
910 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000911 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000912 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000913 R.Priority = CCP_NestedNameSpecifier;
914 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000915 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
916 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000917 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000918 R.QualifierIsInformative = true;
919
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000920 // If this result is supposed to have an informative qualifier, add one.
921 if (R.QualifierIsInformative && !R.Qualifier &&
922 !R.StartsNestedNameSpecifier) {
923 DeclContext *Ctx = R.Declaration->getDeclContext();
924 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
925 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
926 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
927 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000928 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000929 else
930 R.QualifierIsInformative = false;
931 }
932
Douglas Gregor12e13132010-05-26 22:00:08 +0000933 // Adjust the priority if this result comes from a base class.
934 if (InBaseClass)
935 R.Priority += CCD_InBaseClass;
936
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000937 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000938
Douglas Gregor3cdee122010-08-26 16:36:48 +0000939 if (HasObjectTypeQualifiers)
940 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
941 if (Method->isInstance()) {
942 Qualifiers MethodQuals
943 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
944 if (ObjectTypeQualifiers == MethodQuals)
945 R.Priority += CCD_ObjectQualifierMatch;
946 else if (ObjectTypeQualifiers - MethodQuals) {
947 // The method cannot be invoked, because doing so would drop
948 // qualifiers.
949 return;
950 }
951 }
952
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000953 // Insert this result into the set of results.
954 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000955
956 if (!AsNestedNameSpecifier)
957 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000958}
959
Douglas Gregora4477812010-01-14 16:01:26 +0000960void ResultBuilder::AddResult(Result R) {
961 assert(R.Kind != Result::RK_Declaration &&
962 "Declaration results need more context");
963 Results.push_back(R);
964}
965
Douglas Gregor86d9a522009-09-21 16:56:56 +0000966/// \brief Enter into a new scope.
967void ResultBuilder::EnterNewScope() {
968 ShadowMaps.push_back(ShadowMap());
969}
970
971/// \brief Exit from the current scope.
972void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000973 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
974 EEnd = ShadowMaps.back().end();
975 E != EEnd;
976 ++E)
977 E->second.Destroy();
978
Douglas Gregor86d9a522009-09-21 16:56:56 +0000979 ShadowMaps.pop_back();
980}
981
Douglas Gregor791215b2009-09-21 20:51:25 +0000982/// \brief Determines whether this given declaration will be found by
983/// ordinary name lookup.
984bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000985 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
986
Douglas Gregor791215b2009-09-21 20:51:25 +0000987 unsigned IDNS = Decl::IDNS_Ordinary;
988 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000989 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000990 else if (SemaRef.getLangOptions().ObjC1) {
991 if (isa<ObjCIvarDecl>(ND))
992 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +0000993 }
994
Douglas Gregor791215b2009-09-21 20:51:25 +0000995 return ND->getIdentifierNamespace() & IDNS;
996}
997
Douglas Gregor01dfea02010-01-10 23:08:15 +0000998/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000999/// ordinary name lookup but is not a type name.
1000bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
1001 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1002 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1003 return false;
1004
1005 unsigned IDNS = Decl::IDNS_Ordinary;
1006 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +00001007 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +00001008 else if (SemaRef.getLangOptions().ObjC1) {
1009 if (isa<ObjCIvarDecl>(ND))
1010 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +00001011 }
1012
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001013 return ND->getIdentifierNamespace() & IDNS;
1014}
1015
Douglas Gregorf9578432010-07-28 21:50:18 +00001016bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
1017 if (!IsOrdinaryNonTypeName(ND))
1018 return 0;
1019
1020 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1021 if (VD->getType()->isIntegralOrEnumerationType())
1022 return true;
1023
1024 return false;
1025}
1026
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001027/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +00001028/// ordinary name lookup.
1029bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001030 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1031
Douglas Gregor01dfea02010-01-10 23:08:15 +00001032 unsigned IDNS = Decl::IDNS_Ordinary;
1033 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +00001034 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001035
1036 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001037 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1038 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001039}
1040
Douglas Gregor86d9a522009-09-21 16:56:56 +00001041/// \brief Determines whether the given declaration is suitable as the
1042/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1043bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1044 // Allow us to find class templates, too.
1045 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1046 ND = ClassTemplate->getTemplatedDecl();
1047
1048 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1049}
1050
1051/// \brief Determines whether the given declaration is an enumeration.
1052bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1053 return isa<EnumDecl>(ND);
1054}
1055
1056/// \brief Determines whether the given declaration is a class or struct.
1057bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1058 // Allow us to find class templates, too.
1059 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1060 ND = ClassTemplate->getTemplatedDecl();
1061
1062 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001063 return RD->getTagKind() == TTK_Class ||
1064 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001065
1066 return false;
1067}
1068
1069/// \brief Determines whether the given declaration is a union.
1070bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1071 // Allow us to find class templates, too.
1072 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1073 ND = ClassTemplate->getTemplatedDecl();
1074
1075 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001076 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001077
1078 return false;
1079}
1080
1081/// \brief Determines whether the given declaration is a namespace.
1082bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1083 return isa<NamespaceDecl>(ND);
1084}
1085
1086/// \brief Determines whether the given declaration is a namespace or
1087/// namespace alias.
1088bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1089 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1090}
1091
Douglas Gregor76282942009-12-11 17:31:05 +00001092/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001093bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001094 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1095 ND = Using->getTargetDecl();
1096
1097 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001098}
1099
Douglas Gregor76282942009-12-11 17:31:05 +00001100/// \brief Determines which members of a class should be visible via
1101/// "." or "->". Only value declarations, nested name specifiers, and
1102/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001103bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001104 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1105 ND = Using->getTargetDecl();
1106
Douglas Gregorce821962009-12-11 18:14:22 +00001107 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1108 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001109}
1110
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001111static bool isObjCReceiverType(ASTContext &C, QualType T) {
1112 T = C.getCanonicalType(T);
1113 switch (T->getTypeClass()) {
1114 case Type::ObjCObject:
1115 case Type::ObjCInterface:
1116 case Type::ObjCObjectPointer:
1117 return true;
1118
1119 case Type::Builtin:
1120 switch (cast<BuiltinType>(T)->getKind()) {
1121 case BuiltinType::ObjCId:
1122 case BuiltinType::ObjCClass:
1123 case BuiltinType::ObjCSel:
1124 return true;
1125
1126 default:
1127 break;
1128 }
1129 return false;
1130
1131 default:
1132 break;
1133 }
1134
1135 if (!C.getLangOptions().CPlusPlus)
1136 return false;
1137
1138 // FIXME: We could perform more analysis here to determine whether a
1139 // particular class type has any conversions to Objective-C types. For now,
1140 // just accept all class types.
1141 return T->isDependentType() || T->isRecordType();
1142}
1143
1144bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1145 QualType T = getDeclUsageType(SemaRef.Context, ND);
1146 if (T.isNull())
1147 return false;
1148
1149 T = SemaRef.Context.getBaseElementType(T);
1150 return isObjCReceiverType(SemaRef.Context, T);
1151}
1152
Douglas Gregorfb629412010-08-23 21:17:50 +00001153bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1154 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1155 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1156 return false;
1157
1158 QualType T = getDeclUsageType(SemaRef.Context, ND);
1159 if (T.isNull())
1160 return false;
1161
1162 T = SemaRef.Context.getBaseElementType(T);
1163 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1164 T->isObjCIdType() ||
1165 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1166}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001167
Douglas Gregor52779fb2010-09-23 23:01:17 +00001168bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1169 return false;
1170}
1171
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001172/// \rief Determines whether the given declaration is an Objective-C
1173/// instance variable.
1174bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1175 return isa<ObjCIvarDecl>(ND);
1176}
1177
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001178namespace {
1179 /// \brief Visible declaration consumer that adds a code-completion result
1180 /// for each visible declaration.
1181 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1182 ResultBuilder &Results;
1183 DeclContext *CurContext;
1184
1185 public:
1186 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1187 : Results(Results), CurContext(CurContext) { }
1188
Erik Verbruggend1205962011-10-06 07:27:49 +00001189 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1190 bool InBaseClass) {
1191 bool Accessible = true;
1192 if (Ctx) {
1193 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
1194 Accessible = Results.getSema().IsSimplyAccessible(ND, Class);
1195 // FIXME: ObjC access checks are missing.
1196 }
1197 ResultBuilder::Result Result(ND, 0, false, Accessible);
1198 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001199 }
1200 };
1201}
1202
Douglas Gregor86d9a522009-09-21 16:56:56 +00001203/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001204static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001205 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001206 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001207 Results.AddResult(Result("short", CCP_Type));
1208 Results.AddResult(Result("long", CCP_Type));
1209 Results.AddResult(Result("signed", CCP_Type));
1210 Results.AddResult(Result("unsigned", CCP_Type));
1211 Results.AddResult(Result("void", CCP_Type));
1212 Results.AddResult(Result("char", CCP_Type));
1213 Results.AddResult(Result("int", CCP_Type));
1214 Results.AddResult(Result("float", CCP_Type));
1215 Results.AddResult(Result("double", CCP_Type));
1216 Results.AddResult(Result("enum", CCP_Type));
1217 Results.AddResult(Result("struct", CCP_Type));
1218 Results.AddResult(Result("union", CCP_Type));
1219 Results.AddResult(Result("const", CCP_Type));
1220 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001221
Douglas Gregor86d9a522009-09-21 16:56:56 +00001222 if (LangOpts.C99) {
1223 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001224 Results.AddResult(Result("_Complex", CCP_Type));
1225 Results.AddResult(Result("_Imaginary", CCP_Type));
1226 Results.AddResult(Result("_Bool", CCP_Type));
1227 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001228 }
1229
Douglas Gregor218937c2011-02-01 19:23:04 +00001230 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001231 if (LangOpts.CPlusPlus) {
1232 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001233 Results.AddResult(Result("bool", CCP_Type +
1234 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001235 Results.AddResult(Result("class", CCP_Type));
1236 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001237
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001238 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001239 Builder.AddTypedTextChunk("typename");
1240 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1241 Builder.AddPlaceholderChunk("qualifier");
1242 Builder.AddTextChunk("::");
1243 Builder.AddPlaceholderChunk("name");
1244 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001245
Douglas Gregor86d9a522009-09-21 16:56:56 +00001246 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001247 Results.AddResult(Result("auto", CCP_Type));
1248 Results.AddResult(Result("char16_t", CCP_Type));
1249 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001250
Douglas Gregor218937c2011-02-01 19:23:04 +00001251 Builder.AddTypedTextChunk("decltype");
1252 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1253 Builder.AddPlaceholderChunk("expression");
1254 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1255 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001256 }
1257 }
1258
1259 // GNU extensions
1260 if (LangOpts.GNUMode) {
1261 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001262 // Results.AddResult(Result("_Decimal32"));
1263 // Results.AddResult(Result("_Decimal64"));
1264 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001265
Douglas Gregor218937c2011-02-01 19:23:04 +00001266 Builder.AddTypedTextChunk("typeof");
1267 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1268 Builder.AddPlaceholderChunk("expression");
1269 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001270
Douglas Gregor218937c2011-02-01 19:23:04 +00001271 Builder.AddTypedTextChunk("typeof");
1272 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1273 Builder.AddPlaceholderChunk("type");
1274 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1275 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001276 }
1277}
1278
John McCallf312b1e2010-08-26 23:41:50 +00001279static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001280 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001281 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001282 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001283 // Note: we don't suggest either "auto" or "register", because both
1284 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1285 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001286 Results.AddResult(Result("extern"));
1287 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001288}
1289
John McCallf312b1e2010-08-26 23:41:50 +00001290static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001291 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001292 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001293 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001294 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001295 case Sema::PCC_Class:
1296 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001297 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001298 Results.AddResult(Result("explicit"));
1299 Results.AddResult(Result("friend"));
1300 Results.AddResult(Result("mutable"));
1301 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001302 }
1303 // Fall through
1304
John McCallf312b1e2010-08-26 23:41:50 +00001305 case Sema::PCC_ObjCInterface:
1306 case Sema::PCC_ObjCImplementation:
1307 case Sema::PCC_Namespace:
1308 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001309 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001310 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001311 break;
1312
John McCallf312b1e2010-08-26 23:41:50 +00001313 case Sema::PCC_ObjCInstanceVariableList:
1314 case Sema::PCC_Expression:
1315 case Sema::PCC_Statement:
1316 case Sema::PCC_ForInit:
1317 case Sema::PCC_Condition:
1318 case Sema::PCC_RecoveryInFunction:
1319 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001320 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001321 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001322 break;
1323 }
1324}
1325
Douglas Gregorbca403c2010-01-13 23:51:12 +00001326static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1327static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1328static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001329 ResultBuilder &Results,
1330 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001331static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001332 ResultBuilder &Results,
1333 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001334static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001335 ResultBuilder &Results,
1336 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001337static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001338
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001339static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001340 CodeCompletionBuilder Builder(Results.getAllocator());
1341 Builder.AddTypedTextChunk("typedef");
1342 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1343 Builder.AddPlaceholderChunk("type");
1344 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1345 Builder.AddPlaceholderChunk("name");
1346 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001347}
1348
John McCallf312b1e2010-08-26 23:41:50 +00001349static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001350 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001351 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001352 case Sema::PCC_Namespace:
1353 case Sema::PCC_Class:
1354 case Sema::PCC_ObjCInstanceVariableList:
1355 case Sema::PCC_Template:
1356 case Sema::PCC_MemberTemplate:
1357 case Sema::PCC_Statement:
1358 case Sema::PCC_RecoveryInFunction:
1359 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001360 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001361 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001362 return true;
1363
John McCallf312b1e2010-08-26 23:41:50 +00001364 case Sema::PCC_Expression:
1365 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001366 return LangOpts.CPlusPlus;
1367
1368 case Sema::PCC_ObjCInterface:
1369 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001370 return false;
1371
John McCallf312b1e2010-08-26 23:41:50 +00001372 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001373 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001374 }
1375
1376 return false;
1377}
1378
Douglas Gregor8ca72082011-10-18 21:20:17 +00001379/// \brief Retrieve a printing policy suitable for code completion.
1380static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1381 PrintingPolicy Policy = S.getPrintingPolicy();
1382 Policy.AnonymousTagLocations = false;
1383 Policy.SuppressStrongLifetime = true;
Douglas Gregor25270b62011-11-03 00:16:13 +00001384 Policy.SuppressUnwrittenScope = true;
Douglas Gregor8ca72082011-10-18 21:20:17 +00001385 return Policy;
1386}
1387
1388/// \brief Retrieve the string representation of the given type as a string
1389/// that has the appropriate lifetime for code completion.
1390///
1391/// This routine provides a fast path where we provide constant strings for
1392/// common type names.
1393static const char *GetCompletionTypeString(QualType T,
1394 ASTContext &Context,
1395 const PrintingPolicy &Policy,
1396 CodeCompletionAllocator &Allocator) {
1397 if (!T.getLocalQualifiers()) {
1398 // Built-in type names are constant strings.
1399 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1400 return BT->getName(Policy);
1401
1402 // Anonymous tag types are constant strings.
1403 if (const TagType *TagT = dyn_cast<TagType>(T))
1404 if (TagDecl *Tag = TagT->getDecl())
1405 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
1406 switch (Tag->getTagKind()) {
1407 case TTK_Struct: return "struct <anonymous>";
1408 case TTK_Class: return "class <anonymous>";
1409 case TTK_Union: return "union <anonymous>";
1410 case TTK_Enum: return "enum <anonymous>";
1411 }
1412 }
1413 }
1414
1415 // Slow path: format the type as a string.
1416 std::string Result;
1417 T.getAsStringInternal(Result, Policy);
1418 return Allocator.CopyString(Result);
1419}
1420
Douglas Gregor01dfea02010-01-10 23:08:15 +00001421/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001422static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001423 Scope *S,
1424 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001425 ResultBuilder &Results) {
Douglas Gregor8ca72082011-10-18 21:20:17 +00001426 CodeCompletionAllocator &Allocator = Results.getAllocator();
1427 CodeCompletionBuilder Builder(Allocator);
1428 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
Douglas Gregor218937c2011-02-01 19:23:04 +00001429
John McCall0a2c5e22010-08-25 06:19:51 +00001430 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001431 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001432 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001433 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001434 if (Results.includeCodePatterns()) {
1435 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001436 Builder.AddTypedTextChunk("namespace");
1437 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1438 Builder.AddPlaceholderChunk("identifier");
1439 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1440 Builder.AddPlaceholderChunk("declarations");
1441 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1442 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1443 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001444 }
1445
Douglas Gregor01dfea02010-01-10 23:08:15 +00001446 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001447 Builder.AddTypedTextChunk("namespace");
1448 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1449 Builder.AddPlaceholderChunk("name");
1450 Builder.AddChunk(CodeCompletionString::CK_Equal);
1451 Builder.AddPlaceholderChunk("namespace");
1452 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001453
1454 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001455 Builder.AddTypedTextChunk("using");
1456 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1457 Builder.AddTextChunk("namespace");
1458 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1459 Builder.AddPlaceholderChunk("identifier");
1460 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001461
1462 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001463 Builder.AddTypedTextChunk("asm");
1464 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1465 Builder.AddPlaceholderChunk("string-literal");
1466 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1467 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001468
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001469 if (Results.includeCodePatterns()) {
1470 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001471 Builder.AddTypedTextChunk("template");
1472 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1473 Builder.AddPlaceholderChunk("declaration");
1474 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001475 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001476 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001477
1478 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001479 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001480
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001481 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001482 // Fall through
1483
John McCallf312b1e2010-08-26 23:41:50 +00001484 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001485 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001486 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001487 Builder.AddTypedTextChunk("using");
1488 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1489 Builder.AddPlaceholderChunk("qualifier");
1490 Builder.AddTextChunk("::");
1491 Builder.AddPlaceholderChunk("name");
1492 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001493
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001494 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001495 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001496 Builder.AddTypedTextChunk("using");
1497 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1498 Builder.AddTextChunk("typename");
1499 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1500 Builder.AddPlaceholderChunk("qualifier");
1501 Builder.AddTextChunk("::");
1502 Builder.AddPlaceholderChunk("name");
1503 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001504 }
1505
John McCallf312b1e2010-08-26 23:41:50 +00001506 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001507 AddTypedefResult(Results);
1508
Douglas Gregor01dfea02010-01-10 23:08:15 +00001509 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001510 Builder.AddTypedTextChunk("public");
1511 Builder.AddChunk(CodeCompletionString::CK_Colon);
1512 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001513
1514 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001515 Builder.AddTypedTextChunk("protected");
1516 Builder.AddChunk(CodeCompletionString::CK_Colon);
1517 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001518
1519 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001520 Builder.AddTypedTextChunk("private");
1521 Builder.AddChunk(CodeCompletionString::CK_Colon);
1522 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001523 }
1524 }
1525 // Fall through
1526
John McCallf312b1e2010-08-26 23:41:50 +00001527 case Sema::PCC_Template:
1528 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001529 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001530 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001531 Builder.AddTypedTextChunk("template");
1532 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1533 Builder.AddPlaceholderChunk("parameters");
1534 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1535 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001536 }
1537
Douglas Gregorbca403c2010-01-13 23:51:12 +00001538 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1539 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001540 break;
1541
John McCallf312b1e2010-08-26 23:41:50 +00001542 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001543 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1544 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1545 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001546 break;
1547
John McCallf312b1e2010-08-26 23:41:50 +00001548 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001549 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1550 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1551 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001552 break;
1553
John McCallf312b1e2010-08-26 23:41:50 +00001554 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001555 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001556 break;
1557
John McCallf312b1e2010-08-26 23:41:50 +00001558 case Sema::PCC_RecoveryInFunction:
1559 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001560 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001561
Douglas Gregorec3310a2011-04-12 02:47:21 +00001562 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1563 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001564 Builder.AddTypedTextChunk("try");
1565 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1566 Builder.AddPlaceholderChunk("statements");
1567 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1568 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1569 Builder.AddTextChunk("catch");
1570 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1571 Builder.AddPlaceholderChunk("declaration");
1572 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1573 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1574 Builder.AddPlaceholderChunk("statements");
1575 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1576 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1577 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001578 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001579 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001580 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001581
Douglas Gregord8e8a582010-05-25 21:41:55 +00001582 if (Results.includeCodePatterns()) {
1583 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001584 Builder.AddTypedTextChunk("if");
1585 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001586 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001587 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001588 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001589 Builder.AddPlaceholderChunk("expression");
1590 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1591 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1592 Builder.AddPlaceholderChunk("statements");
1593 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1594 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1595 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001596
Douglas Gregord8e8a582010-05-25 21:41:55 +00001597 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001598 Builder.AddTypedTextChunk("switch");
1599 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001600 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001601 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001602 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001603 Builder.AddPlaceholderChunk("expression");
1604 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1605 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1606 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1607 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1608 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001609 }
1610
Douglas Gregor01dfea02010-01-10 23:08:15 +00001611 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001612 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001613 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001614 Builder.AddTypedTextChunk("case");
1615 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1616 Builder.AddPlaceholderChunk("expression");
1617 Builder.AddChunk(CodeCompletionString::CK_Colon);
1618 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001619
1620 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001621 Builder.AddTypedTextChunk("default");
1622 Builder.AddChunk(CodeCompletionString::CK_Colon);
1623 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001624 }
1625
Douglas Gregord8e8a582010-05-25 21:41:55 +00001626 if (Results.includeCodePatterns()) {
1627 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001628 Builder.AddTypedTextChunk("while");
1629 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001630 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001631 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001632 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001633 Builder.AddPlaceholderChunk("expression");
1634 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1635 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1636 Builder.AddPlaceholderChunk("statements");
1637 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1638 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1639 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001640
1641 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001642 Builder.AddTypedTextChunk("do");
1643 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1644 Builder.AddPlaceholderChunk("statements");
1645 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1646 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1647 Builder.AddTextChunk("while");
1648 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1649 Builder.AddPlaceholderChunk("expression");
1650 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1651 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001652
Douglas Gregord8e8a582010-05-25 21:41:55 +00001653 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001654 Builder.AddTypedTextChunk("for");
1655 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001656 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001657 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001658 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001659 Builder.AddPlaceholderChunk("init-expression");
1660 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1661 Builder.AddPlaceholderChunk("condition");
1662 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1663 Builder.AddPlaceholderChunk("inc-expression");
1664 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1665 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1666 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1667 Builder.AddPlaceholderChunk("statements");
1668 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1669 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1670 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001671 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001672
1673 if (S->getContinueParent()) {
1674 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001675 Builder.AddTypedTextChunk("continue");
1676 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001677 }
1678
1679 if (S->getBreakParent()) {
1680 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001681 Builder.AddTypedTextChunk("break");
1682 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001683 }
1684
1685 // "return expression ;" or "return ;", depending on whether we
1686 // know the function is void or not.
1687 bool isVoid = false;
1688 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1689 isVoid = Function->getResultType()->isVoidType();
1690 else if (ObjCMethodDecl *Method
1691 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1692 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001693 else if (SemaRef.getCurBlock() &&
1694 !SemaRef.getCurBlock()->ReturnType.isNull())
1695 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001696 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001697 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001698 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1699 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001700 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001701 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001702
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001703 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001704 Builder.AddTypedTextChunk("goto");
1705 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1706 Builder.AddPlaceholderChunk("label");
1707 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001708
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001709 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001710 Builder.AddTypedTextChunk("using");
1711 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1712 Builder.AddTextChunk("namespace");
1713 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1714 Builder.AddPlaceholderChunk("identifier");
1715 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001716 }
1717
1718 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001719 case Sema::PCC_ForInit:
1720 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001721 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001722 // Fall through: conditions and statements can have expressions.
1723
Douglas Gregor02688102010-09-14 23:59:36 +00001724 case Sema::PCC_ParenthesizedExpression:
John McCallf85e1932011-06-15 23:02:42 +00001725 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1726 CCC == Sema::PCC_ParenthesizedExpression) {
1727 // (__bridge <type>)<expression>
1728 Builder.AddTypedTextChunk("__bridge");
1729 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1730 Builder.AddPlaceholderChunk("type");
1731 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1732 Builder.AddPlaceholderChunk("expression");
1733 Results.AddResult(Result(Builder.TakeString()));
1734
1735 // (__bridge_transfer <Objective-C type>)<expression>
1736 Builder.AddTypedTextChunk("__bridge_transfer");
1737 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1738 Builder.AddPlaceholderChunk("Objective-C type");
1739 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1740 Builder.AddPlaceholderChunk("expression");
1741 Results.AddResult(Result(Builder.TakeString()));
1742
1743 // (__bridge_retained <CF type>)<expression>
1744 Builder.AddTypedTextChunk("__bridge_retained");
1745 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1746 Builder.AddPlaceholderChunk("CF type");
1747 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1748 Builder.AddPlaceholderChunk("expression");
1749 Results.AddResult(Result(Builder.TakeString()));
1750 }
1751 // Fall through
1752
John McCallf312b1e2010-08-26 23:41:50 +00001753 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001754 if (SemaRef.getLangOptions().CPlusPlus) {
1755 // 'this', if we're in a non-static member function.
Douglas Gregor8ca72082011-10-18 21:20:17 +00001756 QualType ThisTy = SemaRef.getCurrentThisType(false);
1757 if (!ThisTy.isNull()) {
1758 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1759 SemaRef.Context,
1760 Policy,
1761 Allocator));
1762 Builder.AddTypedTextChunk("this");
1763 Results.AddResult(Result(Builder.TakeString()));
1764 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001765
Douglas Gregor8ca72082011-10-18 21:20:17 +00001766 // true
1767 Builder.AddResultTypeChunk("bool");
1768 Builder.AddTypedTextChunk("true");
1769 Results.AddResult(Result(Builder.TakeString()));
1770
1771 // false
1772 Builder.AddResultTypeChunk("bool");
1773 Builder.AddTypedTextChunk("false");
1774 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001775
Douglas Gregorec3310a2011-04-12 02:47:21 +00001776 if (SemaRef.getLangOptions().RTTI) {
1777 // dynamic_cast < type-id > ( expression )
1778 Builder.AddTypedTextChunk("dynamic_cast");
1779 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1780 Builder.AddPlaceholderChunk("type");
1781 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1782 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1783 Builder.AddPlaceholderChunk("expression");
1784 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1785 Results.AddResult(Result(Builder.TakeString()));
1786 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001787
1788 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001789 Builder.AddTypedTextChunk("static_cast");
1790 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1791 Builder.AddPlaceholderChunk("type");
1792 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1793 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1794 Builder.AddPlaceholderChunk("expression");
1795 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1796 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001797
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001798 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001799 Builder.AddTypedTextChunk("reinterpret_cast");
1800 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1801 Builder.AddPlaceholderChunk("type");
1802 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1803 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1804 Builder.AddPlaceholderChunk("expression");
1805 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1806 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001807
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001808 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001809 Builder.AddTypedTextChunk("const_cast");
1810 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1811 Builder.AddPlaceholderChunk("type");
1812 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1813 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1814 Builder.AddPlaceholderChunk("expression");
1815 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1816 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001817
Douglas Gregorec3310a2011-04-12 02:47:21 +00001818 if (SemaRef.getLangOptions().RTTI) {
1819 // typeid ( expression-or-type )
Douglas Gregor8ca72082011-10-18 21:20:17 +00001820 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001821 Builder.AddTypedTextChunk("typeid");
1822 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1823 Builder.AddPlaceholderChunk("expression-or-type");
1824 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1825 Results.AddResult(Result(Builder.TakeString()));
1826 }
1827
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001828 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001829 Builder.AddTypedTextChunk("new");
1830 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1831 Builder.AddPlaceholderChunk("type");
1832 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1833 Builder.AddPlaceholderChunk("expressions");
1834 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1835 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001836
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001837 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001838 Builder.AddTypedTextChunk("new");
1839 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1840 Builder.AddPlaceholderChunk("type");
1841 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1842 Builder.AddPlaceholderChunk("size");
1843 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1844 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1845 Builder.AddPlaceholderChunk("expressions");
1846 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1847 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001848
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001849 // delete expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001850 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001851 Builder.AddTypedTextChunk("delete");
1852 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1853 Builder.AddPlaceholderChunk("expression");
1854 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001855
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001856 // delete [] expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001857 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001858 Builder.AddTypedTextChunk("delete");
1859 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1860 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1861 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1862 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1863 Builder.AddPlaceholderChunk("expression");
1864 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001865
Douglas Gregorec3310a2011-04-12 02:47:21 +00001866 if (SemaRef.getLangOptions().CXXExceptions) {
1867 // throw expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001868 Builder.AddResultTypeChunk("void");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001869 Builder.AddTypedTextChunk("throw");
1870 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1871 Builder.AddPlaceholderChunk("expression");
1872 Results.AddResult(Result(Builder.TakeString()));
1873 }
Douglas Gregora50216c2011-10-18 16:29:03 +00001874
Douglas Gregor12e13132010-05-26 22:00:08 +00001875 // FIXME: Rethrow?
Douglas Gregora50216c2011-10-18 16:29:03 +00001876
1877 if (SemaRef.getLangOptions().CPlusPlus0x) {
1878 // nullptr
Douglas Gregor8ca72082011-10-18 21:20:17 +00001879 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001880 Builder.AddTypedTextChunk("nullptr");
1881 Results.AddResult(Result(Builder.TakeString()));
1882
1883 // alignof
Douglas Gregor8ca72082011-10-18 21:20:17 +00001884 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001885 Builder.AddTypedTextChunk("alignof");
1886 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1887 Builder.AddPlaceholderChunk("type");
1888 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1889 Results.AddResult(Result(Builder.TakeString()));
1890
1891 // noexcept
Douglas Gregor8ca72082011-10-18 21:20:17 +00001892 Builder.AddResultTypeChunk("bool");
Douglas Gregora50216c2011-10-18 16:29:03 +00001893 Builder.AddTypedTextChunk("noexcept");
1894 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1895 Builder.AddPlaceholderChunk("expression");
1896 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1897 Results.AddResult(Result(Builder.TakeString()));
1898
1899 // sizeof... expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001900 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001901 Builder.AddTypedTextChunk("sizeof...");
1902 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1903 Builder.AddPlaceholderChunk("parameter-pack");
1904 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1905 Results.AddResult(Result(Builder.TakeString()));
1906 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001907 }
1908
1909 if (SemaRef.getLangOptions().ObjC1) {
1910 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001911 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1912 // The interface can be NULL.
1913 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregor8ca72082011-10-18 21:20:17 +00001914 if (ID->getSuperClass()) {
1915 std::string SuperType;
1916 SuperType = ID->getSuperClass()->getNameAsString();
1917 if (Method->isInstanceMethod())
1918 SuperType += " *";
1919
1920 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
1921 Builder.AddTypedTextChunk("super");
1922 Results.AddResult(Result(Builder.TakeString()));
1923 }
Ted Kremenek681e2562010-05-31 21:43:10 +00001924 }
1925
Douglas Gregorbca403c2010-01-13 23:51:12 +00001926 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001927 }
1928
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001929 // sizeof expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001930 Builder.AddResultTypeChunk("size_t");
Douglas Gregor218937c2011-02-01 19:23:04 +00001931 Builder.AddTypedTextChunk("sizeof");
1932 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1933 Builder.AddPlaceholderChunk("expression-or-type");
1934 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1935 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001936 break;
1937 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001938
John McCallf312b1e2010-08-26 23:41:50 +00001939 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001940 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001941 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001942 }
1943
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001944 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1945 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001946
John McCallf312b1e2010-08-26 23:41:50 +00001947 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001948 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001949}
1950
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001951/// \brief If the given declaration has an associated type, add it as a result
1952/// type chunk.
1953static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001954 const PrintingPolicy &Policy,
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001955 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001956 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001957 if (!ND)
1958 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001959
1960 // Skip constructors and conversion functions, which have their return types
1961 // built into their names.
1962 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1963 return;
1964
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001965 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001966 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001967 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1968 T = Function->getResultType();
1969 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1970 T = Method->getResultType();
1971 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1972 T = FunTmpl->getTemplatedDecl()->getResultType();
1973 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1974 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1975 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1976 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00001977 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001978 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001979 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001980 T = Property->getType();
1981
1982 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1983 return;
1984
Douglas Gregor8987b232011-09-27 23:30:47 +00001985 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00001986 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001987}
1988
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001989static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001990 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001991 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1992 if (Sentinel->getSentinel() == 0) {
1993 if (Context.getLangOptions().ObjC1 &&
1994 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001995 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001996 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001997 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001998 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001999 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002000 }
2001}
2002
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002003static void appendWithSpace(std::string &Result, StringRef Text) {
2004 if (!Result.empty())
2005 Result += ' ';
2006 Result += Text.str();
2007}
2008static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
2009 std::string Result;
2010 if (ObjCQuals & Decl::OBJC_TQ_In)
2011 appendWithSpace(Result, "in");
2012 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2013 appendWithSpace(Result, "inout");
2014 else if (ObjCQuals & Decl::OBJC_TQ_Out)
2015 appendWithSpace(Result, "out");
2016 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2017 appendWithSpace(Result, "bycopy");
2018 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2019 appendWithSpace(Result, "byref");
2020 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2021 appendWithSpace(Result, "oneway");
2022 return Result;
2023}
2024
Douglas Gregor83482d12010-08-24 16:15:59 +00002025static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002026 const PrintingPolicy &Policy,
Douglas Gregoraba48082010-08-29 19:47:46 +00002027 ParmVarDecl *Param,
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002028 bool SuppressName = false,
2029 bool SuppressBlock = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00002030 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2031 if (Param->getType()->isDependentType() ||
2032 !Param->getType()->isBlockPointerType()) {
2033 // The argument for a dependent or non-block parameter is a placeholder
2034 // containing that parameter's type.
2035 std::string Result;
2036
Douglas Gregoraba48082010-08-29 19:47:46 +00002037 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002038 Result = Param->getIdentifier()->getName();
2039
John McCallf85e1932011-06-15 23:02:42 +00002040 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002041
2042 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002043 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2044 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00002045 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002046 Result += Param->getIdentifier()->getName();
2047 }
2048 return Result;
2049 }
2050
2051 // The argument for a block pointer parameter is a block literal with
2052 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00002053 FunctionTypeLoc *Block = 0;
2054 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00002055 TypeLoc TL;
2056 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2057 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2058 while (true) {
2059 // Look through typedefs.
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002060 if (!SuppressBlock) {
2061 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
2062 if (TypeSourceInfo *InnerTSInfo
2063 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
2064 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2065 continue;
2066 }
2067 }
2068
2069 // Look through qualified types
2070 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2071 TL = QualifiedTL->getUnqualifiedLoc();
Douglas Gregor83482d12010-08-24 16:15:59 +00002072 continue;
2073 }
2074 }
2075
Douglas Gregor83482d12010-08-24 16:15:59 +00002076 // Try to get the function prototype behind the block pointer type,
2077 // then we're done.
2078 if (BlockPointerTypeLoc *BlockPtr
2079 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002080 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002081 Block = dyn_cast<FunctionTypeLoc>(&TL);
2082 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002083 }
2084 break;
2085 }
2086 }
2087
2088 if (!Block) {
2089 // We were unable to find a FunctionProtoTypeLoc with parameter names
2090 // for the block; just use the parameter type as a placeholder.
2091 std::string Result;
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002092 if (!ObjCMethodParam && Param->getIdentifier())
2093 Result = Param->getIdentifier()->getName();
2094
John McCallf85e1932011-06-15 23:02:42 +00002095 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002096
2097 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002098 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2099 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002100 if (Param->getIdentifier())
2101 Result += Param->getIdentifier()->getName();
2102 }
2103
2104 return Result;
2105 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002106
Douglas Gregor83482d12010-08-24 16:15:59 +00002107 // We have the function prototype behind the block pointer type, as it was
2108 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002109 std::string Result;
2110 QualType ResultType = Block->getTypePtr()->getResultType();
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002111 if (!ResultType->isVoidType() || SuppressBlock)
John McCallf85e1932011-06-15 23:02:42 +00002112 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002113
2114 // Format the parameter list.
2115 std::string Params;
Douglas Gregor830072c2011-02-15 22:37:09 +00002116 if (!BlockProto || Block->getNumArgs() == 0) {
2117 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002118 Params = "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002119 else
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002120 Params = "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002121 } else {
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002122 Params += "(";
Douglas Gregor38276252010-09-08 22:47:51 +00002123 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2124 if (I)
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002125 Params += ", ";
2126 Params += FormatFunctionParameter(Context, Policy, Block->getArg(I),
2127 /*SuppressName=*/false,
2128 /*SuppressBlock=*/true);
Douglas Gregor38276252010-09-08 22:47:51 +00002129
Douglas Gregor830072c2011-02-15 22:37:09 +00002130 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002131 Params += ", ...";
Douglas Gregor38276252010-09-08 22:47:51 +00002132 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002133 Params += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002134 }
Douglas Gregor38276252010-09-08 22:47:51 +00002135
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002136 if (SuppressBlock) {
2137 // Format as a parameter.
2138 Result = Result + " (^";
2139 if (Param->getIdentifier())
2140 Result += Param->getIdentifier()->getName();
2141 Result += ")";
2142 Result += Params;
2143 } else {
2144 // Format as a block literal argument.
2145 Result = '^' + Result;
2146 Result += Params;
2147
2148 if (Param->getIdentifier())
2149 Result += Param->getIdentifier()->getName();
2150 }
2151
Douglas Gregor83482d12010-08-24 16:15:59 +00002152 return Result;
2153}
2154
Douglas Gregor86d9a522009-09-21 16:56:56 +00002155/// \brief Add function parameter chunks to the given code completion string.
2156static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002157 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002158 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002159 CodeCompletionBuilder &Result,
2160 unsigned Start = 0,
2161 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002162 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002163 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002164
Douglas Gregor218937c2011-02-01 19:23:04 +00002165 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002166 ParmVarDecl *Param = Function->getParamDecl(P);
2167
Douglas Gregor218937c2011-02-01 19:23:04 +00002168 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002169 // When we see an optional default argument, put that argument and
2170 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002171 CodeCompletionBuilder Opt(Result.getAllocator());
2172 if (!FirstParameter)
2173 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002174 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregor218937c2011-02-01 19:23:04 +00002175 Result.AddOptionalChunk(Opt.TakeString());
2176 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002177 }
2178
Douglas Gregor218937c2011-02-01 19:23:04 +00002179 if (FirstParameter)
2180 FirstParameter = false;
2181 else
2182 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2183
2184 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002185
2186 // Format the placeholder string.
Douglas Gregor8987b232011-09-27 23:30:47 +00002187 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2188 Param);
Douglas Gregor83482d12010-08-24 16:15:59 +00002189
Douglas Gregore17794f2010-08-31 05:13:43 +00002190 if (Function->isVariadic() && P == N - 1)
2191 PlaceholderStr += ", ...";
2192
Douglas Gregor86d9a522009-09-21 16:56:56 +00002193 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002194 Result.AddPlaceholderChunk(
2195 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002196 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002197
2198 if (const FunctionProtoType *Proto
2199 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002200 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002201 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002202 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002203
Douglas Gregor218937c2011-02-01 19:23:04 +00002204 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002205 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002206}
2207
2208/// \brief Add template parameter chunks to the given code completion string.
2209static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002210 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002211 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002212 CodeCompletionBuilder &Result,
2213 unsigned MaxParameters = 0,
2214 unsigned Start = 0,
2215 bool InDefaultArg = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002216 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002217 bool FirstParameter = true;
2218
2219 TemplateParameterList *Params = Template->getTemplateParameters();
2220 TemplateParameterList::iterator PEnd = Params->end();
2221 if (MaxParameters)
2222 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002223 for (TemplateParameterList::iterator P = Params->begin() + Start;
2224 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002225 bool HasDefaultArg = false;
2226 std::string PlaceholderStr;
2227 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2228 if (TTP->wasDeclaredWithTypename())
2229 PlaceholderStr = "typename";
2230 else
2231 PlaceholderStr = "class";
2232
2233 if (TTP->getIdentifier()) {
2234 PlaceholderStr += ' ';
2235 PlaceholderStr += TTP->getIdentifier()->getName();
2236 }
2237
2238 HasDefaultArg = TTP->hasDefaultArgument();
2239 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002240 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002241 if (NTTP->getIdentifier())
2242 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002243 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002244 HasDefaultArg = NTTP->hasDefaultArgument();
2245 } else {
2246 assert(isa<TemplateTemplateParmDecl>(*P));
2247 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2248
2249 // Since putting the template argument list into the placeholder would
2250 // be very, very long, we just use an abbreviation.
2251 PlaceholderStr = "template<...> class";
2252 if (TTP->getIdentifier()) {
2253 PlaceholderStr += ' ';
2254 PlaceholderStr += TTP->getIdentifier()->getName();
2255 }
2256
2257 HasDefaultArg = TTP->hasDefaultArgument();
2258 }
2259
Douglas Gregor218937c2011-02-01 19:23:04 +00002260 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002261 // When we see an optional default argument, put that argument and
2262 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002263 CodeCompletionBuilder Opt(Result.getAllocator());
2264 if (!FirstParameter)
2265 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002266 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregor218937c2011-02-01 19:23:04 +00002267 P - Params->begin(), true);
2268 Result.AddOptionalChunk(Opt.TakeString());
2269 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002270 }
2271
Douglas Gregor218937c2011-02-01 19:23:04 +00002272 InDefaultArg = false;
2273
Douglas Gregor86d9a522009-09-21 16:56:56 +00002274 if (FirstParameter)
2275 FirstParameter = false;
2276 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002277 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002278
2279 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002280 Result.AddPlaceholderChunk(
2281 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002282 }
2283}
2284
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002285/// \brief Add a qualifier to the given code-completion string, if the
2286/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002287static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002288AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002289 NestedNameSpecifier *Qualifier,
2290 bool QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002291 ASTContext &Context,
2292 const PrintingPolicy &Policy) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002293 if (!Qualifier)
2294 return;
2295
2296 std::string PrintedNNS;
2297 {
2298 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor8987b232011-09-27 23:30:47 +00002299 Qualifier->print(OS, Policy);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002300 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002301 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002302 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002303 else
Douglas Gregordae68752011-02-01 22:57:45 +00002304 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002305}
2306
Douglas Gregor218937c2011-02-01 19:23:04 +00002307static void
2308AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2309 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002310 const FunctionProtoType *Proto
2311 = Function->getType()->getAs<FunctionProtoType>();
2312 if (!Proto || !Proto->getTypeQuals())
2313 return;
2314
Douglas Gregora63f6de2011-02-01 21:15:40 +00002315 // FIXME: Add ref-qualifier!
2316
2317 // Handle single qualifiers without copying
2318 if (Proto->getTypeQuals() == Qualifiers::Const) {
2319 Result.AddInformativeChunk(" const");
2320 return;
2321 }
2322
2323 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2324 Result.AddInformativeChunk(" volatile");
2325 return;
2326 }
2327
2328 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2329 Result.AddInformativeChunk(" restrict");
2330 return;
2331 }
2332
2333 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002334 std::string QualsStr;
2335 if (Proto->getTypeQuals() & Qualifiers::Const)
2336 QualsStr += " const";
2337 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2338 QualsStr += " volatile";
2339 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2340 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002341 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002342}
2343
Douglas Gregor6f942b22010-09-21 16:06:22 +00002344/// \brief Add the name of the given declaration
Douglas Gregor8987b232011-09-27 23:30:47 +00002345static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2346 NamedDecl *ND, CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002347 typedef CodeCompletionString::Chunk Chunk;
2348
2349 DeclarationName Name = ND->getDeclName();
2350 if (!Name)
2351 return;
2352
2353 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002354 case DeclarationName::CXXOperatorName: {
2355 const char *OperatorName = 0;
2356 switch (Name.getCXXOverloadedOperator()) {
2357 case OO_None:
2358 case OO_Conditional:
2359 case NUM_OVERLOADED_OPERATORS:
2360 OperatorName = "operator";
2361 break;
2362
2363#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2364 case OO_##Name: OperatorName = "operator" Spelling; break;
2365#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2366#include "clang/Basic/OperatorKinds.def"
2367
2368 case OO_New: OperatorName = "operator new"; break;
2369 case OO_Delete: OperatorName = "operator delete"; break;
2370 case OO_Array_New: OperatorName = "operator new[]"; break;
2371 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2372 case OO_Call: OperatorName = "operator()"; break;
2373 case OO_Subscript: OperatorName = "operator[]"; break;
2374 }
2375 Result.AddTypedTextChunk(OperatorName);
2376 break;
2377 }
2378
Douglas Gregor6f942b22010-09-21 16:06:22 +00002379 case DeclarationName::Identifier:
2380 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002381 case DeclarationName::CXXDestructorName:
2382 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002383 Result.AddTypedTextChunk(
2384 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002385 break;
2386
2387 case DeclarationName::CXXUsingDirective:
2388 case DeclarationName::ObjCZeroArgSelector:
2389 case DeclarationName::ObjCOneArgSelector:
2390 case DeclarationName::ObjCMultiArgSelector:
2391 break;
2392
2393 case DeclarationName::CXXConstructorName: {
2394 CXXRecordDecl *Record = 0;
2395 QualType Ty = Name.getCXXNameType();
2396 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2397 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2398 else if (const InjectedClassNameType *InjectedTy
2399 = Ty->getAs<InjectedClassNameType>())
2400 Record = InjectedTy->getDecl();
2401 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002402 Result.AddTypedTextChunk(
2403 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002404 break;
2405 }
2406
Douglas Gregordae68752011-02-01 22:57:45 +00002407 Result.AddTypedTextChunk(
2408 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002409 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002410 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002411 AddTemplateParameterChunks(Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002412 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002413 }
2414 break;
2415 }
2416 }
2417}
2418
Douglas Gregor86d9a522009-09-21 16:56:56 +00002419/// \brief If possible, create a new code completion string for the given
2420/// result.
2421///
2422/// \returns Either a new, heap-allocated code completion string describing
2423/// how to use this result, or NULL to indicate that the string or name of the
2424/// result is all that is needed.
2425CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002426CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002427 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002428 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002429 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002430
Douglas Gregor8987b232011-09-27 23:30:47 +00002431 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregor218937c2011-02-01 19:23:04 +00002432 if (Kind == RK_Pattern) {
2433 Pattern->Priority = Priority;
2434 Pattern->Availability = Availability;
2435 return Pattern;
2436 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002437
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002438 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002439 Result.AddTypedTextChunk(Keyword);
2440 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002441 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002442
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002443 if (Kind == RK_Macro) {
2444 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002445 assert(MI && "Not a macro?");
2446
Douglas Gregordae68752011-02-01 22:57:45 +00002447 Result.AddTypedTextChunk(
2448 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002449
2450 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002451 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002452
2453 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002454 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregore4244702011-07-30 08:17:44 +00002455 bool CombineVariadicArgument = false;
2456 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2457 if (MI->isVariadic() && AEnd - A > 1) {
2458 AEnd -= 2;
2459 CombineVariadicArgument = true;
2460 }
2461 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002462 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002463 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002464
Douglas Gregore4244702011-07-30 08:17:44 +00002465 if (!MI->isVariadic() || A + 1 != AEnd) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002466 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002467 Result.AddPlaceholderChunk(
2468 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002469 continue;
2470 }
2471
Douglas Gregore4244702011-07-30 08:17:44 +00002472 // Variadic argument; cope with the difference between GNU and C99
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002473 // variadic macros, providing a single placeholder for the rest of the
2474 // arguments.
2475 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002476 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002477 else {
2478 std::string Arg = (*A)->getName();
2479 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002480 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002481 }
2482 }
Douglas Gregore4244702011-07-30 08:17:44 +00002483
2484 if (CombineVariadicArgument) {
2485 // Handle the next-to-last argument, combining it with the variadic
2486 // argument.
2487 std::string LastArg = (*A)->getName();
2488 ++A;
2489 if ((*A)->isStr("__VA_ARGS__"))
2490 LastArg += ", ...";
2491 else
2492 LastArg += ", " + (*A)->getName().str() + "...";
2493 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(LastArg));
2494 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002495 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2496 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002497 }
2498
Douglas Gregord8e8a582010-05-25 21:41:55 +00002499 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002500 NamedDecl *ND = Declaration;
2501
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002502 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002503 Result.AddTypedTextChunk(
2504 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002505 Result.AddTextChunk("::");
2506 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002507 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00002508
2509 for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2510 if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2511 Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2512 }
2513 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002514
Douglas Gregor8987b232011-09-27 23:30:47 +00002515 AddResultTypeChunk(S.Context, Policy, ND, Result);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002516
Douglas Gregor86d9a522009-09-21 16:56:56 +00002517 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002518 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002519 S.Context, Policy);
2520 AddTypedNameChunk(S.Context, Policy, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002521 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002522 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002523 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002524 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002525 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002526 }
2527
2528 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002529 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002530 S.Context, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002531 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor8987b232011-09-27 23:30:47 +00002532 AddTypedNameChunk(S.Context, Policy, Function, Result);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002533
Douglas Gregor86d9a522009-09-21 16:56:56 +00002534 // Figure out which template parameters are deduced (or have default
2535 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002536 SmallVector<bool, 16> Deduced;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002537 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2538 unsigned LastDeducibleArgument;
2539 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2540 --LastDeducibleArgument) {
2541 if (!Deduced[LastDeducibleArgument - 1]) {
2542 // C++0x: Figure out if the template argument has a default. If so,
2543 // the user doesn't need to type this argument.
2544 // FIXME: We need to abstract template parameters better!
2545 bool HasDefaultArg = false;
2546 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002547 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002548 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2549 HasDefaultArg = TTP->hasDefaultArgument();
2550 else if (NonTypeTemplateParmDecl *NTTP
2551 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2552 HasDefaultArg = NTTP->hasDefaultArgument();
2553 else {
2554 assert(isa<TemplateTemplateParmDecl>(Param));
2555 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002556 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002557 }
2558
2559 if (!HasDefaultArg)
2560 break;
2561 }
2562 }
2563
2564 if (LastDeducibleArgument) {
2565 // Some of the function template arguments cannot be deduced from a
2566 // function call, so we introduce an explicit template argument list
2567 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002568 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002569 AddTemplateParameterChunks(S.Context, Policy, FunTmpl, Result,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002570 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002571 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002572 }
2573
2574 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002575 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002576 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002577 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002578 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002579 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002580 }
2581
2582 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002583 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002584 S.Context, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002585 Result.AddTypedTextChunk(
2586 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002587 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002588 AddTemplateParameterChunks(S.Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002589 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2590 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002591 }
2592
Douglas Gregor9630eb62009-11-17 16:44:22 +00002593 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002594 Selector Sel = Method->getSelector();
2595 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002596 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002597 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002598 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002599 }
2600
Douglas Gregor813d8342011-02-18 22:29:55 +00002601 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002602 SelName += ':';
2603 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002604 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002605 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002606 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002607
2608 // If there is only one parameter, and we're past it, add an empty
2609 // typed-text chunk since there is nothing to type.
2610 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002611 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002612 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002613 unsigned Idx = 0;
2614 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2615 PEnd = Method->param_end();
2616 P != PEnd; (void)++P, ++Idx) {
2617 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002618 std::string Keyword;
2619 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002620 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002621 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002622 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002623 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002624 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002625 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002626 else
Douglas Gregordae68752011-02-01 22:57:45 +00002627 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002628 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002629
2630 // If we're before the starting parameter, skip the placeholder.
2631 if (Idx < StartParameter)
2632 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002633
2634 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002635
2636 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregor8987b232011-09-27 23:30:47 +00002637 Arg = FormatFunctionParameter(S.Context, Policy, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002638 else {
John McCallf85e1932011-06-15 23:02:42 +00002639 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002640 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2641 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002642 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002643 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002644 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002645 }
2646
Douglas Gregore17794f2010-08-31 05:13:43 +00002647 if (Method->isVariadic() && (P + 1) == PEnd)
2648 Arg += ", ...";
2649
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002650 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002651 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002652 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002653 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002654 else
Douglas Gregordae68752011-02-01 22:57:45 +00002655 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002656 }
2657
Douglas Gregor2a17af02009-12-23 00:21:46 +00002658 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002659 if (Method->param_size() == 0) {
2660 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002661 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002662 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002663 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002664 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002665 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002666 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002667
2668 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002669 }
2670
Douglas Gregor218937c2011-02-01 19:23:04 +00002671 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002672 }
2673
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002674 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002675 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002676 S.Context, Policy);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002677
Douglas Gregordae68752011-02-01 22:57:45 +00002678 Result.AddTypedTextChunk(
2679 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002680 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002681}
2682
Douglas Gregor86d802e2009-09-23 00:34:09 +00002683CodeCompletionString *
2684CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2685 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002686 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002687 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002688 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor8987b232011-09-27 23:30:47 +00002689 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCallf85e1932011-06-15 23:02:42 +00002690
Douglas Gregor218937c2011-02-01 19:23:04 +00002691 // FIXME: Set priority, availability appropriately.
2692 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002693 FunctionDecl *FDecl = getFunction();
Douglas Gregor8987b232011-09-27 23:30:47 +00002694 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002695 const FunctionProtoType *Proto
2696 = dyn_cast<FunctionProtoType>(getFunctionType());
2697 if (!FDecl && !Proto) {
2698 // Function without a prototype. Just give the return type and a
2699 // highlighted ellipsis.
2700 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002701 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
Douglas Gregor8987b232011-09-27 23:30:47 +00002702 S.Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002703 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002704 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2705 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2706 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2707 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002708 }
2709
2710 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002711 Result.AddTextChunk(
2712 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002713 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002714 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002715 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002716 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002717
Douglas Gregor218937c2011-02-01 19:23:04 +00002718 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002719 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2720 for (unsigned I = 0; I != NumParams; ++I) {
2721 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002722 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002723
2724 std::string ArgString;
2725 QualType ArgType;
2726
2727 if (FDecl) {
2728 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2729 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2730 } else {
2731 ArgType = Proto->getArgType(I);
2732 }
2733
John McCallf85e1932011-06-15 23:02:42 +00002734 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002735
2736 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002737 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002738 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002739 else
Douglas Gregordae68752011-02-01 22:57:45 +00002740 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002741 }
2742
2743 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002744 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002745 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002746 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002747 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002748 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002749 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002750 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002751
Douglas Gregor218937c2011-02-01 19:23:04 +00002752 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002753}
2754
Chris Lattner5f9e2722011-07-23 10:55:15 +00002755unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002756 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002757 bool PreferredTypeIsPointer) {
2758 unsigned Priority = CCP_Macro;
2759
Douglas Gregorb05496d2010-09-20 21:11:48 +00002760 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2761 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2762 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002763 Priority = CCP_Constant;
2764 if (PreferredTypeIsPointer)
2765 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002766 }
2767 // Treat "YES", "NO", "true", and "false" as constants.
2768 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2769 MacroName.equals("true") || MacroName.equals("false"))
2770 Priority = CCP_Constant;
2771 // Treat "bool" as a type.
2772 else if (MacroName.equals("bool"))
2773 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2774
Douglas Gregor1827e102010-08-16 16:18:59 +00002775
2776 return Priority;
2777}
2778
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002779CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2780 if (!D)
2781 return CXCursor_UnexposedDecl;
2782
2783 switch (D->getKind()) {
2784 case Decl::Enum: return CXCursor_EnumDecl;
2785 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2786 case Decl::Field: return CXCursor_FieldDecl;
2787 case Decl::Function:
2788 return CXCursor_FunctionDecl;
2789 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2790 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2791 case Decl::ObjCClass:
2792 // FIXME
2793 return CXCursor_UnexposedDecl;
2794 case Decl::ObjCForwardProtocol:
2795 // FIXME
2796 return CXCursor_UnexposedDecl;
2797 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2798 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2799 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2800 case Decl::ObjCMethod:
2801 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2802 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2803 case Decl::CXXMethod: return CXCursor_CXXMethod;
2804 case Decl::CXXConstructor: return CXCursor_Constructor;
2805 case Decl::CXXDestructor: return CXCursor_Destructor;
2806 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2807 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2808 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2809 case Decl::ParmVar: return CXCursor_ParmDecl;
2810 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002811 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002812 case Decl::Var: return CXCursor_VarDecl;
2813 case Decl::Namespace: return CXCursor_Namespace;
2814 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2815 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2816 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2817 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2818 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2819 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00002820 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002821 case Decl::ClassTemplatePartialSpecialization:
2822 return CXCursor_ClassTemplatePartialSpecialization;
2823 case Decl::UsingDirective: return CXCursor_UsingDirective;
2824
2825 case Decl::Using:
2826 case Decl::UnresolvedUsingValue:
2827 case Decl::UnresolvedUsingTypename:
2828 return CXCursor_UsingDeclaration;
2829
Douglas Gregor352697a2011-06-03 23:08:58 +00002830 case Decl::ObjCPropertyImpl:
2831 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2832 case ObjCPropertyImplDecl::Dynamic:
2833 return CXCursor_ObjCDynamicDecl;
2834
2835 case ObjCPropertyImplDecl::Synthesize:
2836 return CXCursor_ObjCSynthesizeDecl;
2837 }
2838 break;
2839
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002840 default:
2841 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2842 switch (TD->getTagKind()) {
2843 case TTK_Struct: return CXCursor_StructDecl;
2844 case TTK_Class: return CXCursor_ClassDecl;
2845 case TTK_Union: return CXCursor_UnionDecl;
2846 case TTK_Enum: return CXCursor_EnumDecl;
2847 }
2848 }
2849 }
2850
2851 return CXCursor_UnexposedDecl;
2852}
2853
Douglas Gregor590c7d52010-07-08 20:55:51 +00002854static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2855 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002856 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002857
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002858 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002859
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002860 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2861 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002862 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002863 Results.AddResult(Result(M->first,
2864 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002865 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002866 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002867 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002868
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002869 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002870
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002871}
2872
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002873static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2874 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002875 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002876
2877 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002878
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002879 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2880 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2881 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2882 Results.AddResult(Result("__func__", CCP_Constant));
2883 Results.ExitScope();
2884}
2885
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002886static void HandleCodeCompleteResults(Sema *S,
2887 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002888 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002889 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002890 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002891 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002892 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002893}
2894
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002895static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2896 Sema::ParserCompletionContext PCC) {
2897 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002898 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002899 return CodeCompletionContext::CCC_TopLevel;
2900
John McCallf312b1e2010-08-26 23:41:50 +00002901 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002902 return CodeCompletionContext::CCC_ClassStructUnion;
2903
John McCallf312b1e2010-08-26 23:41:50 +00002904 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002905 return CodeCompletionContext::CCC_ObjCInterface;
2906
John McCallf312b1e2010-08-26 23:41:50 +00002907 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002908 return CodeCompletionContext::CCC_ObjCImplementation;
2909
John McCallf312b1e2010-08-26 23:41:50 +00002910 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002911 return CodeCompletionContext::CCC_ObjCIvarList;
2912
John McCallf312b1e2010-08-26 23:41:50 +00002913 case Sema::PCC_Template:
2914 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002915 if (S.CurContext->isFileContext())
2916 return CodeCompletionContext::CCC_TopLevel;
2917 else if (S.CurContext->isRecord())
2918 return CodeCompletionContext::CCC_ClassStructUnion;
2919 else
2920 return CodeCompletionContext::CCC_Other;
2921
John McCallf312b1e2010-08-26 23:41:50 +00002922 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002923 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002924
John McCallf312b1e2010-08-26 23:41:50 +00002925 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002926 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2927 S.getLangOptions().ObjC1)
2928 return CodeCompletionContext::CCC_ParenthesizedExpression;
2929 else
2930 return CodeCompletionContext::CCC_Expression;
2931
2932 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002933 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002934 return CodeCompletionContext::CCC_Expression;
2935
John McCallf312b1e2010-08-26 23:41:50 +00002936 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002937 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002938
John McCallf312b1e2010-08-26 23:41:50 +00002939 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002940 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002941
2942 case Sema::PCC_ParenthesizedExpression:
2943 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002944
2945 case Sema::PCC_LocalDeclarationSpecifiers:
2946 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002947 }
2948
2949 return CodeCompletionContext::CCC_Other;
2950}
2951
Douglas Gregorf6961522010-08-27 21:18:54 +00002952/// \brief If we're in a C++ virtual member function, add completion results
2953/// that invoke the functions we override, since it's common to invoke the
2954/// overridden function as well as adding new functionality.
2955///
2956/// \param S The semantic analysis object for which we are generating results.
2957///
2958/// \param InContext This context in which the nested-name-specifier preceding
2959/// the code-completion point
2960static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2961 ResultBuilder &Results) {
2962 // Look through blocks.
2963 DeclContext *CurContext = S.CurContext;
2964 while (isa<BlockDecl>(CurContext))
2965 CurContext = CurContext->getParent();
2966
2967
2968 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2969 if (!Method || !Method->isVirtual())
2970 return;
2971
2972 // We need to have names for all of the parameters, if we're going to
2973 // generate a forwarding call.
2974 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2975 PEnd = Method->param_end();
2976 P != PEnd;
2977 ++P) {
2978 if (!(*P)->getDeclName())
2979 return;
2980 }
2981
Douglas Gregor8987b232011-09-27 23:30:47 +00002982 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorf6961522010-08-27 21:18:54 +00002983 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2984 MEnd = Method->end_overridden_methods();
2985 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002986 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002987 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2988 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2989 continue;
2990
2991 // If we need a nested-name-specifier, add one now.
2992 if (!InContext) {
2993 NestedNameSpecifier *NNS
2994 = getRequiredQualification(S.Context, CurContext,
2995 Overridden->getDeclContext());
2996 if (NNS) {
2997 std::string Str;
2998 llvm::raw_string_ostream OS(Str);
Douglas Gregor8987b232011-09-27 23:30:47 +00002999 NNS->print(OS, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00003000 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003001 }
3002 } else if (!InContext->Equals(Overridden->getDeclContext()))
3003 continue;
3004
Douglas Gregordae68752011-02-01 22:57:45 +00003005 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003006 Overridden->getNameAsString()));
3007 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00003008 bool FirstParam = true;
3009 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3010 PEnd = Method->param_end();
3011 P != PEnd; ++P) {
3012 if (FirstParam)
3013 FirstParam = false;
3014 else
Douglas Gregor218937c2011-02-01 19:23:04 +00003015 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00003016
Douglas Gregordae68752011-02-01 22:57:45 +00003017 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003018 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003019 }
Douglas Gregor218937c2011-02-01 19:23:04 +00003020 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3021 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00003022 CCP_SuperCompletion,
3023 CXCursor_CXXMethod));
3024 Results.Ignore(Overridden);
3025 }
3026}
3027
Douglas Gregor01dfea02010-01-10 23:08:15 +00003028void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003029 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00003030 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003031 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003032 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00003033 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003034
Douglas Gregor01dfea02010-01-10 23:08:15 +00003035 // Determine how to filter results, e.g., so that the names of
3036 // values (functions, enumerators, function templates, etc.) are
3037 // only allowed where we can have an expression.
3038 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003039 case PCC_Namespace:
3040 case PCC_Class:
3041 case PCC_ObjCInterface:
3042 case PCC_ObjCImplementation:
3043 case PCC_ObjCInstanceVariableList:
3044 case PCC_Template:
3045 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00003046 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003047 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00003048 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3049 break;
3050
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003051 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00003052 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00003053 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003054 case PCC_ForInit:
3055 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00003056 if (WantTypesInContext(CompletionContext, getLangOptions()))
3057 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3058 else
3059 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00003060
3061 if (getLangOptions().CPlusPlus)
3062 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00003063 break;
Douglas Gregordc845342010-05-25 05:58:43 +00003064
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003065 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00003066 // Unfiltered
3067 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00003068 }
3069
Douglas Gregor3cdee122010-08-26 16:36:48 +00003070 // If we are in a C++ non-static member function, check the qualifiers on
3071 // the member function to filter/prioritize the results list.
3072 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3073 if (CurMethod->isInstance())
3074 Results.setObjectTypeQualifiers(
3075 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3076
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00003077 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003078 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3079 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003080
Douglas Gregorbca403c2010-01-13 23:51:12 +00003081 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003082 Results.ExitScope();
3083
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003084 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00003085 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00003086 case PCC_Expression:
3087 case PCC_Statement:
3088 case PCC_RecoveryInFunction:
3089 if (S->getFnParent())
3090 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3091 break;
3092
3093 case PCC_Namespace:
3094 case PCC_Class:
3095 case PCC_ObjCInterface:
3096 case PCC_ObjCImplementation:
3097 case PCC_ObjCInstanceVariableList:
3098 case PCC_Template:
3099 case PCC_MemberTemplate:
3100 case PCC_ForInit:
3101 case PCC_Condition:
3102 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003103 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003104 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003105 }
3106
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003107 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003108 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003109
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003110 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003111 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003112}
3113
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003114static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3115 ParsedType Receiver,
3116 IdentifierInfo **SelIdents,
3117 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003118 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003119 bool IsSuper,
3120 ResultBuilder &Results);
3121
3122void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3123 bool AllowNonIdentifiers,
3124 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003125 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003126 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003127 AllowNestedNameSpecifiers
3128 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3129 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003130 Results.EnterNewScope();
3131
3132 // Type qualifiers can come after names.
3133 Results.AddResult(Result("const"));
3134 Results.AddResult(Result("volatile"));
3135 if (getLangOptions().C99)
3136 Results.AddResult(Result("restrict"));
3137
3138 if (getLangOptions().CPlusPlus) {
3139 if (AllowNonIdentifiers) {
3140 Results.AddResult(Result("operator"));
3141 }
3142
3143 // Add nested-name-specifiers.
3144 if (AllowNestedNameSpecifiers) {
3145 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003146 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003147 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3148 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3149 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003150 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003151 }
3152 }
3153 Results.ExitScope();
3154
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003155 // If we're in a context where we might have an expression (rather than a
3156 // declaration), and what we've seen so far is an Objective-C type that could
3157 // be a receiver of a class message, this may be a class message send with
3158 // the initial opening bracket '[' missing. Add appropriate completions.
3159 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3160 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3161 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3162 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3163 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3164 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3165 DS.getTypeQualifiers() == 0 &&
3166 S &&
3167 (S->getFlags() & Scope::DeclScope) != 0 &&
3168 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3169 Scope::FunctionPrototypeScope |
3170 Scope::AtCatchScope)) == 0) {
3171 ParsedType T = DS.getRepAsType();
3172 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003173 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003174 }
3175
Douglas Gregor4497dd42010-08-24 04:59:56 +00003176 // Note that we intentionally suppress macro results here, since we do not
3177 // encourage using macros to produce the names of entities.
3178
Douglas Gregor52779fb2010-09-23 23:01:17 +00003179 HandleCodeCompleteResults(this, CodeCompleter,
3180 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003181 Results.data(), Results.size());
3182}
3183
Douglas Gregorfb629412010-08-23 21:17:50 +00003184struct Sema::CodeCompleteExpressionData {
3185 CodeCompleteExpressionData(QualType PreferredType = QualType())
3186 : PreferredType(PreferredType), IntegralConstantExpression(false),
3187 ObjCCollection(false) { }
3188
3189 QualType PreferredType;
3190 bool IntegralConstantExpression;
3191 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003192 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003193};
3194
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003195/// \brief Perform code-completion in an expression context when we know what
3196/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003197///
3198/// \param IntegralConstantExpression Only permit integral constant
3199/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003200void Sema::CodeCompleteExpression(Scope *S,
3201 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003202 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003203 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3204 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003205 if (Data.ObjCCollection)
3206 Results.setFilter(&ResultBuilder::IsObjCCollection);
3207 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003208 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003209 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003210 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3211 else
3212 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003213
3214 if (!Data.PreferredType.isNull())
3215 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3216
3217 // Ignore any declarations that we were told that we don't care about.
3218 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3219 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003220
3221 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003222 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3223 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003224
3225 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003226 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003227 Results.ExitScope();
3228
Douglas Gregor590c7d52010-07-08 20:55:51 +00003229 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003230 if (!Data.PreferredType.isNull())
3231 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3232 || Data.PreferredType->isMemberPointerType()
3233 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003234
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003235 if (S->getFnParent() &&
3236 !Data.ObjCCollection &&
3237 !Data.IntegralConstantExpression)
3238 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3239
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003240 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003241 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003242 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003243 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3244 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003245 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003246}
3247
Douglas Gregorac5fd842010-09-18 01:28:11 +00003248void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3249 if (E.isInvalid())
3250 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3251 else if (getLangOptions().ObjC1)
3252 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003253}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003254
Douglas Gregor73449212010-12-09 23:01:55 +00003255/// \brief The set of properties that have already been added, referenced by
3256/// property name.
3257typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3258
Douglas Gregor95ac6552009-11-18 01:29:26 +00003259static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003260 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003261 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003262 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003263 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003264 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003265 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003266
3267 // Add properties in this container.
3268 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3269 PEnd = Container->prop_end();
3270 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003271 ++P) {
3272 if (AddedProperties.insert(P->getIdentifier()))
3273 Results.MaybeAddResult(Result(*P, 0), CurContext);
3274 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003275
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003276 // Add nullary methods
3277 if (AllowNullaryMethods) {
3278 ASTContext &Context = Container->getASTContext();
Douglas Gregor8987b232011-09-27 23:30:47 +00003279 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003280 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3281 MEnd = Container->meth_end();
3282 M != MEnd; ++M) {
3283 if (M->getSelector().isUnarySelector())
3284 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3285 if (AddedProperties.insert(Name)) {
3286 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor8987b232011-09-27 23:30:47 +00003287 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003288 Builder.AddTypedTextChunk(
3289 Results.getAllocator().CopyString(Name->getName()));
3290
3291 CXAvailabilityKind Availability = CXAvailability_Available;
3292 switch (M->getAvailability()) {
3293 case AR_Available:
3294 case AR_NotYetIntroduced:
3295 Availability = CXAvailability_Available;
3296 break;
3297
3298 case AR_Deprecated:
3299 Availability = CXAvailability_Deprecated;
3300 break;
3301
3302 case AR_Unavailable:
3303 Availability = CXAvailability_NotAvailable;
3304 break;
3305 }
3306
3307 Results.MaybeAddResult(Result(Builder.TakeString(),
3308 CCP_MemberDeclaration + CCD_MethodAsProperty,
3309 M->isInstanceMethod()
3310 ? CXCursor_ObjCInstanceMethodDecl
3311 : CXCursor_ObjCClassMethodDecl,
3312 Availability),
3313 CurContext);
3314 }
3315 }
3316 }
3317
3318
Douglas Gregor95ac6552009-11-18 01:29:26 +00003319 // Add properties in referenced protocols.
3320 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3321 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3322 PEnd = Protocol->protocol_end();
3323 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003324 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3325 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003326 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003327 if (AllowCategories) {
3328 // Look through categories.
3329 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3330 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003331 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3332 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003333 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003334
3335 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003336 for (ObjCInterfaceDecl::all_protocol_iterator
3337 I = IFace->all_referenced_protocol_begin(),
3338 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003339 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3340 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003341
3342 // Look in the superclass.
3343 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003344 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3345 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003346 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003347 } else if (const ObjCCategoryDecl *Category
3348 = dyn_cast<ObjCCategoryDecl>(Container)) {
3349 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003350 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3351 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003352 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003353 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3354 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003355 }
3356}
3357
Richard Trieuf81e5a92011-09-09 02:00:50 +00003358void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *BaseE,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003359 SourceLocation OpLoc,
3360 bool IsArrow) {
3361 if (!BaseE || !CodeCompleter)
3362 return;
3363
John McCall0a2c5e22010-08-25 06:19:51 +00003364 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003365
Douglas Gregor81b747b2009-09-17 21:32:03 +00003366 Expr *Base = static_cast<Expr *>(BaseE);
3367 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003368
3369 if (IsArrow) {
3370 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3371 BaseType = Ptr->getPointeeType();
3372 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003373 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003374 else
3375 return;
3376 }
3377
Douglas Gregor3da626b2011-07-07 16:03:39 +00003378 enum CodeCompletionContext::Kind contextKind;
3379
3380 if (IsArrow) {
3381 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3382 }
3383 else {
3384 if (BaseType->isObjCObjectPointerType() ||
3385 BaseType->isObjCObjectOrInterfaceType()) {
3386 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3387 }
3388 else {
3389 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3390 }
3391 }
3392
Douglas Gregor218937c2011-02-01 19:23:04 +00003393 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003394 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003395 BaseType),
3396 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003397 Results.EnterNewScope();
3398 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003399 // Indicate that we are performing a member access, and the cv-qualifiers
3400 // for the base object type.
3401 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3402
Douglas Gregor95ac6552009-11-18 01:29:26 +00003403 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003404 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003405 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003406 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3407 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003408
Douglas Gregor95ac6552009-11-18 01:29:26 +00003409 if (getLangOptions().CPlusPlus) {
3410 if (!Results.empty()) {
3411 // The "template" keyword can follow "->" or "." in the grammar.
3412 // However, we only want to suggest the template keyword if something
3413 // is dependent.
3414 bool IsDependent = BaseType->isDependentType();
3415 if (!IsDependent) {
3416 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3417 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3418 IsDependent = Ctx->isDependentContext();
3419 break;
3420 }
3421 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003422
Douglas Gregor95ac6552009-11-18 01:29:26 +00003423 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003424 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003425 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003426 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003427 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3428 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003429 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003430
3431 // Add property results based on our interface.
3432 const ObjCObjectPointerType *ObjCPtr
3433 = BaseType->getAsObjCInterfacePointerType();
3434 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003435 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3436 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003437 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003438
3439 // Add properties from the protocols in a qualified interface.
3440 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3441 E = ObjCPtr->qual_end();
3442 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003443 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3444 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003445 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003446 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003447 // Objective-C instance variable access.
3448 ObjCInterfaceDecl *Class = 0;
3449 if (const ObjCObjectPointerType *ObjCPtr
3450 = BaseType->getAs<ObjCObjectPointerType>())
3451 Class = ObjCPtr->getInterfaceDecl();
3452 else
John McCallc12c5bb2010-05-15 11:32:37 +00003453 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003454
3455 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003456 if (Class) {
3457 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3458 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003459 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3460 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003461 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003462 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003463
3464 // FIXME: How do we cope with isa?
3465
3466 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003467
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003468 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003469 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003470 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003471 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003472}
3473
Douglas Gregor374929f2009-09-18 15:37:17 +00003474void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3475 if (!CodeCompleter)
3476 return;
3477
John McCall0a2c5e22010-08-25 06:19:51 +00003478 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003479 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003480 enum CodeCompletionContext::Kind ContextKind
3481 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003482 switch ((DeclSpec::TST)TagSpec) {
3483 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003484 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003485 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003486 break;
3487
3488 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003489 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003490 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003491 break;
3492
3493 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003494 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003495 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003496 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003497 break;
3498
3499 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003500 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003501 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003502
Douglas Gregor218937c2011-02-01 19:23:04 +00003503 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003504 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003505
3506 // First pass: look for tags.
3507 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003508 LookupVisibleDecls(S, LookupTagName, Consumer,
3509 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003510
Douglas Gregor8071e422010-08-15 06:18:01 +00003511 if (CodeCompleter->includeGlobals()) {
3512 // Second pass: look for nested name specifiers.
3513 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3514 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3515 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003516
Douglas Gregor52779fb2010-09-23 23:01:17 +00003517 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003518 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003519}
3520
Douglas Gregor1a480c42010-08-27 17:35:51 +00003521void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003522 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3523 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003524 Results.EnterNewScope();
3525 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3526 Results.AddResult("const");
3527 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3528 Results.AddResult("volatile");
3529 if (getLangOptions().C99 &&
3530 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3531 Results.AddResult("restrict");
3532 Results.ExitScope();
3533 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003534 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003535 Results.data(), Results.size());
3536}
3537
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003538void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003539 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003540 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003541
John McCall781472f2010-08-25 08:40:02 +00003542 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003543 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3544 if (!type->isEnumeralType()) {
3545 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003546 Data.IntegralConstantExpression = true;
3547 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003548 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003549 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003550
3551 // Code-complete the cases of a switch statement over an enumeration type
3552 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003553 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003554
3555 // Determine which enumerators we have already seen in the switch statement.
3556 // FIXME: Ideally, we would also be able to look *past* the code-completion
3557 // token, in case we are code-completing in the middle of the switch and not
3558 // at the end. However, we aren't able to do so at the moment.
3559 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003560 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003561 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3562 SC = SC->getNextSwitchCase()) {
3563 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3564 if (!Case)
3565 continue;
3566
3567 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3568 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3569 if (EnumConstantDecl *Enumerator
3570 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3571 // We look into the AST of the case statement to determine which
3572 // enumerator was named. Alternatively, we could compute the value of
3573 // the integral constant expression, then compare it against the
3574 // values of each enumerator. However, value-based approach would not
3575 // work as well with C++ templates where enumerators declared within a
3576 // template are type- and value-dependent.
3577 EnumeratorsSeen.insert(Enumerator);
3578
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003579 // If this is a qualified-id, keep track of the nested-name-specifier
3580 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003581 //
3582 // switch (TagD.getKind()) {
3583 // case TagDecl::TK_enum:
3584 // break;
3585 // case XXX
3586 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003587 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003588 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3589 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003590 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003591 }
3592 }
3593
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003594 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3595 // If there are no prior enumerators in C++, check whether we have to
3596 // qualify the names of the enumerators that we suggest, because they
3597 // may not be visible in this scope.
3598 Qualifier = getRequiredQualification(Context, CurContext,
3599 Enum->getDeclContext());
3600
3601 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3602 }
3603
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003604 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003605 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3606 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003607 Results.EnterNewScope();
3608 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3609 EEnd = Enum->enumerator_end();
3610 E != EEnd; ++E) {
3611 if (EnumeratorsSeen.count(*E))
3612 continue;
3613
Douglas Gregor5c722c702011-02-18 23:30:37 +00003614 CodeCompletionResult R(*E, Qualifier);
3615 R.Priority = CCP_EnumInCase;
3616 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003617 }
3618 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003619
Douglas Gregor3da626b2011-07-07 16:03:39 +00003620 //We need to make sure we're setting the right context,
3621 //so only say we include macros if the code completer says we do
3622 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3623 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003624 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003625 kind = CodeCompletionContext::CCC_OtherWithMacros;
3626 }
3627
3628
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003629 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003630 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003631 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003632}
3633
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003634namespace {
3635 struct IsBetterOverloadCandidate {
3636 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003637 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003638
3639 public:
John McCall5769d612010-02-08 23:07:23 +00003640 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3641 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003642
3643 bool
3644 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003645 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003646 }
3647 };
3648}
3649
Douglas Gregord28dcd72010-05-30 06:10:08 +00003650static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3651 if (NumArgs && !Args)
3652 return true;
3653
3654 for (unsigned I = 0; I != NumArgs; ++I)
3655 if (!Args[I])
3656 return true;
3657
3658 return false;
3659}
3660
Richard Trieuf81e5a92011-09-09 02:00:50 +00003661void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3662 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003663 if (!CodeCompleter)
3664 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003665
3666 // When we're code-completing for a call, we fall back to ordinary
3667 // name code-completion whenever we can't produce specific
3668 // results. We may want to revisit this strategy in the future,
3669 // e.g., by merging the two kinds of results.
3670
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003671 Expr *Fn = (Expr *)FnIn;
3672 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003673
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003674 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003675 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003676 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003677 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003678 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003679 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003680
John McCall3b4294e2009-12-16 12:17:52 +00003681 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003682 SourceLocation Loc = Fn->getExprLoc();
3683 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003684
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003685 // FIXME: What if we're calling something that isn't a function declaration?
3686 // FIXME: What if we're calling a pseudo-destructor?
3687 // FIXME: What if we're calling a member function?
3688
Douglas Gregorc0265402010-01-21 15:46:19 +00003689 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003690 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003691
John McCall3b4294e2009-12-16 12:17:52 +00003692 Expr *NakedFn = Fn->IgnoreParenCasts();
3693 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3694 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3695 /*PartialOverloading=*/ true);
3696 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3697 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003698 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003699 if (!getLangOptions().CPlusPlus ||
3700 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003701 Results.push_back(ResultCandidate(FDecl));
3702 else
John McCall86820f52010-01-26 01:37:31 +00003703 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003704 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3705 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003706 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003707 }
John McCall3b4294e2009-12-16 12:17:52 +00003708 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003709
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003710 QualType ParamType;
3711
Douglas Gregorc0265402010-01-21 15:46:19 +00003712 if (!CandidateSet.empty()) {
3713 // Sort the overload candidate set by placing the best overloads first.
3714 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003715 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003716
Douglas Gregorc0265402010-01-21 15:46:19 +00003717 // Add the remaining viable overload candidates as code-completion reslults.
3718 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3719 CandEnd = CandidateSet.end();
3720 Cand != CandEnd; ++Cand) {
3721 if (Cand->Viable)
3722 Results.push_back(ResultCandidate(Cand->Function));
3723 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003724
3725 // From the viable candidates, try to determine the type of this parameter.
3726 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3727 if (const FunctionType *FType = Results[I].getFunctionType())
3728 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3729 if (NumArgs < Proto->getNumArgs()) {
3730 if (ParamType.isNull())
3731 ParamType = Proto->getArgType(NumArgs);
3732 else if (!Context.hasSameUnqualifiedType(
3733 ParamType.getNonReferenceType(),
3734 Proto->getArgType(NumArgs).getNonReferenceType())) {
3735 ParamType = QualType();
3736 break;
3737 }
3738 }
3739 }
3740 } else {
3741 // Try to determine the parameter type from the type of the expression
3742 // being called.
3743 QualType FunctionType = Fn->getType();
3744 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3745 FunctionType = Ptr->getPointeeType();
3746 else if (const BlockPointerType *BlockPtr
3747 = FunctionType->getAs<BlockPointerType>())
3748 FunctionType = BlockPtr->getPointeeType();
3749 else if (const MemberPointerType *MemPtr
3750 = FunctionType->getAs<MemberPointerType>())
3751 FunctionType = MemPtr->getPointeeType();
3752
3753 if (const FunctionProtoType *Proto
3754 = FunctionType->getAs<FunctionProtoType>()) {
3755 if (NumArgs < Proto->getNumArgs())
3756 ParamType = Proto->getArgType(NumArgs);
3757 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003758 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003759
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003760 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003761 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003762 else
3763 CodeCompleteExpression(S, ParamType);
3764
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003765 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003766 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3767 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003768}
3769
John McCalld226f652010-08-21 09:40:31 +00003770void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3771 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003772 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003773 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003774 return;
3775 }
3776
3777 CodeCompleteExpression(S, VD->getType());
3778}
3779
3780void Sema::CodeCompleteReturn(Scope *S) {
3781 QualType ResultType;
3782 if (isa<BlockDecl>(CurContext)) {
3783 if (BlockScopeInfo *BSI = getCurBlock())
3784 ResultType = BSI->ReturnType;
3785 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3786 ResultType = Function->getResultType();
3787 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3788 ResultType = Method->getResultType();
3789
3790 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003791 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003792 else
3793 CodeCompleteExpression(S, ResultType);
3794}
3795
Douglas Gregord2d8be62011-07-30 08:36:53 +00003796void Sema::CodeCompleteAfterIf(Scope *S) {
3797 typedef CodeCompletionResult Result;
3798 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3799 mapCodeCompletionContext(*this, PCC_Statement));
3800 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3801 Results.EnterNewScope();
3802
3803 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3804 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3805 CodeCompleter->includeGlobals());
3806
3807 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3808
3809 // "else" block
3810 CodeCompletionBuilder Builder(Results.getAllocator());
3811 Builder.AddTypedTextChunk("else");
3812 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3813 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3814 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3815 Builder.AddPlaceholderChunk("statements");
3816 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3817 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3818 Results.AddResult(Builder.TakeString());
3819
3820 // "else if" block
3821 Builder.AddTypedTextChunk("else");
3822 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3823 Builder.AddTextChunk("if");
3824 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3825 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3826 if (getLangOptions().CPlusPlus)
3827 Builder.AddPlaceholderChunk("condition");
3828 else
3829 Builder.AddPlaceholderChunk("expression");
3830 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3831 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3832 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3833 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3834 Builder.AddPlaceholderChunk("statements");
3835 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3836 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3837 Results.AddResult(Builder.TakeString());
3838
3839 Results.ExitScope();
3840
3841 if (S->getFnParent())
3842 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3843
3844 if (CodeCompleter->includeMacros())
3845 AddMacroResults(PP, Results);
3846
3847 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3848 Results.data(),Results.size());
3849}
3850
Richard Trieuf81e5a92011-09-09 02:00:50 +00003851void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003852 if (LHS)
3853 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3854 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003855 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003856}
3857
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003858void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003859 bool EnteringContext) {
3860 if (!SS.getScopeRep() || !CodeCompleter)
3861 return;
3862
Douglas Gregor86d9a522009-09-21 16:56:56 +00003863 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3864 if (!Ctx)
3865 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003866
3867 // Try to instantiate any non-dependent declaration contexts before
3868 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003869 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003870 return;
3871
Douglas Gregor218937c2011-02-01 19:23:04 +00003872 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3873 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003874 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003875
Douglas Gregor86d9a522009-09-21 16:56:56 +00003876 // The "template" keyword can follow "::" in the grammar, but only
3877 // put it into the grammar if the nested-name-specifier is dependent.
3878 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3879 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003880 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003881
3882 // Add calls to overridden virtual functions, if there are any.
3883 //
3884 // FIXME: This isn't wonderful, because we don't know whether we're actually
3885 // in a context that permits expressions. This is a general issue with
3886 // qualified-id completions.
3887 if (!EnteringContext)
3888 MaybeAddOverrideCalls(*this, Ctx, Results);
3889 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003890
Douglas Gregorf6961522010-08-27 21:18:54 +00003891 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3892 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3893
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003894 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003895 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003896 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003897}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003898
3899void Sema::CodeCompleteUsing(Scope *S) {
3900 if (!CodeCompleter)
3901 return;
3902
Douglas Gregor218937c2011-02-01 19:23:04 +00003903 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003904 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3905 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003906 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003907
3908 // If we aren't in class scope, we could see the "namespace" keyword.
3909 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003910 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003911
3912 // After "using", we can see anything that would start a
3913 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003914 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003915 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3916 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003917 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003918
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003919 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003920 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003921 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003922}
3923
3924void Sema::CodeCompleteUsingDirective(Scope *S) {
3925 if (!CodeCompleter)
3926 return;
3927
Douglas Gregor86d9a522009-09-21 16:56:56 +00003928 // After "using namespace", we expect to see a namespace name or namespace
3929 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003930 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3931 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003932 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003933 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003934 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003935 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3936 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003937 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003938 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003939 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003940 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003941}
3942
3943void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3944 if (!CodeCompleter)
3945 return;
3946
Douglas Gregor86d9a522009-09-21 16:56:56 +00003947 DeclContext *Ctx = (DeclContext *)S->getEntity();
3948 if (!S->getParent())
3949 Ctx = Context.getTranslationUnitDecl();
3950
Douglas Gregor52779fb2010-09-23 23:01:17 +00003951 bool SuppressedGlobalResults
3952 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3953
Douglas Gregor218937c2011-02-01 19:23:04 +00003954 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003955 SuppressedGlobalResults
3956 ? CodeCompletionContext::CCC_Namespace
3957 : CodeCompletionContext::CCC_Other,
3958 &ResultBuilder::IsNamespace);
3959
3960 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003961 // We only want to see those namespaces that have already been defined
3962 // within this scope, because its likely that the user is creating an
3963 // extended namespace declaration. Keep track of the most recent
3964 // definition of each namespace.
3965 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3966 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3967 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3968 NS != NSEnd; ++NS)
3969 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3970
3971 // Add the most recent definition (or extended definition) of each
3972 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003973 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003974 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3975 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3976 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003977 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003978 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003979 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003980 }
3981
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003982 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003983 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003984 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003985}
3986
3987void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3988 if (!CodeCompleter)
3989 return;
3990
Douglas Gregor86d9a522009-09-21 16:56:56 +00003991 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003992 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3993 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003994 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003995 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003996 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3997 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003998 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003999 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004000 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004001}
4002
Douglas Gregored8d3222009-09-18 20:05:18 +00004003void Sema::CodeCompleteOperatorName(Scope *S) {
4004 if (!CodeCompleter)
4005 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00004006
John McCall0a2c5e22010-08-25 06:19:51 +00004007 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004008 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4009 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004010 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004011 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00004012
Douglas Gregor86d9a522009-09-21 16:56:56 +00004013 // Add the names of overloadable operators.
4014#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4015 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00004016 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00004017#include "clang/Basic/OperatorKinds.def"
4018
4019 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00004020 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004021 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004022 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4023 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00004024
4025 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00004026 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004027 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004028
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004029 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00004030 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004031 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00004032}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004033
Douglas Gregor0133f522010-08-28 00:00:50 +00004034void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00004035 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00004036 unsigned NumInitializers) {
Douglas Gregor8987b232011-09-27 23:30:47 +00004037 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor0133f522010-08-28 00:00:50 +00004038 CXXConstructorDecl *Constructor
4039 = static_cast<CXXConstructorDecl *>(ConstructorD);
4040 if (!Constructor)
4041 return;
4042
Douglas Gregor218937c2011-02-01 19:23:04 +00004043 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004044 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00004045 Results.EnterNewScope();
4046
4047 // Fill in any already-initialized fields or base classes.
4048 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4049 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4050 for (unsigned I = 0; I != NumInitializers; ++I) {
4051 if (Initializers[I]->isBaseInitializer())
4052 InitializedBases.insert(
4053 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4054 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00004055 InitializedFields.insert(cast<FieldDecl>(
4056 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00004057 }
4058
4059 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00004060 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00004061 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00004062 CXXRecordDecl *ClassDecl = Constructor->getParent();
4063 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4064 BaseEnd = ClassDecl->bases_end();
4065 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004066 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4067 SawLastInitializer
4068 = NumInitializers > 0 &&
4069 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4070 Context.hasSameUnqualifiedType(Base->getType(),
4071 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004072 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004073 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004074
Douglas Gregor218937c2011-02-01 19:23:04 +00004075 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004076 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004077 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004078 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4079 Builder.AddPlaceholderChunk("args");
4080 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4081 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004082 SawLastInitializer? CCP_NextInitializer
4083 : CCP_MemberDeclaration));
4084 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004085 }
4086
4087 // Add completions for virtual base classes.
4088 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4089 BaseEnd = ClassDecl->vbases_end();
4090 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004091 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4092 SawLastInitializer
4093 = NumInitializers > 0 &&
4094 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4095 Context.hasSameUnqualifiedType(Base->getType(),
4096 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004097 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004098 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004099
Douglas Gregor218937c2011-02-01 19:23:04 +00004100 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004101 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004102 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004103 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4104 Builder.AddPlaceholderChunk("args");
4105 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4106 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004107 SawLastInitializer? CCP_NextInitializer
4108 : CCP_MemberDeclaration));
4109 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004110 }
4111
4112 // Add completions for members.
4113 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4114 FieldEnd = ClassDecl->field_end();
4115 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004116 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4117 SawLastInitializer
4118 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004119 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4120 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004121 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004122 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004123
4124 if (!Field->getDeclName())
4125 continue;
4126
Douglas Gregordae68752011-02-01 22:57:45 +00004127 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004128 Field->getIdentifier()->getName()));
4129 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4130 Builder.AddPlaceholderChunk("args");
4131 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4132 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004133 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004134 : CCP_MemberDeclaration,
4135 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004136 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004137 }
4138 Results.ExitScope();
4139
Douglas Gregor52779fb2010-09-23 23:01:17 +00004140 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004141 Results.data(), Results.size());
4142}
4143
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004144// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4145// true or false.
4146#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004147static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004148 ResultBuilder &Results,
4149 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004150 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004151 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004152 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004153
Douglas Gregor218937c2011-02-01 19:23:04 +00004154 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004155 if (LangOpts.ObjC2) {
4156 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004157 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4158 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4159 Builder.AddPlaceholderChunk("property");
4160 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004161
4162 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004163 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4164 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4165 Builder.AddPlaceholderChunk("property");
4166 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004167 }
4168}
4169
Douglas Gregorbca403c2010-01-13 23:51:12 +00004170static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004171 ResultBuilder &Results,
4172 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004173 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004174
4175 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004176 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004177
4178 if (LangOpts.ObjC2) {
4179 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004180 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004181
4182 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004183 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004184
4185 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004186 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004187 }
4188}
4189
Douglas Gregorbca403c2010-01-13 23:51:12 +00004190static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004191 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004192 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004193
4194 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004195 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4196 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4197 Builder.AddPlaceholderChunk("name");
4198 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004199
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004200 if (Results.includeCodePatterns()) {
4201 // @interface name
4202 // FIXME: Could introduce the whole pattern, including superclasses and
4203 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004204 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4205 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4206 Builder.AddPlaceholderChunk("class");
4207 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004208
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004209 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004210 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4211 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4212 Builder.AddPlaceholderChunk("protocol");
4213 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004214
4215 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004216 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4217 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4218 Builder.AddPlaceholderChunk("class");
4219 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004220 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004221
4222 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004223 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4224 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4225 Builder.AddPlaceholderChunk("alias");
4226 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4227 Builder.AddPlaceholderChunk("class");
4228 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004229}
4230
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004231void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004232 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004233 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4234 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004235 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004236 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorbca403c2010-01-13 23:51:12 +00004237 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004238 else if (CurContext->isObjCContainer())
Douglas Gregorbca403c2010-01-13 23:51:12 +00004239 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004240 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004241 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004242 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004243 HandleCodeCompleteResults(this, CodeCompleter,
4244 CodeCompletionContext::CCC_Other,
4245 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004246}
4247
Douglas Gregorbca403c2010-01-13 23:51:12 +00004248static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004249 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004250 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004251
4252 // @encode ( type-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004253 const char *EncodeType = "char[]";
4254 if (Results.getSema().getLangOptions().CPlusPlus ||
4255 Results.getSema().getLangOptions().ConstStrings)
4256 EncodeType = " const char[]";
4257 Builder.AddResultTypeChunk(EncodeType);
Douglas Gregor218937c2011-02-01 19:23:04 +00004258 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4259 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4260 Builder.AddPlaceholderChunk("type-name");
4261 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4262 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004263
4264 // @protocol ( protocol-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004265 Builder.AddResultTypeChunk("Protocol *");
Douglas Gregor218937c2011-02-01 19:23:04 +00004266 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4267 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4268 Builder.AddPlaceholderChunk("protocol-name");
4269 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4270 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004271
4272 // @selector ( selector )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004273 Builder.AddResultTypeChunk("SEL");
Douglas Gregor218937c2011-02-01 19:23:04 +00004274 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4275 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4276 Builder.AddPlaceholderChunk("selector");
4277 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4278 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004279}
4280
Douglas Gregorbca403c2010-01-13 23:51:12 +00004281static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004282 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004283 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004284
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004285 if (Results.includeCodePatterns()) {
4286 // @try { statements } @catch ( declaration ) { statements } @finally
4287 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004288 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4289 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4290 Builder.AddPlaceholderChunk("statements");
4291 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4292 Builder.AddTextChunk("@catch");
4293 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4294 Builder.AddPlaceholderChunk("parameter");
4295 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4296 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4297 Builder.AddPlaceholderChunk("statements");
4298 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4299 Builder.AddTextChunk("@finally");
4300 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4301 Builder.AddPlaceholderChunk("statements");
4302 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4303 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004304 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004305
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004306 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004307 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4308 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4309 Builder.AddPlaceholderChunk("expression");
4310 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004311
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004312 if (Results.includeCodePatterns()) {
4313 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004314 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4315 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4316 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4317 Builder.AddPlaceholderChunk("expression");
4318 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4319 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4320 Builder.AddPlaceholderChunk("statements");
4321 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4322 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004323 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004324}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004325
Douglas Gregorbca403c2010-01-13 23:51:12 +00004326static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004327 ResultBuilder &Results,
4328 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004329 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004330 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4331 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4332 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004333 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004334 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004335}
4336
4337void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004338 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4339 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004340 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004341 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004342 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004343 HandleCodeCompleteResults(this, CodeCompleter,
4344 CodeCompletionContext::CCC_Other,
4345 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004346}
4347
4348void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004349 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4350 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004351 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004352 AddObjCStatementResults(Results, false);
4353 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004354 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004355 HandleCodeCompleteResults(this, CodeCompleter,
4356 CodeCompletionContext::CCC_Other,
4357 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004358}
4359
4360void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004361 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4362 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004363 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004364 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004365 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004366 HandleCodeCompleteResults(this, CodeCompleter,
4367 CodeCompletionContext::CCC_Other,
4368 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004369}
4370
Douglas Gregor988358f2009-11-19 00:14:45 +00004371/// \brief Determine whether the addition of the given flag to an Objective-C
4372/// property's attributes will cause a conflict.
4373static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4374 // Check if we've already added this flag.
4375 if (Attributes & NewFlag)
4376 return true;
4377
4378 Attributes |= NewFlag;
4379
4380 // Check for collisions with "readonly".
4381 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4382 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4383 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004384 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004385 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004386 ObjCDeclSpec::DQ_PR_retain |
4387 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004388 return true;
4389
John McCallf85e1932011-06-15 23:02:42 +00004390 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004391 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004392 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004393 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004394 ObjCDeclSpec::DQ_PR_retain|
4395 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004396 if (AssignCopyRetMask &&
4397 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004398 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004399 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004400 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4401 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004402 return true;
4403
4404 return false;
4405}
4406
Douglas Gregora93b1082009-11-18 23:08:07 +00004407void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004408 if (!CodeCompleter)
4409 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004410
Steve Naroffece8e712009-10-08 21:55:05 +00004411 unsigned Attributes = ODS.getPropertyAttributes();
4412
John McCall0a2c5e22010-08-25 06:19:51 +00004413 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004414 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4415 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004416 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004417 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004418 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004419 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004420 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004421 if (!ObjCPropertyFlagConflicts(Attributes,
4422 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4423 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004424 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004425 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004426 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004427 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004428 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4429 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004430 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004431 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004432 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004433 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004434 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4435 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004436 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004437 CodeCompletionBuilder Setter(Results.getAllocator());
4438 Setter.AddTypedTextChunk("setter");
4439 Setter.AddTextChunk(" = ");
4440 Setter.AddPlaceholderChunk("method");
4441 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004442 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004443 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004444 CodeCompletionBuilder Getter(Results.getAllocator());
4445 Getter.AddTypedTextChunk("getter");
4446 Getter.AddTextChunk(" = ");
4447 Getter.AddPlaceholderChunk("method");
4448 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004449 }
Steve Naroffece8e712009-10-08 21:55:05 +00004450 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004451 HandleCodeCompleteResults(this, CodeCompleter,
4452 CodeCompletionContext::CCC_Other,
4453 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004454}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004455
Douglas Gregor4ad96852009-11-19 07:41:15 +00004456/// \brief Descripts the kind of Objective-C method that we want to find
4457/// via code completion.
4458enum ObjCMethodKind {
4459 MK_Any, //< Any kind of method, provided it means other specified criteria.
4460 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4461 MK_OneArgSelector //< One-argument selector.
4462};
4463
Douglas Gregor458433d2010-08-26 15:07:07 +00004464static bool isAcceptableObjCSelector(Selector Sel,
4465 ObjCMethodKind WantKind,
4466 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004467 unsigned NumSelIdents,
4468 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004469 if (NumSelIdents > Sel.getNumArgs())
4470 return false;
4471
4472 switch (WantKind) {
4473 case MK_Any: break;
4474 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4475 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4476 }
4477
Douglas Gregorcf544262010-11-17 21:36:08 +00004478 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4479 return false;
4480
Douglas Gregor458433d2010-08-26 15:07:07 +00004481 for (unsigned I = 0; I != NumSelIdents; ++I)
4482 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4483 return false;
4484
4485 return true;
4486}
4487
Douglas Gregor4ad96852009-11-19 07:41:15 +00004488static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4489 ObjCMethodKind WantKind,
4490 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004491 unsigned NumSelIdents,
4492 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004493 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004494 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004495}
Douglas Gregord36adf52010-09-16 16:06:31 +00004496
4497namespace {
4498 /// \brief A set of selectors, which is used to avoid introducing multiple
4499 /// completions with the same selector into the result set.
4500 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4501}
4502
Douglas Gregor36ecb042009-11-17 23:22:23 +00004503/// \brief Add all of the Objective-C methods in the given Objective-C
4504/// container to the set of results.
4505///
4506/// The container will be a class, protocol, category, or implementation of
4507/// any of the above. This mether will recurse to include methods from
4508/// the superclasses of classes along with their categories, protocols, and
4509/// implementations.
4510///
4511/// \param Container the container in which we'll look to find methods.
4512///
4513/// \param WantInstance whether to add instance methods (only); if false, this
4514/// routine will add factory methods (only).
4515///
4516/// \param CurContext the context in which we're performing the lookup that
4517/// finds methods.
4518///
Douglas Gregorcf544262010-11-17 21:36:08 +00004519/// \param AllowSameLength Whether we allow a method to be added to the list
4520/// when it has the same number of parameters as we have selector identifiers.
4521///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004522/// \param Results the structure into which we'll add results.
4523static void AddObjCMethods(ObjCContainerDecl *Container,
4524 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004525 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004526 IdentifierInfo **SelIdents,
4527 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004528 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004529 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004530 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004531 ResultBuilder &Results,
4532 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004533 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004534 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4535 MEnd = Container->meth_end();
4536 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004537 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4538 // Check whether the selector identifiers we've been given are a
4539 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004540 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4541 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004542 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004543
Douglas Gregord36adf52010-09-16 16:06:31 +00004544 if (!Selectors.insert((*M)->getSelector()))
4545 continue;
4546
Douglas Gregord3c68542009-11-19 01:08:35 +00004547 Result R = Result(*M, 0);
4548 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004549 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004550 if (!InOriginalClass)
4551 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004552 Results.MaybeAddResult(R, CurContext);
4553 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004554 }
4555
Douglas Gregore396c7b2010-09-16 15:34:59 +00004556 // Visit the protocols of protocols.
4557 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4558 const ObjCList<ObjCProtocolDecl> &Protocols
4559 = Protocol->getReferencedProtocols();
4560 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4561 E = Protocols.end();
4562 I != E; ++I)
4563 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004564 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004565 }
4566
Douglas Gregor36ecb042009-11-17 23:22:23 +00004567 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4568 if (!IFace)
4569 return;
4570
4571 // Add methods in protocols.
4572 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4573 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4574 E = Protocols.end();
4575 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004576 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004577 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004578
4579 // Add methods in categories.
4580 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4581 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004582 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004583 NumSelIdents, CurContext, Selectors, AllowSameLength,
4584 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004585
4586 // Add a categories protocol methods.
4587 const ObjCList<ObjCProtocolDecl> &Protocols
4588 = CatDecl->getReferencedProtocols();
4589 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4590 E = Protocols.end();
4591 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004592 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004593 NumSelIdents, CurContext, Selectors, AllowSameLength,
4594 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004595
4596 // Add methods in category implementations.
4597 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004598 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004599 NumSelIdents, CurContext, Selectors, AllowSameLength,
4600 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004601 }
4602
4603 // Add methods in superclass.
4604 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004605 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004606 SelIdents, NumSelIdents, CurContext, Selectors,
4607 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004608
4609 // Add methods in our implementation, if any.
4610 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004611 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004612 NumSelIdents, CurContext, Selectors, AllowSameLength,
4613 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004614}
4615
4616
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004617void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004618 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004619
4620 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004621 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004622 if (!Class) {
4623 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004624 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004625 Class = Category->getClassInterface();
4626
4627 if (!Class)
4628 return;
4629 }
4630
4631 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004632 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4633 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004634 Results.EnterNewScope();
4635
Douglas Gregord36adf52010-09-16 16:06:31 +00004636 VisitedSelectorSet Selectors;
4637 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004638 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004639 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004640 HandleCodeCompleteResults(this, CodeCompleter,
4641 CodeCompletionContext::CCC_Other,
4642 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004643}
4644
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004645void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004646 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004647
4648 // Try to find the interface where setters might live.
4649 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004650 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004651 if (!Class) {
4652 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004653 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004654 Class = Category->getClassInterface();
4655
4656 if (!Class)
4657 return;
4658 }
4659
4660 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004661 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4662 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004663 Results.EnterNewScope();
4664
Douglas Gregord36adf52010-09-16 16:06:31 +00004665 VisitedSelectorSet Selectors;
4666 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004667 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004668
4669 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004670 HandleCodeCompleteResults(this, CodeCompleter,
4671 CodeCompletionContext::CCC_Other,
4672 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004673}
4674
Douglas Gregorafc45782011-02-15 22:19:42 +00004675void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4676 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004677 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004678 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4679 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004680 Results.EnterNewScope();
4681
4682 // Add context-sensitive, Objective-C parameter-passing keywords.
4683 bool AddedInOut = false;
4684 if ((DS.getObjCDeclQualifier() &
4685 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4686 Results.AddResult("in");
4687 Results.AddResult("inout");
4688 AddedInOut = true;
4689 }
4690 if ((DS.getObjCDeclQualifier() &
4691 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4692 Results.AddResult("out");
4693 if (!AddedInOut)
4694 Results.AddResult("inout");
4695 }
4696 if ((DS.getObjCDeclQualifier() &
4697 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4698 ObjCDeclSpec::DQ_Oneway)) == 0) {
4699 Results.AddResult("bycopy");
4700 Results.AddResult("byref");
4701 Results.AddResult("oneway");
4702 }
4703
Douglas Gregorafc45782011-02-15 22:19:42 +00004704 // If we're completing the return type of an Objective-C method and the
4705 // identifier IBAction refers to a macro, provide a completion item for
4706 // an action, e.g.,
4707 // IBAction)<#selector#>:(id)sender
4708 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4709 Context.Idents.get("IBAction").hasMacroDefinition()) {
4710 typedef CodeCompletionString::Chunk Chunk;
4711 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4712 CXAvailability_Available);
4713 Builder.AddTypedTextChunk("IBAction");
4714 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4715 Builder.AddPlaceholderChunk("selector");
4716 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4717 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4718 Builder.AddTextChunk("id");
4719 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4720 Builder.AddTextChunk("sender");
4721 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4722 }
4723
Douglas Gregord32b0222010-08-24 01:06:58 +00004724 // Add various builtin type names and specifiers.
4725 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4726 Results.ExitScope();
4727
4728 // Add the various type names
4729 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4730 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4731 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4732 CodeCompleter->includeGlobals());
4733
4734 if (CodeCompleter->includeMacros())
4735 AddMacroResults(PP, Results);
4736
4737 HandleCodeCompleteResults(this, CodeCompleter,
4738 CodeCompletionContext::CCC_Type,
4739 Results.data(), Results.size());
4740}
4741
Douglas Gregor22f56992010-04-06 19:22:33 +00004742/// \brief When we have an expression with type "id", we may assume
4743/// that it has some more-specific class type based on knowledge of
4744/// common uses of Objective-C. This routine returns that class type,
4745/// or NULL if no better result could be determined.
4746static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004747 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004748 if (!Msg)
4749 return 0;
4750
4751 Selector Sel = Msg->getSelector();
4752 if (Sel.isNull())
4753 return 0;
4754
4755 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4756 if (!Id)
4757 return 0;
4758
4759 ObjCMethodDecl *Method = Msg->getMethodDecl();
4760 if (!Method)
4761 return 0;
4762
4763 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004764 ObjCInterfaceDecl *IFace = 0;
4765 switch (Msg->getReceiverKind()) {
4766 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004767 if (const ObjCObjectType *ObjType
4768 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4769 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004770 break;
4771
4772 case ObjCMessageExpr::Instance: {
4773 QualType T = Msg->getInstanceReceiver()->getType();
4774 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4775 IFace = Ptr->getInterfaceDecl();
4776 break;
4777 }
4778
4779 case ObjCMessageExpr::SuperInstance:
4780 case ObjCMessageExpr::SuperClass:
4781 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004782 }
4783
4784 if (!IFace)
4785 return 0;
4786
4787 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4788 if (Method->isInstanceMethod())
4789 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4790 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004791 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004792 .Case("autorelease", IFace)
4793 .Case("copy", IFace)
4794 .Case("copyWithZone", IFace)
4795 .Case("mutableCopy", IFace)
4796 .Case("mutableCopyWithZone", IFace)
4797 .Case("awakeFromCoder", IFace)
4798 .Case("replacementObjectFromCoder", IFace)
4799 .Case("class", IFace)
4800 .Case("classForCoder", IFace)
4801 .Case("superclass", Super)
4802 .Default(0);
4803
4804 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4805 .Case("new", IFace)
4806 .Case("alloc", IFace)
4807 .Case("allocWithZone", IFace)
4808 .Case("class", IFace)
4809 .Case("superclass", Super)
4810 .Default(0);
4811}
4812
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004813// Add a special completion for a message send to "super", which fills in the
4814// most likely case of forwarding all of our arguments to the superclass
4815// function.
4816///
4817/// \param S The semantic analysis object.
4818///
4819/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4820/// the "super" keyword. Otherwise, we just need to provide the arguments.
4821///
4822/// \param SelIdents The identifiers in the selector that have already been
4823/// provided as arguments for a send to "super".
4824///
4825/// \param NumSelIdents The number of identifiers in \p SelIdents.
4826///
4827/// \param Results The set of results to augment.
4828///
4829/// \returns the Objective-C method declaration that would be invoked by
4830/// this "super" completion. If NULL, no completion was added.
4831static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4832 IdentifierInfo **SelIdents,
4833 unsigned NumSelIdents,
4834 ResultBuilder &Results) {
4835 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4836 if (!CurMethod)
4837 return 0;
4838
4839 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4840 if (!Class)
4841 return 0;
4842
4843 // Try to find a superclass method with the same selector.
4844 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004845 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4846 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004847 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4848 CurMethod->isInstanceMethod());
4849
Douglas Gregor78bcd912011-02-16 00:51:18 +00004850 // Check in categories or class extensions.
4851 if (!SuperMethod) {
4852 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4853 Category = Category->getNextClassCategory())
4854 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4855 CurMethod->isInstanceMethod())))
4856 break;
4857 }
4858 }
4859
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004860 if (!SuperMethod)
4861 return 0;
4862
4863 // Check whether the superclass method has the same signature.
4864 if (CurMethod->param_size() != SuperMethod->param_size() ||
4865 CurMethod->isVariadic() != SuperMethod->isVariadic())
4866 return 0;
4867
4868 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4869 CurPEnd = CurMethod->param_end(),
4870 SuperP = SuperMethod->param_begin();
4871 CurP != CurPEnd; ++CurP, ++SuperP) {
4872 // Make sure the parameter types are compatible.
4873 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4874 (*SuperP)->getType()))
4875 return 0;
4876
4877 // Make sure we have a parameter name to forward!
4878 if (!(*CurP)->getIdentifier())
4879 return 0;
4880 }
4881
4882 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004883 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004884
4885 // Give this completion a return type.
Douglas Gregor8987b232011-09-27 23:30:47 +00004886 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
4887 Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004888
4889 // If we need the "super" keyword, add it (plus some spacing).
4890 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004891 Builder.AddTypedTextChunk("super");
4892 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004893 }
4894
4895 Selector Sel = CurMethod->getSelector();
4896 if (Sel.isUnarySelector()) {
4897 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004898 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004899 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004900 else
Douglas Gregordae68752011-02-01 22:57:45 +00004901 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004902 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004903 } else {
4904 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4905 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4906 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004907 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004908
4909 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004910 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004911 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004912 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004913 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004914 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004915 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004916 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004917 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004918 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004919 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004920 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004921 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004922 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004923 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004924 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004925 }
4926 }
4927 }
4928
Douglas Gregor218937c2011-02-01 19:23:04 +00004929 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004930 SuperMethod->isInstanceMethod()
4931 ? CXCursor_ObjCInstanceMethodDecl
4932 : CXCursor_ObjCClassMethodDecl));
4933 return SuperMethod;
4934}
4935
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004936void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004937 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004938 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4939 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004940 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004941
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004942 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4943 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004944 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4945 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004946
4947 // If we are in an Objective-C method inside a class that has a superclass,
4948 // add "super" as an option.
4949 if (ObjCMethodDecl *Method = getCurMethodDecl())
4950 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004951 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004952 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004953
4954 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4955 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004956
4957 Results.ExitScope();
4958
4959 if (CodeCompleter->includeMacros())
4960 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004961 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004962 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004963
4964}
4965
Douglas Gregor2725ca82010-04-21 19:57:20 +00004966void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4967 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004968 unsigned NumSelIdents,
4969 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004970 ObjCInterfaceDecl *CDecl = 0;
4971 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4972 // Figure out which interface we're in.
4973 CDecl = CurMethod->getClassInterface();
4974 if (!CDecl)
4975 return;
4976
4977 // Find the superclass of this class.
4978 CDecl = CDecl->getSuperClass();
4979 if (!CDecl)
4980 return;
4981
4982 if (CurMethod->isInstanceMethod()) {
4983 // We are inside an instance method, which means that the message
4984 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004985 // current object.
4986 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004987 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004988 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004989 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004990 }
4991
4992 // Fall through to send to the superclass in CDecl.
4993 } else {
4994 // "super" may be the name of a type or variable. Figure out which
4995 // it is.
4996 IdentifierInfo *Super = &Context.Idents.get("super");
4997 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4998 LookupOrdinaryName);
4999 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5000 // "super" names an interface. Use it.
5001 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00005002 if (const ObjCObjectType *Iface
5003 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5004 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00005005 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5006 // "super" names an unresolved type; we can't be more specific.
5007 } else {
5008 // Assume that "super" names some kind of value and parse that way.
5009 CXXScopeSpec SS;
5010 UnqualifiedId id;
5011 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00005012 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005013 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005014 SelIdents, NumSelIdents,
5015 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005016 }
5017
5018 // Fall through
5019 }
5020
John McCallb3d87482010-08-24 05:47:05 +00005021 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00005022 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00005023 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00005024 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005025 NumSelIdents, AtArgumentExpression,
5026 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005027}
5028
Douglas Gregorb9d77572010-09-21 00:03:25 +00005029/// \brief Given a set of code-completion results for the argument of a message
5030/// send, determine the preferred type (if any) for that argument expression.
5031static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5032 unsigned NumSelIdents) {
5033 typedef CodeCompletionResult Result;
5034 ASTContext &Context = Results.getSema().Context;
5035
5036 QualType PreferredType;
5037 unsigned BestPriority = CCP_Unlikely * 2;
5038 Result *ResultsData = Results.data();
5039 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5040 Result &R = ResultsData[I];
5041 if (R.Kind == Result::RK_Declaration &&
5042 isa<ObjCMethodDecl>(R.Declaration)) {
5043 if (R.Priority <= BestPriority) {
5044 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5045 if (NumSelIdents <= Method->param_size()) {
5046 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5047 ->getType();
5048 if (R.Priority < BestPriority || PreferredType.isNull()) {
5049 BestPriority = R.Priority;
5050 PreferredType = MyPreferredType;
5051 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5052 MyPreferredType)) {
5053 PreferredType = QualType();
5054 }
5055 }
5056 }
5057 }
5058 }
5059
5060 return PreferredType;
5061}
5062
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005063static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5064 ParsedType Receiver,
5065 IdentifierInfo **SelIdents,
5066 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005067 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005068 bool IsSuper,
5069 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005070 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00005071 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005072
Douglas Gregor24a069f2009-11-17 17:59:40 +00005073 // If the given name refers to an interface type, retrieve the
5074 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00005075 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005076 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005077 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00005078 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5079 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00005080 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005081
Douglas Gregor36ecb042009-11-17 23:22:23 +00005082 // Add all of the factory methods in this Objective-C class, its protocols,
5083 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00005084 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005085
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005086 // If this is a send-to-super, try to add the special "super" send
5087 // completion.
5088 if (IsSuper) {
5089 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005090 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5091 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005092 Results.Ignore(SuperMethod);
5093 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005094
Douglas Gregor265f7492010-08-27 15:29:55 +00005095 // If we're inside an Objective-C method definition, prefer its selector to
5096 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005097 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005098 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005099
Douglas Gregord36adf52010-09-16 16:06:31 +00005100 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005101 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005102 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005103 SemaRef.CurContext, Selectors, AtArgumentExpression,
5104 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005105 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005106 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005107
Douglas Gregor719770d2010-04-06 17:30:22 +00005108 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005109 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005110 if (SemaRef.ExternalSource) {
5111 for (uint32_t I = 0,
5112 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005113 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005114 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5115 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005116 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005117
5118 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005119 }
5120 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005121
5122 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5123 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005124 M != MEnd; ++M) {
5125 for (ObjCMethodList *MethList = &M->second.second;
5126 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005127 MethList = MethList->Next) {
5128 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5129 NumSelIdents))
5130 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005131
Douglas Gregor13438f92010-04-06 16:40:00 +00005132 Result R(MethList->Method, 0);
5133 R.StartParameter = NumSelIdents;
5134 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005135 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005136 }
5137 }
5138 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005139
5140 Results.ExitScope();
5141}
Douglas Gregor13438f92010-04-06 16:40:00 +00005142
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005143void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5144 IdentifierInfo **SelIdents,
5145 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005146 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005147 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005148
5149 QualType T = this->GetTypeFromParser(Receiver);
5150
Douglas Gregor218937c2011-02-01 19:23:04 +00005151 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005152 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005153 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005154
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005155 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5156 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005157
5158 // If we're actually at the argument expression (rather than prior to the
5159 // selector), we're actually performing code completion for an expression.
5160 // Determine whether we have a single, best method. If so, we can
5161 // code-complete the expression using the corresponding parameter type as
5162 // our preferred type, improving completion results.
5163 if (AtArgumentExpression) {
5164 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005165 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005166 if (PreferredType.isNull())
5167 CodeCompleteOrdinaryName(S, PCC_Expression);
5168 else
5169 CodeCompleteExpression(S, PreferredType);
5170 return;
5171 }
5172
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005173 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005174 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005175 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005176}
5177
Richard Trieuf81e5a92011-09-09 02:00:50 +00005178void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005179 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005180 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005181 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005182 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005183 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005184
5185 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005186
Douglas Gregor36ecb042009-11-17 23:22:23 +00005187 // If necessary, apply function/array conversion to the receiver.
5188 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005189 if (RecExpr) {
5190 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5191 if (Conv.isInvalid()) // conversion failed. bail.
5192 return;
5193 RecExpr = Conv.take();
5194 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005195 QualType ReceiverType = RecExpr? RecExpr->getType()
5196 : Super? Context.getObjCObjectPointerType(
5197 Context.getObjCInterfaceType(Super))
5198 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005199
Douglas Gregorda892642010-11-08 21:12:30 +00005200 // If we're messaging an expression with type "id" or "Class", check
5201 // whether we know something special about the receiver that allows
5202 // us to assume a more-specific receiver type.
5203 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5204 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5205 if (ReceiverType->isObjCClassType())
5206 return CodeCompleteObjCClassMessage(S,
5207 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5208 SelIdents, NumSelIdents,
5209 AtArgumentExpression, Super);
5210
5211 ReceiverType = Context.getObjCObjectPointerType(
5212 Context.getObjCInterfaceType(IFace));
5213 }
5214
Douglas Gregor36ecb042009-11-17 23:22:23 +00005215 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005216 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005217 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005218 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005219
Douglas Gregor36ecb042009-11-17 23:22:23 +00005220 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005221
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005222 // If this is a send-to-super, try to add the special "super" send
5223 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005224 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005225 if (ObjCMethodDecl *SuperMethod
5226 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5227 Results))
5228 Results.Ignore(SuperMethod);
5229 }
5230
Douglas Gregor265f7492010-08-27 15:29:55 +00005231 // If we're inside an Objective-C method definition, prefer its selector to
5232 // others.
5233 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5234 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005235
Douglas Gregord36adf52010-09-16 16:06:31 +00005236 // Keep track of the selectors we've already added.
5237 VisitedSelectorSet Selectors;
5238
Douglas Gregorf74a4192009-11-18 00:06:18 +00005239 // Handle messages to Class. This really isn't a message to an instance
5240 // method, so we treat it the same way we would treat a message send to a
5241 // class method.
5242 if (ReceiverType->isObjCClassType() ||
5243 ReceiverType->isObjCQualifiedClassType()) {
5244 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5245 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005246 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005247 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005248 }
5249 }
5250 // Handle messages to a qualified ID ("id<foo>").
5251 else if (const ObjCObjectPointerType *QualID
5252 = ReceiverType->getAsObjCQualifiedIdType()) {
5253 // Search protocols for instance methods.
5254 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5255 E = QualID->qual_end();
5256 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005257 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005258 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005259 }
5260 // Handle messages to a pointer to interface type.
5261 else if (const ObjCObjectPointerType *IFacePtr
5262 = ReceiverType->getAsObjCInterfacePointerType()) {
5263 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005264 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005265 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5266 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005267
5268 // Search protocols for instance methods.
5269 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5270 E = IFacePtr->qual_end();
5271 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005272 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005273 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005274 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005275 // Handle messages to "id".
5276 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005277 // We're messaging "id", so provide all instance methods we know
5278 // about as code-completion results.
5279
5280 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005281 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005282 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005283 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5284 I != N; ++I) {
5285 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005286 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005287 continue;
5288
Sebastian Redldb9d2142010-08-02 23:18:59 +00005289 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005290 }
5291 }
5292
Sebastian Redldb9d2142010-08-02 23:18:59 +00005293 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5294 MEnd = MethodPool.end();
5295 M != MEnd; ++M) {
5296 for (ObjCMethodList *MethList = &M->second.first;
5297 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005298 MethList = MethList->Next) {
5299 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5300 NumSelIdents))
5301 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005302
5303 if (!Selectors.insert(MethList->Method->getSelector()))
5304 continue;
5305
Douglas Gregor13438f92010-04-06 16:40:00 +00005306 Result R(MethList->Method, 0);
5307 R.StartParameter = NumSelIdents;
5308 R.AllParametersAreInformative = false;
5309 Results.MaybeAddResult(R, CurContext);
5310 }
5311 }
5312 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005313 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005314
5315
5316 // If we're actually at the argument expression (rather than prior to the
5317 // selector), we're actually performing code completion for an expression.
5318 // Determine whether we have a single, best method. If so, we can
5319 // code-complete the expression using the corresponding parameter type as
5320 // our preferred type, improving completion results.
5321 if (AtArgumentExpression) {
5322 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5323 NumSelIdents);
5324 if (PreferredType.isNull())
5325 CodeCompleteOrdinaryName(S, PCC_Expression);
5326 else
5327 CodeCompleteExpression(S, PreferredType);
5328 return;
5329 }
5330
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005331 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005332 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005333 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005334}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005335
Douglas Gregorfb629412010-08-23 21:17:50 +00005336void Sema::CodeCompleteObjCForCollection(Scope *S,
5337 DeclGroupPtrTy IterationVar) {
5338 CodeCompleteExpressionData Data;
5339 Data.ObjCCollection = true;
5340
5341 if (IterationVar.getAsOpaquePtr()) {
5342 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5343 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5344 if (*I)
5345 Data.IgnoreDecls.push_back(*I);
5346 }
5347 }
5348
5349 CodeCompleteExpression(S, Data);
5350}
5351
Douglas Gregor458433d2010-08-26 15:07:07 +00005352void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5353 unsigned NumSelIdents) {
5354 // If we have an external source, load the entire class method
5355 // pool from the AST file.
5356 if (ExternalSource) {
5357 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5358 I != N; ++I) {
5359 Selector Sel = ExternalSource->GetExternalSelector(I);
5360 if (Sel.isNull() || MethodPool.count(Sel))
5361 continue;
5362
5363 ReadMethodPool(Sel);
5364 }
5365 }
5366
Douglas Gregor218937c2011-02-01 19:23:04 +00005367 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5368 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005369 Results.EnterNewScope();
5370 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5371 MEnd = MethodPool.end();
5372 M != MEnd; ++M) {
5373
5374 Selector Sel = M->first;
5375 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5376 continue;
5377
Douglas Gregor218937c2011-02-01 19:23:04 +00005378 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005379 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005380 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005381 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005382 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005383 continue;
5384 }
5385
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005386 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005387 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005388 if (I == NumSelIdents) {
5389 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005390 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005391 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005392 Accumulator.clear();
5393 }
5394 }
5395
Benjamin Kramera0651c52011-07-26 16:59:25 +00005396 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005397 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005398 }
Douglas Gregordae68752011-02-01 22:57:45 +00005399 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005400 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005401 }
5402 Results.ExitScope();
5403
5404 HandleCodeCompleteResults(this, CodeCompleter,
5405 CodeCompletionContext::CCC_SelectorName,
5406 Results.data(), Results.size());
5407}
5408
Douglas Gregor55385fe2009-11-18 04:19:12 +00005409/// \brief Add all of the protocol declarations that we find in the given
5410/// (translation unit) context.
5411static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005412 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005413 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005414 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005415
5416 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5417 DEnd = Ctx->decls_end();
5418 D != DEnd; ++D) {
5419 // Record any protocols we find.
5420 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005421 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005422 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005423
5424 // Record any forward-declared protocols we find.
5425 if (ObjCForwardProtocolDecl *Forward
5426 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5427 for (ObjCForwardProtocolDecl::protocol_iterator
5428 P = Forward->protocol_begin(),
5429 PEnd = Forward->protocol_end();
5430 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005431 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005432 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005433 }
5434 }
5435}
5436
5437void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5438 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005439 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5440 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005441
Douglas Gregor70c23352010-12-09 21:44:02 +00005442 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5443 Results.EnterNewScope();
5444
5445 // Tell the result set to ignore all of the protocols we have
5446 // already seen.
5447 // FIXME: This doesn't work when caching code-completion results.
5448 for (unsigned I = 0; I != NumProtocols; ++I)
5449 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5450 Protocols[I].second))
5451 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005452
Douglas Gregor70c23352010-12-09 21:44:02 +00005453 // Add all protocols.
5454 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5455 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005456
Douglas Gregor70c23352010-12-09 21:44:02 +00005457 Results.ExitScope();
5458 }
5459
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005460 HandleCodeCompleteResults(this, CodeCompleter,
5461 CodeCompletionContext::CCC_ObjCProtocolName,
5462 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005463}
5464
5465void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005466 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5467 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005468
Douglas Gregor70c23352010-12-09 21:44:02 +00005469 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5470 Results.EnterNewScope();
5471
5472 // Add all protocols.
5473 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5474 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005475
Douglas Gregor70c23352010-12-09 21:44:02 +00005476 Results.ExitScope();
5477 }
5478
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005479 HandleCodeCompleteResults(this, CodeCompleter,
5480 CodeCompletionContext::CCC_ObjCProtocolName,
5481 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005482}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005483
5484/// \brief Add all of the Objective-C interface declarations that we find in
5485/// the given (translation unit) context.
5486static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5487 bool OnlyForwardDeclarations,
5488 bool OnlyUnimplemented,
5489 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005490 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005491
5492 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5493 DEnd = Ctx->decls_end();
5494 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005495 // Record any interfaces we find.
5496 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5497 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5498 (!OnlyUnimplemented || !Class->getImplementation()))
5499 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005500
5501 // Record any forward-declared interfaces we find.
5502 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005503 ObjCInterfaceDecl *IDecl = Forward->getForwardInterfaceDecl();
5504 if ((!OnlyForwardDeclarations || IDecl->isForwardDecl()) &&
5505 (!OnlyUnimplemented || !IDecl->getImplementation()))
5506 Results.AddResult(Result(IDecl, 0), CurContext,
5507 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005508 }
5509 }
5510}
5511
5512void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005513 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5514 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005515 Results.EnterNewScope();
5516
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005517 if (CodeCompleter->includeGlobals()) {
5518 // Add all classes.
5519 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5520 false, Results);
5521 }
5522
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005523 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005524
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005525 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005526 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005527 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005528}
5529
Douglas Gregorc83c6872010-04-15 22:33:43 +00005530void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5531 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005532 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005533 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005534 Results.EnterNewScope();
5535
5536 // Make sure that we ignore the class we're currently defining.
5537 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005538 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005539 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005540 Results.Ignore(CurClass);
5541
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005542 if (CodeCompleter->includeGlobals()) {
5543 // Add all classes.
5544 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5545 false, Results);
5546 }
5547
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005548 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005549
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005550 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005551 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005552 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005553}
5554
5555void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005556 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5557 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005558 Results.EnterNewScope();
5559
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005560 if (CodeCompleter->includeGlobals()) {
5561 // Add all unimplemented classes.
5562 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5563 true, Results);
5564 }
5565
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005566 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005567
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005568 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005569 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005570 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005571}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005572
5573void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005574 IdentifierInfo *ClassName,
5575 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005576 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005577
Douglas Gregor218937c2011-02-01 19:23:04 +00005578 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005579 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005580
5581 // Ignore any categories we find that have already been implemented by this
5582 // interface.
5583 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5584 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005585 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005586 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5587 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5588 Category = Category->getNextClassCategory())
5589 CategoryNames.insert(Category->getIdentifier());
5590
5591 // Add all of the categories we know about.
5592 Results.EnterNewScope();
5593 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5594 for (DeclContext::decl_iterator D = TU->decls_begin(),
5595 DEnd = TU->decls_end();
5596 D != DEnd; ++D)
5597 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5598 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005599 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005600 Results.ExitScope();
5601
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005602 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005603 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005604 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005605}
5606
5607void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005608 IdentifierInfo *ClassName,
5609 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005610 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005611
5612 // Find the corresponding interface. If we couldn't find the interface, the
5613 // program itself is ill-formed. However, we'll try to be helpful still by
5614 // providing the list of all of the categories we know about.
5615 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005616 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005617 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5618 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005619 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005620
Douglas Gregor218937c2011-02-01 19:23:04 +00005621 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005622 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005623
5624 // Add all of the categories that have have corresponding interface
5625 // declarations in this class and any of its superclasses, except for
5626 // already-implemented categories in the class itself.
5627 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5628 Results.EnterNewScope();
5629 bool IgnoreImplemented = true;
5630 while (Class) {
5631 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5632 Category = Category->getNextClassCategory())
5633 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5634 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005635 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005636
5637 Class = Class->getSuperClass();
5638 IgnoreImplemented = false;
5639 }
5640 Results.ExitScope();
5641
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005642 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005643 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005644 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005645}
Douglas Gregor322328b2009-11-18 22:32:06 +00005646
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005647void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005648 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005649 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5650 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005651
5652 // Figure out where this @synthesize lives.
5653 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005654 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005655 if (!Container ||
5656 (!isa<ObjCImplementationDecl>(Container) &&
5657 !isa<ObjCCategoryImplDecl>(Container)))
5658 return;
5659
5660 // Ignore any properties that have already been implemented.
5661 for (DeclContext::decl_iterator D = Container->decls_begin(),
5662 DEnd = Container->decls_end();
5663 D != DEnd; ++D)
5664 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5665 Results.Ignore(PropertyImpl->getPropertyDecl());
5666
5667 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005668 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005669 Results.EnterNewScope();
5670 if (ObjCImplementationDecl *ClassImpl
5671 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005672 AddObjCProperties(ClassImpl->getClassInterface(), false,
5673 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005674 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005675 else
5676 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005677 false, /*AllowNullaryMethods=*/false, CurContext,
5678 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005679 Results.ExitScope();
5680
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005681 HandleCodeCompleteResults(this, CodeCompleter,
5682 CodeCompletionContext::CCC_Other,
5683 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005684}
5685
5686void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005687 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005688 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005689 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5690 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005691
5692 // Figure out where this @synthesize lives.
5693 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005694 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005695 if (!Container ||
5696 (!isa<ObjCImplementationDecl>(Container) &&
5697 !isa<ObjCCategoryImplDecl>(Container)))
5698 return;
5699
5700 // Figure out which interface we're looking into.
5701 ObjCInterfaceDecl *Class = 0;
5702 if (ObjCImplementationDecl *ClassImpl
5703 = dyn_cast<ObjCImplementationDecl>(Container))
5704 Class = ClassImpl->getClassInterface();
5705 else
5706 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5707 ->getClassInterface();
5708
Douglas Gregore8426052011-04-18 14:40:46 +00005709 // Determine the type of the property we're synthesizing.
5710 QualType PropertyType = Context.getObjCIdType();
5711 if (Class) {
5712 if (ObjCPropertyDecl *Property
5713 = Class->FindPropertyDeclaration(PropertyName)) {
5714 PropertyType
5715 = Property->getType().getNonReferenceType().getUnqualifiedType();
5716
5717 // Give preference to ivars
5718 Results.setPreferredType(PropertyType);
5719 }
5720 }
5721
Douglas Gregor322328b2009-11-18 22:32:06 +00005722 // Add all of the instance variables in this class and its superclasses.
5723 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005724 bool SawSimilarlyNamedIvar = false;
5725 std::string NameWithPrefix;
5726 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005727 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005728 std::string NameWithSuffix = PropertyName->getName().str();
5729 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005730 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005731 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5732 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005733 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5734
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005735 // Determine whether we've seen an ivar with a name similar to the
5736 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005737 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005738 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005739 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005740 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005741
5742 // Reduce the priority of this result by one, to give it a slight
5743 // advantage over other results whose names don't match so closely.
5744 if (Results.size() &&
5745 Results.data()[Results.size() - 1].Kind
5746 == CodeCompletionResult::RK_Declaration &&
5747 Results.data()[Results.size() - 1].Declaration == Ivar)
5748 Results.data()[Results.size() - 1].Priority--;
5749 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005750 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005751 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005752
5753 if (!SawSimilarlyNamedIvar) {
5754 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005755 // an ivar of the appropriate type.
5756 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005757 typedef CodeCompletionResult Result;
5758 CodeCompletionAllocator &Allocator = Results.getAllocator();
5759 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5760
Douglas Gregor8987b232011-09-27 23:30:47 +00005761 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8426052011-04-18 14:40:46 +00005762 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005763 Policy, Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005764 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5765 Results.AddResult(Result(Builder.TakeString(), Priority,
5766 CXCursor_ObjCIvarDecl));
5767 }
5768
Douglas Gregor322328b2009-11-18 22:32:06 +00005769 Results.ExitScope();
5770
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005771 HandleCodeCompleteResults(this, CodeCompleter,
5772 CodeCompletionContext::CCC_Other,
5773 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005774}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005775
Douglas Gregor408be5a2010-08-25 01:08:01 +00005776// Mapping from selectors to the methods that implement that selector, along
5777// with the "in original class" flag.
5778typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5779 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005780
5781/// \brief Find all of the methods that reside in the given container
5782/// (and its superclasses, protocols, etc.) that meet the given
5783/// criteria. Insert those methods into the map of known methods,
5784/// indexed by selector so they can be easily found.
5785static void FindImplementableMethods(ASTContext &Context,
5786 ObjCContainerDecl *Container,
5787 bool WantInstanceMethods,
5788 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005789 KnownMethodsMap &KnownMethods,
5790 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005791 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5792 // Recurse into protocols.
5793 const ObjCList<ObjCProtocolDecl> &Protocols
5794 = IFace->getReferencedProtocols();
5795 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005796 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005797 I != E; ++I)
5798 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005799 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005800
Douglas Gregorea766182010-10-18 18:21:28 +00005801 // Add methods from any class extensions and categories.
5802 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5803 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005804 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5805 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005806 KnownMethods, false);
5807
5808 // Visit the superclass.
5809 if (IFace->getSuperClass())
5810 FindImplementableMethods(Context, IFace->getSuperClass(),
5811 WantInstanceMethods, ReturnType,
5812 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005813 }
5814
5815 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5816 // Recurse into protocols.
5817 const ObjCList<ObjCProtocolDecl> &Protocols
5818 = Category->getReferencedProtocols();
5819 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005820 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005821 I != E; ++I)
5822 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005823 KnownMethods, InOriginalClass);
5824
5825 // If this category is the original class, jump to the interface.
5826 if (InOriginalClass && Category->getClassInterface())
5827 FindImplementableMethods(Context, Category->getClassInterface(),
5828 WantInstanceMethods, ReturnType, KnownMethods,
5829 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005830 }
5831
5832 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5833 // Recurse into protocols.
5834 const ObjCList<ObjCProtocolDecl> &Protocols
5835 = Protocol->getReferencedProtocols();
5836 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5837 E = Protocols.end();
5838 I != E; ++I)
5839 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005840 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005841 }
5842
5843 // Add methods in this container. This operation occurs last because
5844 // we want the methods from this container to override any methods
5845 // we've previously seen with the same selector.
5846 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5847 MEnd = Container->meth_end();
5848 M != MEnd; ++M) {
5849 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5850 if (!ReturnType.isNull() &&
5851 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5852 continue;
5853
Douglas Gregor408be5a2010-08-25 01:08:01 +00005854 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005855 }
5856 }
5857}
5858
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005859/// \brief Add the parenthesized return or parameter type chunk to a code
5860/// completion string.
5861static void AddObjCPassingTypeChunk(QualType Type,
5862 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005863 const PrintingPolicy &Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005864 CodeCompletionBuilder &Builder) {
5865 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor8987b232011-09-27 23:30:47 +00005866 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005867 Builder.getAllocator()));
5868 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5869}
5870
5871/// \brief Determine whether the given class is or inherits from a class by
5872/// the given name.
5873static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005874 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005875 if (!Class)
5876 return false;
5877
5878 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5879 return true;
5880
5881 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5882}
5883
5884/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5885/// Key-Value Observing (KVO).
5886static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5887 bool IsInstanceMethod,
5888 QualType ReturnType,
5889 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005890 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005891 ResultBuilder &Results) {
5892 IdentifierInfo *PropName = Property->getIdentifier();
5893 if (!PropName || PropName->getLength() == 0)
5894 return;
5895
Douglas Gregor8987b232011-09-27 23:30:47 +00005896 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5897
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005898 // Builder that will create each code completion.
5899 typedef CodeCompletionResult Result;
5900 CodeCompletionAllocator &Allocator = Results.getAllocator();
5901 CodeCompletionBuilder Builder(Allocator);
5902
5903 // The selector table.
5904 SelectorTable &Selectors = Context.Selectors;
5905
5906 // The property name, copied into the code completion allocation region
5907 // on demand.
5908 struct KeyHolder {
5909 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005910 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005911 const char *CopiedKey;
5912
Chris Lattner5f9e2722011-07-23 10:55:15 +00005913 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005914 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5915
5916 operator const char *() {
5917 if (CopiedKey)
5918 return CopiedKey;
5919
5920 return CopiedKey = Allocator.CopyString(Key);
5921 }
5922 } Key(Allocator, PropName->getName());
5923
5924 // The uppercased name of the property name.
5925 std::string UpperKey = PropName->getName();
5926 if (!UpperKey.empty())
5927 UpperKey[0] = toupper(UpperKey[0]);
5928
5929 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5930 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5931 Property->getType());
5932 bool ReturnTypeMatchesVoid
5933 = ReturnType.isNull() || ReturnType->isVoidType();
5934
5935 // Add the normal accessor -(type)key.
5936 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005937 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005938 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5939 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00005940 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005941
5942 Builder.AddTypedTextChunk(Key);
5943 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5944 CXCursor_ObjCInstanceMethodDecl));
5945 }
5946
5947 // If we have an integral or boolean property (or the user has provided
5948 // an integral or boolean return type), add the accessor -(type)isKey.
5949 if (IsInstanceMethod &&
5950 ((!ReturnType.isNull() &&
5951 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5952 (ReturnType.isNull() &&
5953 (Property->getType()->isIntegerType() ||
5954 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005955 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005956 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005957 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005958 if (ReturnType.isNull()) {
5959 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5960 Builder.AddTextChunk("BOOL");
5961 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5962 }
5963
5964 Builder.AddTypedTextChunk(
5965 Allocator.CopyString(SelectorId->getName()));
5966 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5967 CXCursor_ObjCInstanceMethodDecl));
5968 }
5969 }
5970
5971 // Add the normal mutator.
5972 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5973 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005974 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005975 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005976 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005977 if (ReturnType.isNull()) {
5978 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5979 Builder.AddTextChunk("void");
5980 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5981 }
5982
5983 Builder.AddTypedTextChunk(
5984 Allocator.CopyString(SelectorId->getName()));
5985 Builder.AddTypedTextChunk(":");
Douglas Gregor8987b232011-09-27 23:30:47 +00005986 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005987 Builder.AddTextChunk(Key);
5988 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5989 CXCursor_ObjCInstanceMethodDecl));
5990 }
5991 }
5992
5993 // Indexed and unordered accessors
5994 unsigned IndexedGetterPriority = CCP_CodePattern;
5995 unsigned IndexedSetterPriority = CCP_CodePattern;
5996 unsigned UnorderedGetterPriority = CCP_CodePattern;
5997 unsigned UnorderedSetterPriority = CCP_CodePattern;
5998 if (const ObjCObjectPointerType *ObjCPointer
5999 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6000 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6001 // If this interface type is not provably derived from a known
6002 // collection, penalize the corresponding completions.
6003 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6004 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6005 if (!InheritsFromClassNamed(IFace, "NSArray"))
6006 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6007 }
6008
6009 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6010 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6011 if (!InheritsFromClassNamed(IFace, "NSSet"))
6012 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6013 }
6014 }
6015 } else {
6016 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6017 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6018 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6019 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6020 }
6021
6022 // Add -(NSUInteger)countOf<key>
6023 if (IsInstanceMethod &&
6024 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006025 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006026 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006027 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006028 if (ReturnType.isNull()) {
6029 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6030 Builder.AddTextChunk("NSUInteger");
6031 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6032 }
6033
6034 Builder.AddTypedTextChunk(
6035 Allocator.CopyString(SelectorId->getName()));
6036 Results.AddResult(Result(Builder.TakeString(),
6037 std::min(IndexedGetterPriority,
6038 UnorderedGetterPriority),
6039 CXCursor_ObjCInstanceMethodDecl));
6040 }
6041 }
6042
6043 // Indexed getters
6044 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6045 if (IsInstanceMethod &&
6046 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00006047 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006048 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006049 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006050 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006051 if (ReturnType.isNull()) {
6052 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6053 Builder.AddTextChunk("id");
6054 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6055 }
6056
6057 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6058 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6059 Builder.AddTextChunk("NSUInteger");
6060 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6061 Builder.AddTextChunk("index");
6062 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6063 CXCursor_ObjCInstanceMethodDecl));
6064 }
6065 }
6066
6067 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6068 if (IsInstanceMethod &&
6069 (ReturnType.isNull() ||
6070 (ReturnType->isObjCObjectPointerType() &&
6071 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6072 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6073 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006074 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006075 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006076 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006077 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006078 if (ReturnType.isNull()) {
6079 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6080 Builder.AddTextChunk("NSArray *");
6081 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6082 }
6083
6084 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6085 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6086 Builder.AddTextChunk("NSIndexSet *");
6087 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6088 Builder.AddTextChunk("indexes");
6089 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6090 CXCursor_ObjCInstanceMethodDecl));
6091 }
6092 }
6093
6094 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6095 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006096 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006097 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006098 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006099 &Context.Idents.get("range")
6100 };
6101
Douglas Gregore74c25c2011-05-04 23:50:46 +00006102 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006103 if (ReturnType.isNull()) {
6104 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6105 Builder.AddTextChunk("void");
6106 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6107 }
6108
6109 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6110 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6111 Builder.AddPlaceholderChunk("object-type");
6112 Builder.AddTextChunk(" **");
6113 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6114 Builder.AddTextChunk("buffer");
6115 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6116 Builder.AddTypedTextChunk("range:");
6117 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6118 Builder.AddTextChunk("NSRange");
6119 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6120 Builder.AddTextChunk("inRange");
6121 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6122 CXCursor_ObjCInstanceMethodDecl));
6123 }
6124 }
6125
6126 // Mutable indexed accessors
6127
6128 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6129 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006130 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006131 IdentifierInfo *SelectorIds[2] = {
6132 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006133 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006134 };
6135
Douglas Gregore74c25c2011-05-04 23:50:46 +00006136 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006137 if (ReturnType.isNull()) {
6138 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6139 Builder.AddTextChunk("void");
6140 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6141 }
6142
6143 Builder.AddTypedTextChunk("insertObject:");
6144 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6145 Builder.AddPlaceholderChunk("object-type");
6146 Builder.AddTextChunk(" *");
6147 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6148 Builder.AddTextChunk("object");
6149 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6150 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6151 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6152 Builder.AddPlaceholderChunk("NSUInteger");
6153 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6154 Builder.AddTextChunk("index");
6155 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6156 CXCursor_ObjCInstanceMethodDecl));
6157 }
6158 }
6159
6160 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6161 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006162 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006163 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006164 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006165 &Context.Idents.get("atIndexes")
6166 };
6167
Douglas Gregore74c25c2011-05-04 23:50:46 +00006168 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006169 if (ReturnType.isNull()) {
6170 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6171 Builder.AddTextChunk("void");
6172 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6173 }
6174
6175 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6176 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6177 Builder.AddTextChunk("NSArray *");
6178 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6179 Builder.AddTextChunk("array");
6180 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6181 Builder.AddTypedTextChunk("atIndexes:");
6182 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6183 Builder.AddPlaceholderChunk("NSIndexSet *");
6184 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6185 Builder.AddTextChunk("indexes");
6186 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6187 CXCursor_ObjCInstanceMethodDecl));
6188 }
6189 }
6190
6191 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6192 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006193 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006194 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006195 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006196 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006197 if (ReturnType.isNull()) {
6198 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6199 Builder.AddTextChunk("void");
6200 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6201 }
6202
6203 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6204 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6205 Builder.AddTextChunk("NSUInteger");
6206 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6207 Builder.AddTextChunk("index");
6208 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6209 CXCursor_ObjCInstanceMethodDecl));
6210 }
6211 }
6212
6213 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6214 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006215 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006216 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006217 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006218 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006219 if (ReturnType.isNull()) {
6220 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6221 Builder.AddTextChunk("void");
6222 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6223 }
6224
6225 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6226 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6227 Builder.AddTextChunk("NSIndexSet *");
6228 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6229 Builder.AddTextChunk("indexes");
6230 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6231 CXCursor_ObjCInstanceMethodDecl));
6232 }
6233 }
6234
6235 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6236 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006237 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006238 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006239 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006240 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006241 &Context.Idents.get("withObject")
6242 };
6243
Douglas Gregore74c25c2011-05-04 23:50:46 +00006244 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006245 if (ReturnType.isNull()) {
6246 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6247 Builder.AddTextChunk("void");
6248 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6249 }
6250
6251 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6252 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6253 Builder.AddPlaceholderChunk("NSUInteger");
6254 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6255 Builder.AddTextChunk("index");
6256 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6257 Builder.AddTypedTextChunk("withObject:");
6258 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6259 Builder.AddTextChunk("id");
6260 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6261 Builder.AddTextChunk("object");
6262 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6263 CXCursor_ObjCInstanceMethodDecl));
6264 }
6265 }
6266
6267 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6268 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006269 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006270 = (Twine("replace") + UpperKey + "AtIndexes").str();
6271 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006272 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006273 &Context.Idents.get(SelectorName1),
6274 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006275 };
6276
Douglas Gregore74c25c2011-05-04 23:50:46 +00006277 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006278 if (ReturnType.isNull()) {
6279 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6280 Builder.AddTextChunk("void");
6281 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6282 }
6283
6284 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6285 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6286 Builder.AddPlaceholderChunk("NSIndexSet *");
6287 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6288 Builder.AddTextChunk("indexes");
6289 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6290 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6291 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6292 Builder.AddTextChunk("NSArray *");
6293 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6294 Builder.AddTextChunk("array");
6295 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6296 CXCursor_ObjCInstanceMethodDecl));
6297 }
6298 }
6299
6300 // Unordered getters
6301 // - (NSEnumerator *)enumeratorOfKey
6302 if (IsInstanceMethod &&
6303 (ReturnType.isNull() ||
6304 (ReturnType->isObjCObjectPointerType() &&
6305 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6306 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6307 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006308 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006309 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006310 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006311 if (ReturnType.isNull()) {
6312 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6313 Builder.AddTextChunk("NSEnumerator *");
6314 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6315 }
6316
6317 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6318 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6319 CXCursor_ObjCInstanceMethodDecl));
6320 }
6321 }
6322
6323 // - (type *)memberOfKey:(type *)object
6324 if (IsInstanceMethod &&
6325 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006326 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006327 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006328 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006329 if (ReturnType.isNull()) {
6330 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6331 Builder.AddPlaceholderChunk("object-type");
6332 Builder.AddTextChunk(" *");
6333 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6334 }
6335
6336 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6337 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6338 if (ReturnType.isNull()) {
6339 Builder.AddPlaceholderChunk("object-type");
6340 Builder.AddTextChunk(" *");
6341 } else {
6342 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006343 Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006344 Builder.getAllocator()));
6345 }
6346 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6347 Builder.AddTextChunk("object");
6348 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6349 CXCursor_ObjCInstanceMethodDecl));
6350 }
6351 }
6352
6353 // Mutable unordered accessors
6354 // - (void)addKeyObject:(type *)object
6355 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006356 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006357 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006358 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006359 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006360 if (ReturnType.isNull()) {
6361 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6362 Builder.AddTextChunk("void");
6363 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6364 }
6365
6366 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6367 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6368 Builder.AddPlaceholderChunk("object-type");
6369 Builder.AddTextChunk(" *");
6370 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6371 Builder.AddTextChunk("object");
6372 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6373 CXCursor_ObjCInstanceMethodDecl));
6374 }
6375 }
6376
6377 // - (void)addKey:(NSSet *)objects
6378 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006379 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006380 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006381 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006382 if (ReturnType.isNull()) {
6383 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6384 Builder.AddTextChunk("void");
6385 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6386 }
6387
6388 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6389 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6390 Builder.AddTextChunk("NSSet *");
6391 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6392 Builder.AddTextChunk("objects");
6393 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6394 CXCursor_ObjCInstanceMethodDecl));
6395 }
6396 }
6397
6398 // - (void)removeKeyObject:(type *)object
6399 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006400 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006401 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006402 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006403 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006404 if (ReturnType.isNull()) {
6405 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6406 Builder.AddTextChunk("void");
6407 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6408 }
6409
6410 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6411 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6412 Builder.AddPlaceholderChunk("object-type");
6413 Builder.AddTextChunk(" *");
6414 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6415 Builder.AddTextChunk("object");
6416 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6417 CXCursor_ObjCInstanceMethodDecl));
6418 }
6419 }
6420
6421 // - (void)removeKey:(NSSet *)objects
6422 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006423 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006424 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006425 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006426 if (ReturnType.isNull()) {
6427 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6428 Builder.AddTextChunk("void");
6429 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6430 }
6431
6432 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6433 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6434 Builder.AddTextChunk("NSSet *");
6435 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6436 Builder.AddTextChunk("objects");
6437 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6438 CXCursor_ObjCInstanceMethodDecl));
6439 }
6440 }
6441
6442 // - (void)intersectKey:(NSSet *)objects
6443 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006444 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006445 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006446 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006447 if (ReturnType.isNull()) {
6448 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6449 Builder.AddTextChunk("void");
6450 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6451 }
6452
6453 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6454 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6455 Builder.AddTextChunk("NSSet *");
6456 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6457 Builder.AddTextChunk("objects");
6458 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6459 CXCursor_ObjCInstanceMethodDecl));
6460 }
6461 }
6462
6463 // Key-Value Observing
6464 // + (NSSet *)keyPathsForValuesAffectingKey
6465 if (!IsInstanceMethod &&
6466 (ReturnType.isNull() ||
6467 (ReturnType->isObjCObjectPointerType() &&
6468 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6469 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6470 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006471 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006472 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006473 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006474 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006475 if (ReturnType.isNull()) {
6476 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6477 Builder.AddTextChunk("NSSet *");
6478 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6479 }
6480
6481 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6482 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006483 CXCursor_ObjCClassMethodDecl));
6484 }
6485 }
6486
6487 // + (BOOL)automaticallyNotifiesObserversForKey
6488 if (!IsInstanceMethod &&
6489 (ReturnType.isNull() ||
6490 ReturnType->isIntegerType() ||
6491 ReturnType->isBooleanType())) {
6492 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006493 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006494 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6495 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6496 if (ReturnType.isNull()) {
6497 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6498 Builder.AddTextChunk("BOOL");
6499 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6500 }
6501
6502 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6503 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6504 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006505 }
6506 }
6507}
6508
Douglas Gregore8f5a172010-04-07 00:21:17 +00006509void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6510 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006511 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006512 // Determine the return type of the method we're declaring, if
6513 // provided.
6514 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006515 Decl *IDecl = 0;
6516 if (CurContext->isObjCContainer()) {
6517 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6518 IDecl = cast<Decl>(OCD);
6519 }
Douglas Gregorea766182010-10-18 18:21:28 +00006520 // Determine where we should start searching for methods.
6521 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006522 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006523 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006524 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6525 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006526 IsInImplementation = true;
6527 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006528 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006529 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006530 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006531 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006532 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006533 }
6534
6535 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006536 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006537 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006538 }
6539
Douglas Gregorea766182010-10-18 18:21:28 +00006540 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006541 HandleCodeCompleteResults(this, CodeCompleter,
6542 CodeCompletionContext::CCC_Other,
6543 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006544 return;
6545 }
6546
6547 // Find all of the methods that we could declare/implement here.
6548 KnownMethodsMap KnownMethods;
6549 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006550 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006551
Douglas Gregore8f5a172010-04-07 00:21:17 +00006552 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006553 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006554 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6555 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006556 Results.EnterNewScope();
Douglas Gregor8987b232011-09-27 23:30:47 +00006557 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006558 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6559 MEnd = KnownMethods.end();
6560 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006561 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006562 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006563
6564 // If the result type was not already provided, add it to the
6565 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006566 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00006567 AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,
6568 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006569
6570 Selector Sel = Method->getSelector();
6571
6572 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006573 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006574 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006575
6576 // Add parameters to the pattern.
6577 unsigned I = 0;
6578 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6579 PEnd = Method->param_end();
6580 P != PEnd; (void)++P, ++I) {
6581 // Add the part of the selector name.
6582 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006583 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006584 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006585 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6586 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006587 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006588 } else
6589 break;
6590
6591 // Add the parameter type.
Douglas Gregor8987b232011-09-27 23:30:47 +00006592 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,
6593 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006594
6595 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006596 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006597 }
6598
6599 if (Method->isVariadic()) {
6600 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006601 Builder.AddChunk(CodeCompletionString::CK_Comma);
6602 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006603 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006604
Douglas Gregor447107d2010-05-28 00:57:46 +00006605 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006606 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006607 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6608 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6609 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006610 if (!Method->getResultType()->isVoidType()) {
6611 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006612 Builder.AddTextChunk("return");
6613 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6614 Builder.AddPlaceholderChunk("expression");
6615 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006616 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006617 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006618
Douglas Gregor218937c2011-02-01 19:23:04 +00006619 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6620 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006621 }
6622
Douglas Gregor408be5a2010-08-25 01:08:01 +00006623 unsigned Priority = CCP_CodePattern;
6624 if (!M->second.second)
6625 Priority += CCD_InBaseClass;
6626
Douglas Gregor218937c2011-02-01 19:23:04 +00006627 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006628 Method->isInstanceMethod()
6629 ? CXCursor_ObjCInstanceMethodDecl
6630 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006631 }
6632
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006633 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6634 // the properties in this class and its categories.
6635 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006636 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006637 Containers.push_back(SearchDecl);
6638
Douglas Gregore74c25c2011-05-04 23:50:46 +00006639 VisitedSelectorSet KnownSelectors;
6640 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6641 MEnd = KnownMethods.end();
6642 M != MEnd; ++M)
6643 KnownSelectors.insert(M->first);
6644
6645
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006646 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6647 if (!IFace)
6648 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6649 IFace = Category->getClassInterface();
6650
6651 if (IFace) {
6652 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6653 Category = Category->getNextClassCategory())
6654 Containers.push_back(Category);
6655 }
6656
6657 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6658 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6659 PEnd = Containers[I]->prop_end();
6660 P != PEnd; ++P) {
6661 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006662 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006663 }
6664 }
6665 }
6666
Douglas Gregore8f5a172010-04-07 00:21:17 +00006667 Results.ExitScope();
6668
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006669 HandleCodeCompleteResults(this, CodeCompleter,
6670 CodeCompletionContext::CCC_Other,
6671 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006672}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006673
6674void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6675 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006676 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006677 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006678 IdentifierInfo **SelIdents,
6679 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006680 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006681 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006682 if (ExternalSource) {
6683 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6684 I != N; ++I) {
6685 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006686 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006687 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006688
6689 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006690 }
6691 }
6692
6693 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006694 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006695 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6696 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006697
6698 if (ReturnTy)
6699 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006700
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006701 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006702 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6703 MEnd = MethodPool.end();
6704 M != MEnd; ++M) {
6705 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6706 &M->second.second;
6707 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006708 MethList = MethList->Next) {
6709 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6710 NumSelIdents))
6711 continue;
6712
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006713 if (AtParameterName) {
6714 // Suggest parameter names we've seen before.
6715 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6716 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6717 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006718 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006719 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006720 Param->getIdentifier()->getName()));
6721 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006722 }
6723 }
6724
6725 continue;
6726 }
6727
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006728 Result R(MethList->Method, 0);
6729 R.StartParameter = NumSelIdents;
6730 R.AllParametersAreInformative = false;
6731 R.DeclaringEntity = true;
6732 Results.MaybeAddResult(R, CurContext);
6733 }
6734 }
6735
6736 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006737 HandleCodeCompleteResults(this, CodeCompleter,
6738 CodeCompletionContext::CCC_Other,
6739 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006740}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006741
Douglas Gregorf29c5232010-08-24 22:20:20 +00006742void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006743 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006744 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006745 Results.EnterNewScope();
6746
6747 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006748 CodeCompletionBuilder Builder(Results.getAllocator());
6749 Builder.AddTypedTextChunk("if");
6750 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6751 Builder.AddPlaceholderChunk("condition");
6752 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006753
6754 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006755 Builder.AddTypedTextChunk("ifdef");
6756 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6757 Builder.AddPlaceholderChunk("macro");
6758 Results.AddResult(Builder.TakeString());
6759
Douglas Gregorf44e8542010-08-24 19:08:16 +00006760 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006761 Builder.AddTypedTextChunk("ifndef");
6762 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6763 Builder.AddPlaceholderChunk("macro");
6764 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006765
6766 if (InConditional) {
6767 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006768 Builder.AddTypedTextChunk("elif");
6769 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6770 Builder.AddPlaceholderChunk("condition");
6771 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006772
6773 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006774 Builder.AddTypedTextChunk("else");
6775 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006776
6777 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006778 Builder.AddTypedTextChunk("endif");
6779 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006780 }
6781
6782 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006783 Builder.AddTypedTextChunk("include");
6784 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6785 Builder.AddTextChunk("\"");
6786 Builder.AddPlaceholderChunk("header");
6787 Builder.AddTextChunk("\"");
6788 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006789
6790 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006791 Builder.AddTypedTextChunk("include");
6792 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6793 Builder.AddTextChunk("<");
6794 Builder.AddPlaceholderChunk("header");
6795 Builder.AddTextChunk(">");
6796 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006797
6798 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006799 Builder.AddTypedTextChunk("define");
6800 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6801 Builder.AddPlaceholderChunk("macro");
6802 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006803
6804 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006805 Builder.AddTypedTextChunk("define");
6806 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6807 Builder.AddPlaceholderChunk("macro");
6808 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6809 Builder.AddPlaceholderChunk("args");
6810 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6811 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006812
6813 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006814 Builder.AddTypedTextChunk("undef");
6815 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6816 Builder.AddPlaceholderChunk("macro");
6817 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006818
6819 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006820 Builder.AddTypedTextChunk("line");
6821 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6822 Builder.AddPlaceholderChunk("number");
6823 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006824
6825 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006826 Builder.AddTypedTextChunk("line");
6827 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6828 Builder.AddPlaceholderChunk("number");
6829 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6830 Builder.AddTextChunk("\"");
6831 Builder.AddPlaceholderChunk("filename");
6832 Builder.AddTextChunk("\"");
6833 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006834
6835 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006836 Builder.AddTypedTextChunk("error");
6837 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6838 Builder.AddPlaceholderChunk("message");
6839 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006840
6841 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006842 Builder.AddTypedTextChunk("pragma");
6843 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6844 Builder.AddPlaceholderChunk("arguments");
6845 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006846
6847 if (getLangOptions().ObjC1) {
6848 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006849 Builder.AddTypedTextChunk("import");
6850 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6851 Builder.AddTextChunk("\"");
6852 Builder.AddPlaceholderChunk("header");
6853 Builder.AddTextChunk("\"");
6854 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006855
6856 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006857 Builder.AddTypedTextChunk("import");
6858 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6859 Builder.AddTextChunk("<");
6860 Builder.AddPlaceholderChunk("header");
6861 Builder.AddTextChunk(">");
6862 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006863 }
6864
6865 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006866 Builder.AddTypedTextChunk("include_next");
6867 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6868 Builder.AddTextChunk("\"");
6869 Builder.AddPlaceholderChunk("header");
6870 Builder.AddTextChunk("\"");
6871 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006872
6873 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006874 Builder.AddTypedTextChunk("include_next");
6875 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6876 Builder.AddTextChunk("<");
6877 Builder.AddPlaceholderChunk("header");
6878 Builder.AddTextChunk(">");
6879 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006880
6881 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006882 Builder.AddTypedTextChunk("warning");
6883 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6884 Builder.AddPlaceholderChunk("message");
6885 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006886
6887 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6888 // completions for them. And __include_macros is a Clang-internal extension
6889 // that we don't want to encourage anyone to use.
6890
6891 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6892 Results.ExitScope();
6893
Douglas Gregorf44e8542010-08-24 19:08:16 +00006894 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006895 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006896 Results.data(), Results.size());
6897}
6898
6899void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006900 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006901 S->getFnParent()? Sema::PCC_RecoveryInFunction
6902 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006903}
6904
Douglas Gregorf29c5232010-08-24 22:20:20 +00006905void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006906 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006907 IsDefinition? CodeCompletionContext::CCC_MacroName
6908 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006909 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6910 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006911 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006912 Results.EnterNewScope();
6913 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6914 MEnd = PP.macro_end();
6915 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006916 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006917 M->first->getName()));
6918 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006919 }
6920 Results.ExitScope();
6921 } else if (IsDefinition) {
6922 // FIXME: Can we detect when the user just wrote an include guard above?
6923 }
6924
Douglas Gregor52779fb2010-09-23 23:01:17 +00006925 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006926 Results.data(), Results.size());
6927}
6928
Douglas Gregorf29c5232010-08-24 22:20:20 +00006929void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006930 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006931 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006932
6933 if (!CodeCompleter || CodeCompleter->includeMacros())
6934 AddMacroResults(PP, Results);
6935
6936 // defined (<macro>)
6937 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006938 CodeCompletionBuilder Builder(Results.getAllocator());
6939 Builder.AddTypedTextChunk("defined");
6940 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6941 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6942 Builder.AddPlaceholderChunk("macro");
6943 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6944 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006945 Results.ExitScope();
6946
6947 HandleCodeCompleteResults(this, CodeCompleter,
6948 CodeCompletionContext::CCC_PreprocessorExpression,
6949 Results.data(), Results.size());
6950}
6951
6952void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6953 IdentifierInfo *Macro,
6954 MacroInfo *MacroInfo,
6955 unsigned Argument) {
6956 // FIXME: In the future, we could provide "overload" results, much like we
6957 // do for function calls.
6958
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00006959 // Now just ignore this. There will be another code-completion callback
6960 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00006961}
6962
Douglas Gregor55817af2010-08-25 17:04:25 +00006963void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006964 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006965 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006966 0, 0);
6967}
6968
Douglas Gregordae68752011-02-01 22:57:45 +00006969void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006970 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006971 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006972 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6973 CodeCompletionDeclConsumer Consumer(Builder,
6974 Context.getTranslationUnitDecl());
6975 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6976 Consumer);
6977 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006978
6979 if (!CodeCompleter || CodeCompleter->includeMacros())
6980 AddMacroResults(PP, Builder);
6981
6982 Results.clear();
6983 Results.insert(Results.end(),
6984 Builder.data(), Builder.data() + Builder.size());
6985}