blob: 2bff705060e9c09d965c3f570bed807bf8c5d7b1 [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;
Douglas Gregor17015ef2011-11-03 16:51:37 +00001192 if (Ctx)
1193 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
1194
Erik Verbruggend1205962011-10-06 07:27:49 +00001195 ResultBuilder::Result Result(ND, 0, false, Accessible);
1196 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001197 }
1198 };
1199}
1200
Douglas Gregor86d9a522009-09-21 16:56:56 +00001201/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001202static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001203 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001204 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001205 Results.AddResult(Result("short", CCP_Type));
1206 Results.AddResult(Result("long", CCP_Type));
1207 Results.AddResult(Result("signed", CCP_Type));
1208 Results.AddResult(Result("unsigned", CCP_Type));
1209 Results.AddResult(Result("void", CCP_Type));
1210 Results.AddResult(Result("char", CCP_Type));
1211 Results.AddResult(Result("int", CCP_Type));
1212 Results.AddResult(Result("float", CCP_Type));
1213 Results.AddResult(Result("double", CCP_Type));
1214 Results.AddResult(Result("enum", CCP_Type));
1215 Results.AddResult(Result("struct", CCP_Type));
1216 Results.AddResult(Result("union", CCP_Type));
1217 Results.AddResult(Result("const", CCP_Type));
1218 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001219
Douglas Gregor86d9a522009-09-21 16:56:56 +00001220 if (LangOpts.C99) {
1221 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001222 Results.AddResult(Result("_Complex", CCP_Type));
1223 Results.AddResult(Result("_Imaginary", CCP_Type));
1224 Results.AddResult(Result("_Bool", CCP_Type));
1225 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001226 }
1227
Douglas Gregor218937c2011-02-01 19:23:04 +00001228 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001229 if (LangOpts.CPlusPlus) {
1230 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001231 Results.AddResult(Result("bool", CCP_Type +
1232 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001233 Results.AddResult(Result("class", CCP_Type));
1234 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001235
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001236 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001237 Builder.AddTypedTextChunk("typename");
1238 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1239 Builder.AddPlaceholderChunk("qualifier");
1240 Builder.AddTextChunk("::");
1241 Builder.AddPlaceholderChunk("name");
1242 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001243
Douglas Gregor86d9a522009-09-21 16:56:56 +00001244 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001245 Results.AddResult(Result("auto", CCP_Type));
1246 Results.AddResult(Result("char16_t", CCP_Type));
1247 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001248
Douglas Gregor218937c2011-02-01 19:23:04 +00001249 Builder.AddTypedTextChunk("decltype");
1250 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1251 Builder.AddPlaceholderChunk("expression");
1252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1253 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001254 }
1255 }
1256
1257 // GNU extensions
1258 if (LangOpts.GNUMode) {
1259 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001260 // Results.AddResult(Result("_Decimal32"));
1261 // Results.AddResult(Result("_Decimal64"));
1262 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001263
Douglas Gregor218937c2011-02-01 19:23:04 +00001264 Builder.AddTypedTextChunk("typeof");
1265 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1266 Builder.AddPlaceholderChunk("expression");
1267 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001268
Douglas Gregor218937c2011-02-01 19:23:04 +00001269 Builder.AddTypedTextChunk("typeof");
1270 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1271 Builder.AddPlaceholderChunk("type");
1272 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1273 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001274 }
1275}
1276
John McCallf312b1e2010-08-26 23:41:50 +00001277static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001278 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001279 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001280 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001281 // Note: we don't suggest either "auto" or "register", because both
1282 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1283 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001284 Results.AddResult(Result("extern"));
1285 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001286}
1287
John McCallf312b1e2010-08-26 23:41:50 +00001288static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001289 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001290 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001291 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001292 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001293 case Sema::PCC_Class:
1294 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001295 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001296 Results.AddResult(Result("explicit"));
1297 Results.AddResult(Result("friend"));
1298 Results.AddResult(Result("mutable"));
1299 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001300 }
1301 // Fall through
1302
John McCallf312b1e2010-08-26 23:41:50 +00001303 case Sema::PCC_ObjCInterface:
1304 case Sema::PCC_ObjCImplementation:
1305 case Sema::PCC_Namespace:
1306 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001307 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001308 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001309 break;
1310
John McCallf312b1e2010-08-26 23:41:50 +00001311 case Sema::PCC_ObjCInstanceVariableList:
1312 case Sema::PCC_Expression:
1313 case Sema::PCC_Statement:
1314 case Sema::PCC_ForInit:
1315 case Sema::PCC_Condition:
1316 case Sema::PCC_RecoveryInFunction:
1317 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001318 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001319 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001320 break;
1321 }
1322}
1323
Douglas Gregorbca403c2010-01-13 23:51:12 +00001324static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1325static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1326static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001327 ResultBuilder &Results,
1328 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001329static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001330 ResultBuilder &Results,
1331 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001332static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001333 ResultBuilder &Results,
1334 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001335static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001336
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001337static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001338 CodeCompletionBuilder Builder(Results.getAllocator());
1339 Builder.AddTypedTextChunk("typedef");
1340 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1341 Builder.AddPlaceholderChunk("type");
1342 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1343 Builder.AddPlaceholderChunk("name");
1344 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001345}
1346
John McCallf312b1e2010-08-26 23:41:50 +00001347static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001348 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001349 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001350 case Sema::PCC_Namespace:
1351 case Sema::PCC_Class:
1352 case Sema::PCC_ObjCInstanceVariableList:
1353 case Sema::PCC_Template:
1354 case Sema::PCC_MemberTemplate:
1355 case Sema::PCC_Statement:
1356 case Sema::PCC_RecoveryInFunction:
1357 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001358 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001359 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001360 return true;
1361
John McCallf312b1e2010-08-26 23:41:50 +00001362 case Sema::PCC_Expression:
1363 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001364 return LangOpts.CPlusPlus;
1365
1366 case Sema::PCC_ObjCInterface:
1367 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001368 return false;
1369
John McCallf312b1e2010-08-26 23:41:50 +00001370 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001371 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001372 }
1373
1374 return false;
1375}
1376
Douglas Gregor8ca72082011-10-18 21:20:17 +00001377/// \brief Retrieve a printing policy suitable for code completion.
1378static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1379 PrintingPolicy Policy = S.getPrintingPolicy();
1380 Policy.AnonymousTagLocations = false;
1381 Policy.SuppressStrongLifetime = true;
Douglas Gregor25270b62011-11-03 00:16:13 +00001382 Policy.SuppressUnwrittenScope = true;
Douglas Gregor8ca72082011-10-18 21:20:17 +00001383 return Policy;
1384}
1385
1386/// \brief Retrieve the string representation of the given type as a string
1387/// that has the appropriate lifetime for code completion.
1388///
1389/// This routine provides a fast path where we provide constant strings for
1390/// common type names.
1391static const char *GetCompletionTypeString(QualType T,
1392 ASTContext &Context,
1393 const PrintingPolicy &Policy,
1394 CodeCompletionAllocator &Allocator) {
1395 if (!T.getLocalQualifiers()) {
1396 // Built-in type names are constant strings.
1397 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1398 return BT->getName(Policy);
1399
1400 // Anonymous tag types are constant strings.
1401 if (const TagType *TagT = dyn_cast<TagType>(T))
1402 if (TagDecl *Tag = TagT->getDecl())
1403 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
1404 switch (Tag->getTagKind()) {
1405 case TTK_Struct: return "struct <anonymous>";
1406 case TTK_Class: return "class <anonymous>";
1407 case TTK_Union: return "union <anonymous>";
1408 case TTK_Enum: return "enum <anonymous>";
1409 }
1410 }
1411 }
1412
1413 // Slow path: format the type as a string.
1414 std::string Result;
1415 T.getAsStringInternal(Result, Policy);
1416 return Allocator.CopyString(Result);
1417}
1418
Douglas Gregor01dfea02010-01-10 23:08:15 +00001419/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001420static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001421 Scope *S,
1422 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001423 ResultBuilder &Results) {
Douglas Gregor8ca72082011-10-18 21:20:17 +00001424 CodeCompletionAllocator &Allocator = Results.getAllocator();
1425 CodeCompletionBuilder Builder(Allocator);
1426 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
Douglas Gregor218937c2011-02-01 19:23:04 +00001427
John McCall0a2c5e22010-08-25 06:19:51 +00001428 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001429 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001430 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001431 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001432 if (Results.includeCodePatterns()) {
1433 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001434 Builder.AddTypedTextChunk("namespace");
1435 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1436 Builder.AddPlaceholderChunk("identifier");
1437 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1438 Builder.AddPlaceholderChunk("declarations");
1439 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1440 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1441 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001442 }
1443
Douglas Gregor01dfea02010-01-10 23:08:15 +00001444 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001445 Builder.AddTypedTextChunk("namespace");
1446 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1447 Builder.AddPlaceholderChunk("name");
1448 Builder.AddChunk(CodeCompletionString::CK_Equal);
1449 Builder.AddPlaceholderChunk("namespace");
1450 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001451
1452 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001453 Builder.AddTypedTextChunk("using");
1454 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1455 Builder.AddTextChunk("namespace");
1456 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1457 Builder.AddPlaceholderChunk("identifier");
1458 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001459
1460 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001461 Builder.AddTypedTextChunk("asm");
1462 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1463 Builder.AddPlaceholderChunk("string-literal");
1464 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1465 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001466
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001467 if (Results.includeCodePatterns()) {
1468 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001469 Builder.AddTypedTextChunk("template");
1470 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1471 Builder.AddPlaceholderChunk("declaration");
1472 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001473 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001474 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001475
1476 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001477 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001478
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001479 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001480 // Fall through
1481
John McCallf312b1e2010-08-26 23:41:50 +00001482 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001483 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001484 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001485 Builder.AddTypedTextChunk("using");
1486 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1487 Builder.AddPlaceholderChunk("qualifier");
1488 Builder.AddTextChunk("::");
1489 Builder.AddPlaceholderChunk("name");
1490 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001491
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001492 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001493 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001494 Builder.AddTypedTextChunk("using");
1495 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1496 Builder.AddTextChunk("typename");
1497 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1498 Builder.AddPlaceholderChunk("qualifier");
1499 Builder.AddTextChunk("::");
1500 Builder.AddPlaceholderChunk("name");
1501 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001502 }
1503
John McCallf312b1e2010-08-26 23:41:50 +00001504 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001505 AddTypedefResult(Results);
1506
Douglas Gregor01dfea02010-01-10 23:08:15 +00001507 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001508 Builder.AddTypedTextChunk("public");
1509 Builder.AddChunk(CodeCompletionString::CK_Colon);
1510 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001511
1512 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001513 Builder.AddTypedTextChunk("protected");
1514 Builder.AddChunk(CodeCompletionString::CK_Colon);
1515 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001516
1517 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001518 Builder.AddTypedTextChunk("private");
1519 Builder.AddChunk(CodeCompletionString::CK_Colon);
1520 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001521 }
1522 }
1523 // Fall through
1524
John McCallf312b1e2010-08-26 23:41:50 +00001525 case Sema::PCC_Template:
1526 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001527 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001528 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001529 Builder.AddTypedTextChunk("template");
1530 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1531 Builder.AddPlaceholderChunk("parameters");
1532 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1533 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001534 }
1535
Douglas Gregorbca403c2010-01-13 23:51:12 +00001536 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1537 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001538 break;
1539
John McCallf312b1e2010-08-26 23:41:50 +00001540 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001541 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1542 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1543 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001544 break;
1545
John McCallf312b1e2010-08-26 23:41:50 +00001546 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001547 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1548 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1549 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001550 break;
1551
John McCallf312b1e2010-08-26 23:41:50 +00001552 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001553 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001554 break;
1555
John McCallf312b1e2010-08-26 23:41:50 +00001556 case Sema::PCC_RecoveryInFunction:
1557 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001558 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001559
Douglas Gregorec3310a2011-04-12 02:47:21 +00001560 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1561 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001562 Builder.AddTypedTextChunk("try");
1563 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1564 Builder.AddPlaceholderChunk("statements");
1565 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1566 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1567 Builder.AddTextChunk("catch");
1568 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1569 Builder.AddPlaceholderChunk("declaration");
1570 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1571 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1572 Builder.AddPlaceholderChunk("statements");
1573 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1574 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1575 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001576 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001577 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001578 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001579
Douglas Gregord8e8a582010-05-25 21:41:55 +00001580 if (Results.includeCodePatterns()) {
1581 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001582 Builder.AddTypedTextChunk("if");
1583 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001584 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001585 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001586 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001587 Builder.AddPlaceholderChunk("expression");
1588 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1589 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1590 Builder.AddPlaceholderChunk("statements");
1591 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1592 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1593 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001594
Douglas Gregord8e8a582010-05-25 21:41:55 +00001595 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001596 Builder.AddTypedTextChunk("switch");
1597 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001598 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001599 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001600 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001601 Builder.AddPlaceholderChunk("expression");
1602 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1603 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1604 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1605 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1606 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001607 }
1608
Douglas Gregor01dfea02010-01-10 23:08:15 +00001609 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001610 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001611 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001612 Builder.AddTypedTextChunk("case");
1613 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1614 Builder.AddPlaceholderChunk("expression");
1615 Builder.AddChunk(CodeCompletionString::CK_Colon);
1616 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001617
1618 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001619 Builder.AddTypedTextChunk("default");
1620 Builder.AddChunk(CodeCompletionString::CK_Colon);
1621 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001622 }
1623
Douglas Gregord8e8a582010-05-25 21:41:55 +00001624 if (Results.includeCodePatterns()) {
1625 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001626 Builder.AddTypedTextChunk("while");
1627 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001628 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001629 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001630 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001631 Builder.AddPlaceholderChunk("expression");
1632 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1633 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1634 Builder.AddPlaceholderChunk("statements");
1635 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1636 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1637 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001638
1639 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001640 Builder.AddTypedTextChunk("do");
1641 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1642 Builder.AddPlaceholderChunk("statements");
1643 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1644 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1645 Builder.AddTextChunk("while");
1646 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1647 Builder.AddPlaceholderChunk("expression");
1648 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1649 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001650
Douglas Gregord8e8a582010-05-25 21:41:55 +00001651 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001652 Builder.AddTypedTextChunk("for");
1653 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001654 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001655 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001656 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001657 Builder.AddPlaceholderChunk("init-expression");
1658 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1659 Builder.AddPlaceholderChunk("condition");
1660 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1661 Builder.AddPlaceholderChunk("inc-expression");
1662 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1663 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1664 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1665 Builder.AddPlaceholderChunk("statements");
1666 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1667 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1668 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001669 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001670
1671 if (S->getContinueParent()) {
1672 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001673 Builder.AddTypedTextChunk("continue");
1674 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001675 }
1676
1677 if (S->getBreakParent()) {
1678 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001679 Builder.AddTypedTextChunk("break");
1680 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001681 }
1682
1683 // "return expression ;" or "return ;", depending on whether we
1684 // know the function is void or not.
1685 bool isVoid = false;
1686 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1687 isVoid = Function->getResultType()->isVoidType();
1688 else if (ObjCMethodDecl *Method
1689 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1690 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001691 else if (SemaRef.getCurBlock() &&
1692 !SemaRef.getCurBlock()->ReturnType.isNull())
1693 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001694 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001695 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001696 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1697 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001698 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001699 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001700
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001701 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001702 Builder.AddTypedTextChunk("goto");
1703 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1704 Builder.AddPlaceholderChunk("label");
1705 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001706
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001707 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001708 Builder.AddTypedTextChunk("using");
1709 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1710 Builder.AddTextChunk("namespace");
1711 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1712 Builder.AddPlaceholderChunk("identifier");
1713 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001714 }
1715
1716 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001717 case Sema::PCC_ForInit:
1718 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001719 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001720 // Fall through: conditions and statements can have expressions.
1721
Douglas Gregor02688102010-09-14 23:59:36 +00001722 case Sema::PCC_ParenthesizedExpression:
John McCallf85e1932011-06-15 23:02:42 +00001723 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1724 CCC == Sema::PCC_ParenthesizedExpression) {
1725 // (__bridge <type>)<expression>
1726 Builder.AddTypedTextChunk("__bridge");
1727 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1728 Builder.AddPlaceholderChunk("type");
1729 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1730 Builder.AddPlaceholderChunk("expression");
1731 Results.AddResult(Result(Builder.TakeString()));
1732
1733 // (__bridge_transfer <Objective-C type>)<expression>
1734 Builder.AddTypedTextChunk("__bridge_transfer");
1735 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1736 Builder.AddPlaceholderChunk("Objective-C type");
1737 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1738 Builder.AddPlaceholderChunk("expression");
1739 Results.AddResult(Result(Builder.TakeString()));
1740
1741 // (__bridge_retained <CF type>)<expression>
1742 Builder.AddTypedTextChunk("__bridge_retained");
1743 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1744 Builder.AddPlaceholderChunk("CF type");
1745 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1746 Builder.AddPlaceholderChunk("expression");
1747 Results.AddResult(Result(Builder.TakeString()));
1748 }
1749 // Fall through
1750
John McCallf312b1e2010-08-26 23:41:50 +00001751 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001752 if (SemaRef.getLangOptions().CPlusPlus) {
1753 // 'this', if we're in a non-static member function.
Douglas Gregor8ca72082011-10-18 21:20:17 +00001754 QualType ThisTy = SemaRef.getCurrentThisType(false);
1755 if (!ThisTy.isNull()) {
1756 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1757 SemaRef.Context,
1758 Policy,
1759 Allocator));
1760 Builder.AddTypedTextChunk("this");
1761 Results.AddResult(Result(Builder.TakeString()));
1762 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001763
Douglas Gregor8ca72082011-10-18 21:20:17 +00001764 // true
1765 Builder.AddResultTypeChunk("bool");
1766 Builder.AddTypedTextChunk("true");
1767 Results.AddResult(Result(Builder.TakeString()));
1768
1769 // false
1770 Builder.AddResultTypeChunk("bool");
1771 Builder.AddTypedTextChunk("false");
1772 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001773
Douglas Gregorec3310a2011-04-12 02:47:21 +00001774 if (SemaRef.getLangOptions().RTTI) {
1775 // dynamic_cast < type-id > ( expression )
1776 Builder.AddTypedTextChunk("dynamic_cast");
1777 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1778 Builder.AddPlaceholderChunk("type");
1779 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1780 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1781 Builder.AddPlaceholderChunk("expression");
1782 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1783 Results.AddResult(Result(Builder.TakeString()));
1784 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001785
1786 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001787 Builder.AddTypedTextChunk("static_cast");
1788 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1789 Builder.AddPlaceholderChunk("type");
1790 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1791 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1792 Builder.AddPlaceholderChunk("expression");
1793 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1794 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001795
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001796 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001797 Builder.AddTypedTextChunk("reinterpret_cast");
1798 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1799 Builder.AddPlaceholderChunk("type");
1800 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1801 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1802 Builder.AddPlaceholderChunk("expression");
1803 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1804 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001805
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001806 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001807 Builder.AddTypedTextChunk("const_cast");
1808 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1809 Builder.AddPlaceholderChunk("type");
1810 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1811 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1812 Builder.AddPlaceholderChunk("expression");
1813 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1814 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001815
Douglas Gregorec3310a2011-04-12 02:47:21 +00001816 if (SemaRef.getLangOptions().RTTI) {
1817 // typeid ( expression-or-type )
Douglas Gregor8ca72082011-10-18 21:20:17 +00001818 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001819 Builder.AddTypedTextChunk("typeid");
1820 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1821 Builder.AddPlaceholderChunk("expression-or-type");
1822 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1823 Results.AddResult(Result(Builder.TakeString()));
1824 }
1825
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001826 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001827 Builder.AddTypedTextChunk("new");
1828 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1829 Builder.AddPlaceholderChunk("type");
1830 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1831 Builder.AddPlaceholderChunk("expressions");
1832 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1833 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001834
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001835 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001836 Builder.AddTypedTextChunk("new");
1837 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1838 Builder.AddPlaceholderChunk("type");
1839 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1840 Builder.AddPlaceholderChunk("size");
1841 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1842 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1843 Builder.AddPlaceholderChunk("expressions");
1844 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1845 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001846
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001847 // delete expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001848 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001849 Builder.AddTypedTextChunk("delete");
1850 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1851 Builder.AddPlaceholderChunk("expression");
1852 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001853
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001854 // delete [] expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001855 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001856 Builder.AddTypedTextChunk("delete");
1857 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1858 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1859 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1860 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1861 Builder.AddPlaceholderChunk("expression");
1862 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001863
Douglas Gregorec3310a2011-04-12 02:47:21 +00001864 if (SemaRef.getLangOptions().CXXExceptions) {
1865 // throw expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001866 Builder.AddResultTypeChunk("void");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001867 Builder.AddTypedTextChunk("throw");
1868 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1869 Builder.AddPlaceholderChunk("expression");
1870 Results.AddResult(Result(Builder.TakeString()));
1871 }
Douglas Gregora50216c2011-10-18 16:29:03 +00001872
Douglas Gregor12e13132010-05-26 22:00:08 +00001873 // FIXME: Rethrow?
Douglas Gregora50216c2011-10-18 16:29:03 +00001874
1875 if (SemaRef.getLangOptions().CPlusPlus0x) {
1876 // nullptr
Douglas Gregor8ca72082011-10-18 21:20:17 +00001877 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001878 Builder.AddTypedTextChunk("nullptr");
1879 Results.AddResult(Result(Builder.TakeString()));
1880
1881 // alignof
Douglas Gregor8ca72082011-10-18 21:20:17 +00001882 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001883 Builder.AddTypedTextChunk("alignof");
1884 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1885 Builder.AddPlaceholderChunk("type");
1886 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1887 Results.AddResult(Result(Builder.TakeString()));
1888
1889 // noexcept
Douglas Gregor8ca72082011-10-18 21:20:17 +00001890 Builder.AddResultTypeChunk("bool");
Douglas Gregora50216c2011-10-18 16:29:03 +00001891 Builder.AddTypedTextChunk("noexcept");
1892 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1893 Builder.AddPlaceholderChunk("expression");
1894 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1895 Results.AddResult(Result(Builder.TakeString()));
1896
1897 // sizeof... expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001898 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001899 Builder.AddTypedTextChunk("sizeof...");
1900 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1901 Builder.AddPlaceholderChunk("parameter-pack");
1902 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1903 Results.AddResult(Result(Builder.TakeString()));
1904 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001905 }
1906
1907 if (SemaRef.getLangOptions().ObjC1) {
1908 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001909 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1910 // The interface can be NULL.
1911 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregor8ca72082011-10-18 21:20:17 +00001912 if (ID->getSuperClass()) {
1913 std::string SuperType;
1914 SuperType = ID->getSuperClass()->getNameAsString();
1915 if (Method->isInstanceMethod())
1916 SuperType += " *";
1917
1918 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
1919 Builder.AddTypedTextChunk("super");
1920 Results.AddResult(Result(Builder.TakeString()));
1921 }
Ted Kremenek681e2562010-05-31 21:43:10 +00001922 }
1923
Douglas Gregorbca403c2010-01-13 23:51:12 +00001924 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001925 }
1926
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001927 // sizeof expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001928 Builder.AddResultTypeChunk("size_t");
Douglas Gregor218937c2011-02-01 19:23:04 +00001929 Builder.AddTypedTextChunk("sizeof");
1930 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1931 Builder.AddPlaceholderChunk("expression-or-type");
1932 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1933 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001934 break;
1935 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001936
John McCallf312b1e2010-08-26 23:41:50 +00001937 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001938 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001939 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001940 }
1941
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001942 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1943 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001944
John McCallf312b1e2010-08-26 23:41:50 +00001945 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001946 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001947}
1948
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001949/// \brief If the given declaration has an associated type, add it as a result
1950/// type chunk.
1951static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001952 const PrintingPolicy &Policy,
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001953 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001954 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001955 if (!ND)
1956 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001957
1958 // Skip constructors and conversion functions, which have their return types
1959 // built into their names.
1960 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1961 return;
1962
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001963 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001964 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001965 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1966 T = Function->getResultType();
1967 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1968 T = Method->getResultType();
1969 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1970 T = FunTmpl->getTemplatedDecl()->getResultType();
1971 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1972 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1973 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1974 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00001975 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001976 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001977 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001978 T = Property->getType();
1979
1980 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1981 return;
1982
Douglas Gregor8987b232011-09-27 23:30:47 +00001983 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00001984 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001985}
1986
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001987static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001988 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001989 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1990 if (Sentinel->getSentinel() == 0) {
1991 if (Context.getLangOptions().ObjC1 &&
1992 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001993 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001994 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001995 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001996 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001997 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001998 }
1999}
2000
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002001static void appendWithSpace(std::string &Result, StringRef Text) {
2002 if (!Result.empty())
2003 Result += ' ';
2004 Result += Text.str();
2005}
2006static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
2007 std::string Result;
2008 if (ObjCQuals & Decl::OBJC_TQ_In)
2009 appendWithSpace(Result, "in");
2010 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2011 appendWithSpace(Result, "inout");
2012 else if (ObjCQuals & Decl::OBJC_TQ_Out)
2013 appendWithSpace(Result, "out");
2014 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2015 appendWithSpace(Result, "bycopy");
2016 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2017 appendWithSpace(Result, "byref");
2018 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2019 appendWithSpace(Result, "oneway");
2020 return Result;
2021}
2022
Douglas Gregor83482d12010-08-24 16:15:59 +00002023static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002024 const PrintingPolicy &Policy,
Douglas Gregoraba48082010-08-29 19:47:46 +00002025 ParmVarDecl *Param,
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002026 bool SuppressName = false,
2027 bool SuppressBlock = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00002028 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2029 if (Param->getType()->isDependentType() ||
2030 !Param->getType()->isBlockPointerType()) {
2031 // The argument for a dependent or non-block parameter is a placeholder
2032 // containing that parameter's type.
2033 std::string Result;
2034
Douglas Gregoraba48082010-08-29 19:47:46 +00002035 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002036 Result = Param->getIdentifier()->getName();
2037
John McCallf85e1932011-06-15 23:02:42 +00002038 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002039
2040 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002041 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2042 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00002043 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002044 Result += Param->getIdentifier()->getName();
2045 }
2046 return Result;
2047 }
2048
2049 // The argument for a block pointer parameter is a block literal with
2050 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00002051 FunctionTypeLoc *Block = 0;
2052 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00002053 TypeLoc TL;
2054 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2055 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2056 while (true) {
2057 // Look through typedefs.
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002058 if (!SuppressBlock) {
2059 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
2060 if (TypeSourceInfo *InnerTSInfo
2061 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
2062 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2063 continue;
2064 }
2065 }
2066
2067 // Look through qualified types
2068 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2069 TL = QualifiedTL->getUnqualifiedLoc();
Douglas Gregor83482d12010-08-24 16:15:59 +00002070 continue;
2071 }
2072 }
2073
Douglas Gregor83482d12010-08-24 16:15:59 +00002074 // Try to get the function prototype behind the block pointer type,
2075 // then we're done.
2076 if (BlockPointerTypeLoc *BlockPtr
2077 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002078 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002079 Block = dyn_cast<FunctionTypeLoc>(&TL);
2080 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002081 }
2082 break;
2083 }
2084 }
2085
2086 if (!Block) {
2087 // We were unable to find a FunctionProtoTypeLoc with parameter names
2088 // for the block; just use the parameter type as a placeholder.
2089 std::string Result;
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002090 if (!ObjCMethodParam && Param->getIdentifier())
2091 Result = Param->getIdentifier()->getName();
2092
John McCallf85e1932011-06-15 23:02:42 +00002093 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002094
2095 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002096 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2097 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002098 if (Param->getIdentifier())
2099 Result += Param->getIdentifier()->getName();
2100 }
2101
2102 return Result;
2103 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002104
Douglas Gregor83482d12010-08-24 16:15:59 +00002105 // We have the function prototype behind the block pointer type, as it was
2106 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002107 std::string Result;
2108 QualType ResultType = Block->getTypePtr()->getResultType();
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002109 if (!ResultType->isVoidType() || SuppressBlock)
John McCallf85e1932011-06-15 23:02:42 +00002110 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002111
2112 // Format the parameter list.
2113 std::string Params;
Douglas Gregor830072c2011-02-15 22:37:09 +00002114 if (!BlockProto || Block->getNumArgs() == 0) {
2115 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002116 Params = "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002117 else
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002118 Params = "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002119 } else {
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002120 Params += "(";
Douglas Gregor38276252010-09-08 22:47:51 +00002121 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2122 if (I)
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002123 Params += ", ";
2124 Params += FormatFunctionParameter(Context, Policy, Block->getArg(I),
2125 /*SuppressName=*/false,
2126 /*SuppressBlock=*/true);
Douglas Gregor38276252010-09-08 22:47:51 +00002127
Douglas Gregor830072c2011-02-15 22:37:09 +00002128 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002129 Params += ", ...";
Douglas Gregor38276252010-09-08 22:47:51 +00002130 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002131 Params += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002132 }
Douglas Gregor38276252010-09-08 22:47:51 +00002133
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002134 if (SuppressBlock) {
2135 // Format as a parameter.
2136 Result = Result + " (^";
2137 if (Param->getIdentifier())
2138 Result += Param->getIdentifier()->getName();
2139 Result += ")";
2140 Result += Params;
2141 } else {
2142 // Format as a block literal argument.
2143 Result = '^' + Result;
2144 Result += Params;
2145
2146 if (Param->getIdentifier())
2147 Result += Param->getIdentifier()->getName();
2148 }
2149
Douglas Gregor83482d12010-08-24 16:15:59 +00002150 return Result;
2151}
2152
Douglas Gregor86d9a522009-09-21 16:56:56 +00002153/// \brief Add function parameter chunks to the given code completion string.
2154static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002155 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002156 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002157 CodeCompletionBuilder &Result,
2158 unsigned Start = 0,
2159 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002160 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002161 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002162
Douglas Gregor218937c2011-02-01 19:23:04 +00002163 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002164 ParmVarDecl *Param = Function->getParamDecl(P);
2165
Douglas Gregor218937c2011-02-01 19:23:04 +00002166 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002167 // When we see an optional default argument, put that argument and
2168 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002169 CodeCompletionBuilder Opt(Result.getAllocator());
2170 if (!FirstParameter)
2171 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002172 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregor218937c2011-02-01 19:23:04 +00002173 Result.AddOptionalChunk(Opt.TakeString());
2174 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002175 }
2176
Douglas Gregor218937c2011-02-01 19:23:04 +00002177 if (FirstParameter)
2178 FirstParameter = false;
2179 else
2180 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2181
2182 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002183
2184 // Format the placeholder string.
Douglas Gregor8987b232011-09-27 23:30:47 +00002185 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2186 Param);
Douglas Gregor83482d12010-08-24 16:15:59 +00002187
Douglas Gregore17794f2010-08-31 05:13:43 +00002188 if (Function->isVariadic() && P == N - 1)
2189 PlaceholderStr += ", ...";
2190
Douglas Gregor86d9a522009-09-21 16:56:56 +00002191 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002192 Result.AddPlaceholderChunk(
2193 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002194 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002195
2196 if (const FunctionProtoType *Proto
2197 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002198 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002199 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002200 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002201
Douglas Gregor218937c2011-02-01 19:23:04 +00002202 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002203 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002204}
2205
2206/// \brief Add template parameter chunks to the given code completion string.
2207static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002208 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002209 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002210 CodeCompletionBuilder &Result,
2211 unsigned MaxParameters = 0,
2212 unsigned Start = 0,
2213 bool InDefaultArg = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002214 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002215 bool FirstParameter = true;
2216
2217 TemplateParameterList *Params = Template->getTemplateParameters();
2218 TemplateParameterList::iterator PEnd = Params->end();
2219 if (MaxParameters)
2220 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002221 for (TemplateParameterList::iterator P = Params->begin() + Start;
2222 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002223 bool HasDefaultArg = false;
2224 std::string PlaceholderStr;
2225 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2226 if (TTP->wasDeclaredWithTypename())
2227 PlaceholderStr = "typename";
2228 else
2229 PlaceholderStr = "class";
2230
2231 if (TTP->getIdentifier()) {
2232 PlaceholderStr += ' ';
2233 PlaceholderStr += TTP->getIdentifier()->getName();
2234 }
2235
2236 HasDefaultArg = TTP->hasDefaultArgument();
2237 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002238 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002239 if (NTTP->getIdentifier())
2240 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002241 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002242 HasDefaultArg = NTTP->hasDefaultArgument();
2243 } else {
2244 assert(isa<TemplateTemplateParmDecl>(*P));
2245 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2246
2247 // Since putting the template argument list into the placeholder would
2248 // be very, very long, we just use an abbreviation.
2249 PlaceholderStr = "template<...> class";
2250 if (TTP->getIdentifier()) {
2251 PlaceholderStr += ' ';
2252 PlaceholderStr += TTP->getIdentifier()->getName();
2253 }
2254
2255 HasDefaultArg = TTP->hasDefaultArgument();
2256 }
2257
Douglas Gregor218937c2011-02-01 19:23:04 +00002258 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002259 // When we see an optional default argument, put that argument and
2260 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002261 CodeCompletionBuilder Opt(Result.getAllocator());
2262 if (!FirstParameter)
2263 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002264 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregor218937c2011-02-01 19:23:04 +00002265 P - Params->begin(), true);
2266 Result.AddOptionalChunk(Opt.TakeString());
2267 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002268 }
2269
Douglas Gregor218937c2011-02-01 19:23:04 +00002270 InDefaultArg = false;
2271
Douglas Gregor86d9a522009-09-21 16:56:56 +00002272 if (FirstParameter)
2273 FirstParameter = false;
2274 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002275 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002276
2277 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002278 Result.AddPlaceholderChunk(
2279 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002280 }
2281}
2282
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002283/// \brief Add a qualifier to the given code-completion string, if the
2284/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002285static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002286AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002287 NestedNameSpecifier *Qualifier,
2288 bool QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002289 ASTContext &Context,
2290 const PrintingPolicy &Policy) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002291 if (!Qualifier)
2292 return;
2293
2294 std::string PrintedNNS;
2295 {
2296 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor8987b232011-09-27 23:30:47 +00002297 Qualifier->print(OS, Policy);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002298 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002299 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002300 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002301 else
Douglas Gregordae68752011-02-01 22:57:45 +00002302 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002303}
2304
Douglas Gregor218937c2011-02-01 19:23:04 +00002305static void
2306AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2307 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002308 const FunctionProtoType *Proto
2309 = Function->getType()->getAs<FunctionProtoType>();
2310 if (!Proto || !Proto->getTypeQuals())
2311 return;
2312
Douglas Gregora63f6de2011-02-01 21:15:40 +00002313 // FIXME: Add ref-qualifier!
2314
2315 // Handle single qualifiers without copying
2316 if (Proto->getTypeQuals() == Qualifiers::Const) {
2317 Result.AddInformativeChunk(" const");
2318 return;
2319 }
2320
2321 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2322 Result.AddInformativeChunk(" volatile");
2323 return;
2324 }
2325
2326 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2327 Result.AddInformativeChunk(" restrict");
2328 return;
2329 }
2330
2331 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002332 std::string QualsStr;
2333 if (Proto->getTypeQuals() & Qualifiers::Const)
2334 QualsStr += " const";
2335 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2336 QualsStr += " volatile";
2337 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2338 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002339 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002340}
2341
Douglas Gregor6f942b22010-09-21 16:06:22 +00002342/// \brief Add the name of the given declaration
Douglas Gregor8987b232011-09-27 23:30:47 +00002343static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2344 NamedDecl *ND, CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002345 typedef CodeCompletionString::Chunk Chunk;
2346
2347 DeclarationName Name = ND->getDeclName();
2348 if (!Name)
2349 return;
2350
2351 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002352 case DeclarationName::CXXOperatorName: {
2353 const char *OperatorName = 0;
2354 switch (Name.getCXXOverloadedOperator()) {
2355 case OO_None:
2356 case OO_Conditional:
2357 case NUM_OVERLOADED_OPERATORS:
2358 OperatorName = "operator";
2359 break;
2360
2361#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2362 case OO_##Name: OperatorName = "operator" Spelling; break;
2363#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2364#include "clang/Basic/OperatorKinds.def"
2365
2366 case OO_New: OperatorName = "operator new"; break;
2367 case OO_Delete: OperatorName = "operator delete"; break;
2368 case OO_Array_New: OperatorName = "operator new[]"; break;
2369 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2370 case OO_Call: OperatorName = "operator()"; break;
2371 case OO_Subscript: OperatorName = "operator[]"; break;
2372 }
2373 Result.AddTypedTextChunk(OperatorName);
2374 break;
2375 }
2376
Douglas Gregor6f942b22010-09-21 16:06:22 +00002377 case DeclarationName::Identifier:
2378 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002379 case DeclarationName::CXXDestructorName:
2380 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002381 Result.AddTypedTextChunk(
2382 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002383 break;
2384
2385 case DeclarationName::CXXUsingDirective:
2386 case DeclarationName::ObjCZeroArgSelector:
2387 case DeclarationName::ObjCOneArgSelector:
2388 case DeclarationName::ObjCMultiArgSelector:
2389 break;
2390
2391 case DeclarationName::CXXConstructorName: {
2392 CXXRecordDecl *Record = 0;
2393 QualType Ty = Name.getCXXNameType();
2394 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2395 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2396 else if (const InjectedClassNameType *InjectedTy
2397 = Ty->getAs<InjectedClassNameType>())
2398 Record = InjectedTy->getDecl();
2399 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002400 Result.AddTypedTextChunk(
2401 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002402 break;
2403 }
2404
Douglas Gregordae68752011-02-01 22:57:45 +00002405 Result.AddTypedTextChunk(
2406 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002407 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002408 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002409 AddTemplateParameterChunks(Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002410 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002411 }
2412 break;
2413 }
2414 }
2415}
2416
Douglas Gregor86d9a522009-09-21 16:56:56 +00002417/// \brief If possible, create a new code completion string for the given
2418/// result.
2419///
2420/// \returns Either a new, heap-allocated code completion string describing
2421/// how to use this result, or NULL to indicate that the string or name of the
2422/// result is all that is needed.
2423CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002424CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002425 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002426 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002427 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002428
Douglas Gregor8987b232011-09-27 23:30:47 +00002429 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregor218937c2011-02-01 19:23:04 +00002430 if (Kind == RK_Pattern) {
2431 Pattern->Priority = Priority;
2432 Pattern->Availability = Availability;
2433 return Pattern;
2434 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002435
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002436 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002437 Result.AddTypedTextChunk(Keyword);
2438 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002439 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002440
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002441 if (Kind == RK_Macro) {
2442 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002443 assert(MI && "Not a macro?");
2444
Douglas Gregordae68752011-02-01 22:57:45 +00002445 Result.AddTypedTextChunk(
2446 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002447
2448 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002449 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002450
2451 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002452 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregore4244702011-07-30 08:17:44 +00002453 bool CombineVariadicArgument = false;
2454 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2455 if (MI->isVariadic() && AEnd - A > 1) {
2456 AEnd -= 2;
2457 CombineVariadicArgument = true;
2458 }
2459 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002460 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002461 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002462
Douglas Gregore4244702011-07-30 08:17:44 +00002463 if (!MI->isVariadic() || A + 1 != AEnd) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002464 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002465 Result.AddPlaceholderChunk(
2466 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002467 continue;
2468 }
2469
Douglas Gregore4244702011-07-30 08:17:44 +00002470 // Variadic argument; cope with the difference between GNU and C99
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002471 // variadic macros, providing a single placeholder for the rest of the
2472 // arguments.
2473 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002474 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002475 else {
2476 std::string Arg = (*A)->getName();
2477 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002478 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002479 }
2480 }
Douglas Gregore4244702011-07-30 08:17:44 +00002481
2482 if (CombineVariadicArgument) {
2483 // Handle the next-to-last argument, combining it with the variadic
2484 // argument.
2485 std::string LastArg = (*A)->getName();
2486 ++A;
2487 if ((*A)->isStr("__VA_ARGS__"))
2488 LastArg += ", ...";
2489 else
2490 LastArg += ", " + (*A)->getName().str() + "...";
2491 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(LastArg));
2492 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002493 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2494 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002495 }
2496
Douglas Gregord8e8a582010-05-25 21:41:55 +00002497 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002498 NamedDecl *ND = Declaration;
2499
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002500 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002501 Result.AddTypedTextChunk(
2502 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002503 Result.AddTextChunk("::");
2504 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002505 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00002506
2507 for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2508 if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2509 Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2510 }
2511 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002512
Douglas Gregor8987b232011-09-27 23:30:47 +00002513 AddResultTypeChunk(S.Context, Policy, ND, Result);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002514
Douglas Gregor86d9a522009-09-21 16:56:56 +00002515 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002516 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002517 S.Context, Policy);
2518 AddTypedNameChunk(S.Context, Policy, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002519 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002520 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002521 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002522 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002523 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002524 }
2525
2526 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002527 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002528 S.Context, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002529 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor8987b232011-09-27 23:30:47 +00002530 AddTypedNameChunk(S.Context, Policy, Function, Result);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002531
Douglas Gregor86d9a522009-09-21 16:56:56 +00002532 // Figure out which template parameters are deduced (or have default
2533 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002534 SmallVector<bool, 16> Deduced;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002535 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2536 unsigned LastDeducibleArgument;
2537 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2538 --LastDeducibleArgument) {
2539 if (!Deduced[LastDeducibleArgument - 1]) {
2540 // C++0x: Figure out if the template argument has a default. If so,
2541 // the user doesn't need to type this argument.
2542 // FIXME: We need to abstract template parameters better!
2543 bool HasDefaultArg = false;
2544 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002545 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002546 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2547 HasDefaultArg = TTP->hasDefaultArgument();
2548 else if (NonTypeTemplateParmDecl *NTTP
2549 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2550 HasDefaultArg = NTTP->hasDefaultArgument();
2551 else {
2552 assert(isa<TemplateTemplateParmDecl>(Param));
2553 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002554 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002555 }
2556
2557 if (!HasDefaultArg)
2558 break;
2559 }
2560 }
2561
2562 if (LastDeducibleArgument) {
2563 // Some of the function template arguments cannot be deduced from a
2564 // function call, so we introduce an explicit template argument list
2565 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002566 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002567 AddTemplateParameterChunks(S.Context, Policy, FunTmpl, Result,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002568 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002569 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002570 }
2571
2572 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002573 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002574 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002575 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002576 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002577 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002578 }
2579
2580 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002581 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002582 S.Context, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002583 Result.AddTypedTextChunk(
2584 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002585 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002586 AddTemplateParameterChunks(S.Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002587 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2588 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002589 }
2590
Douglas Gregor9630eb62009-11-17 16:44:22 +00002591 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002592 Selector Sel = Method->getSelector();
2593 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002594 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002595 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002596 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002597 }
2598
Douglas Gregor813d8342011-02-18 22:29:55 +00002599 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002600 SelName += ':';
2601 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002602 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002603 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002604 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002605
2606 // If there is only one parameter, and we're past it, add an empty
2607 // typed-text chunk since there is nothing to type.
2608 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002609 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002610 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002611 unsigned Idx = 0;
2612 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2613 PEnd = Method->param_end();
2614 P != PEnd; (void)++P, ++Idx) {
2615 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002616 std::string Keyword;
2617 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002618 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002619 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002620 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002621 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002622 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002623 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002624 else
Douglas Gregordae68752011-02-01 22:57:45 +00002625 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002626 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002627
2628 // If we're before the starting parameter, skip the placeholder.
2629 if (Idx < StartParameter)
2630 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002631
2632 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002633
2634 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregor8987b232011-09-27 23:30:47 +00002635 Arg = FormatFunctionParameter(S.Context, Policy, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002636 else {
John McCallf85e1932011-06-15 23:02:42 +00002637 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002638 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2639 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002640 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002641 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002642 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002643 }
2644
Douglas Gregore17794f2010-08-31 05:13:43 +00002645 if (Method->isVariadic() && (P + 1) == PEnd)
2646 Arg += ", ...";
2647
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002648 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002649 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002650 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002651 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002652 else
Douglas Gregordae68752011-02-01 22:57:45 +00002653 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002654 }
2655
Douglas Gregor2a17af02009-12-23 00:21:46 +00002656 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002657 if (Method->param_size() == 0) {
2658 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002659 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002660 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002661 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002662 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002663 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002664 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002665
2666 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002667 }
2668
Douglas Gregor218937c2011-02-01 19:23:04 +00002669 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002670 }
2671
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002672 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002673 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002674 S.Context, Policy);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002675
Douglas Gregordae68752011-02-01 22:57:45 +00002676 Result.AddTypedTextChunk(
2677 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002678 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002679}
2680
Douglas Gregor86d802e2009-09-23 00:34:09 +00002681CodeCompletionString *
2682CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2683 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002684 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002685 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002686 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor8987b232011-09-27 23:30:47 +00002687 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCallf85e1932011-06-15 23:02:42 +00002688
Douglas Gregor218937c2011-02-01 19:23:04 +00002689 // FIXME: Set priority, availability appropriately.
2690 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002691 FunctionDecl *FDecl = getFunction();
Douglas Gregor8987b232011-09-27 23:30:47 +00002692 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002693 const FunctionProtoType *Proto
2694 = dyn_cast<FunctionProtoType>(getFunctionType());
2695 if (!FDecl && !Proto) {
2696 // Function without a prototype. Just give the return type and a
2697 // highlighted ellipsis.
2698 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002699 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
Douglas Gregor8987b232011-09-27 23:30:47 +00002700 S.Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002701 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002702 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2703 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2704 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2705 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002706 }
2707
2708 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002709 Result.AddTextChunk(
2710 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002711 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002712 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002713 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002714 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002715
Douglas Gregor218937c2011-02-01 19:23:04 +00002716 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002717 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2718 for (unsigned I = 0; I != NumParams; ++I) {
2719 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002720 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002721
2722 std::string ArgString;
2723 QualType ArgType;
2724
2725 if (FDecl) {
2726 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2727 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2728 } else {
2729 ArgType = Proto->getArgType(I);
2730 }
2731
John McCallf85e1932011-06-15 23:02:42 +00002732 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002733
2734 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002735 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002736 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002737 else
Douglas Gregordae68752011-02-01 22:57:45 +00002738 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002739 }
2740
2741 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002742 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002743 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002744 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002745 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002746 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002747 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002748 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002749
Douglas Gregor218937c2011-02-01 19:23:04 +00002750 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002751}
2752
Chris Lattner5f9e2722011-07-23 10:55:15 +00002753unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002754 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002755 bool PreferredTypeIsPointer) {
2756 unsigned Priority = CCP_Macro;
2757
Douglas Gregorb05496d2010-09-20 21:11:48 +00002758 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2759 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2760 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002761 Priority = CCP_Constant;
2762 if (PreferredTypeIsPointer)
2763 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002764 }
2765 // Treat "YES", "NO", "true", and "false" as constants.
2766 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2767 MacroName.equals("true") || MacroName.equals("false"))
2768 Priority = CCP_Constant;
2769 // Treat "bool" as a type.
2770 else if (MacroName.equals("bool"))
2771 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2772
Douglas Gregor1827e102010-08-16 16:18:59 +00002773
2774 return Priority;
2775}
2776
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002777CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2778 if (!D)
2779 return CXCursor_UnexposedDecl;
2780
2781 switch (D->getKind()) {
2782 case Decl::Enum: return CXCursor_EnumDecl;
2783 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2784 case Decl::Field: return CXCursor_FieldDecl;
2785 case Decl::Function:
2786 return CXCursor_FunctionDecl;
2787 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2788 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2789 case Decl::ObjCClass:
2790 // FIXME
2791 return CXCursor_UnexposedDecl;
2792 case Decl::ObjCForwardProtocol:
2793 // FIXME
2794 return CXCursor_UnexposedDecl;
2795 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2796 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2797 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2798 case Decl::ObjCMethod:
2799 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2800 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2801 case Decl::CXXMethod: return CXCursor_CXXMethod;
2802 case Decl::CXXConstructor: return CXCursor_Constructor;
2803 case Decl::CXXDestructor: return CXCursor_Destructor;
2804 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2805 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2806 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2807 case Decl::ParmVar: return CXCursor_ParmDecl;
2808 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002809 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002810 case Decl::Var: return CXCursor_VarDecl;
2811 case Decl::Namespace: return CXCursor_Namespace;
2812 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2813 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2814 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2815 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2816 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2817 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00002818 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002819 case Decl::ClassTemplatePartialSpecialization:
2820 return CXCursor_ClassTemplatePartialSpecialization;
2821 case Decl::UsingDirective: return CXCursor_UsingDirective;
2822
2823 case Decl::Using:
2824 case Decl::UnresolvedUsingValue:
2825 case Decl::UnresolvedUsingTypename:
2826 return CXCursor_UsingDeclaration;
2827
Douglas Gregor352697a2011-06-03 23:08:58 +00002828 case Decl::ObjCPropertyImpl:
2829 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2830 case ObjCPropertyImplDecl::Dynamic:
2831 return CXCursor_ObjCDynamicDecl;
2832
2833 case ObjCPropertyImplDecl::Synthesize:
2834 return CXCursor_ObjCSynthesizeDecl;
2835 }
2836 break;
2837
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002838 default:
2839 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2840 switch (TD->getTagKind()) {
2841 case TTK_Struct: return CXCursor_StructDecl;
2842 case TTK_Class: return CXCursor_ClassDecl;
2843 case TTK_Union: return CXCursor_UnionDecl;
2844 case TTK_Enum: return CXCursor_EnumDecl;
2845 }
2846 }
2847 }
2848
2849 return CXCursor_UnexposedDecl;
2850}
2851
Douglas Gregor590c7d52010-07-08 20:55:51 +00002852static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2853 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002854 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002855
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002856 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002857
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002858 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2859 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002860 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002861 Results.AddResult(Result(M->first,
2862 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002863 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002864 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002865 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002866
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002867 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002868
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002869}
2870
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002871static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2872 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002873 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002874
2875 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002876
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002877 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2878 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2879 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2880 Results.AddResult(Result("__func__", CCP_Constant));
2881 Results.ExitScope();
2882}
2883
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002884static void HandleCodeCompleteResults(Sema *S,
2885 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002886 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002887 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002888 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002889 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002890 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002891}
2892
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002893static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2894 Sema::ParserCompletionContext PCC) {
2895 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002896 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002897 return CodeCompletionContext::CCC_TopLevel;
2898
John McCallf312b1e2010-08-26 23:41:50 +00002899 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002900 return CodeCompletionContext::CCC_ClassStructUnion;
2901
John McCallf312b1e2010-08-26 23:41:50 +00002902 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002903 return CodeCompletionContext::CCC_ObjCInterface;
2904
John McCallf312b1e2010-08-26 23:41:50 +00002905 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002906 return CodeCompletionContext::CCC_ObjCImplementation;
2907
John McCallf312b1e2010-08-26 23:41:50 +00002908 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002909 return CodeCompletionContext::CCC_ObjCIvarList;
2910
John McCallf312b1e2010-08-26 23:41:50 +00002911 case Sema::PCC_Template:
2912 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002913 if (S.CurContext->isFileContext())
2914 return CodeCompletionContext::CCC_TopLevel;
2915 else if (S.CurContext->isRecord())
2916 return CodeCompletionContext::CCC_ClassStructUnion;
2917 else
2918 return CodeCompletionContext::CCC_Other;
2919
John McCallf312b1e2010-08-26 23:41:50 +00002920 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002921 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002922
John McCallf312b1e2010-08-26 23:41:50 +00002923 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002924 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2925 S.getLangOptions().ObjC1)
2926 return CodeCompletionContext::CCC_ParenthesizedExpression;
2927 else
2928 return CodeCompletionContext::CCC_Expression;
2929
2930 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002931 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002932 return CodeCompletionContext::CCC_Expression;
2933
John McCallf312b1e2010-08-26 23:41:50 +00002934 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002935 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002936
John McCallf312b1e2010-08-26 23:41:50 +00002937 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002938 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002939
2940 case Sema::PCC_ParenthesizedExpression:
2941 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002942
2943 case Sema::PCC_LocalDeclarationSpecifiers:
2944 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002945 }
2946
2947 return CodeCompletionContext::CCC_Other;
2948}
2949
Douglas Gregorf6961522010-08-27 21:18:54 +00002950/// \brief If we're in a C++ virtual member function, add completion results
2951/// that invoke the functions we override, since it's common to invoke the
2952/// overridden function as well as adding new functionality.
2953///
2954/// \param S The semantic analysis object for which we are generating results.
2955///
2956/// \param InContext This context in which the nested-name-specifier preceding
2957/// the code-completion point
2958static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2959 ResultBuilder &Results) {
2960 // Look through blocks.
2961 DeclContext *CurContext = S.CurContext;
2962 while (isa<BlockDecl>(CurContext))
2963 CurContext = CurContext->getParent();
2964
2965
2966 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2967 if (!Method || !Method->isVirtual())
2968 return;
2969
2970 // We need to have names for all of the parameters, if we're going to
2971 // generate a forwarding call.
2972 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2973 PEnd = Method->param_end();
2974 P != PEnd;
2975 ++P) {
2976 if (!(*P)->getDeclName())
2977 return;
2978 }
2979
Douglas Gregor8987b232011-09-27 23:30:47 +00002980 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorf6961522010-08-27 21:18:54 +00002981 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2982 MEnd = Method->end_overridden_methods();
2983 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002984 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002985 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2986 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2987 continue;
2988
2989 // If we need a nested-name-specifier, add one now.
2990 if (!InContext) {
2991 NestedNameSpecifier *NNS
2992 = getRequiredQualification(S.Context, CurContext,
2993 Overridden->getDeclContext());
2994 if (NNS) {
2995 std::string Str;
2996 llvm::raw_string_ostream OS(Str);
Douglas Gregor8987b232011-09-27 23:30:47 +00002997 NNS->print(OS, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002998 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002999 }
3000 } else if (!InContext->Equals(Overridden->getDeclContext()))
3001 continue;
3002
Douglas Gregordae68752011-02-01 22:57:45 +00003003 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003004 Overridden->getNameAsString()));
3005 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00003006 bool FirstParam = true;
3007 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3008 PEnd = Method->param_end();
3009 P != PEnd; ++P) {
3010 if (FirstParam)
3011 FirstParam = false;
3012 else
Douglas Gregor218937c2011-02-01 19:23:04 +00003013 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00003014
Douglas Gregordae68752011-02-01 22:57:45 +00003015 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003016 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003017 }
Douglas Gregor218937c2011-02-01 19:23:04 +00003018 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3019 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00003020 CCP_SuperCompletion,
3021 CXCursor_CXXMethod));
3022 Results.Ignore(Overridden);
3023 }
3024}
3025
Douglas Gregor01dfea02010-01-10 23:08:15 +00003026void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003027 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00003028 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003029 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003030 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00003031 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003032
Douglas Gregor01dfea02010-01-10 23:08:15 +00003033 // Determine how to filter results, e.g., so that the names of
3034 // values (functions, enumerators, function templates, etc.) are
3035 // only allowed where we can have an expression.
3036 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003037 case PCC_Namespace:
3038 case PCC_Class:
3039 case PCC_ObjCInterface:
3040 case PCC_ObjCImplementation:
3041 case PCC_ObjCInstanceVariableList:
3042 case PCC_Template:
3043 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00003044 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003045 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00003046 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3047 break;
3048
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003049 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00003050 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00003051 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003052 case PCC_ForInit:
3053 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00003054 if (WantTypesInContext(CompletionContext, getLangOptions()))
3055 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3056 else
3057 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00003058
3059 if (getLangOptions().CPlusPlus)
3060 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00003061 break;
Douglas Gregordc845342010-05-25 05:58:43 +00003062
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003063 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00003064 // Unfiltered
3065 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00003066 }
3067
Douglas Gregor3cdee122010-08-26 16:36:48 +00003068 // If we are in a C++ non-static member function, check the qualifiers on
3069 // the member function to filter/prioritize the results list.
3070 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3071 if (CurMethod->isInstance())
3072 Results.setObjectTypeQualifiers(
3073 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3074
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00003075 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003076 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3077 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003078
Douglas Gregorbca403c2010-01-13 23:51:12 +00003079 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003080 Results.ExitScope();
3081
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003082 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00003083 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00003084 case PCC_Expression:
3085 case PCC_Statement:
3086 case PCC_RecoveryInFunction:
3087 if (S->getFnParent())
3088 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3089 break;
3090
3091 case PCC_Namespace:
3092 case PCC_Class:
3093 case PCC_ObjCInterface:
3094 case PCC_ObjCImplementation:
3095 case PCC_ObjCInstanceVariableList:
3096 case PCC_Template:
3097 case PCC_MemberTemplate:
3098 case PCC_ForInit:
3099 case PCC_Condition:
3100 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003101 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003102 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003103 }
3104
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003105 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003106 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003107
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003108 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003109 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003110}
3111
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003112static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3113 ParsedType Receiver,
3114 IdentifierInfo **SelIdents,
3115 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003116 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003117 bool IsSuper,
3118 ResultBuilder &Results);
3119
3120void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3121 bool AllowNonIdentifiers,
3122 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003123 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003124 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003125 AllowNestedNameSpecifiers
3126 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3127 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003128 Results.EnterNewScope();
3129
3130 // Type qualifiers can come after names.
3131 Results.AddResult(Result("const"));
3132 Results.AddResult(Result("volatile"));
3133 if (getLangOptions().C99)
3134 Results.AddResult(Result("restrict"));
3135
3136 if (getLangOptions().CPlusPlus) {
3137 if (AllowNonIdentifiers) {
3138 Results.AddResult(Result("operator"));
3139 }
3140
3141 // Add nested-name-specifiers.
3142 if (AllowNestedNameSpecifiers) {
3143 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003144 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003145 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3146 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3147 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003148 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003149 }
3150 }
3151 Results.ExitScope();
3152
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003153 // If we're in a context where we might have an expression (rather than a
3154 // declaration), and what we've seen so far is an Objective-C type that could
3155 // be a receiver of a class message, this may be a class message send with
3156 // the initial opening bracket '[' missing. Add appropriate completions.
3157 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3158 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3159 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3160 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3161 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3162 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3163 DS.getTypeQualifiers() == 0 &&
3164 S &&
3165 (S->getFlags() & Scope::DeclScope) != 0 &&
3166 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3167 Scope::FunctionPrototypeScope |
3168 Scope::AtCatchScope)) == 0) {
3169 ParsedType T = DS.getRepAsType();
3170 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003171 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003172 }
3173
Douglas Gregor4497dd42010-08-24 04:59:56 +00003174 // Note that we intentionally suppress macro results here, since we do not
3175 // encourage using macros to produce the names of entities.
3176
Douglas Gregor52779fb2010-09-23 23:01:17 +00003177 HandleCodeCompleteResults(this, CodeCompleter,
3178 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003179 Results.data(), Results.size());
3180}
3181
Douglas Gregorfb629412010-08-23 21:17:50 +00003182struct Sema::CodeCompleteExpressionData {
3183 CodeCompleteExpressionData(QualType PreferredType = QualType())
3184 : PreferredType(PreferredType), IntegralConstantExpression(false),
3185 ObjCCollection(false) { }
3186
3187 QualType PreferredType;
3188 bool IntegralConstantExpression;
3189 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003190 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003191};
3192
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003193/// \brief Perform code-completion in an expression context when we know what
3194/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003195///
3196/// \param IntegralConstantExpression Only permit integral constant
3197/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003198void Sema::CodeCompleteExpression(Scope *S,
3199 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003200 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003201 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3202 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003203 if (Data.ObjCCollection)
3204 Results.setFilter(&ResultBuilder::IsObjCCollection);
3205 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003206 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003207 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003208 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3209 else
3210 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003211
3212 if (!Data.PreferredType.isNull())
3213 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3214
3215 // Ignore any declarations that we were told that we don't care about.
3216 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3217 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003218
3219 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003220 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3221 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003222
3223 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003224 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003225 Results.ExitScope();
3226
Douglas Gregor590c7d52010-07-08 20:55:51 +00003227 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003228 if (!Data.PreferredType.isNull())
3229 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3230 || Data.PreferredType->isMemberPointerType()
3231 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003232
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003233 if (S->getFnParent() &&
3234 !Data.ObjCCollection &&
3235 !Data.IntegralConstantExpression)
3236 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3237
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003238 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003239 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003240 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003241 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3242 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003243 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003244}
3245
Douglas Gregorac5fd842010-09-18 01:28:11 +00003246void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3247 if (E.isInvalid())
3248 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3249 else if (getLangOptions().ObjC1)
3250 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003251}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003252
Douglas Gregor73449212010-12-09 23:01:55 +00003253/// \brief The set of properties that have already been added, referenced by
3254/// property name.
3255typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3256
Douglas Gregor95ac6552009-11-18 01:29:26 +00003257static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003258 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003259 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003260 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003261 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003262 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003263 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003264
3265 // Add properties in this container.
3266 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3267 PEnd = Container->prop_end();
3268 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003269 ++P) {
3270 if (AddedProperties.insert(P->getIdentifier()))
3271 Results.MaybeAddResult(Result(*P, 0), CurContext);
3272 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003273
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003274 // Add nullary methods
3275 if (AllowNullaryMethods) {
3276 ASTContext &Context = Container->getASTContext();
Douglas Gregor8987b232011-09-27 23:30:47 +00003277 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003278 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3279 MEnd = Container->meth_end();
3280 M != MEnd; ++M) {
3281 if (M->getSelector().isUnarySelector())
3282 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3283 if (AddedProperties.insert(Name)) {
3284 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor8987b232011-09-27 23:30:47 +00003285 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003286 Builder.AddTypedTextChunk(
3287 Results.getAllocator().CopyString(Name->getName()));
3288
3289 CXAvailabilityKind Availability = CXAvailability_Available;
3290 switch (M->getAvailability()) {
3291 case AR_Available:
3292 case AR_NotYetIntroduced:
3293 Availability = CXAvailability_Available;
3294 break;
3295
3296 case AR_Deprecated:
3297 Availability = CXAvailability_Deprecated;
3298 break;
3299
3300 case AR_Unavailable:
3301 Availability = CXAvailability_NotAvailable;
3302 break;
3303 }
3304
3305 Results.MaybeAddResult(Result(Builder.TakeString(),
3306 CCP_MemberDeclaration + CCD_MethodAsProperty,
3307 M->isInstanceMethod()
3308 ? CXCursor_ObjCInstanceMethodDecl
3309 : CXCursor_ObjCClassMethodDecl,
3310 Availability),
3311 CurContext);
3312 }
3313 }
3314 }
3315
3316
Douglas Gregor95ac6552009-11-18 01:29:26 +00003317 // Add properties in referenced protocols.
3318 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3319 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3320 PEnd = Protocol->protocol_end();
3321 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003322 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3323 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003324 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003325 if (AllowCategories) {
3326 // Look through categories.
3327 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3328 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003329 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3330 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003331 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003332
3333 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003334 for (ObjCInterfaceDecl::all_protocol_iterator
3335 I = IFace->all_referenced_protocol_begin(),
3336 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003337 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3338 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003339
3340 // Look in the superclass.
3341 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003342 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3343 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003344 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003345 } else if (const ObjCCategoryDecl *Category
3346 = dyn_cast<ObjCCategoryDecl>(Container)) {
3347 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003348 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3349 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003350 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003351 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3352 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003353 }
3354}
3355
Richard Trieuf81e5a92011-09-09 02:00:50 +00003356void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *BaseE,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003357 SourceLocation OpLoc,
3358 bool IsArrow) {
3359 if (!BaseE || !CodeCompleter)
3360 return;
3361
John McCall0a2c5e22010-08-25 06:19:51 +00003362 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003363
Douglas Gregor81b747b2009-09-17 21:32:03 +00003364 Expr *Base = static_cast<Expr *>(BaseE);
3365 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003366
3367 if (IsArrow) {
3368 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3369 BaseType = Ptr->getPointeeType();
3370 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003371 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003372 else
3373 return;
3374 }
3375
Douglas Gregor3da626b2011-07-07 16:03:39 +00003376 enum CodeCompletionContext::Kind contextKind;
3377
3378 if (IsArrow) {
3379 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3380 }
3381 else {
3382 if (BaseType->isObjCObjectPointerType() ||
3383 BaseType->isObjCObjectOrInterfaceType()) {
3384 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3385 }
3386 else {
3387 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3388 }
3389 }
3390
Douglas Gregor218937c2011-02-01 19:23:04 +00003391 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003392 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003393 BaseType),
3394 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003395 Results.EnterNewScope();
3396 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003397 // Indicate that we are performing a member access, and the cv-qualifiers
3398 // for the base object type.
3399 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3400
Douglas Gregor95ac6552009-11-18 01:29:26 +00003401 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003402 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003403 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003404 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3405 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003406
Douglas Gregor95ac6552009-11-18 01:29:26 +00003407 if (getLangOptions().CPlusPlus) {
3408 if (!Results.empty()) {
3409 // The "template" keyword can follow "->" or "." in the grammar.
3410 // However, we only want to suggest the template keyword if something
3411 // is dependent.
3412 bool IsDependent = BaseType->isDependentType();
3413 if (!IsDependent) {
3414 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3415 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3416 IsDependent = Ctx->isDependentContext();
3417 break;
3418 }
3419 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003420
Douglas Gregor95ac6552009-11-18 01:29:26 +00003421 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003422 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003423 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003424 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003425 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3426 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003427 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003428
3429 // Add property results based on our interface.
3430 const ObjCObjectPointerType *ObjCPtr
3431 = BaseType->getAsObjCInterfacePointerType();
3432 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003433 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3434 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003435 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003436
3437 // Add properties from the protocols in a qualified interface.
3438 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3439 E = ObjCPtr->qual_end();
3440 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003441 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3442 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003443 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003444 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003445 // Objective-C instance variable access.
3446 ObjCInterfaceDecl *Class = 0;
3447 if (const ObjCObjectPointerType *ObjCPtr
3448 = BaseType->getAs<ObjCObjectPointerType>())
3449 Class = ObjCPtr->getInterfaceDecl();
3450 else
John McCallc12c5bb2010-05-15 11:32:37 +00003451 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003452
3453 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003454 if (Class) {
3455 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3456 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003457 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3458 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003459 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003460 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003461
3462 // FIXME: How do we cope with isa?
3463
3464 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003465
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003466 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003467 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003468 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003469 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003470}
3471
Douglas Gregor374929f2009-09-18 15:37:17 +00003472void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3473 if (!CodeCompleter)
3474 return;
3475
John McCall0a2c5e22010-08-25 06:19:51 +00003476 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003477 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003478 enum CodeCompletionContext::Kind ContextKind
3479 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003480 switch ((DeclSpec::TST)TagSpec) {
3481 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003482 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003483 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003484 break;
3485
3486 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003487 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003488 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003489 break;
3490
3491 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003492 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003493 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003494 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003495 break;
3496
3497 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003498 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003499 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003500
Douglas Gregor218937c2011-02-01 19:23:04 +00003501 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003502 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003503
3504 // First pass: look for tags.
3505 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003506 LookupVisibleDecls(S, LookupTagName, Consumer,
3507 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003508
Douglas Gregor8071e422010-08-15 06:18:01 +00003509 if (CodeCompleter->includeGlobals()) {
3510 // Second pass: look for nested name specifiers.
3511 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3512 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3513 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003514
Douglas Gregor52779fb2010-09-23 23:01:17 +00003515 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003516 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003517}
3518
Douglas Gregor1a480c42010-08-27 17:35:51 +00003519void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003520 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3521 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003522 Results.EnterNewScope();
3523 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3524 Results.AddResult("const");
3525 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3526 Results.AddResult("volatile");
3527 if (getLangOptions().C99 &&
3528 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3529 Results.AddResult("restrict");
3530 Results.ExitScope();
3531 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003532 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003533 Results.data(), Results.size());
3534}
3535
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003536void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003537 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003538 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003539
John McCall781472f2010-08-25 08:40:02 +00003540 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003541 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3542 if (!type->isEnumeralType()) {
3543 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003544 Data.IntegralConstantExpression = true;
3545 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003546 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003547 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003548
3549 // Code-complete the cases of a switch statement over an enumeration type
3550 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003551 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003552
3553 // Determine which enumerators we have already seen in the switch statement.
3554 // FIXME: Ideally, we would also be able to look *past* the code-completion
3555 // token, in case we are code-completing in the middle of the switch and not
3556 // at the end. However, we aren't able to do so at the moment.
3557 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003558 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003559 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3560 SC = SC->getNextSwitchCase()) {
3561 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3562 if (!Case)
3563 continue;
3564
3565 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3566 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3567 if (EnumConstantDecl *Enumerator
3568 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3569 // We look into the AST of the case statement to determine which
3570 // enumerator was named. Alternatively, we could compute the value of
3571 // the integral constant expression, then compare it against the
3572 // values of each enumerator. However, value-based approach would not
3573 // work as well with C++ templates where enumerators declared within a
3574 // template are type- and value-dependent.
3575 EnumeratorsSeen.insert(Enumerator);
3576
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003577 // If this is a qualified-id, keep track of the nested-name-specifier
3578 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003579 //
3580 // switch (TagD.getKind()) {
3581 // case TagDecl::TK_enum:
3582 // break;
3583 // case XXX
3584 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003585 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003586 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3587 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003588 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003589 }
3590 }
3591
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003592 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3593 // If there are no prior enumerators in C++, check whether we have to
3594 // qualify the names of the enumerators that we suggest, because they
3595 // may not be visible in this scope.
3596 Qualifier = getRequiredQualification(Context, CurContext,
3597 Enum->getDeclContext());
3598
3599 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3600 }
3601
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003602 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003603 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3604 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003605 Results.EnterNewScope();
3606 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3607 EEnd = Enum->enumerator_end();
3608 E != EEnd; ++E) {
3609 if (EnumeratorsSeen.count(*E))
3610 continue;
3611
Douglas Gregor5c722c702011-02-18 23:30:37 +00003612 CodeCompletionResult R(*E, Qualifier);
3613 R.Priority = CCP_EnumInCase;
3614 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003615 }
3616 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003617
Douglas Gregor3da626b2011-07-07 16:03:39 +00003618 //We need to make sure we're setting the right context,
3619 //so only say we include macros if the code completer says we do
3620 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3621 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003622 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003623 kind = CodeCompletionContext::CCC_OtherWithMacros;
3624 }
3625
3626
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003627 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003628 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003629 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003630}
3631
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003632namespace {
3633 struct IsBetterOverloadCandidate {
3634 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003635 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003636
3637 public:
John McCall5769d612010-02-08 23:07:23 +00003638 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3639 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003640
3641 bool
3642 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003643 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003644 }
3645 };
3646}
3647
Douglas Gregord28dcd72010-05-30 06:10:08 +00003648static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3649 if (NumArgs && !Args)
3650 return true;
3651
3652 for (unsigned I = 0; I != NumArgs; ++I)
3653 if (!Args[I])
3654 return true;
3655
3656 return false;
3657}
3658
Richard Trieuf81e5a92011-09-09 02:00:50 +00003659void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3660 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003661 if (!CodeCompleter)
3662 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003663
3664 // When we're code-completing for a call, we fall back to ordinary
3665 // name code-completion whenever we can't produce specific
3666 // results. We may want to revisit this strategy in the future,
3667 // e.g., by merging the two kinds of results.
3668
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003669 Expr *Fn = (Expr *)FnIn;
3670 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003671
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003672 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003673 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003674 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003675 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003676 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003677 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003678
John McCall3b4294e2009-12-16 12:17:52 +00003679 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003680 SourceLocation Loc = Fn->getExprLoc();
3681 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003682
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003683 // FIXME: What if we're calling something that isn't a function declaration?
3684 // FIXME: What if we're calling a pseudo-destructor?
3685 // FIXME: What if we're calling a member function?
3686
Douglas Gregorc0265402010-01-21 15:46:19 +00003687 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003688 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003689
John McCall3b4294e2009-12-16 12:17:52 +00003690 Expr *NakedFn = Fn->IgnoreParenCasts();
3691 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3692 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3693 /*PartialOverloading=*/ true);
3694 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3695 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003696 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003697 if (!getLangOptions().CPlusPlus ||
3698 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003699 Results.push_back(ResultCandidate(FDecl));
3700 else
John McCall86820f52010-01-26 01:37:31 +00003701 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003702 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3703 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003704 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003705 }
John McCall3b4294e2009-12-16 12:17:52 +00003706 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003707
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003708 QualType ParamType;
3709
Douglas Gregorc0265402010-01-21 15:46:19 +00003710 if (!CandidateSet.empty()) {
3711 // Sort the overload candidate set by placing the best overloads first.
3712 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003713 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003714
Douglas Gregorc0265402010-01-21 15:46:19 +00003715 // Add the remaining viable overload candidates as code-completion reslults.
3716 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3717 CandEnd = CandidateSet.end();
3718 Cand != CandEnd; ++Cand) {
3719 if (Cand->Viable)
3720 Results.push_back(ResultCandidate(Cand->Function));
3721 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003722
3723 // From the viable candidates, try to determine the type of this parameter.
3724 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3725 if (const FunctionType *FType = Results[I].getFunctionType())
3726 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3727 if (NumArgs < Proto->getNumArgs()) {
3728 if (ParamType.isNull())
3729 ParamType = Proto->getArgType(NumArgs);
3730 else if (!Context.hasSameUnqualifiedType(
3731 ParamType.getNonReferenceType(),
3732 Proto->getArgType(NumArgs).getNonReferenceType())) {
3733 ParamType = QualType();
3734 break;
3735 }
3736 }
3737 }
3738 } else {
3739 // Try to determine the parameter type from the type of the expression
3740 // being called.
3741 QualType FunctionType = Fn->getType();
3742 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3743 FunctionType = Ptr->getPointeeType();
3744 else if (const BlockPointerType *BlockPtr
3745 = FunctionType->getAs<BlockPointerType>())
3746 FunctionType = BlockPtr->getPointeeType();
3747 else if (const MemberPointerType *MemPtr
3748 = FunctionType->getAs<MemberPointerType>())
3749 FunctionType = MemPtr->getPointeeType();
3750
3751 if (const FunctionProtoType *Proto
3752 = FunctionType->getAs<FunctionProtoType>()) {
3753 if (NumArgs < Proto->getNumArgs())
3754 ParamType = Proto->getArgType(NumArgs);
3755 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003756 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003757
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003758 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003759 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003760 else
3761 CodeCompleteExpression(S, ParamType);
3762
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003763 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003764 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3765 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003766}
3767
John McCalld226f652010-08-21 09:40:31 +00003768void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3769 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003770 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003771 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003772 return;
3773 }
3774
3775 CodeCompleteExpression(S, VD->getType());
3776}
3777
3778void Sema::CodeCompleteReturn(Scope *S) {
3779 QualType ResultType;
3780 if (isa<BlockDecl>(CurContext)) {
3781 if (BlockScopeInfo *BSI = getCurBlock())
3782 ResultType = BSI->ReturnType;
3783 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3784 ResultType = Function->getResultType();
3785 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3786 ResultType = Method->getResultType();
3787
3788 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003789 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003790 else
3791 CodeCompleteExpression(S, ResultType);
3792}
3793
Douglas Gregord2d8be62011-07-30 08:36:53 +00003794void Sema::CodeCompleteAfterIf(Scope *S) {
3795 typedef CodeCompletionResult Result;
3796 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3797 mapCodeCompletionContext(*this, PCC_Statement));
3798 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3799 Results.EnterNewScope();
3800
3801 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3802 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3803 CodeCompleter->includeGlobals());
3804
3805 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3806
3807 // "else" block
3808 CodeCompletionBuilder Builder(Results.getAllocator());
3809 Builder.AddTypedTextChunk("else");
3810 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3811 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3812 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3813 Builder.AddPlaceholderChunk("statements");
3814 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3815 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3816 Results.AddResult(Builder.TakeString());
3817
3818 // "else if" block
3819 Builder.AddTypedTextChunk("else");
3820 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3821 Builder.AddTextChunk("if");
3822 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3823 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3824 if (getLangOptions().CPlusPlus)
3825 Builder.AddPlaceholderChunk("condition");
3826 else
3827 Builder.AddPlaceholderChunk("expression");
3828 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3829 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3830 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3831 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3832 Builder.AddPlaceholderChunk("statements");
3833 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3834 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3835 Results.AddResult(Builder.TakeString());
3836
3837 Results.ExitScope();
3838
3839 if (S->getFnParent())
3840 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3841
3842 if (CodeCompleter->includeMacros())
3843 AddMacroResults(PP, Results);
3844
3845 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3846 Results.data(),Results.size());
3847}
3848
Richard Trieuf81e5a92011-09-09 02:00:50 +00003849void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003850 if (LHS)
3851 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3852 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003853 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003854}
3855
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003856void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003857 bool EnteringContext) {
3858 if (!SS.getScopeRep() || !CodeCompleter)
3859 return;
3860
Douglas Gregor86d9a522009-09-21 16:56:56 +00003861 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3862 if (!Ctx)
3863 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003864
3865 // Try to instantiate any non-dependent declaration contexts before
3866 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003867 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003868 return;
3869
Douglas Gregor218937c2011-02-01 19:23:04 +00003870 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3871 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003872 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003873
Douglas Gregor86d9a522009-09-21 16:56:56 +00003874 // The "template" keyword can follow "::" in the grammar, but only
3875 // put it into the grammar if the nested-name-specifier is dependent.
3876 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3877 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003878 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003879
3880 // Add calls to overridden virtual functions, if there are any.
3881 //
3882 // FIXME: This isn't wonderful, because we don't know whether we're actually
3883 // in a context that permits expressions. This is a general issue with
3884 // qualified-id completions.
3885 if (!EnteringContext)
3886 MaybeAddOverrideCalls(*this, Ctx, Results);
3887 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003888
Douglas Gregorf6961522010-08-27 21:18:54 +00003889 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3890 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3891
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003892 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003893 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003894 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003895}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003896
3897void Sema::CodeCompleteUsing(Scope *S) {
3898 if (!CodeCompleter)
3899 return;
3900
Douglas Gregor218937c2011-02-01 19:23:04 +00003901 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003902 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3903 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003904 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003905
3906 // If we aren't in class scope, we could see the "namespace" keyword.
3907 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003908 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003909
3910 // After "using", we can see anything that would start a
3911 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003912 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003913 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3914 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003915 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003916
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003917 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003918 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003919 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003920}
3921
3922void Sema::CodeCompleteUsingDirective(Scope *S) {
3923 if (!CodeCompleter)
3924 return;
3925
Douglas Gregor86d9a522009-09-21 16:56:56 +00003926 // After "using namespace", we expect to see a namespace name or namespace
3927 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003928 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3929 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003930 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003931 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003932 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003933 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3934 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003935 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003936 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003937 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003938 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003939}
3940
3941void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3942 if (!CodeCompleter)
3943 return;
3944
Douglas Gregor86d9a522009-09-21 16:56:56 +00003945 DeclContext *Ctx = (DeclContext *)S->getEntity();
3946 if (!S->getParent())
3947 Ctx = Context.getTranslationUnitDecl();
3948
Douglas Gregor52779fb2010-09-23 23:01:17 +00003949 bool SuppressedGlobalResults
3950 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3951
Douglas Gregor218937c2011-02-01 19:23:04 +00003952 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003953 SuppressedGlobalResults
3954 ? CodeCompletionContext::CCC_Namespace
3955 : CodeCompletionContext::CCC_Other,
3956 &ResultBuilder::IsNamespace);
3957
3958 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003959 // We only want to see those namespaces that have already been defined
3960 // within this scope, because its likely that the user is creating an
3961 // extended namespace declaration. Keep track of the most recent
3962 // definition of each namespace.
3963 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3964 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3965 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3966 NS != NSEnd; ++NS)
3967 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3968
3969 // Add the most recent definition (or extended definition) of each
3970 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003971 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003972 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3973 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3974 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003975 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003976 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003977 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003978 }
3979
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003980 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003981 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003982 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003983}
3984
3985void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3986 if (!CodeCompleter)
3987 return;
3988
Douglas Gregor86d9a522009-09-21 16:56:56 +00003989 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003990 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3991 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003992 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003993 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003994 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3995 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003996 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003997 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003998 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003999}
4000
Douglas Gregored8d3222009-09-18 20:05:18 +00004001void Sema::CodeCompleteOperatorName(Scope *S) {
4002 if (!CodeCompleter)
4003 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00004004
John McCall0a2c5e22010-08-25 06:19:51 +00004005 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004006 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4007 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004008 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004009 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00004010
Douglas Gregor86d9a522009-09-21 16:56:56 +00004011 // Add the names of overloadable operators.
4012#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4013 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00004014 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00004015#include "clang/Basic/OperatorKinds.def"
4016
4017 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00004018 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004019 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004020 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4021 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00004022
4023 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00004024 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004025 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004026
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004027 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00004028 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004029 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00004030}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004031
Douglas Gregor0133f522010-08-28 00:00:50 +00004032void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00004033 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00004034 unsigned NumInitializers) {
Douglas Gregor8987b232011-09-27 23:30:47 +00004035 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor0133f522010-08-28 00:00:50 +00004036 CXXConstructorDecl *Constructor
4037 = static_cast<CXXConstructorDecl *>(ConstructorD);
4038 if (!Constructor)
4039 return;
4040
Douglas Gregor218937c2011-02-01 19:23:04 +00004041 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004042 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00004043 Results.EnterNewScope();
4044
4045 // Fill in any already-initialized fields or base classes.
4046 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4047 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4048 for (unsigned I = 0; I != NumInitializers; ++I) {
4049 if (Initializers[I]->isBaseInitializer())
4050 InitializedBases.insert(
4051 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4052 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00004053 InitializedFields.insert(cast<FieldDecl>(
4054 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00004055 }
4056
4057 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00004058 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00004059 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00004060 CXXRecordDecl *ClassDecl = Constructor->getParent();
4061 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4062 BaseEnd = ClassDecl->bases_end();
4063 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004064 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4065 SawLastInitializer
4066 = NumInitializers > 0 &&
4067 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4068 Context.hasSameUnqualifiedType(Base->getType(),
4069 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004070 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004071 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004072
Douglas Gregor218937c2011-02-01 19:23:04 +00004073 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004074 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004075 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004076 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4077 Builder.AddPlaceholderChunk("args");
4078 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4079 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004080 SawLastInitializer? CCP_NextInitializer
4081 : CCP_MemberDeclaration));
4082 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004083 }
4084
4085 // Add completions for virtual base classes.
4086 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4087 BaseEnd = ClassDecl->vbases_end();
4088 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004089 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4090 SawLastInitializer
4091 = NumInitializers > 0 &&
4092 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4093 Context.hasSameUnqualifiedType(Base->getType(),
4094 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004095 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004096 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004097
Douglas Gregor218937c2011-02-01 19:23:04 +00004098 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004099 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004100 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004101 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4102 Builder.AddPlaceholderChunk("args");
4103 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4104 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004105 SawLastInitializer? CCP_NextInitializer
4106 : CCP_MemberDeclaration));
4107 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004108 }
4109
4110 // Add completions for members.
4111 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4112 FieldEnd = ClassDecl->field_end();
4113 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004114 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4115 SawLastInitializer
4116 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004117 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4118 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004119 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004120 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004121
4122 if (!Field->getDeclName())
4123 continue;
4124
Douglas Gregordae68752011-02-01 22:57:45 +00004125 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004126 Field->getIdentifier()->getName()));
4127 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4128 Builder.AddPlaceholderChunk("args");
4129 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4130 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004131 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004132 : CCP_MemberDeclaration,
4133 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004134 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004135 }
4136 Results.ExitScope();
4137
Douglas Gregor52779fb2010-09-23 23:01:17 +00004138 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004139 Results.data(), Results.size());
4140}
4141
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004142// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4143// true or false.
4144#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004145static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004146 ResultBuilder &Results,
4147 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004148 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004149 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004150 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004151
Douglas Gregor218937c2011-02-01 19:23:04 +00004152 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004153 if (LangOpts.ObjC2) {
4154 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004155 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4156 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4157 Builder.AddPlaceholderChunk("property");
4158 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004159
4160 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004161 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4162 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4163 Builder.AddPlaceholderChunk("property");
4164 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004165 }
4166}
4167
Douglas Gregorbca403c2010-01-13 23:51:12 +00004168static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004169 ResultBuilder &Results,
4170 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004171 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004172
4173 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004174 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004175
4176 if (LangOpts.ObjC2) {
4177 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004178 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004179
4180 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004181 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004182
4183 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004184 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004185 }
4186}
4187
Douglas Gregorbca403c2010-01-13 23:51:12 +00004188static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004189 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004190 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004191
4192 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004193 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4194 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4195 Builder.AddPlaceholderChunk("name");
4196 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004197
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004198 if (Results.includeCodePatterns()) {
4199 // @interface name
4200 // FIXME: Could introduce the whole pattern, including superclasses and
4201 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004202 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4203 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4204 Builder.AddPlaceholderChunk("class");
4205 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004206
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004207 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004208 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4209 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4210 Builder.AddPlaceholderChunk("protocol");
4211 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004212
4213 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004214 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4215 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4216 Builder.AddPlaceholderChunk("class");
4217 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004218 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004219
4220 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004221 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4222 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4223 Builder.AddPlaceholderChunk("alias");
4224 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4225 Builder.AddPlaceholderChunk("class");
4226 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004227}
4228
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004229void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004230 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004231 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4232 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004233 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004234 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorbca403c2010-01-13 23:51:12 +00004235 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004236 else if (CurContext->isObjCContainer())
Douglas Gregorbca403c2010-01-13 23:51:12 +00004237 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004238 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004239 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004240 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004241 HandleCodeCompleteResults(this, CodeCompleter,
4242 CodeCompletionContext::CCC_Other,
4243 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004244}
4245
Douglas Gregorbca403c2010-01-13 23:51:12 +00004246static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004247 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004248 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004249
4250 // @encode ( type-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004251 const char *EncodeType = "char[]";
4252 if (Results.getSema().getLangOptions().CPlusPlus ||
4253 Results.getSema().getLangOptions().ConstStrings)
4254 EncodeType = " const char[]";
4255 Builder.AddResultTypeChunk(EncodeType);
Douglas Gregor218937c2011-02-01 19:23:04 +00004256 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4257 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4258 Builder.AddPlaceholderChunk("type-name");
4259 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4260 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004261
4262 // @protocol ( protocol-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004263 Builder.AddResultTypeChunk("Protocol *");
Douglas Gregor218937c2011-02-01 19:23:04 +00004264 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4265 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4266 Builder.AddPlaceholderChunk("protocol-name");
4267 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4268 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004269
4270 // @selector ( selector )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004271 Builder.AddResultTypeChunk("SEL");
Douglas Gregor218937c2011-02-01 19:23:04 +00004272 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4273 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4274 Builder.AddPlaceholderChunk("selector");
4275 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4276 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004277}
4278
Douglas Gregorbca403c2010-01-13 23:51:12 +00004279static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004280 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004281 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004282
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004283 if (Results.includeCodePatterns()) {
4284 // @try { statements } @catch ( declaration ) { statements } @finally
4285 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004286 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4287 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4288 Builder.AddPlaceholderChunk("statements");
4289 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4290 Builder.AddTextChunk("@catch");
4291 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4292 Builder.AddPlaceholderChunk("parameter");
4293 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4294 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4295 Builder.AddPlaceholderChunk("statements");
4296 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4297 Builder.AddTextChunk("@finally");
4298 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4299 Builder.AddPlaceholderChunk("statements");
4300 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4301 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004302 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004303
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004304 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004305 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4306 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4307 Builder.AddPlaceholderChunk("expression");
4308 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004309
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004310 if (Results.includeCodePatterns()) {
4311 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004312 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4313 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4314 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4315 Builder.AddPlaceholderChunk("expression");
4316 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4317 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4318 Builder.AddPlaceholderChunk("statements");
4319 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4320 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004321 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004322}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004323
Douglas Gregorbca403c2010-01-13 23:51:12 +00004324static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004325 ResultBuilder &Results,
4326 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004327 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004328 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4329 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4330 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004331 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004332 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004333}
4334
4335void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004336 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4337 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004338 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004339 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004340 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004341 HandleCodeCompleteResults(this, CodeCompleter,
4342 CodeCompletionContext::CCC_Other,
4343 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004344}
4345
4346void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004347 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4348 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004349 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004350 AddObjCStatementResults(Results, false);
4351 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004352 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004353 HandleCodeCompleteResults(this, CodeCompleter,
4354 CodeCompletionContext::CCC_Other,
4355 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004356}
4357
4358void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004359 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4360 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004361 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004362 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004363 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004364 HandleCodeCompleteResults(this, CodeCompleter,
4365 CodeCompletionContext::CCC_Other,
4366 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004367}
4368
Douglas Gregor988358f2009-11-19 00:14:45 +00004369/// \brief Determine whether the addition of the given flag to an Objective-C
4370/// property's attributes will cause a conflict.
4371static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4372 // Check if we've already added this flag.
4373 if (Attributes & NewFlag)
4374 return true;
4375
4376 Attributes |= NewFlag;
4377
4378 // Check for collisions with "readonly".
4379 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4380 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4381 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004382 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004383 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004384 ObjCDeclSpec::DQ_PR_retain |
4385 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004386 return true;
4387
John McCallf85e1932011-06-15 23:02:42 +00004388 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004389 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004390 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004391 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004392 ObjCDeclSpec::DQ_PR_retain|
4393 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004394 if (AssignCopyRetMask &&
4395 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004396 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004397 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004398 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4399 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004400 return true;
4401
4402 return false;
4403}
4404
Douglas Gregora93b1082009-11-18 23:08:07 +00004405void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004406 if (!CodeCompleter)
4407 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004408
Steve Naroffece8e712009-10-08 21:55:05 +00004409 unsigned Attributes = ODS.getPropertyAttributes();
4410
John McCall0a2c5e22010-08-25 06:19:51 +00004411 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004412 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4413 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004414 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004415 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004416 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004417 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004418 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004419 if (!ObjCPropertyFlagConflicts(Attributes,
4420 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4421 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004422 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004423 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004424 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004425 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004426 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4427 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004428 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004429 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004430 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004431 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004432 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4433 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004434 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004435 CodeCompletionBuilder Setter(Results.getAllocator());
4436 Setter.AddTypedTextChunk("setter");
4437 Setter.AddTextChunk(" = ");
4438 Setter.AddPlaceholderChunk("method");
4439 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004440 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004441 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004442 CodeCompletionBuilder Getter(Results.getAllocator());
4443 Getter.AddTypedTextChunk("getter");
4444 Getter.AddTextChunk(" = ");
4445 Getter.AddPlaceholderChunk("method");
4446 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004447 }
Steve Naroffece8e712009-10-08 21:55:05 +00004448 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004449 HandleCodeCompleteResults(this, CodeCompleter,
4450 CodeCompletionContext::CCC_Other,
4451 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004452}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004453
Douglas Gregor4ad96852009-11-19 07:41:15 +00004454/// \brief Descripts the kind of Objective-C method that we want to find
4455/// via code completion.
4456enum ObjCMethodKind {
4457 MK_Any, //< Any kind of method, provided it means other specified criteria.
4458 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4459 MK_OneArgSelector //< One-argument selector.
4460};
4461
Douglas Gregor458433d2010-08-26 15:07:07 +00004462static bool isAcceptableObjCSelector(Selector Sel,
4463 ObjCMethodKind WantKind,
4464 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004465 unsigned NumSelIdents,
4466 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004467 if (NumSelIdents > Sel.getNumArgs())
4468 return false;
4469
4470 switch (WantKind) {
4471 case MK_Any: break;
4472 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4473 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4474 }
4475
Douglas Gregorcf544262010-11-17 21:36:08 +00004476 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4477 return false;
4478
Douglas Gregor458433d2010-08-26 15:07:07 +00004479 for (unsigned I = 0; I != NumSelIdents; ++I)
4480 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4481 return false;
4482
4483 return true;
4484}
4485
Douglas Gregor4ad96852009-11-19 07:41:15 +00004486static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4487 ObjCMethodKind WantKind,
4488 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004489 unsigned NumSelIdents,
4490 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004491 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004492 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004493}
Douglas Gregord36adf52010-09-16 16:06:31 +00004494
4495namespace {
4496 /// \brief A set of selectors, which is used to avoid introducing multiple
4497 /// completions with the same selector into the result set.
4498 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4499}
4500
Douglas Gregor36ecb042009-11-17 23:22:23 +00004501/// \brief Add all of the Objective-C methods in the given Objective-C
4502/// container to the set of results.
4503///
4504/// The container will be a class, protocol, category, or implementation of
4505/// any of the above. This mether will recurse to include methods from
4506/// the superclasses of classes along with their categories, protocols, and
4507/// implementations.
4508///
4509/// \param Container the container in which we'll look to find methods.
4510///
4511/// \param WantInstance whether to add instance methods (only); if false, this
4512/// routine will add factory methods (only).
4513///
4514/// \param CurContext the context in which we're performing the lookup that
4515/// finds methods.
4516///
Douglas Gregorcf544262010-11-17 21:36:08 +00004517/// \param AllowSameLength Whether we allow a method to be added to the list
4518/// when it has the same number of parameters as we have selector identifiers.
4519///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004520/// \param Results the structure into which we'll add results.
4521static void AddObjCMethods(ObjCContainerDecl *Container,
4522 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004523 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004524 IdentifierInfo **SelIdents,
4525 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004526 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004527 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004528 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004529 ResultBuilder &Results,
4530 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004531 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004532 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4533 MEnd = Container->meth_end();
4534 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004535 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4536 // Check whether the selector identifiers we've been given are a
4537 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004538 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4539 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004540 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004541
Douglas Gregord36adf52010-09-16 16:06:31 +00004542 if (!Selectors.insert((*M)->getSelector()))
4543 continue;
4544
Douglas Gregord3c68542009-11-19 01:08:35 +00004545 Result R = Result(*M, 0);
4546 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004547 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004548 if (!InOriginalClass)
4549 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004550 Results.MaybeAddResult(R, CurContext);
4551 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004552 }
4553
Douglas Gregore396c7b2010-09-16 15:34:59 +00004554 // Visit the protocols of protocols.
4555 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4556 const ObjCList<ObjCProtocolDecl> &Protocols
4557 = Protocol->getReferencedProtocols();
4558 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4559 E = Protocols.end();
4560 I != E; ++I)
4561 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004562 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004563 }
4564
Douglas Gregor36ecb042009-11-17 23:22:23 +00004565 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4566 if (!IFace)
4567 return;
4568
4569 // Add methods in protocols.
4570 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4571 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4572 E = Protocols.end();
4573 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004574 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004575 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004576
4577 // Add methods in categories.
4578 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4579 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004580 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004581 NumSelIdents, CurContext, Selectors, AllowSameLength,
4582 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004583
4584 // Add a categories protocol methods.
4585 const ObjCList<ObjCProtocolDecl> &Protocols
4586 = CatDecl->getReferencedProtocols();
4587 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4588 E = Protocols.end();
4589 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004590 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004591 NumSelIdents, CurContext, Selectors, AllowSameLength,
4592 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004593
4594 // Add methods in category implementations.
4595 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004596 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004597 NumSelIdents, CurContext, Selectors, AllowSameLength,
4598 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004599 }
4600
4601 // Add methods in superclass.
4602 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004603 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004604 SelIdents, NumSelIdents, CurContext, Selectors,
4605 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004606
4607 // Add methods in our implementation, if any.
4608 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004609 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004610 NumSelIdents, CurContext, Selectors, AllowSameLength,
4611 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004612}
4613
4614
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004615void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004616 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004617
4618 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004619 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004620 if (!Class) {
4621 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004622 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004623 Class = Category->getClassInterface();
4624
4625 if (!Class)
4626 return;
4627 }
4628
4629 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004630 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4631 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004632 Results.EnterNewScope();
4633
Douglas Gregord36adf52010-09-16 16:06:31 +00004634 VisitedSelectorSet Selectors;
4635 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004636 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004637 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004638 HandleCodeCompleteResults(this, CodeCompleter,
4639 CodeCompletionContext::CCC_Other,
4640 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004641}
4642
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004643void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004644 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004645
4646 // Try to find the interface where setters might live.
4647 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004648 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004649 if (!Class) {
4650 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004651 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004652 Class = Category->getClassInterface();
4653
4654 if (!Class)
4655 return;
4656 }
4657
4658 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004659 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4660 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004661 Results.EnterNewScope();
4662
Douglas Gregord36adf52010-09-16 16:06:31 +00004663 VisitedSelectorSet Selectors;
4664 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004665 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004666
4667 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004668 HandleCodeCompleteResults(this, CodeCompleter,
4669 CodeCompletionContext::CCC_Other,
4670 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004671}
4672
Douglas Gregorafc45782011-02-15 22:19:42 +00004673void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4674 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004675 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004676 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4677 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004678 Results.EnterNewScope();
4679
4680 // Add context-sensitive, Objective-C parameter-passing keywords.
4681 bool AddedInOut = false;
4682 if ((DS.getObjCDeclQualifier() &
4683 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4684 Results.AddResult("in");
4685 Results.AddResult("inout");
4686 AddedInOut = true;
4687 }
4688 if ((DS.getObjCDeclQualifier() &
4689 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4690 Results.AddResult("out");
4691 if (!AddedInOut)
4692 Results.AddResult("inout");
4693 }
4694 if ((DS.getObjCDeclQualifier() &
4695 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4696 ObjCDeclSpec::DQ_Oneway)) == 0) {
4697 Results.AddResult("bycopy");
4698 Results.AddResult("byref");
4699 Results.AddResult("oneway");
4700 }
4701
Douglas Gregorafc45782011-02-15 22:19:42 +00004702 // If we're completing the return type of an Objective-C method and the
4703 // identifier IBAction refers to a macro, provide a completion item for
4704 // an action, e.g.,
4705 // IBAction)<#selector#>:(id)sender
4706 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4707 Context.Idents.get("IBAction").hasMacroDefinition()) {
4708 typedef CodeCompletionString::Chunk Chunk;
4709 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4710 CXAvailability_Available);
4711 Builder.AddTypedTextChunk("IBAction");
4712 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4713 Builder.AddPlaceholderChunk("selector");
4714 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4715 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4716 Builder.AddTextChunk("id");
4717 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4718 Builder.AddTextChunk("sender");
4719 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4720 }
4721
Douglas Gregord32b0222010-08-24 01:06:58 +00004722 // Add various builtin type names and specifiers.
4723 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4724 Results.ExitScope();
4725
4726 // Add the various type names
4727 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4728 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4729 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4730 CodeCompleter->includeGlobals());
4731
4732 if (CodeCompleter->includeMacros())
4733 AddMacroResults(PP, Results);
4734
4735 HandleCodeCompleteResults(this, CodeCompleter,
4736 CodeCompletionContext::CCC_Type,
4737 Results.data(), Results.size());
4738}
4739
Douglas Gregor22f56992010-04-06 19:22:33 +00004740/// \brief When we have an expression with type "id", we may assume
4741/// that it has some more-specific class type based on knowledge of
4742/// common uses of Objective-C. This routine returns that class type,
4743/// or NULL if no better result could be determined.
4744static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004745 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004746 if (!Msg)
4747 return 0;
4748
4749 Selector Sel = Msg->getSelector();
4750 if (Sel.isNull())
4751 return 0;
4752
4753 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4754 if (!Id)
4755 return 0;
4756
4757 ObjCMethodDecl *Method = Msg->getMethodDecl();
4758 if (!Method)
4759 return 0;
4760
4761 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004762 ObjCInterfaceDecl *IFace = 0;
4763 switch (Msg->getReceiverKind()) {
4764 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004765 if (const ObjCObjectType *ObjType
4766 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4767 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004768 break;
4769
4770 case ObjCMessageExpr::Instance: {
4771 QualType T = Msg->getInstanceReceiver()->getType();
4772 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4773 IFace = Ptr->getInterfaceDecl();
4774 break;
4775 }
4776
4777 case ObjCMessageExpr::SuperInstance:
4778 case ObjCMessageExpr::SuperClass:
4779 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004780 }
4781
4782 if (!IFace)
4783 return 0;
4784
4785 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4786 if (Method->isInstanceMethod())
4787 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4788 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004789 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004790 .Case("autorelease", IFace)
4791 .Case("copy", IFace)
4792 .Case("copyWithZone", IFace)
4793 .Case("mutableCopy", IFace)
4794 .Case("mutableCopyWithZone", IFace)
4795 .Case("awakeFromCoder", IFace)
4796 .Case("replacementObjectFromCoder", IFace)
4797 .Case("class", IFace)
4798 .Case("classForCoder", IFace)
4799 .Case("superclass", Super)
4800 .Default(0);
4801
4802 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4803 .Case("new", IFace)
4804 .Case("alloc", IFace)
4805 .Case("allocWithZone", IFace)
4806 .Case("class", IFace)
4807 .Case("superclass", Super)
4808 .Default(0);
4809}
4810
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004811// Add a special completion for a message send to "super", which fills in the
4812// most likely case of forwarding all of our arguments to the superclass
4813// function.
4814///
4815/// \param S The semantic analysis object.
4816///
4817/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4818/// the "super" keyword. Otherwise, we just need to provide the arguments.
4819///
4820/// \param SelIdents The identifiers in the selector that have already been
4821/// provided as arguments for a send to "super".
4822///
4823/// \param NumSelIdents The number of identifiers in \p SelIdents.
4824///
4825/// \param Results The set of results to augment.
4826///
4827/// \returns the Objective-C method declaration that would be invoked by
4828/// this "super" completion. If NULL, no completion was added.
4829static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4830 IdentifierInfo **SelIdents,
4831 unsigned NumSelIdents,
4832 ResultBuilder &Results) {
4833 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4834 if (!CurMethod)
4835 return 0;
4836
4837 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4838 if (!Class)
4839 return 0;
4840
4841 // Try to find a superclass method with the same selector.
4842 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004843 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4844 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004845 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4846 CurMethod->isInstanceMethod());
4847
Douglas Gregor78bcd912011-02-16 00:51:18 +00004848 // Check in categories or class extensions.
4849 if (!SuperMethod) {
4850 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4851 Category = Category->getNextClassCategory())
4852 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4853 CurMethod->isInstanceMethod())))
4854 break;
4855 }
4856 }
4857
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004858 if (!SuperMethod)
4859 return 0;
4860
4861 // Check whether the superclass method has the same signature.
4862 if (CurMethod->param_size() != SuperMethod->param_size() ||
4863 CurMethod->isVariadic() != SuperMethod->isVariadic())
4864 return 0;
4865
4866 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4867 CurPEnd = CurMethod->param_end(),
4868 SuperP = SuperMethod->param_begin();
4869 CurP != CurPEnd; ++CurP, ++SuperP) {
4870 // Make sure the parameter types are compatible.
4871 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4872 (*SuperP)->getType()))
4873 return 0;
4874
4875 // Make sure we have a parameter name to forward!
4876 if (!(*CurP)->getIdentifier())
4877 return 0;
4878 }
4879
4880 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004881 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004882
4883 // Give this completion a return type.
Douglas Gregor8987b232011-09-27 23:30:47 +00004884 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
4885 Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004886
4887 // If we need the "super" keyword, add it (plus some spacing).
4888 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004889 Builder.AddTypedTextChunk("super");
4890 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004891 }
4892
4893 Selector Sel = CurMethod->getSelector();
4894 if (Sel.isUnarySelector()) {
4895 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004896 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004897 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004898 else
Douglas Gregordae68752011-02-01 22:57:45 +00004899 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004900 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004901 } else {
4902 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4903 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4904 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004905 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004906
4907 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004908 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004909 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004910 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004911 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004912 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004913 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004914 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004915 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004916 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004917 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004918 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004919 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004920 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004921 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004922 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004923 }
4924 }
4925 }
4926
Douglas Gregor218937c2011-02-01 19:23:04 +00004927 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004928 SuperMethod->isInstanceMethod()
4929 ? CXCursor_ObjCInstanceMethodDecl
4930 : CXCursor_ObjCClassMethodDecl));
4931 return SuperMethod;
4932}
4933
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004934void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004935 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004936 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4937 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004938 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004939
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004940 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4941 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004942 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4943 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004944
4945 // If we are in an Objective-C method inside a class that has a superclass,
4946 // add "super" as an option.
4947 if (ObjCMethodDecl *Method = getCurMethodDecl())
4948 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004949 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004950 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004951
4952 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4953 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004954
4955 Results.ExitScope();
4956
4957 if (CodeCompleter->includeMacros())
4958 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004959 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004960 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004961
4962}
4963
Douglas Gregor2725ca82010-04-21 19:57:20 +00004964void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4965 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004966 unsigned NumSelIdents,
4967 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004968 ObjCInterfaceDecl *CDecl = 0;
4969 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4970 // Figure out which interface we're in.
4971 CDecl = CurMethod->getClassInterface();
4972 if (!CDecl)
4973 return;
4974
4975 // Find the superclass of this class.
4976 CDecl = CDecl->getSuperClass();
4977 if (!CDecl)
4978 return;
4979
4980 if (CurMethod->isInstanceMethod()) {
4981 // We are inside an instance method, which means that the message
4982 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004983 // current object.
4984 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004985 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004986 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004987 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004988 }
4989
4990 // Fall through to send to the superclass in CDecl.
4991 } else {
4992 // "super" may be the name of a type or variable. Figure out which
4993 // it is.
4994 IdentifierInfo *Super = &Context.Idents.get("super");
4995 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4996 LookupOrdinaryName);
4997 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4998 // "super" names an interface. Use it.
4999 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00005000 if (const ObjCObjectType *Iface
5001 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5002 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00005003 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5004 // "super" names an unresolved type; we can't be more specific.
5005 } else {
5006 // Assume that "super" names some kind of value and parse that way.
5007 CXXScopeSpec SS;
5008 UnqualifiedId id;
5009 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00005010 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005011 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005012 SelIdents, NumSelIdents,
5013 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005014 }
5015
5016 // Fall through
5017 }
5018
John McCallb3d87482010-08-24 05:47:05 +00005019 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00005020 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00005021 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00005022 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005023 NumSelIdents, AtArgumentExpression,
5024 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005025}
5026
Douglas Gregorb9d77572010-09-21 00:03:25 +00005027/// \brief Given a set of code-completion results for the argument of a message
5028/// send, determine the preferred type (if any) for that argument expression.
5029static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5030 unsigned NumSelIdents) {
5031 typedef CodeCompletionResult Result;
5032 ASTContext &Context = Results.getSema().Context;
5033
5034 QualType PreferredType;
5035 unsigned BestPriority = CCP_Unlikely * 2;
5036 Result *ResultsData = Results.data();
5037 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5038 Result &R = ResultsData[I];
5039 if (R.Kind == Result::RK_Declaration &&
5040 isa<ObjCMethodDecl>(R.Declaration)) {
5041 if (R.Priority <= BestPriority) {
5042 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5043 if (NumSelIdents <= Method->param_size()) {
5044 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5045 ->getType();
5046 if (R.Priority < BestPriority || PreferredType.isNull()) {
5047 BestPriority = R.Priority;
5048 PreferredType = MyPreferredType;
5049 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5050 MyPreferredType)) {
5051 PreferredType = QualType();
5052 }
5053 }
5054 }
5055 }
5056 }
5057
5058 return PreferredType;
5059}
5060
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005061static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5062 ParsedType Receiver,
5063 IdentifierInfo **SelIdents,
5064 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005065 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005066 bool IsSuper,
5067 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005068 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00005069 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005070
Douglas Gregor24a069f2009-11-17 17:59:40 +00005071 // If the given name refers to an interface type, retrieve the
5072 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00005073 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005074 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005075 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00005076 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5077 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00005078 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005079
Douglas Gregor36ecb042009-11-17 23:22:23 +00005080 // Add all of the factory methods in this Objective-C class, its protocols,
5081 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00005082 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005083
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005084 // If this is a send-to-super, try to add the special "super" send
5085 // completion.
5086 if (IsSuper) {
5087 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005088 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5089 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005090 Results.Ignore(SuperMethod);
5091 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005092
Douglas Gregor265f7492010-08-27 15:29:55 +00005093 // If we're inside an Objective-C method definition, prefer its selector to
5094 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005095 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005096 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005097
Douglas Gregord36adf52010-09-16 16:06:31 +00005098 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005099 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005100 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005101 SemaRef.CurContext, Selectors, AtArgumentExpression,
5102 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005103 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005104 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005105
Douglas Gregor719770d2010-04-06 17:30:22 +00005106 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005107 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005108 if (SemaRef.ExternalSource) {
5109 for (uint32_t I = 0,
5110 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005111 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005112 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5113 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005114 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005115
5116 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005117 }
5118 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005119
5120 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5121 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005122 M != MEnd; ++M) {
5123 for (ObjCMethodList *MethList = &M->second.second;
5124 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005125 MethList = MethList->Next) {
5126 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5127 NumSelIdents))
5128 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005129
Douglas Gregor13438f92010-04-06 16:40:00 +00005130 Result R(MethList->Method, 0);
5131 R.StartParameter = NumSelIdents;
5132 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005133 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005134 }
5135 }
5136 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005137
5138 Results.ExitScope();
5139}
Douglas Gregor13438f92010-04-06 16:40:00 +00005140
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005141void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5142 IdentifierInfo **SelIdents,
5143 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005144 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005145 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005146
5147 QualType T = this->GetTypeFromParser(Receiver);
5148
Douglas Gregor218937c2011-02-01 19:23:04 +00005149 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005150 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005151 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005152
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005153 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5154 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005155
5156 // If we're actually at the argument expression (rather than prior to the
5157 // selector), we're actually performing code completion for an expression.
5158 // Determine whether we have a single, best method. If so, we can
5159 // code-complete the expression using the corresponding parameter type as
5160 // our preferred type, improving completion results.
5161 if (AtArgumentExpression) {
5162 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005163 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005164 if (PreferredType.isNull())
5165 CodeCompleteOrdinaryName(S, PCC_Expression);
5166 else
5167 CodeCompleteExpression(S, PreferredType);
5168 return;
5169 }
5170
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005171 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005172 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005173 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005174}
5175
Richard Trieuf81e5a92011-09-09 02:00:50 +00005176void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005177 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005178 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005179 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005180 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005181 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005182
5183 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005184
Douglas Gregor36ecb042009-11-17 23:22:23 +00005185 // If necessary, apply function/array conversion to the receiver.
5186 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005187 if (RecExpr) {
5188 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5189 if (Conv.isInvalid()) // conversion failed. bail.
5190 return;
5191 RecExpr = Conv.take();
5192 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005193 QualType ReceiverType = RecExpr? RecExpr->getType()
5194 : Super? Context.getObjCObjectPointerType(
5195 Context.getObjCInterfaceType(Super))
5196 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005197
Douglas Gregorda892642010-11-08 21:12:30 +00005198 // If we're messaging an expression with type "id" or "Class", check
5199 // whether we know something special about the receiver that allows
5200 // us to assume a more-specific receiver type.
5201 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5202 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5203 if (ReceiverType->isObjCClassType())
5204 return CodeCompleteObjCClassMessage(S,
5205 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5206 SelIdents, NumSelIdents,
5207 AtArgumentExpression, Super);
5208
5209 ReceiverType = Context.getObjCObjectPointerType(
5210 Context.getObjCInterfaceType(IFace));
5211 }
5212
Douglas Gregor36ecb042009-11-17 23:22:23 +00005213 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005214 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005215 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005216 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005217
Douglas Gregor36ecb042009-11-17 23:22:23 +00005218 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005219
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005220 // If this is a send-to-super, try to add the special "super" send
5221 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005222 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005223 if (ObjCMethodDecl *SuperMethod
5224 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5225 Results))
5226 Results.Ignore(SuperMethod);
5227 }
5228
Douglas Gregor265f7492010-08-27 15:29:55 +00005229 // If we're inside an Objective-C method definition, prefer its selector to
5230 // others.
5231 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5232 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005233
Douglas Gregord36adf52010-09-16 16:06:31 +00005234 // Keep track of the selectors we've already added.
5235 VisitedSelectorSet Selectors;
5236
Douglas Gregorf74a4192009-11-18 00:06:18 +00005237 // Handle messages to Class. This really isn't a message to an instance
5238 // method, so we treat it the same way we would treat a message send to a
5239 // class method.
5240 if (ReceiverType->isObjCClassType() ||
5241 ReceiverType->isObjCQualifiedClassType()) {
5242 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5243 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005244 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005245 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005246 }
5247 }
5248 // Handle messages to a qualified ID ("id<foo>").
5249 else if (const ObjCObjectPointerType *QualID
5250 = ReceiverType->getAsObjCQualifiedIdType()) {
5251 // Search protocols for instance methods.
5252 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5253 E = QualID->qual_end();
5254 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005255 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005256 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005257 }
5258 // Handle messages to a pointer to interface type.
5259 else if (const ObjCObjectPointerType *IFacePtr
5260 = ReceiverType->getAsObjCInterfacePointerType()) {
5261 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005262 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005263 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5264 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005265
5266 // Search protocols for instance methods.
5267 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5268 E = IFacePtr->qual_end();
5269 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005270 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005271 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005272 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005273 // Handle messages to "id".
5274 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005275 // We're messaging "id", so provide all instance methods we know
5276 // about as code-completion results.
5277
5278 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005279 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005280 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005281 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5282 I != N; ++I) {
5283 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005284 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005285 continue;
5286
Sebastian Redldb9d2142010-08-02 23:18:59 +00005287 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005288 }
5289 }
5290
Sebastian Redldb9d2142010-08-02 23:18:59 +00005291 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5292 MEnd = MethodPool.end();
5293 M != MEnd; ++M) {
5294 for (ObjCMethodList *MethList = &M->second.first;
5295 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005296 MethList = MethList->Next) {
5297 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5298 NumSelIdents))
5299 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005300
5301 if (!Selectors.insert(MethList->Method->getSelector()))
5302 continue;
5303
Douglas Gregor13438f92010-04-06 16:40:00 +00005304 Result R(MethList->Method, 0);
5305 R.StartParameter = NumSelIdents;
5306 R.AllParametersAreInformative = false;
5307 Results.MaybeAddResult(R, CurContext);
5308 }
5309 }
5310 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005311 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005312
5313
5314 // If we're actually at the argument expression (rather than prior to the
5315 // selector), we're actually performing code completion for an expression.
5316 // Determine whether we have a single, best method. If so, we can
5317 // code-complete the expression using the corresponding parameter type as
5318 // our preferred type, improving completion results.
5319 if (AtArgumentExpression) {
5320 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5321 NumSelIdents);
5322 if (PreferredType.isNull())
5323 CodeCompleteOrdinaryName(S, PCC_Expression);
5324 else
5325 CodeCompleteExpression(S, PreferredType);
5326 return;
5327 }
5328
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005329 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005330 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005331 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005332}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005333
Douglas Gregorfb629412010-08-23 21:17:50 +00005334void Sema::CodeCompleteObjCForCollection(Scope *S,
5335 DeclGroupPtrTy IterationVar) {
5336 CodeCompleteExpressionData Data;
5337 Data.ObjCCollection = true;
5338
5339 if (IterationVar.getAsOpaquePtr()) {
5340 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5341 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5342 if (*I)
5343 Data.IgnoreDecls.push_back(*I);
5344 }
5345 }
5346
5347 CodeCompleteExpression(S, Data);
5348}
5349
Douglas Gregor458433d2010-08-26 15:07:07 +00005350void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5351 unsigned NumSelIdents) {
5352 // If we have an external source, load the entire class method
5353 // pool from the AST file.
5354 if (ExternalSource) {
5355 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5356 I != N; ++I) {
5357 Selector Sel = ExternalSource->GetExternalSelector(I);
5358 if (Sel.isNull() || MethodPool.count(Sel))
5359 continue;
5360
5361 ReadMethodPool(Sel);
5362 }
5363 }
5364
Douglas Gregor218937c2011-02-01 19:23:04 +00005365 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5366 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005367 Results.EnterNewScope();
5368 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5369 MEnd = MethodPool.end();
5370 M != MEnd; ++M) {
5371
5372 Selector Sel = M->first;
5373 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5374 continue;
5375
Douglas Gregor218937c2011-02-01 19:23:04 +00005376 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005377 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005378 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005379 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005380 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005381 continue;
5382 }
5383
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005384 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005385 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005386 if (I == NumSelIdents) {
5387 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005388 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005389 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005390 Accumulator.clear();
5391 }
5392 }
5393
Benjamin Kramera0651c52011-07-26 16:59:25 +00005394 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005395 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005396 }
Douglas Gregordae68752011-02-01 22:57:45 +00005397 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005398 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005399 }
5400 Results.ExitScope();
5401
5402 HandleCodeCompleteResults(this, CodeCompleter,
5403 CodeCompletionContext::CCC_SelectorName,
5404 Results.data(), Results.size());
5405}
5406
Douglas Gregor55385fe2009-11-18 04:19:12 +00005407/// \brief Add all of the protocol declarations that we find in the given
5408/// (translation unit) context.
5409static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005410 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005411 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005412 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005413
5414 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5415 DEnd = Ctx->decls_end();
5416 D != DEnd; ++D) {
5417 // Record any protocols we find.
5418 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005419 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005420 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005421
5422 // Record any forward-declared protocols we find.
5423 if (ObjCForwardProtocolDecl *Forward
5424 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5425 for (ObjCForwardProtocolDecl::protocol_iterator
5426 P = Forward->protocol_begin(),
5427 PEnd = Forward->protocol_end();
5428 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005429 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005430 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005431 }
5432 }
5433}
5434
5435void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5436 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005437 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5438 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005439
Douglas Gregor70c23352010-12-09 21:44:02 +00005440 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5441 Results.EnterNewScope();
5442
5443 // Tell the result set to ignore all of the protocols we have
5444 // already seen.
5445 // FIXME: This doesn't work when caching code-completion results.
5446 for (unsigned I = 0; I != NumProtocols; ++I)
5447 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5448 Protocols[I].second))
5449 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005450
Douglas Gregor70c23352010-12-09 21:44:02 +00005451 // Add all protocols.
5452 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5453 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005454
Douglas Gregor70c23352010-12-09 21:44:02 +00005455 Results.ExitScope();
5456 }
5457
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005458 HandleCodeCompleteResults(this, CodeCompleter,
5459 CodeCompletionContext::CCC_ObjCProtocolName,
5460 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005461}
5462
5463void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005464 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5465 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005466
Douglas Gregor70c23352010-12-09 21:44:02 +00005467 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5468 Results.EnterNewScope();
5469
5470 // Add all protocols.
5471 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5472 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005473
Douglas Gregor70c23352010-12-09 21:44:02 +00005474 Results.ExitScope();
5475 }
5476
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005477 HandleCodeCompleteResults(this, CodeCompleter,
5478 CodeCompletionContext::CCC_ObjCProtocolName,
5479 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005480}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005481
5482/// \brief Add all of the Objective-C interface declarations that we find in
5483/// the given (translation unit) context.
5484static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5485 bool OnlyForwardDeclarations,
5486 bool OnlyUnimplemented,
5487 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005488 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005489
5490 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5491 DEnd = Ctx->decls_end();
5492 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005493 // Record any interfaces we find.
5494 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5495 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5496 (!OnlyUnimplemented || !Class->getImplementation()))
5497 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005498
5499 // Record any forward-declared interfaces we find.
5500 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005501 ObjCInterfaceDecl *IDecl = Forward->getForwardInterfaceDecl();
5502 if ((!OnlyForwardDeclarations || IDecl->isForwardDecl()) &&
5503 (!OnlyUnimplemented || !IDecl->getImplementation()))
5504 Results.AddResult(Result(IDecl, 0), CurContext,
5505 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005506 }
5507 }
5508}
5509
5510void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005511 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5512 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005513 Results.EnterNewScope();
5514
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005515 if (CodeCompleter->includeGlobals()) {
5516 // Add all classes.
5517 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5518 false, Results);
5519 }
5520
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005521 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005522
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005523 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005524 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005525 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005526}
5527
Douglas Gregorc83c6872010-04-15 22:33:43 +00005528void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5529 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005530 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005531 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005532 Results.EnterNewScope();
5533
5534 // Make sure that we ignore the class we're currently defining.
5535 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005536 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005537 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005538 Results.Ignore(CurClass);
5539
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005540 if (CodeCompleter->includeGlobals()) {
5541 // Add all classes.
5542 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5543 false, Results);
5544 }
5545
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005546 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005547
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005548 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005549 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005550 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005551}
5552
5553void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005554 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5555 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005556 Results.EnterNewScope();
5557
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005558 if (CodeCompleter->includeGlobals()) {
5559 // Add all unimplemented classes.
5560 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5561 true, Results);
5562 }
5563
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005564 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005565
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005566 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005567 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005568 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005569}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005570
5571void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005572 IdentifierInfo *ClassName,
5573 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005574 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005575
Douglas Gregor218937c2011-02-01 19:23:04 +00005576 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005577 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005578
5579 // Ignore any categories we find that have already been implemented by this
5580 // interface.
5581 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5582 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005583 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005584 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5585 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5586 Category = Category->getNextClassCategory())
5587 CategoryNames.insert(Category->getIdentifier());
5588
5589 // Add all of the categories we know about.
5590 Results.EnterNewScope();
5591 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5592 for (DeclContext::decl_iterator D = TU->decls_begin(),
5593 DEnd = TU->decls_end();
5594 D != DEnd; ++D)
5595 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5596 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005597 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005598 Results.ExitScope();
5599
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005600 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005601 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005602 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005603}
5604
5605void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005606 IdentifierInfo *ClassName,
5607 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005608 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005609
5610 // Find the corresponding interface. If we couldn't find the interface, the
5611 // program itself is ill-formed. However, we'll try to be helpful still by
5612 // providing the list of all of the categories we know about.
5613 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005614 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005615 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5616 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005617 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005618
Douglas Gregor218937c2011-02-01 19:23:04 +00005619 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005620 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005621
5622 // Add all of the categories that have have corresponding interface
5623 // declarations in this class and any of its superclasses, except for
5624 // already-implemented categories in the class itself.
5625 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5626 Results.EnterNewScope();
5627 bool IgnoreImplemented = true;
5628 while (Class) {
5629 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5630 Category = Category->getNextClassCategory())
5631 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5632 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005633 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005634
5635 Class = Class->getSuperClass();
5636 IgnoreImplemented = false;
5637 }
5638 Results.ExitScope();
5639
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005640 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005641 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005642 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005643}
Douglas Gregor322328b2009-11-18 22:32:06 +00005644
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005645void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005646 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005647 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5648 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005649
5650 // Figure out where this @synthesize lives.
5651 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005652 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005653 if (!Container ||
5654 (!isa<ObjCImplementationDecl>(Container) &&
5655 !isa<ObjCCategoryImplDecl>(Container)))
5656 return;
5657
5658 // Ignore any properties that have already been implemented.
5659 for (DeclContext::decl_iterator D = Container->decls_begin(),
5660 DEnd = Container->decls_end();
5661 D != DEnd; ++D)
5662 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5663 Results.Ignore(PropertyImpl->getPropertyDecl());
5664
5665 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005666 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005667 Results.EnterNewScope();
5668 if (ObjCImplementationDecl *ClassImpl
5669 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005670 AddObjCProperties(ClassImpl->getClassInterface(), false,
5671 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005672 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005673 else
5674 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005675 false, /*AllowNullaryMethods=*/false, CurContext,
5676 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005677 Results.ExitScope();
5678
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005679 HandleCodeCompleteResults(this, CodeCompleter,
5680 CodeCompletionContext::CCC_Other,
5681 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005682}
5683
5684void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005685 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005686 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005687 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5688 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005689
5690 // Figure out where this @synthesize lives.
5691 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005692 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005693 if (!Container ||
5694 (!isa<ObjCImplementationDecl>(Container) &&
5695 !isa<ObjCCategoryImplDecl>(Container)))
5696 return;
5697
5698 // Figure out which interface we're looking into.
5699 ObjCInterfaceDecl *Class = 0;
5700 if (ObjCImplementationDecl *ClassImpl
5701 = dyn_cast<ObjCImplementationDecl>(Container))
5702 Class = ClassImpl->getClassInterface();
5703 else
5704 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5705 ->getClassInterface();
5706
Douglas Gregore8426052011-04-18 14:40:46 +00005707 // Determine the type of the property we're synthesizing.
5708 QualType PropertyType = Context.getObjCIdType();
5709 if (Class) {
5710 if (ObjCPropertyDecl *Property
5711 = Class->FindPropertyDeclaration(PropertyName)) {
5712 PropertyType
5713 = Property->getType().getNonReferenceType().getUnqualifiedType();
5714
5715 // Give preference to ivars
5716 Results.setPreferredType(PropertyType);
5717 }
5718 }
5719
Douglas Gregor322328b2009-11-18 22:32:06 +00005720 // Add all of the instance variables in this class and its superclasses.
5721 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005722 bool SawSimilarlyNamedIvar = false;
5723 std::string NameWithPrefix;
5724 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005725 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005726 std::string NameWithSuffix = PropertyName->getName().str();
5727 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005728 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005729 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5730 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005731 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5732
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005733 // Determine whether we've seen an ivar with a name similar to the
5734 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005735 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005736 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005737 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005738 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005739
5740 // Reduce the priority of this result by one, to give it a slight
5741 // advantage over other results whose names don't match so closely.
5742 if (Results.size() &&
5743 Results.data()[Results.size() - 1].Kind
5744 == CodeCompletionResult::RK_Declaration &&
5745 Results.data()[Results.size() - 1].Declaration == Ivar)
5746 Results.data()[Results.size() - 1].Priority--;
5747 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005748 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005749 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005750
5751 if (!SawSimilarlyNamedIvar) {
5752 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005753 // an ivar of the appropriate type.
5754 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005755 typedef CodeCompletionResult Result;
5756 CodeCompletionAllocator &Allocator = Results.getAllocator();
5757 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5758
Douglas Gregor8987b232011-09-27 23:30:47 +00005759 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8426052011-04-18 14:40:46 +00005760 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005761 Policy, Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005762 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5763 Results.AddResult(Result(Builder.TakeString(), Priority,
5764 CXCursor_ObjCIvarDecl));
5765 }
5766
Douglas Gregor322328b2009-11-18 22:32:06 +00005767 Results.ExitScope();
5768
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005769 HandleCodeCompleteResults(this, CodeCompleter,
5770 CodeCompletionContext::CCC_Other,
5771 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005772}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005773
Douglas Gregor408be5a2010-08-25 01:08:01 +00005774// Mapping from selectors to the methods that implement that selector, along
5775// with the "in original class" flag.
5776typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5777 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005778
5779/// \brief Find all of the methods that reside in the given container
5780/// (and its superclasses, protocols, etc.) that meet the given
5781/// criteria. Insert those methods into the map of known methods,
5782/// indexed by selector so they can be easily found.
5783static void FindImplementableMethods(ASTContext &Context,
5784 ObjCContainerDecl *Container,
5785 bool WantInstanceMethods,
5786 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005787 KnownMethodsMap &KnownMethods,
5788 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005789 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5790 // Recurse into protocols.
5791 const ObjCList<ObjCProtocolDecl> &Protocols
5792 = IFace->getReferencedProtocols();
5793 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005794 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005795 I != E; ++I)
5796 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005797 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005798
Douglas Gregorea766182010-10-18 18:21:28 +00005799 // Add methods from any class extensions and categories.
5800 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5801 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005802 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5803 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005804 KnownMethods, false);
5805
5806 // Visit the superclass.
5807 if (IFace->getSuperClass())
5808 FindImplementableMethods(Context, IFace->getSuperClass(),
5809 WantInstanceMethods, ReturnType,
5810 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005811 }
5812
5813 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5814 // Recurse into protocols.
5815 const ObjCList<ObjCProtocolDecl> &Protocols
5816 = Category->getReferencedProtocols();
5817 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005818 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005819 I != E; ++I)
5820 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005821 KnownMethods, InOriginalClass);
5822
5823 // If this category is the original class, jump to the interface.
5824 if (InOriginalClass && Category->getClassInterface())
5825 FindImplementableMethods(Context, Category->getClassInterface(),
5826 WantInstanceMethods, ReturnType, KnownMethods,
5827 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005828 }
5829
5830 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5831 // Recurse into protocols.
5832 const ObjCList<ObjCProtocolDecl> &Protocols
5833 = Protocol->getReferencedProtocols();
5834 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5835 E = Protocols.end();
5836 I != E; ++I)
5837 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005838 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005839 }
5840
5841 // Add methods in this container. This operation occurs last because
5842 // we want the methods from this container to override any methods
5843 // we've previously seen with the same selector.
5844 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5845 MEnd = Container->meth_end();
5846 M != MEnd; ++M) {
5847 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5848 if (!ReturnType.isNull() &&
5849 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5850 continue;
5851
Douglas Gregor408be5a2010-08-25 01:08:01 +00005852 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005853 }
5854 }
5855}
5856
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005857/// \brief Add the parenthesized return or parameter type chunk to a code
5858/// completion string.
5859static void AddObjCPassingTypeChunk(QualType Type,
5860 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005861 const PrintingPolicy &Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005862 CodeCompletionBuilder &Builder) {
5863 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor8987b232011-09-27 23:30:47 +00005864 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005865 Builder.getAllocator()));
5866 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5867}
5868
5869/// \brief Determine whether the given class is or inherits from a class by
5870/// the given name.
5871static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005872 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005873 if (!Class)
5874 return false;
5875
5876 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5877 return true;
5878
5879 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5880}
5881
5882/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5883/// Key-Value Observing (KVO).
5884static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5885 bool IsInstanceMethod,
5886 QualType ReturnType,
5887 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005888 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005889 ResultBuilder &Results) {
5890 IdentifierInfo *PropName = Property->getIdentifier();
5891 if (!PropName || PropName->getLength() == 0)
5892 return;
5893
Douglas Gregor8987b232011-09-27 23:30:47 +00005894 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5895
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005896 // Builder that will create each code completion.
5897 typedef CodeCompletionResult Result;
5898 CodeCompletionAllocator &Allocator = Results.getAllocator();
5899 CodeCompletionBuilder Builder(Allocator);
5900
5901 // The selector table.
5902 SelectorTable &Selectors = Context.Selectors;
5903
5904 // The property name, copied into the code completion allocation region
5905 // on demand.
5906 struct KeyHolder {
5907 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005908 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005909 const char *CopiedKey;
5910
Chris Lattner5f9e2722011-07-23 10:55:15 +00005911 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005912 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5913
5914 operator const char *() {
5915 if (CopiedKey)
5916 return CopiedKey;
5917
5918 return CopiedKey = Allocator.CopyString(Key);
5919 }
5920 } Key(Allocator, PropName->getName());
5921
5922 // The uppercased name of the property name.
5923 std::string UpperKey = PropName->getName();
5924 if (!UpperKey.empty())
5925 UpperKey[0] = toupper(UpperKey[0]);
5926
5927 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5928 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5929 Property->getType());
5930 bool ReturnTypeMatchesVoid
5931 = ReturnType.isNull() || ReturnType->isVoidType();
5932
5933 // Add the normal accessor -(type)key.
5934 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005935 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005936 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5937 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00005938 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005939
5940 Builder.AddTypedTextChunk(Key);
5941 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5942 CXCursor_ObjCInstanceMethodDecl));
5943 }
5944
5945 // If we have an integral or boolean property (or the user has provided
5946 // an integral or boolean return type), add the accessor -(type)isKey.
5947 if (IsInstanceMethod &&
5948 ((!ReturnType.isNull() &&
5949 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5950 (ReturnType.isNull() &&
5951 (Property->getType()->isIntegerType() ||
5952 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005953 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005954 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005955 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005956 if (ReturnType.isNull()) {
5957 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5958 Builder.AddTextChunk("BOOL");
5959 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5960 }
5961
5962 Builder.AddTypedTextChunk(
5963 Allocator.CopyString(SelectorId->getName()));
5964 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5965 CXCursor_ObjCInstanceMethodDecl));
5966 }
5967 }
5968
5969 // Add the normal mutator.
5970 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5971 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005972 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005973 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005974 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005975 if (ReturnType.isNull()) {
5976 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5977 Builder.AddTextChunk("void");
5978 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5979 }
5980
5981 Builder.AddTypedTextChunk(
5982 Allocator.CopyString(SelectorId->getName()));
5983 Builder.AddTypedTextChunk(":");
Douglas Gregor8987b232011-09-27 23:30:47 +00005984 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005985 Builder.AddTextChunk(Key);
5986 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5987 CXCursor_ObjCInstanceMethodDecl));
5988 }
5989 }
5990
5991 // Indexed and unordered accessors
5992 unsigned IndexedGetterPriority = CCP_CodePattern;
5993 unsigned IndexedSetterPriority = CCP_CodePattern;
5994 unsigned UnorderedGetterPriority = CCP_CodePattern;
5995 unsigned UnorderedSetterPriority = CCP_CodePattern;
5996 if (const ObjCObjectPointerType *ObjCPointer
5997 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5998 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5999 // If this interface type is not provably derived from a known
6000 // collection, penalize the corresponding completions.
6001 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6002 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6003 if (!InheritsFromClassNamed(IFace, "NSArray"))
6004 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6005 }
6006
6007 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6008 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6009 if (!InheritsFromClassNamed(IFace, "NSSet"))
6010 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6011 }
6012 }
6013 } else {
6014 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6015 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6016 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6017 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6018 }
6019
6020 // Add -(NSUInteger)countOf<key>
6021 if (IsInstanceMethod &&
6022 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006023 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006024 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006025 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006026 if (ReturnType.isNull()) {
6027 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6028 Builder.AddTextChunk("NSUInteger");
6029 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6030 }
6031
6032 Builder.AddTypedTextChunk(
6033 Allocator.CopyString(SelectorId->getName()));
6034 Results.AddResult(Result(Builder.TakeString(),
6035 std::min(IndexedGetterPriority,
6036 UnorderedGetterPriority),
6037 CXCursor_ObjCInstanceMethodDecl));
6038 }
6039 }
6040
6041 // Indexed getters
6042 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6043 if (IsInstanceMethod &&
6044 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00006045 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006046 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006047 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006048 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006049 if (ReturnType.isNull()) {
6050 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6051 Builder.AddTextChunk("id");
6052 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6053 }
6054
6055 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6056 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6057 Builder.AddTextChunk("NSUInteger");
6058 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6059 Builder.AddTextChunk("index");
6060 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6061 CXCursor_ObjCInstanceMethodDecl));
6062 }
6063 }
6064
6065 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6066 if (IsInstanceMethod &&
6067 (ReturnType.isNull() ||
6068 (ReturnType->isObjCObjectPointerType() &&
6069 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6070 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6071 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006072 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006073 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006074 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006075 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006076 if (ReturnType.isNull()) {
6077 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6078 Builder.AddTextChunk("NSArray *");
6079 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6080 }
6081
6082 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6083 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6084 Builder.AddTextChunk("NSIndexSet *");
6085 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6086 Builder.AddTextChunk("indexes");
6087 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6088 CXCursor_ObjCInstanceMethodDecl));
6089 }
6090 }
6091
6092 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6093 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006094 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006095 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006096 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006097 &Context.Idents.get("range")
6098 };
6099
Douglas Gregore74c25c2011-05-04 23:50:46 +00006100 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006101 if (ReturnType.isNull()) {
6102 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6103 Builder.AddTextChunk("void");
6104 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6105 }
6106
6107 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6108 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6109 Builder.AddPlaceholderChunk("object-type");
6110 Builder.AddTextChunk(" **");
6111 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6112 Builder.AddTextChunk("buffer");
6113 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6114 Builder.AddTypedTextChunk("range:");
6115 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6116 Builder.AddTextChunk("NSRange");
6117 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6118 Builder.AddTextChunk("inRange");
6119 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6120 CXCursor_ObjCInstanceMethodDecl));
6121 }
6122 }
6123
6124 // Mutable indexed accessors
6125
6126 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6127 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006128 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006129 IdentifierInfo *SelectorIds[2] = {
6130 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006131 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006132 };
6133
Douglas Gregore74c25c2011-05-04 23:50:46 +00006134 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006135 if (ReturnType.isNull()) {
6136 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6137 Builder.AddTextChunk("void");
6138 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6139 }
6140
6141 Builder.AddTypedTextChunk("insertObject:");
6142 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6143 Builder.AddPlaceholderChunk("object-type");
6144 Builder.AddTextChunk(" *");
6145 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6146 Builder.AddTextChunk("object");
6147 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6148 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6149 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6150 Builder.AddPlaceholderChunk("NSUInteger");
6151 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6152 Builder.AddTextChunk("index");
6153 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6154 CXCursor_ObjCInstanceMethodDecl));
6155 }
6156 }
6157
6158 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6159 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006160 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006161 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006162 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006163 &Context.Idents.get("atIndexes")
6164 };
6165
Douglas Gregore74c25c2011-05-04 23:50:46 +00006166 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006167 if (ReturnType.isNull()) {
6168 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6169 Builder.AddTextChunk("void");
6170 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6171 }
6172
6173 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6174 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6175 Builder.AddTextChunk("NSArray *");
6176 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6177 Builder.AddTextChunk("array");
6178 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6179 Builder.AddTypedTextChunk("atIndexes:");
6180 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6181 Builder.AddPlaceholderChunk("NSIndexSet *");
6182 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6183 Builder.AddTextChunk("indexes");
6184 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6185 CXCursor_ObjCInstanceMethodDecl));
6186 }
6187 }
6188
6189 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6190 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006191 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006192 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006193 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006194 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006195 if (ReturnType.isNull()) {
6196 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6197 Builder.AddTextChunk("void");
6198 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6199 }
6200
6201 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6202 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6203 Builder.AddTextChunk("NSUInteger");
6204 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6205 Builder.AddTextChunk("index");
6206 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6207 CXCursor_ObjCInstanceMethodDecl));
6208 }
6209 }
6210
6211 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6212 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006213 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006214 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006215 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006216 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006217 if (ReturnType.isNull()) {
6218 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6219 Builder.AddTextChunk("void");
6220 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6221 }
6222
6223 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6224 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6225 Builder.AddTextChunk("NSIndexSet *");
6226 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6227 Builder.AddTextChunk("indexes");
6228 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6229 CXCursor_ObjCInstanceMethodDecl));
6230 }
6231 }
6232
6233 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6234 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006235 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006236 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006237 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006238 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006239 &Context.Idents.get("withObject")
6240 };
6241
Douglas Gregore74c25c2011-05-04 23:50:46 +00006242 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006243 if (ReturnType.isNull()) {
6244 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6245 Builder.AddTextChunk("void");
6246 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6247 }
6248
6249 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6250 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6251 Builder.AddPlaceholderChunk("NSUInteger");
6252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6253 Builder.AddTextChunk("index");
6254 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6255 Builder.AddTypedTextChunk("withObject:");
6256 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6257 Builder.AddTextChunk("id");
6258 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6259 Builder.AddTextChunk("object");
6260 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6261 CXCursor_ObjCInstanceMethodDecl));
6262 }
6263 }
6264
6265 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6266 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006267 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006268 = (Twine("replace") + UpperKey + "AtIndexes").str();
6269 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006270 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006271 &Context.Idents.get(SelectorName1),
6272 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006273 };
6274
Douglas Gregore74c25c2011-05-04 23:50:46 +00006275 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006276 if (ReturnType.isNull()) {
6277 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6278 Builder.AddTextChunk("void");
6279 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6280 }
6281
6282 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6283 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6284 Builder.AddPlaceholderChunk("NSIndexSet *");
6285 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6286 Builder.AddTextChunk("indexes");
6287 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6288 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6289 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6290 Builder.AddTextChunk("NSArray *");
6291 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6292 Builder.AddTextChunk("array");
6293 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6294 CXCursor_ObjCInstanceMethodDecl));
6295 }
6296 }
6297
6298 // Unordered getters
6299 // - (NSEnumerator *)enumeratorOfKey
6300 if (IsInstanceMethod &&
6301 (ReturnType.isNull() ||
6302 (ReturnType->isObjCObjectPointerType() &&
6303 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6304 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6305 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006306 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006307 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006308 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006309 if (ReturnType.isNull()) {
6310 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6311 Builder.AddTextChunk("NSEnumerator *");
6312 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6313 }
6314
6315 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6316 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6317 CXCursor_ObjCInstanceMethodDecl));
6318 }
6319 }
6320
6321 // - (type *)memberOfKey:(type *)object
6322 if (IsInstanceMethod &&
6323 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006324 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006325 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006326 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006327 if (ReturnType.isNull()) {
6328 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6329 Builder.AddPlaceholderChunk("object-type");
6330 Builder.AddTextChunk(" *");
6331 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6332 }
6333
6334 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6335 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6336 if (ReturnType.isNull()) {
6337 Builder.AddPlaceholderChunk("object-type");
6338 Builder.AddTextChunk(" *");
6339 } else {
6340 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006341 Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006342 Builder.getAllocator()));
6343 }
6344 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6345 Builder.AddTextChunk("object");
6346 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6347 CXCursor_ObjCInstanceMethodDecl));
6348 }
6349 }
6350
6351 // Mutable unordered accessors
6352 // - (void)addKeyObject:(type *)object
6353 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006354 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006355 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006356 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006357 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006358 if (ReturnType.isNull()) {
6359 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6360 Builder.AddTextChunk("void");
6361 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6362 }
6363
6364 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6365 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6366 Builder.AddPlaceholderChunk("object-type");
6367 Builder.AddTextChunk(" *");
6368 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6369 Builder.AddTextChunk("object");
6370 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6371 CXCursor_ObjCInstanceMethodDecl));
6372 }
6373 }
6374
6375 // - (void)addKey:(NSSet *)objects
6376 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006377 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006378 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006379 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006380 if (ReturnType.isNull()) {
6381 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6382 Builder.AddTextChunk("void");
6383 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6384 }
6385
6386 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6387 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6388 Builder.AddTextChunk("NSSet *");
6389 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6390 Builder.AddTextChunk("objects");
6391 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6392 CXCursor_ObjCInstanceMethodDecl));
6393 }
6394 }
6395
6396 // - (void)removeKeyObject:(type *)object
6397 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006398 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006399 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006400 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006401 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006402 if (ReturnType.isNull()) {
6403 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6404 Builder.AddTextChunk("void");
6405 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6406 }
6407
6408 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6409 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6410 Builder.AddPlaceholderChunk("object-type");
6411 Builder.AddTextChunk(" *");
6412 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6413 Builder.AddTextChunk("object");
6414 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6415 CXCursor_ObjCInstanceMethodDecl));
6416 }
6417 }
6418
6419 // - (void)removeKey:(NSSet *)objects
6420 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006421 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006422 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006423 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006424 if (ReturnType.isNull()) {
6425 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6426 Builder.AddTextChunk("void");
6427 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6428 }
6429
6430 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6431 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6432 Builder.AddTextChunk("NSSet *");
6433 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6434 Builder.AddTextChunk("objects");
6435 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6436 CXCursor_ObjCInstanceMethodDecl));
6437 }
6438 }
6439
6440 // - (void)intersectKey:(NSSet *)objects
6441 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006442 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006443 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006444 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006445 if (ReturnType.isNull()) {
6446 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6447 Builder.AddTextChunk("void");
6448 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6449 }
6450
6451 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6452 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6453 Builder.AddTextChunk("NSSet *");
6454 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6455 Builder.AddTextChunk("objects");
6456 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6457 CXCursor_ObjCInstanceMethodDecl));
6458 }
6459 }
6460
6461 // Key-Value Observing
6462 // + (NSSet *)keyPathsForValuesAffectingKey
6463 if (!IsInstanceMethod &&
6464 (ReturnType.isNull() ||
6465 (ReturnType->isObjCObjectPointerType() &&
6466 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6467 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6468 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006469 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006470 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006471 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006472 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006473 if (ReturnType.isNull()) {
6474 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6475 Builder.AddTextChunk("NSSet *");
6476 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6477 }
6478
6479 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6480 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006481 CXCursor_ObjCClassMethodDecl));
6482 }
6483 }
6484
6485 // + (BOOL)automaticallyNotifiesObserversForKey
6486 if (!IsInstanceMethod &&
6487 (ReturnType.isNull() ||
6488 ReturnType->isIntegerType() ||
6489 ReturnType->isBooleanType())) {
6490 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006491 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006492 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6493 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6494 if (ReturnType.isNull()) {
6495 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6496 Builder.AddTextChunk("BOOL");
6497 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6498 }
6499
6500 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6501 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6502 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006503 }
6504 }
6505}
6506
Douglas Gregore8f5a172010-04-07 00:21:17 +00006507void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6508 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006509 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006510 // Determine the return type of the method we're declaring, if
6511 // provided.
6512 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006513 Decl *IDecl = 0;
6514 if (CurContext->isObjCContainer()) {
6515 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6516 IDecl = cast<Decl>(OCD);
6517 }
Douglas Gregorea766182010-10-18 18:21:28 +00006518 // Determine where we should start searching for methods.
6519 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006520 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006521 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006522 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6523 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006524 IsInImplementation = true;
6525 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006526 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006527 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006528 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006529 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006530 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006531 }
6532
6533 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006534 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006535 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006536 }
6537
Douglas Gregorea766182010-10-18 18:21:28 +00006538 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006539 HandleCodeCompleteResults(this, CodeCompleter,
6540 CodeCompletionContext::CCC_Other,
6541 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006542 return;
6543 }
6544
6545 // Find all of the methods that we could declare/implement here.
6546 KnownMethodsMap KnownMethods;
6547 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006548 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006549
Douglas Gregore8f5a172010-04-07 00:21:17 +00006550 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006551 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006552 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6553 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006554 Results.EnterNewScope();
Douglas Gregor8987b232011-09-27 23:30:47 +00006555 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006556 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6557 MEnd = KnownMethods.end();
6558 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006559 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006560 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006561
6562 // If the result type was not already provided, add it to the
6563 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006564 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00006565 AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,
6566 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006567
6568 Selector Sel = Method->getSelector();
6569
6570 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006571 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006572 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006573
6574 // Add parameters to the pattern.
6575 unsigned I = 0;
6576 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6577 PEnd = Method->param_end();
6578 P != PEnd; (void)++P, ++I) {
6579 // Add the part of the selector name.
6580 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006581 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006582 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006583 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6584 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006585 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006586 } else
6587 break;
6588
6589 // Add the parameter type.
Douglas Gregor8987b232011-09-27 23:30:47 +00006590 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,
6591 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006592
6593 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006594 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006595 }
6596
6597 if (Method->isVariadic()) {
6598 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006599 Builder.AddChunk(CodeCompletionString::CK_Comma);
6600 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006601 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006602
Douglas Gregor447107d2010-05-28 00:57:46 +00006603 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006604 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006605 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6606 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6607 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006608 if (!Method->getResultType()->isVoidType()) {
6609 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006610 Builder.AddTextChunk("return");
6611 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6612 Builder.AddPlaceholderChunk("expression");
6613 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006614 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006615 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006616
Douglas Gregor218937c2011-02-01 19:23:04 +00006617 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6618 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006619 }
6620
Douglas Gregor408be5a2010-08-25 01:08:01 +00006621 unsigned Priority = CCP_CodePattern;
6622 if (!M->second.second)
6623 Priority += CCD_InBaseClass;
6624
Douglas Gregor218937c2011-02-01 19:23:04 +00006625 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006626 Method->isInstanceMethod()
6627 ? CXCursor_ObjCInstanceMethodDecl
6628 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006629 }
6630
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006631 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6632 // the properties in this class and its categories.
6633 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006634 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006635 Containers.push_back(SearchDecl);
6636
Douglas Gregore74c25c2011-05-04 23:50:46 +00006637 VisitedSelectorSet KnownSelectors;
6638 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6639 MEnd = KnownMethods.end();
6640 M != MEnd; ++M)
6641 KnownSelectors.insert(M->first);
6642
6643
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006644 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6645 if (!IFace)
6646 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6647 IFace = Category->getClassInterface();
6648
6649 if (IFace) {
6650 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6651 Category = Category->getNextClassCategory())
6652 Containers.push_back(Category);
6653 }
6654
6655 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6656 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6657 PEnd = Containers[I]->prop_end();
6658 P != PEnd; ++P) {
6659 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006660 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006661 }
6662 }
6663 }
6664
Douglas Gregore8f5a172010-04-07 00:21:17 +00006665 Results.ExitScope();
6666
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006667 HandleCodeCompleteResults(this, CodeCompleter,
6668 CodeCompletionContext::CCC_Other,
6669 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006670}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006671
6672void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6673 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006674 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006675 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006676 IdentifierInfo **SelIdents,
6677 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006678 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006679 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006680 if (ExternalSource) {
6681 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6682 I != N; ++I) {
6683 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006684 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006685 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006686
6687 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006688 }
6689 }
6690
6691 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006692 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006693 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6694 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006695
6696 if (ReturnTy)
6697 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006698
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006699 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006700 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6701 MEnd = MethodPool.end();
6702 M != MEnd; ++M) {
6703 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6704 &M->second.second;
6705 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006706 MethList = MethList->Next) {
6707 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6708 NumSelIdents))
6709 continue;
6710
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006711 if (AtParameterName) {
6712 // Suggest parameter names we've seen before.
6713 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6714 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6715 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006716 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006717 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006718 Param->getIdentifier()->getName()));
6719 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006720 }
6721 }
6722
6723 continue;
6724 }
6725
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006726 Result R(MethList->Method, 0);
6727 R.StartParameter = NumSelIdents;
6728 R.AllParametersAreInformative = false;
6729 R.DeclaringEntity = true;
6730 Results.MaybeAddResult(R, CurContext);
6731 }
6732 }
6733
6734 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006735 HandleCodeCompleteResults(this, CodeCompleter,
6736 CodeCompletionContext::CCC_Other,
6737 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006738}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006739
Douglas Gregorf29c5232010-08-24 22:20:20 +00006740void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006741 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006742 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006743 Results.EnterNewScope();
6744
6745 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006746 CodeCompletionBuilder Builder(Results.getAllocator());
6747 Builder.AddTypedTextChunk("if");
6748 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6749 Builder.AddPlaceholderChunk("condition");
6750 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006751
6752 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006753 Builder.AddTypedTextChunk("ifdef");
6754 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6755 Builder.AddPlaceholderChunk("macro");
6756 Results.AddResult(Builder.TakeString());
6757
Douglas Gregorf44e8542010-08-24 19:08:16 +00006758 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006759 Builder.AddTypedTextChunk("ifndef");
6760 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6761 Builder.AddPlaceholderChunk("macro");
6762 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006763
6764 if (InConditional) {
6765 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006766 Builder.AddTypedTextChunk("elif");
6767 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6768 Builder.AddPlaceholderChunk("condition");
6769 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006770
6771 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006772 Builder.AddTypedTextChunk("else");
6773 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006774
6775 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006776 Builder.AddTypedTextChunk("endif");
6777 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006778 }
6779
6780 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006781 Builder.AddTypedTextChunk("include");
6782 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6783 Builder.AddTextChunk("\"");
6784 Builder.AddPlaceholderChunk("header");
6785 Builder.AddTextChunk("\"");
6786 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006787
6788 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006789 Builder.AddTypedTextChunk("include");
6790 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6791 Builder.AddTextChunk("<");
6792 Builder.AddPlaceholderChunk("header");
6793 Builder.AddTextChunk(">");
6794 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006795
6796 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006797 Builder.AddTypedTextChunk("define");
6798 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6799 Builder.AddPlaceholderChunk("macro");
6800 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006801
6802 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006803 Builder.AddTypedTextChunk("define");
6804 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6805 Builder.AddPlaceholderChunk("macro");
6806 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6807 Builder.AddPlaceholderChunk("args");
6808 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6809 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006810
6811 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006812 Builder.AddTypedTextChunk("undef");
6813 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6814 Builder.AddPlaceholderChunk("macro");
6815 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006816
6817 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006818 Builder.AddTypedTextChunk("line");
6819 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6820 Builder.AddPlaceholderChunk("number");
6821 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006822
6823 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006824 Builder.AddTypedTextChunk("line");
6825 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6826 Builder.AddPlaceholderChunk("number");
6827 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6828 Builder.AddTextChunk("\"");
6829 Builder.AddPlaceholderChunk("filename");
6830 Builder.AddTextChunk("\"");
6831 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006832
6833 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006834 Builder.AddTypedTextChunk("error");
6835 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6836 Builder.AddPlaceholderChunk("message");
6837 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006838
6839 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006840 Builder.AddTypedTextChunk("pragma");
6841 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6842 Builder.AddPlaceholderChunk("arguments");
6843 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006844
6845 if (getLangOptions().ObjC1) {
6846 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006847 Builder.AddTypedTextChunk("import");
6848 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6849 Builder.AddTextChunk("\"");
6850 Builder.AddPlaceholderChunk("header");
6851 Builder.AddTextChunk("\"");
6852 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006853
6854 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006855 Builder.AddTypedTextChunk("import");
6856 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6857 Builder.AddTextChunk("<");
6858 Builder.AddPlaceholderChunk("header");
6859 Builder.AddTextChunk(">");
6860 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006861 }
6862
6863 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006864 Builder.AddTypedTextChunk("include_next");
6865 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6866 Builder.AddTextChunk("\"");
6867 Builder.AddPlaceholderChunk("header");
6868 Builder.AddTextChunk("\"");
6869 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006870
6871 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006872 Builder.AddTypedTextChunk("include_next");
6873 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6874 Builder.AddTextChunk("<");
6875 Builder.AddPlaceholderChunk("header");
6876 Builder.AddTextChunk(">");
6877 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006878
6879 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006880 Builder.AddTypedTextChunk("warning");
6881 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6882 Builder.AddPlaceholderChunk("message");
6883 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006884
6885 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6886 // completions for them. And __include_macros is a Clang-internal extension
6887 // that we don't want to encourage anyone to use.
6888
6889 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6890 Results.ExitScope();
6891
Douglas Gregorf44e8542010-08-24 19:08:16 +00006892 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006893 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006894 Results.data(), Results.size());
6895}
6896
6897void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006898 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006899 S->getFnParent()? Sema::PCC_RecoveryInFunction
6900 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006901}
6902
Douglas Gregorf29c5232010-08-24 22:20:20 +00006903void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006904 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006905 IsDefinition? CodeCompletionContext::CCC_MacroName
6906 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006907 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6908 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006909 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006910 Results.EnterNewScope();
6911 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6912 MEnd = PP.macro_end();
6913 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006914 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006915 M->first->getName()));
6916 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006917 }
6918 Results.ExitScope();
6919 } else if (IsDefinition) {
6920 // FIXME: Can we detect when the user just wrote an include guard above?
6921 }
6922
Douglas Gregor52779fb2010-09-23 23:01:17 +00006923 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006924 Results.data(), Results.size());
6925}
6926
Douglas Gregorf29c5232010-08-24 22:20:20 +00006927void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006928 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006929 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006930
6931 if (!CodeCompleter || CodeCompleter->includeMacros())
6932 AddMacroResults(PP, Results);
6933
6934 // defined (<macro>)
6935 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006936 CodeCompletionBuilder Builder(Results.getAllocator());
6937 Builder.AddTypedTextChunk("defined");
6938 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6939 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6940 Builder.AddPlaceholderChunk("macro");
6941 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6942 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006943 Results.ExitScope();
6944
6945 HandleCodeCompleteResults(this, CodeCompleter,
6946 CodeCompletionContext::CCC_PreprocessorExpression,
6947 Results.data(), Results.size());
6948}
6949
6950void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6951 IdentifierInfo *Macro,
6952 MacroInfo *MacroInfo,
6953 unsigned Argument) {
6954 // FIXME: In the future, we could provide "overload" results, much like we
6955 // do for function calls.
6956
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00006957 // Now just ignore this. There will be another code-completion callback
6958 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00006959}
6960
Douglas Gregor55817af2010-08-25 17:04:25 +00006961void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006962 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006963 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006964 0, 0);
6965}
6966
Douglas Gregordae68752011-02-01 22:57:45 +00006967void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006968 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006969 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006970 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6971 CodeCompletionDeclConsumer Consumer(Builder,
6972 Context.getTranslationUnitDecl());
6973 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6974 Consumer);
6975 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006976
6977 if (!CodeCompleter || CodeCompleter->includeMacros())
6978 AddMacroResults(PP, Builder);
6979
6980 Results.clear();
6981 Results.insert(Results.end(),
6982 Builder.data(), Builder.data() + Builder.size());
6983}