blob: 4066a06e5295b73bac9afb56a4c5eca99befba60 [file] [log] [blame]
Douglas Gregor81b747b2009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
John McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
John McCall120d63c2010-08-24 20:38:10 +000015#include "clang/Sema/Overload.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000016#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregor719770d2010-04-06 17:30:22 +000017#include "clang/Sema/ExternalSemaSource.h"
John McCall5f1e0942010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000023#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
Douglas Gregord36adf52010-09-16 16:06:31 +000025#include "llvm/ADT/DenseSet.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000026#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000027#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000028#include "llvm/ADT/StringSwitch.h"
Douglas Gregor458433d2010-08-26 15:07:07 +000029#include "llvm/ADT/Twine.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000030#include <list>
31#include <map>
32#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000033
34using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000035using namespace sema;
Douglas Gregor81b747b2009-09-17 21:32:03 +000036
Douglas Gregor86d9a522009-09-21 16:56:56 +000037namespace {
38 /// \brief A container of code-completion results.
39 class ResultBuilder {
40 public:
41 /// \brief The type of a name-lookup filter, which can be provided to the
42 /// name-lookup routines to specify which declarations should be included in
43 /// the result set (when it returns true) and which declarations should be
44 /// filtered out (returns false).
45 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
46
John McCall0a2c5e22010-08-25 06:19:51 +000047 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +000048
49 private:
50 /// \brief The actual results we have found.
51 std::vector<Result> Results;
52
53 /// \brief A record of all of the declarations we have found and placed
54 /// into the result set, used to ensure that no declaration ever gets into
55 /// the result set twice.
56 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
57
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000058 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
59
60 /// \brief An entry in the shadow map, which is optimized to store
61 /// a single (declaration, index) mapping (the common case) but
62 /// can also store a list of (declaration, index) mappings.
63 class ShadowMapEntry {
Chris Lattner5f9e2722011-07-23 10:55:15 +000064 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000065
66 /// \brief Contains either the solitary NamedDecl * or a vector
67 /// of (declaration, index) pairs.
68 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
69
70 /// \brief When the entry contains a single declaration, this is
71 /// the index associated with that entry.
72 unsigned SingleDeclIndex;
73
74 public:
75 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
76
77 void Add(NamedDecl *ND, unsigned Index) {
78 if (DeclOrVector.isNull()) {
79 // 0 - > 1 elements: just set the single element information.
80 DeclOrVector = ND;
81 SingleDeclIndex = Index;
82 return;
83 }
84
85 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
86 // 1 -> 2 elements: create the vector of results and push in the
87 // existing declaration.
88 DeclIndexPairVector *Vec = new DeclIndexPairVector;
89 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
90 DeclOrVector = Vec;
91 }
92
93 // Add the new element to the end of the vector.
94 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
95 DeclIndexPair(ND, Index));
96 }
97
98 void Destroy() {
99 if (DeclIndexPairVector *Vec
100 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
101 delete Vec;
102 DeclOrVector = ((NamedDecl *)0);
103 }
104 }
105
106 // Iteration.
107 class iterator;
108 iterator begin() const;
109 iterator end() const;
110 };
111
Douglas Gregor86d9a522009-09-21 16:56:56 +0000112 /// \brief A mapping from declaration names to the declarations that have
113 /// this name within a particular scope and their index within the list of
114 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000115 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000116
117 /// \brief The semantic analysis object for which results are being
118 /// produced.
119 Sema &SemaRef;
Douglas Gregor218937c2011-02-01 19:23:04 +0000120
121 /// \brief The allocator used to allocate new code-completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000122 CodeCompletionAllocator &Allocator;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000123
124 /// \brief If non-NULL, a filter function used to remove any code-completion
125 /// results that are not desirable.
126 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000127
128 /// \brief Whether we should allow declarations as
129 /// nested-name-specifiers that would otherwise be filtered out.
130 bool AllowNestedNameSpecifiers;
131
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000132 /// \brief If set, the type that we would prefer our resulting value
133 /// declarations to have.
134 ///
135 /// Closely matching the preferred type gives a boost to a result's
136 /// priority.
137 CanQualType PreferredType;
138
Douglas Gregor86d9a522009-09-21 16:56:56 +0000139 /// \brief A list of shadow maps, which is used to model name hiding at
140 /// different levels of, e.g., the inheritance hierarchy.
141 std::list<ShadowMap> ShadowMaps;
142
Douglas Gregor3cdee122010-08-26 16:36:48 +0000143 /// \brief If we're potentially referring to a C++ member function, the set
144 /// of qualifiers applied to the object type.
145 Qualifiers ObjectTypeQualifiers;
146
147 /// \brief Whether the \p ObjectTypeQualifiers field is active.
148 bool HasObjectTypeQualifiers;
149
Douglas Gregor265f7492010-08-27 15:29:55 +0000150 /// \brief The selector that we prefer.
151 Selector PreferredSelector;
152
Douglas Gregorca45da02010-11-02 20:36:02 +0000153 /// \brief The completion context in which we are gathering results.
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000154 CodeCompletionContext CompletionContext;
155
Douglas Gregorca45da02010-11-02 20:36:02 +0000156 /// \brief If we are in an instance method definition, the @implementation
157 /// object.
158 ObjCImplementationDecl *ObjCImplementation;
159
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000160 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000161
Douglas Gregor6f942b22010-09-21 16:06:22 +0000162 void MaybeAddConstructorResults(Result R);
163
Douglas Gregor86d9a522009-09-21 16:56:56 +0000164 public:
Douglas Gregordae68752011-02-01 22:57:45 +0000165 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Douglas Gregor52779fb2010-09-23 23:01:17 +0000166 const CodeCompletionContext &CompletionContext,
167 LookupFilter Filter = 0)
Douglas Gregor218937c2011-02-01 19:23:04 +0000168 : SemaRef(SemaRef), Allocator(Allocator), Filter(Filter),
169 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregorca45da02010-11-02 20:36:02 +0000170 CompletionContext(CompletionContext),
171 ObjCImplementation(0)
172 {
173 // If this is an Objective-C instance method definition, dig out the
174 // corresponding implementation.
175 switch (CompletionContext.getKind()) {
176 case CodeCompletionContext::CCC_Expression:
177 case CodeCompletionContext::CCC_ObjCMessageReceiver:
178 case CodeCompletionContext::CCC_ParenthesizedExpression:
179 case CodeCompletionContext::CCC_Statement:
180 case CodeCompletionContext::CCC_Recovery:
181 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
182 if (Method->isInstanceMethod())
183 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
184 ObjCImplementation = Interface->getImplementation();
185 break;
186
187 default:
188 break;
189 }
190 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000191
Douglas Gregord8e8a582010-05-25 21:41:55 +0000192 /// \brief Whether we should include code patterns in the completion
193 /// results.
194 bool includeCodePatterns() const {
195 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000196 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000197 }
198
Douglas Gregor86d9a522009-09-21 16:56:56 +0000199 /// \brief Set the filter used for code-completion results.
200 void setFilter(LookupFilter Filter) {
201 this->Filter = Filter;
202 }
203
Douglas Gregor86d9a522009-09-21 16:56:56 +0000204 Result *data() { return Results.empty()? 0 : &Results.front(); }
205 unsigned size() const { return Results.size(); }
206 bool empty() const { return Results.empty(); }
207
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000208 /// \brief Specify the preferred type.
209 void setPreferredType(QualType T) {
210 PreferredType = SemaRef.Context.getCanonicalType(T);
211 }
212
Douglas Gregor3cdee122010-08-26 16:36:48 +0000213 /// \brief Set the cv-qualifiers on the object type, for us in filtering
214 /// calls to member functions.
215 ///
216 /// When there are qualifiers in this set, they will be used to filter
217 /// out member functions that aren't available (because there will be a
218 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
219 /// match.
220 void setObjectTypeQualifiers(Qualifiers Quals) {
221 ObjectTypeQualifiers = Quals;
222 HasObjectTypeQualifiers = true;
223 }
224
Douglas Gregor265f7492010-08-27 15:29:55 +0000225 /// \brief Set the preferred selector.
226 ///
227 /// When an Objective-C method declaration result is added, and that
228 /// method's selector matches this preferred selector, we give that method
229 /// a slight priority boost.
230 void setPreferredSelector(Selector Sel) {
231 PreferredSelector = Sel;
232 }
Douglas Gregorca45da02010-11-02 20:36:02 +0000233
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000234 /// \brief Retrieve the code-completion context for which results are
235 /// being collected.
236 const CodeCompletionContext &getCompletionContext() const {
237 return CompletionContext;
238 }
239
Douglas Gregor45bcd432010-01-14 03:21:49 +0000240 /// \brief Specify whether nested-name-specifiers are allowed.
241 void allowNestedNameSpecifiers(bool Allow = true) {
242 AllowNestedNameSpecifiers = Allow;
243 }
244
Douglas Gregorb9d77572010-09-21 00:03:25 +0000245 /// \brief Return the semantic analysis object for which we are collecting
246 /// code completion results.
247 Sema &getSema() const { return SemaRef; }
248
Douglas Gregor218937c2011-02-01 19:23:04 +0000249 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000250 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Douglas Gregor218937c2011-02-01 19:23:04 +0000251
Douglas Gregore495b7f2010-01-14 00:20:49 +0000252 /// \brief Determine whether the given declaration is at all interesting
253 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000254 ///
255 /// \param ND the declaration that we are inspecting.
256 ///
257 /// \param AsNestedNameSpecifier will be set true if this declaration is
258 /// only interesting when it is a nested-name-specifier.
259 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000260
261 /// \brief Check whether the result is hidden by the Hiding declaration.
262 ///
263 /// \returns true if the result is hidden and cannot be found, false if
264 /// the hidden result could still be found. When false, \p R may be
265 /// modified to describe how the result can be found (e.g., via extra
266 /// qualification).
267 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
268 NamedDecl *Hiding);
269
Douglas Gregor86d9a522009-09-21 16:56:56 +0000270 /// \brief Add a new result to this result set (if it isn't already in one
271 /// of the shadow maps), or replace an existing result (for, e.g., a
272 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000273 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000274 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000275 ///
276 /// \param R the context in which this result will be named.
277 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000278
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000279 /// \brief Add a new result to this result set, where we already know
280 /// the hiding declation (if any).
281 ///
282 /// \param R the result to add (if it is unique).
283 ///
284 /// \param CurContext the context in which this result will be named.
285 ///
286 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000287 ///
288 /// \param InBaseClass whether the result was found in a base
289 /// class of the searched context.
290 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
291 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000292
Douglas Gregora4477812010-01-14 16:01:26 +0000293 /// \brief Add a new non-declaration result to this result set.
294 void AddResult(Result R);
295
Douglas Gregor86d9a522009-09-21 16:56:56 +0000296 /// \brief Enter into a new scope.
297 void EnterNewScope();
298
299 /// \brief Exit from the current scope.
300 void ExitScope();
301
Douglas Gregor55385fe2009-11-18 04:19:12 +0000302 /// \brief Ignore this declaration, if it is seen again.
303 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
304
Douglas Gregor86d9a522009-09-21 16:56:56 +0000305 /// \name Name lookup predicates
306 ///
307 /// These predicates can be passed to the name lookup functions to filter the
308 /// results of name lookup. All of the predicates have the same type, so that
309 ///
310 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000311 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000312 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000313 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000314 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000315 bool IsNestedNameSpecifier(NamedDecl *ND) const;
316 bool IsEnum(NamedDecl *ND) const;
317 bool IsClassOrStruct(NamedDecl *ND) const;
318 bool IsUnion(NamedDecl *ND) const;
319 bool IsNamespace(NamedDecl *ND) const;
320 bool IsNamespaceOrAlias(NamedDecl *ND) const;
321 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000322 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000323 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000324 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000325 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000326 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000327 //@}
328 };
329}
330
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000331class ResultBuilder::ShadowMapEntry::iterator {
332 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
333 unsigned SingleDeclIndex;
334
335public:
336 typedef DeclIndexPair value_type;
337 typedef value_type reference;
338 typedef std::ptrdiff_t difference_type;
339 typedef std::input_iterator_tag iterator_category;
340
341 class pointer {
342 DeclIndexPair Value;
343
344 public:
345 pointer(const DeclIndexPair &Value) : Value(Value) { }
346
347 const DeclIndexPair *operator->() const {
348 return &Value;
349 }
350 };
351
352 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
353
354 iterator(NamedDecl *SingleDecl, unsigned Index)
355 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
356
357 iterator(const DeclIndexPair *Iterator)
358 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
359
360 iterator &operator++() {
361 if (DeclOrIterator.is<NamedDecl *>()) {
362 DeclOrIterator = (NamedDecl *)0;
363 SingleDeclIndex = 0;
364 return *this;
365 }
366
367 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
368 ++I;
369 DeclOrIterator = I;
370 return *this;
371 }
372
Chris Lattner66392d42010-09-04 18:12:20 +0000373 /*iterator operator++(int) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000374 iterator tmp(*this);
375 ++(*this);
376 return tmp;
Chris Lattner66392d42010-09-04 18:12:20 +0000377 }*/
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000378
379 reference operator*() const {
380 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
381 return reference(ND, SingleDeclIndex);
382
Douglas Gregord490f952009-12-06 21:27:58 +0000383 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000384 }
385
386 pointer operator->() const {
387 return pointer(**this);
388 }
389
390 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000391 return X.DeclOrIterator.getOpaqueValue()
392 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000393 X.SingleDeclIndex == Y.SingleDeclIndex;
394 }
395
396 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000397 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000398 }
399};
400
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000401ResultBuilder::ShadowMapEntry::iterator
402ResultBuilder::ShadowMapEntry::begin() const {
403 if (DeclOrVector.isNull())
404 return iterator();
405
406 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
407 return iterator(ND, SingleDeclIndex);
408
409 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
410}
411
412ResultBuilder::ShadowMapEntry::iterator
413ResultBuilder::ShadowMapEntry::end() const {
414 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
415 return iterator();
416
417 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
418}
419
Douglas Gregor456c4a12009-09-21 20:12:40 +0000420/// \brief Compute the qualification required to get from the current context
421/// (\p CurContext) to the target context (\p TargetContext).
422///
423/// \param Context the AST context in which the qualification will be used.
424///
425/// \param CurContext the context where an entity is being named, which is
426/// typically based on the current scope.
427///
428/// \param TargetContext the context in which the named entity actually
429/// resides.
430///
431/// \returns a nested name specifier that refers into the target context, or
432/// NULL if no qualification is needed.
433static NestedNameSpecifier *
434getRequiredQualification(ASTContext &Context,
435 DeclContext *CurContext,
436 DeclContext *TargetContext) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000437 SmallVector<DeclContext *, 4> TargetParents;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000438
439 for (DeclContext *CommonAncestor = TargetContext;
440 CommonAncestor && !CommonAncestor->Encloses(CurContext);
441 CommonAncestor = CommonAncestor->getLookupParent()) {
442 if (CommonAncestor->isTransparentContext() ||
443 CommonAncestor->isFunctionOrMethod())
444 continue;
445
446 TargetParents.push_back(CommonAncestor);
447 }
448
449 NestedNameSpecifier *Result = 0;
450 while (!TargetParents.empty()) {
451 DeclContext *Parent = TargetParents.back();
452 TargetParents.pop_back();
453
Douglas Gregorfb629412010-08-23 21:17:50 +0000454 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
455 if (!Namespace->getIdentifier())
456 continue;
457
Douglas Gregor456c4a12009-09-21 20:12:40 +0000458 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000459 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000460 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
461 Result = NestedNameSpecifier::Create(Context, Result,
462 false,
463 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000464 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000465 return Result;
466}
467
Douglas Gregor45bcd432010-01-14 03:21:49 +0000468bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
469 bool &AsNestedNameSpecifier) const {
470 AsNestedNameSpecifier = false;
471
Douglas Gregore495b7f2010-01-14 00:20:49 +0000472 ND = ND->getUnderlyingDecl();
473 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000474
475 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000476 if (!ND->getDeclName())
477 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000478
479 // Friend declarations and declarations introduced due to friends are never
480 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000481 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000482 return false;
483
Douglas Gregor76282942009-12-11 17:31:05 +0000484 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000485 if (isa<ClassTemplateSpecializationDecl>(ND) ||
486 isa<ClassTemplatePartialSpecializationDecl>(ND))
487 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000488
Douglas Gregor76282942009-12-11 17:31:05 +0000489 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000490 if (isa<UsingDecl>(ND))
491 return false;
492
493 // Some declarations have reserved names that we don't want to ever show.
494 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000495 // __va_list_tag is a freak of nature. Find it and skip it.
496 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000497 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000498
Douglas Gregorf52cede2009-10-09 22:16:47 +0000499 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000500 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000501 //
502 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000503 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000504 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000505 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000506 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
507 (ND->getLocation().isInvalid() ||
508 SemaRef.SourceMgr.isInSystemHeader(
509 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000510 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000511 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000512 }
Douglas Gregor6f942b22010-09-21 16:06:22 +0000513
Douglas Gregor9b0ba872010-11-09 03:59:40 +0000514 // Skip out-of-line declarations and definitions.
515 // NOTE: Unless it's an Objective-C property, method, or ivar, where
516 // the contexts can be messy.
517 if (!ND->getDeclContext()->Equals(ND->getLexicalDeclContext()) &&
518 !(isa<ObjCPropertyDecl>(ND) || isa<ObjCIvarDecl>(ND) ||
519 isa<ObjCMethodDecl>(ND)))
520 return false;
521
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000522 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
523 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
524 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor52779fb2010-09-23 23:01:17 +0000525 Filter != &ResultBuilder::IsNamespaceOrAlias &&
526 Filter != 0))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000527 AsNestedNameSpecifier = true;
528
Douglas Gregor86d9a522009-09-21 16:56:56 +0000529 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000530 if (Filter && !(this->*Filter)(ND)) {
531 // Check whether it is interesting as a nested-name-specifier.
532 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
533 IsNestedNameSpecifier(ND) &&
534 (Filter != &ResultBuilder::IsMember ||
535 (isa<CXXRecordDecl>(ND) &&
536 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
537 AsNestedNameSpecifier = true;
538 return true;
539 }
540
Douglas Gregore495b7f2010-01-14 00:20:49 +0000541 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000542 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000543 // ... then it must be interesting!
544 return true;
545}
546
Douglas Gregor6660d842010-01-14 00:41:07 +0000547bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
548 NamedDecl *Hiding) {
549 // In C, there is no way to refer to a hidden name.
550 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
551 // name if we introduce the tag type.
552 if (!SemaRef.getLangOptions().CPlusPlus)
553 return true;
554
Sebastian Redl7a126a42010-08-31 00:36:30 +0000555 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregor6660d842010-01-14 00:41:07 +0000556
557 // There is no way to qualify a name declared in a function or method.
558 if (HiddenCtx->isFunctionOrMethod())
559 return true;
560
Sebastian Redl7a126a42010-08-31 00:36:30 +0000561 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregor6660d842010-01-14 00:41:07 +0000562 return true;
563
564 // We can refer to the result with the appropriate qualification. Do it.
565 R.Hidden = true;
566 R.QualifierIsInformative = false;
567
568 if (!R.Qualifier)
569 R.Qualifier = getRequiredQualification(SemaRef.Context,
570 CurContext,
571 R.Declaration->getDeclContext());
572 return false;
573}
574
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000575/// \brief A simplified classification of types used to determine whether two
576/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000577SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000578 switch (T->getTypeClass()) {
579 case Type::Builtin:
580 switch (cast<BuiltinType>(T)->getKind()) {
581 case BuiltinType::Void:
582 return STC_Void;
583
584 case BuiltinType::NullPtr:
585 return STC_Pointer;
586
587 case BuiltinType::Overload:
588 case BuiltinType::Dependent:
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000589 return STC_Other;
590
591 case BuiltinType::ObjCId:
592 case BuiltinType::ObjCClass:
593 case BuiltinType::ObjCSel:
594 return STC_ObjectiveC;
595
596 default:
597 return STC_Arithmetic;
598 }
599 return STC_Other;
600
601 case Type::Complex:
602 return STC_Arithmetic;
603
604 case Type::Pointer:
605 return STC_Pointer;
606
607 case Type::BlockPointer:
608 return STC_Block;
609
610 case Type::LValueReference:
611 case Type::RValueReference:
612 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
613
614 case Type::ConstantArray:
615 case Type::IncompleteArray:
616 case Type::VariableArray:
617 case Type::DependentSizedArray:
618 return STC_Array;
619
620 case Type::DependentSizedExtVector:
621 case Type::Vector:
622 case Type::ExtVector:
623 return STC_Arithmetic;
624
625 case Type::FunctionProto:
626 case Type::FunctionNoProto:
627 return STC_Function;
628
629 case Type::Record:
630 return STC_Record;
631
632 case Type::Enum:
633 return STC_Arithmetic;
634
635 case Type::ObjCObject:
636 case Type::ObjCInterface:
637 case Type::ObjCObjectPointer:
638 return STC_ObjectiveC;
639
640 default:
641 return STC_Other;
642 }
643}
644
645/// \brief Get the type that a given expression will have if this declaration
646/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000647QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000648 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
649
650 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
651 return C.getTypeDeclType(Type);
652 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
653 return C.getObjCInterfaceType(Iface);
654
655 QualType T;
656 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000657 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000658 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000659 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000660 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000661 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000662 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
663 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
664 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
665 T = Property->getType();
666 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
667 T = Value->getType();
668 else
669 return QualType();
Douglas Gregor3e64d562011-04-14 20:33:34 +0000670
671 // Dig through references, function pointers, and block pointers to
672 // get down to the likely type of an expression when the entity is
673 // used.
674 do {
675 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
676 T = Ref->getPointeeType();
677 continue;
678 }
679
680 if (const PointerType *Pointer = T->getAs<PointerType>()) {
681 if (Pointer->getPointeeType()->isFunctionType()) {
682 T = Pointer->getPointeeType();
683 continue;
684 }
685
686 break;
687 }
688
689 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
690 T = Block->getPointeeType();
691 continue;
692 }
693
694 if (const FunctionType *Function = T->getAs<FunctionType>()) {
695 T = Function->getResultType();
696 continue;
697 }
698
699 break;
700 } while (true);
701
702 return T;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000703}
704
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000705void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
706 // If this is an Objective-C method declaration whose selector matches our
707 // preferred selector, give it a priority boost.
708 if (!PreferredSelector.isNull())
709 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
710 if (PreferredSelector == Method->getSelector())
711 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000712
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000713 // If we have a preferred type, adjust the priority for results with exactly-
714 // matching or nearly-matching types.
715 if (!PreferredType.isNull()) {
716 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
717 if (!T.isNull()) {
718 CanQualType TC = SemaRef.Context.getCanonicalType(T);
719 // Check for exactly-matching types (modulo qualifiers).
720 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
721 R.Priority /= CCF_ExactTypeMatch;
722 // Check for nearly-matching types, based on classification of each.
723 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000724 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000725 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
726 R.Priority /= CCF_SimilarTypeMatch;
727 }
728 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000729}
730
Douglas Gregor6f942b22010-09-21 16:06:22 +0000731void ResultBuilder::MaybeAddConstructorResults(Result R) {
732 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
733 !CompletionContext.wantConstructorResults())
734 return;
735
736 ASTContext &Context = SemaRef.Context;
737 NamedDecl *D = R.Declaration;
738 CXXRecordDecl *Record = 0;
739 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
740 Record = ClassTemplate->getTemplatedDecl();
741 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
742 // Skip specializations and partial specializations.
743 if (isa<ClassTemplateSpecializationDecl>(Record))
744 return;
745 } else {
746 // There are no constructors here.
747 return;
748 }
749
750 Record = Record->getDefinition();
751 if (!Record)
752 return;
753
754
755 QualType RecordTy = Context.getTypeDeclType(Record);
756 DeclarationName ConstructorName
757 = Context.DeclarationNames.getCXXConstructorName(
758 Context.getCanonicalType(RecordTy));
759 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
760 Ctors.first != Ctors.second; ++Ctors.first) {
761 R.Declaration = *Ctors.first;
762 R.CursorKind = getCursorKindForDecl(R.Declaration);
763 Results.push_back(R);
764 }
765}
766
Douglas Gregore495b7f2010-01-14 00:20:49 +0000767void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
768 assert(!ShadowMaps.empty() && "Must enter into a results scope");
769
770 if (R.Kind != Result::RK_Declaration) {
771 // For non-declaration results, just add the result.
772 Results.push_back(R);
773 return;
774 }
775
776 // Look through using declarations.
777 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
778 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
779 return;
780 }
781
782 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
783 unsigned IDNS = CanonDecl->getIdentifierNamespace();
784
Douglas Gregor45bcd432010-01-14 03:21:49 +0000785 bool AsNestedNameSpecifier = false;
786 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000787 return;
788
Douglas Gregor6f942b22010-09-21 16:06:22 +0000789 // C++ constructors are never found by name lookup.
790 if (isa<CXXConstructorDecl>(R.Declaration))
791 return;
792
Douglas Gregor86d9a522009-09-21 16:56:56 +0000793 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000794 ShadowMapEntry::iterator I, IEnd;
795 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
796 if (NamePos != SMap.end()) {
797 I = NamePos->second.begin();
798 IEnd = NamePos->second.end();
799 }
800
801 for (; I != IEnd; ++I) {
802 NamedDecl *ND = I->first;
803 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000804 if (ND->getCanonicalDecl() == CanonDecl) {
805 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000806 Results[Index].Declaration = R.Declaration;
807
Douglas Gregor86d9a522009-09-21 16:56:56 +0000808 // We're done.
809 return;
810 }
811 }
812
813 // This is a new declaration in this scope. However, check whether this
814 // declaration name is hidden by a similarly-named declaration in an outer
815 // scope.
816 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
817 --SMEnd;
818 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000819 ShadowMapEntry::iterator I, IEnd;
820 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
821 if (NamePos != SM->end()) {
822 I = NamePos->second.begin();
823 IEnd = NamePos->second.end();
824 }
825 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000826 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000827 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000828 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
829 Decl::IDNS_ObjCProtocol)))
830 continue;
831
832 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000833 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000834 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000835 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000836 continue;
837
838 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000839 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000840 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000841
842 break;
843 }
844 }
845
846 // Make sure that any given declaration only shows up in the result set once.
847 if (!AllDeclsFound.insert(CanonDecl))
848 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000849
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000850 // If the filter is for nested-name-specifiers, then this result starts a
851 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000852 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000853 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000854 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000855 } else
856 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000857
Douglas Gregor0563c262009-09-22 23:15:58 +0000858 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000859 if (R.QualifierIsInformative && !R.Qualifier &&
860 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000861 DeclContext *Ctx = R.Declaration->getDeclContext();
862 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
863 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
864 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
865 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
866 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
867 else
868 R.QualifierIsInformative = false;
869 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000870
Douglas Gregor86d9a522009-09-21 16:56:56 +0000871 // Insert this result into the set of results and into the current shadow
872 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000873 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000874 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000875
876 if (!AsNestedNameSpecifier)
877 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000878}
879
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000880void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000881 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000882 if (R.Kind != Result::RK_Declaration) {
883 // For non-declaration results, just add the result.
884 Results.push_back(R);
885 return;
886 }
887
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000888 // Look through using declarations.
889 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
890 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
891 return;
892 }
893
Douglas Gregor45bcd432010-01-14 03:21:49 +0000894 bool AsNestedNameSpecifier = false;
895 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000896 return;
897
Douglas Gregor6f942b22010-09-21 16:06:22 +0000898 // C++ constructors are never found by name lookup.
899 if (isa<CXXConstructorDecl>(R.Declaration))
900 return;
901
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000902 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
903 return;
904
905 // Make sure that any given declaration only shows up in the result set once.
906 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
907 return;
908
909 // If the filter is for nested-name-specifiers, then this result starts a
910 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000911 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000912 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000913 R.Priority = CCP_NestedNameSpecifier;
914 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000915 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
916 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000917 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000918 R.QualifierIsInformative = true;
919
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000920 // If this result is supposed to have an informative qualifier, add one.
921 if (R.QualifierIsInformative && !R.Qualifier &&
922 !R.StartsNestedNameSpecifier) {
923 DeclContext *Ctx = R.Declaration->getDeclContext();
924 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
925 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
926 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
927 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000928 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000929 else
930 R.QualifierIsInformative = false;
931 }
932
Douglas Gregor12e13132010-05-26 22:00:08 +0000933 // Adjust the priority if this result comes from a base class.
934 if (InBaseClass)
935 R.Priority += CCD_InBaseClass;
936
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000937 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000938
Douglas Gregor3cdee122010-08-26 16:36:48 +0000939 if (HasObjectTypeQualifiers)
940 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
941 if (Method->isInstance()) {
942 Qualifiers MethodQuals
943 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
944 if (ObjectTypeQualifiers == MethodQuals)
945 R.Priority += CCD_ObjectQualifierMatch;
946 else if (ObjectTypeQualifiers - MethodQuals) {
947 // The method cannot be invoked, because doing so would drop
948 // qualifiers.
949 return;
950 }
951 }
952
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000953 // Insert this result into the set of results.
954 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000955
956 if (!AsNestedNameSpecifier)
957 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000958}
959
Douglas Gregora4477812010-01-14 16:01:26 +0000960void ResultBuilder::AddResult(Result R) {
961 assert(R.Kind != Result::RK_Declaration &&
962 "Declaration results need more context");
963 Results.push_back(R);
964}
965
Douglas Gregor86d9a522009-09-21 16:56:56 +0000966/// \brief Enter into a new scope.
967void ResultBuilder::EnterNewScope() {
968 ShadowMaps.push_back(ShadowMap());
969}
970
971/// \brief Exit from the current scope.
972void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000973 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
974 EEnd = ShadowMaps.back().end();
975 E != EEnd;
976 ++E)
977 E->second.Destroy();
978
Douglas Gregor86d9a522009-09-21 16:56:56 +0000979 ShadowMaps.pop_back();
980}
981
Douglas Gregor791215b2009-09-21 20:51:25 +0000982/// \brief Determines whether this given declaration will be found by
983/// ordinary name lookup.
984bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000985 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
986
Douglas Gregor791215b2009-09-21 20:51:25 +0000987 unsigned IDNS = Decl::IDNS_Ordinary;
988 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000989 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000990 else if (SemaRef.getLangOptions().ObjC1) {
991 if (isa<ObjCIvarDecl>(ND))
992 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +0000993 }
994
Douglas Gregor791215b2009-09-21 20:51:25 +0000995 return ND->getIdentifierNamespace() & IDNS;
996}
997
Douglas Gregor01dfea02010-01-10 23:08:15 +0000998/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000999/// ordinary name lookup but is not a type name.
1000bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
1001 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1002 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1003 return false;
1004
1005 unsigned IDNS = Decl::IDNS_Ordinary;
1006 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +00001007 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +00001008 else if (SemaRef.getLangOptions().ObjC1) {
1009 if (isa<ObjCIvarDecl>(ND))
1010 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +00001011 }
1012
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001013 return ND->getIdentifierNamespace() & IDNS;
1014}
1015
Douglas Gregorf9578432010-07-28 21:50:18 +00001016bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
1017 if (!IsOrdinaryNonTypeName(ND))
1018 return 0;
1019
1020 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1021 if (VD->getType()->isIntegralOrEnumerationType())
1022 return true;
1023
1024 return false;
1025}
1026
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001027/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +00001028/// ordinary name lookup.
1029bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001030 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1031
Douglas Gregor01dfea02010-01-10 23:08:15 +00001032 unsigned IDNS = Decl::IDNS_Ordinary;
1033 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +00001034 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001035
1036 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001037 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1038 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001039}
1040
Douglas Gregor86d9a522009-09-21 16:56:56 +00001041/// \brief Determines whether the given declaration is suitable as the
1042/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1043bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1044 // Allow us to find class templates, too.
1045 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1046 ND = ClassTemplate->getTemplatedDecl();
1047
1048 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1049}
1050
1051/// \brief Determines whether the given declaration is an enumeration.
1052bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1053 return isa<EnumDecl>(ND);
1054}
1055
1056/// \brief Determines whether the given declaration is a class or struct.
1057bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1058 // Allow us to find class templates, too.
1059 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1060 ND = ClassTemplate->getTemplatedDecl();
1061
1062 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001063 return RD->getTagKind() == TTK_Class ||
1064 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001065
1066 return false;
1067}
1068
1069/// \brief Determines whether the given declaration is a union.
1070bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1071 // Allow us to find class templates, too.
1072 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1073 ND = ClassTemplate->getTemplatedDecl();
1074
1075 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001076 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001077
1078 return false;
1079}
1080
1081/// \brief Determines whether the given declaration is a namespace.
1082bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1083 return isa<NamespaceDecl>(ND);
1084}
1085
1086/// \brief Determines whether the given declaration is a namespace or
1087/// namespace alias.
1088bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1089 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1090}
1091
Douglas Gregor76282942009-12-11 17:31:05 +00001092/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001093bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001094 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1095 ND = Using->getTargetDecl();
1096
1097 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001098}
1099
Douglas Gregor76282942009-12-11 17:31:05 +00001100/// \brief Determines which members of a class should be visible via
1101/// "." or "->". Only value declarations, nested name specifiers, and
1102/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001103bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001104 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1105 ND = Using->getTargetDecl();
1106
Douglas Gregorce821962009-12-11 18:14:22 +00001107 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1108 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001109}
1110
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001111static bool isObjCReceiverType(ASTContext &C, QualType T) {
1112 T = C.getCanonicalType(T);
1113 switch (T->getTypeClass()) {
1114 case Type::ObjCObject:
1115 case Type::ObjCInterface:
1116 case Type::ObjCObjectPointer:
1117 return true;
1118
1119 case Type::Builtin:
1120 switch (cast<BuiltinType>(T)->getKind()) {
1121 case BuiltinType::ObjCId:
1122 case BuiltinType::ObjCClass:
1123 case BuiltinType::ObjCSel:
1124 return true;
1125
1126 default:
1127 break;
1128 }
1129 return false;
1130
1131 default:
1132 break;
1133 }
1134
1135 if (!C.getLangOptions().CPlusPlus)
1136 return false;
1137
1138 // FIXME: We could perform more analysis here to determine whether a
1139 // particular class type has any conversions to Objective-C types. For now,
1140 // just accept all class types.
1141 return T->isDependentType() || T->isRecordType();
1142}
1143
1144bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1145 QualType T = getDeclUsageType(SemaRef.Context, ND);
1146 if (T.isNull())
1147 return false;
1148
1149 T = SemaRef.Context.getBaseElementType(T);
1150 return isObjCReceiverType(SemaRef.Context, T);
1151}
1152
Douglas Gregorfb629412010-08-23 21:17:50 +00001153bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1154 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1155 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1156 return false;
1157
1158 QualType T = getDeclUsageType(SemaRef.Context, ND);
1159 if (T.isNull())
1160 return false;
1161
1162 T = SemaRef.Context.getBaseElementType(T);
1163 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1164 T->isObjCIdType() ||
1165 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1166}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001167
Douglas Gregor52779fb2010-09-23 23:01:17 +00001168bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1169 return false;
1170}
1171
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001172/// \rief Determines whether the given declaration is an Objective-C
1173/// instance variable.
1174bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1175 return isa<ObjCIvarDecl>(ND);
1176}
1177
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001178namespace {
1179 /// \brief Visible declaration consumer that adds a code-completion result
1180 /// for each visible declaration.
1181 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1182 ResultBuilder &Results;
1183 DeclContext *CurContext;
1184
1185 public:
1186 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1187 : Results(Results), CurContext(CurContext) { }
1188
Erik Verbruggend1205962011-10-06 07:27:49 +00001189 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1190 bool InBaseClass) {
1191 bool Accessible = true;
1192 if (Ctx) {
1193 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
1194 Accessible = Results.getSema().IsSimplyAccessible(ND, Class);
1195 // FIXME: ObjC access checks are missing.
1196 }
1197 ResultBuilder::Result Result(ND, 0, false, Accessible);
1198 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001199 }
1200 };
1201}
1202
Douglas Gregor86d9a522009-09-21 16:56:56 +00001203/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001204static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001205 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001206 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001207 Results.AddResult(Result("short", CCP_Type));
1208 Results.AddResult(Result("long", CCP_Type));
1209 Results.AddResult(Result("signed", CCP_Type));
1210 Results.AddResult(Result("unsigned", CCP_Type));
1211 Results.AddResult(Result("void", CCP_Type));
1212 Results.AddResult(Result("char", CCP_Type));
1213 Results.AddResult(Result("int", CCP_Type));
1214 Results.AddResult(Result("float", CCP_Type));
1215 Results.AddResult(Result("double", CCP_Type));
1216 Results.AddResult(Result("enum", CCP_Type));
1217 Results.AddResult(Result("struct", CCP_Type));
1218 Results.AddResult(Result("union", CCP_Type));
1219 Results.AddResult(Result("const", CCP_Type));
1220 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001221
Douglas Gregor86d9a522009-09-21 16:56:56 +00001222 if (LangOpts.C99) {
1223 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001224 Results.AddResult(Result("_Complex", CCP_Type));
1225 Results.AddResult(Result("_Imaginary", CCP_Type));
1226 Results.AddResult(Result("_Bool", CCP_Type));
1227 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001228 }
1229
Douglas Gregor218937c2011-02-01 19:23:04 +00001230 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001231 if (LangOpts.CPlusPlus) {
1232 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001233 Results.AddResult(Result("bool", CCP_Type +
1234 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001235 Results.AddResult(Result("class", CCP_Type));
1236 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001237
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001238 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001239 Builder.AddTypedTextChunk("typename");
1240 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1241 Builder.AddPlaceholderChunk("qualifier");
1242 Builder.AddTextChunk("::");
1243 Builder.AddPlaceholderChunk("name");
1244 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001245
Douglas Gregor86d9a522009-09-21 16:56:56 +00001246 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001247 Results.AddResult(Result("auto", CCP_Type));
1248 Results.AddResult(Result("char16_t", CCP_Type));
1249 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001250
Douglas Gregor218937c2011-02-01 19:23:04 +00001251 Builder.AddTypedTextChunk("decltype");
1252 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1253 Builder.AddPlaceholderChunk("expression");
1254 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1255 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001256 }
1257 }
1258
1259 // GNU extensions
1260 if (LangOpts.GNUMode) {
1261 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001262 // Results.AddResult(Result("_Decimal32"));
1263 // Results.AddResult(Result("_Decimal64"));
1264 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001265
Douglas Gregor218937c2011-02-01 19:23:04 +00001266 Builder.AddTypedTextChunk("typeof");
1267 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1268 Builder.AddPlaceholderChunk("expression");
1269 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001270
Douglas Gregor218937c2011-02-01 19:23:04 +00001271 Builder.AddTypedTextChunk("typeof");
1272 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1273 Builder.AddPlaceholderChunk("type");
1274 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1275 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001276 }
1277}
1278
John McCallf312b1e2010-08-26 23:41:50 +00001279static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001280 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001281 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001282 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001283 // Note: we don't suggest either "auto" or "register", because both
1284 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1285 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001286 Results.AddResult(Result("extern"));
1287 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001288}
1289
John McCallf312b1e2010-08-26 23:41:50 +00001290static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001291 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001292 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001293 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001294 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001295 case Sema::PCC_Class:
1296 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001297 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001298 Results.AddResult(Result("explicit"));
1299 Results.AddResult(Result("friend"));
1300 Results.AddResult(Result("mutable"));
1301 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001302 }
1303 // Fall through
1304
John McCallf312b1e2010-08-26 23:41:50 +00001305 case Sema::PCC_ObjCInterface:
1306 case Sema::PCC_ObjCImplementation:
1307 case Sema::PCC_Namespace:
1308 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001309 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001310 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001311 break;
1312
John McCallf312b1e2010-08-26 23:41:50 +00001313 case Sema::PCC_ObjCInstanceVariableList:
1314 case Sema::PCC_Expression:
1315 case Sema::PCC_Statement:
1316 case Sema::PCC_ForInit:
1317 case Sema::PCC_Condition:
1318 case Sema::PCC_RecoveryInFunction:
1319 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001320 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001321 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001322 break;
1323 }
1324}
1325
Douglas Gregorbca403c2010-01-13 23:51:12 +00001326static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1327static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1328static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001329 ResultBuilder &Results,
1330 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001331static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001332 ResultBuilder &Results,
1333 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001334static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001335 ResultBuilder &Results,
1336 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001337static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001338
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001339static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001340 CodeCompletionBuilder Builder(Results.getAllocator());
1341 Builder.AddTypedTextChunk("typedef");
1342 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1343 Builder.AddPlaceholderChunk("type");
1344 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1345 Builder.AddPlaceholderChunk("name");
1346 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001347}
1348
John McCallf312b1e2010-08-26 23:41:50 +00001349static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001350 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001351 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001352 case Sema::PCC_Namespace:
1353 case Sema::PCC_Class:
1354 case Sema::PCC_ObjCInstanceVariableList:
1355 case Sema::PCC_Template:
1356 case Sema::PCC_MemberTemplate:
1357 case Sema::PCC_Statement:
1358 case Sema::PCC_RecoveryInFunction:
1359 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001360 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001361 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001362 return true;
1363
John McCallf312b1e2010-08-26 23:41:50 +00001364 case Sema::PCC_Expression:
1365 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001366 return LangOpts.CPlusPlus;
1367
1368 case Sema::PCC_ObjCInterface:
1369 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001370 return false;
1371
John McCallf312b1e2010-08-26 23:41:50 +00001372 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001373 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001374 }
1375
1376 return false;
1377}
1378
Douglas Gregor8ca72082011-10-18 21:20:17 +00001379/// \brief Retrieve a printing policy suitable for code completion.
1380static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1381 PrintingPolicy Policy = S.getPrintingPolicy();
1382 Policy.AnonymousTagLocations = false;
1383 Policy.SuppressStrongLifetime = true;
1384 return Policy;
1385}
1386
1387/// \brief Retrieve the string representation of the given type as a string
1388/// that has the appropriate lifetime for code completion.
1389///
1390/// This routine provides a fast path where we provide constant strings for
1391/// common type names.
1392static const char *GetCompletionTypeString(QualType T,
1393 ASTContext &Context,
1394 const PrintingPolicy &Policy,
1395 CodeCompletionAllocator &Allocator) {
1396 if (!T.getLocalQualifiers()) {
1397 // Built-in type names are constant strings.
1398 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1399 return BT->getName(Policy);
1400
1401 // Anonymous tag types are constant strings.
1402 if (const TagType *TagT = dyn_cast<TagType>(T))
1403 if (TagDecl *Tag = TagT->getDecl())
1404 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
1405 switch (Tag->getTagKind()) {
1406 case TTK_Struct: return "struct <anonymous>";
1407 case TTK_Class: return "class <anonymous>";
1408 case TTK_Union: return "union <anonymous>";
1409 case TTK_Enum: return "enum <anonymous>";
1410 }
1411 }
1412 }
1413
1414 // Slow path: format the type as a string.
1415 std::string Result;
1416 T.getAsStringInternal(Result, Policy);
1417 return Allocator.CopyString(Result);
1418}
1419
Douglas Gregor01dfea02010-01-10 23:08:15 +00001420/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001421static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001422 Scope *S,
1423 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001424 ResultBuilder &Results) {
Douglas Gregor8ca72082011-10-18 21:20:17 +00001425 CodeCompletionAllocator &Allocator = Results.getAllocator();
1426 CodeCompletionBuilder Builder(Allocator);
1427 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
Douglas Gregor218937c2011-02-01 19:23:04 +00001428
John McCall0a2c5e22010-08-25 06:19:51 +00001429 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001430 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001431 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001432 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001433 if (Results.includeCodePatterns()) {
1434 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001435 Builder.AddTypedTextChunk("namespace");
1436 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1437 Builder.AddPlaceholderChunk("identifier");
1438 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1439 Builder.AddPlaceholderChunk("declarations");
1440 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1441 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1442 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001443 }
1444
Douglas Gregor01dfea02010-01-10 23:08:15 +00001445 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001446 Builder.AddTypedTextChunk("namespace");
1447 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1448 Builder.AddPlaceholderChunk("name");
1449 Builder.AddChunk(CodeCompletionString::CK_Equal);
1450 Builder.AddPlaceholderChunk("namespace");
1451 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001452
1453 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001454 Builder.AddTypedTextChunk("using");
1455 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1456 Builder.AddTextChunk("namespace");
1457 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1458 Builder.AddPlaceholderChunk("identifier");
1459 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001460
1461 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001462 Builder.AddTypedTextChunk("asm");
1463 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1464 Builder.AddPlaceholderChunk("string-literal");
1465 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1466 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001467
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001468 if (Results.includeCodePatterns()) {
1469 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001470 Builder.AddTypedTextChunk("template");
1471 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1472 Builder.AddPlaceholderChunk("declaration");
1473 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001474 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001475 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001476
1477 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001478 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001479
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001480 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001481 // Fall through
1482
John McCallf312b1e2010-08-26 23:41:50 +00001483 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001484 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001485 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001486 Builder.AddTypedTextChunk("using");
1487 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1488 Builder.AddPlaceholderChunk("qualifier");
1489 Builder.AddTextChunk("::");
1490 Builder.AddPlaceholderChunk("name");
1491 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001492
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001493 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001494 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001495 Builder.AddTypedTextChunk("using");
1496 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1497 Builder.AddTextChunk("typename");
1498 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1499 Builder.AddPlaceholderChunk("qualifier");
1500 Builder.AddTextChunk("::");
1501 Builder.AddPlaceholderChunk("name");
1502 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001503 }
1504
John McCallf312b1e2010-08-26 23:41:50 +00001505 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001506 AddTypedefResult(Results);
1507
Douglas Gregor01dfea02010-01-10 23:08:15 +00001508 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001509 Builder.AddTypedTextChunk("public");
1510 Builder.AddChunk(CodeCompletionString::CK_Colon);
1511 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001512
1513 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001514 Builder.AddTypedTextChunk("protected");
1515 Builder.AddChunk(CodeCompletionString::CK_Colon);
1516 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001517
1518 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001519 Builder.AddTypedTextChunk("private");
1520 Builder.AddChunk(CodeCompletionString::CK_Colon);
1521 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001522 }
1523 }
1524 // Fall through
1525
John McCallf312b1e2010-08-26 23:41:50 +00001526 case Sema::PCC_Template:
1527 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001528 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001529 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001530 Builder.AddTypedTextChunk("template");
1531 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1532 Builder.AddPlaceholderChunk("parameters");
1533 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1534 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001535 }
1536
Douglas Gregorbca403c2010-01-13 23:51:12 +00001537 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1538 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001539 break;
1540
John McCallf312b1e2010-08-26 23:41:50 +00001541 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001542 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1543 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1544 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001545 break;
1546
John McCallf312b1e2010-08-26 23:41:50 +00001547 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001548 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1549 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1550 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001551 break;
1552
John McCallf312b1e2010-08-26 23:41:50 +00001553 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001554 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001555 break;
1556
John McCallf312b1e2010-08-26 23:41:50 +00001557 case Sema::PCC_RecoveryInFunction:
1558 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001559 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001560
Douglas Gregorec3310a2011-04-12 02:47:21 +00001561 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1562 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001563 Builder.AddTypedTextChunk("try");
1564 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1565 Builder.AddPlaceholderChunk("statements");
1566 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1567 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1568 Builder.AddTextChunk("catch");
1569 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1570 Builder.AddPlaceholderChunk("declaration");
1571 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1572 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1573 Builder.AddPlaceholderChunk("statements");
1574 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1575 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1576 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001577 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001578 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001579 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001580
Douglas Gregord8e8a582010-05-25 21:41:55 +00001581 if (Results.includeCodePatterns()) {
1582 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001583 Builder.AddTypedTextChunk("if");
1584 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001585 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001586 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001587 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001588 Builder.AddPlaceholderChunk("expression");
1589 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1590 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1591 Builder.AddPlaceholderChunk("statements");
1592 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1593 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1594 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001595
Douglas Gregord8e8a582010-05-25 21:41:55 +00001596 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001597 Builder.AddTypedTextChunk("switch");
1598 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001599 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001600 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001601 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001602 Builder.AddPlaceholderChunk("expression");
1603 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1604 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1605 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1606 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1607 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001608 }
1609
Douglas Gregor01dfea02010-01-10 23:08:15 +00001610 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001611 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001612 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001613 Builder.AddTypedTextChunk("case");
1614 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1615 Builder.AddPlaceholderChunk("expression");
1616 Builder.AddChunk(CodeCompletionString::CK_Colon);
1617 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001618
1619 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001620 Builder.AddTypedTextChunk("default");
1621 Builder.AddChunk(CodeCompletionString::CK_Colon);
1622 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001623 }
1624
Douglas Gregord8e8a582010-05-25 21:41:55 +00001625 if (Results.includeCodePatterns()) {
1626 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001627 Builder.AddTypedTextChunk("while");
1628 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001629 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001630 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001631 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001632 Builder.AddPlaceholderChunk("expression");
1633 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1634 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1635 Builder.AddPlaceholderChunk("statements");
1636 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1637 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1638 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001639
1640 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001641 Builder.AddTypedTextChunk("do");
1642 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1643 Builder.AddPlaceholderChunk("statements");
1644 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1645 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1646 Builder.AddTextChunk("while");
1647 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1648 Builder.AddPlaceholderChunk("expression");
1649 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1650 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001651
Douglas Gregord8e8a582010-05-25 21:41:55 +00001652 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001653 Builder.AddTypedTextChunk("for");
1654 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001655 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001656 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001657 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001658 Builder.AddPlaceholderChunk("init-expression");
1659 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1660 Builder.AddPlaceholderChunk("condition");
1661 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1662 Builder.AddPlaceholderChunk("inc-expression");
1663 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1664 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1665 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1666 Builder.AddPlaceholderChunk("statements");
1667 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1668 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1669 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001670 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001671
1672 if (S->getContinueParent()) {
1673 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001674 Builder.AddTypedTextChunk("continue");
1675 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001676 }
1677
1678 if (S->getBreakParent()) {
1679 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001680 Builder.AddTypedTextChunk("break");
1681 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001682 }
1683
1684 // "return expression ;" or "return ;", depending on whether we
1685 // know the function is void or not.
1686 bool isVoid = false;
1687 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1688 isVoid = Function->getResultType()->isVoidType();
1689 else if (ObjCMethodDecl *Method
1690 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1691 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001692 else if (SemaRef.getCurBlock() &&
1693 !SemaRef.getCurBlock()->ReturnType.isNull())
1694 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001695 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001696 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001697 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1698 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001699 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001700 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001701
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001702 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001703 Builder.AddTypedTextChunk("goto");
1704 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1705 Builder.AddPlaceholderChunk("label");
1706 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001707
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001708 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001709 Builder.AddTypedTextChunk("using");
1710 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1711 Builder.AddTextChunk("namespace");
1712 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1713 Builder.AddPlaceholderChunk("identifier");
1714 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001715 }
1716
1717 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001718 case Sema::PCC_ForInit:
1719 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001720 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001721 // Fall through: conditions and statements can have expressions.
1722
Douglas Gregor02688102010-09-14 23:59:36 +00001723 case Sema::PCC_ParenthesizedExpression:
John McCallf85e1932011-06-15 23:02:42 +00001724 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1725 CCC == Sema::PCC_ParenthesizedExpression) {
1726 // (__bridge <type>)<expression>
1727 Builder.AddTypedTextChunk("__bridge");
1728 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1729 Builder.AddPlaceholderChunk("type");
1730 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1731 Builder.AddPlaceholderChunk("expression");
1732 Results.AddResult(Result(Builder.TakeString()));
1733
1734 // (__bridge_transfer <Objective-C type>)<expression>
1735 Builder.AddTypedTextChunk("__bridge_transfer");
1736 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1737 Builder.AddPlaceholderChunk("Objective-C type");
1738 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1739 Builder.AddPlaceholderChunk("expression");
1740 Results.AddResult(Result(Builder.TakeString()));
1741
1742 // (__bridge_retained <CF type>)<expression>
1743 Builder.AddTypedTextChunk("__bridge_retained");
1744 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1745 Builder.AddPlaceholderChunk("CF type");
1746 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1747 Builder.AddPlaceholderChunk("expression");
1748 Results.AddResult(Result(Builder.TakeString()));
1749 }
1750 // Fall through
1751
John McCallf312b1e2010-08-26 23:41:50 +00001752 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001753 if (SemaRef.getLangOptions().CPlusPlus) {
1754 // 'this', if we're in a non-static member function.
Douglas Gregor8ca72082011-10-18 21:20:17 +00001755 QualType ThisTy = SemaRef.getCurrentThisType(false);
1756 if (!ThisTy.isNull()) {
1757 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1758 SemaRef.Context,
1759 Policy,
1760 Allocator));
1761 Builder.AddTypedTextChunk("this");
1762 Results.AddResult(Result(Builder.TakeString()));
1763 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001764
Douglas Gregor8ca72082011-10-18 21:20:17 +00001765 // true
1766 Builder.AddResultTypeChunk("bool");
1767 Builder.AddTypedTextChunk("true");
1768 Results.AddResult(Result(Builder.TakeString()));
1769
1770 // false
1771 Builder.AddResultTypeChunk("bool");
1772 Builder.AddTypedTextChunk("false");
1773 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001774
Douglas Gregorec3310a2011-04-12 02:47:21 +00001775 if (SemaRef.getLangOptions().RTTI) {
1776 // dynamic_cast < type-id > ( expression )
1777 Builder.AddTypedTextChunk("dynamic_cast");
1778 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1779 Builder.AddPlaceholderChunk("type");
1780 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1781 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1782 Builder.AddPlaceholderChunk("expression");
1783 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1784 Results.AddResult(Result(Builder.TakeString()));
1785 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001786
1787 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001788 Builder.AddTypedTextChunk("static_cast");
1789 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1790 Builder.AddPlaceholderChunk("type");
1791 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1792 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1793 Builder.AddPlaceholderChunk("expression");
1794 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1795 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001796
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001797 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001798 Builder.AddTypedTextChunk("reinterpret_cast");
1799 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1800 Builder.AddPlaceholderChunk("type");
1801 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1802 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1803 Builder.AddPlaceholderChunk("expression");
1804 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1805 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001806
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001807 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001808 Builder.AddTypedTextChunk("const_cast");
1809 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1810 Builder.AddPlaceholderChunk("type");
1811 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1812 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1813 Builder.AddPlaceholderChunk("expression");
1814 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1815 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001816
Douglas Gregorec3310a2011-04-12 02:47:21 +00001817 if (SemaRef.getLangOptions().RTTI) {
1818 // typeid ( expression-or-type )
Douglas Gregor8ca72082011-10-18 21:20:17 +00001819 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001820 Builder.AddTypedTextChunk("typeid");
1821 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1822 Builder.AddPlaceholderChunk("expression-or-type");
1823 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1824 Results.AddResult(Result(Builder.TakeString()));
1825 }
1826
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001827 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001828 Builder.AddTypedTextChunk("new");
1829 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1830 Builder.AddPlaceholderChunk("type");
1831 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1832 Builder.AddPlaceholderChunk("expressions");
1833 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1834 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001835
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001836 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001837 Builder.AddTypedTextChunk("new");
1838 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1839 Builder.AddPlaceholderChunk("type");
1840 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1841 Builder.AddPlaceholderChunk("size");
1842 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1843 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1844 Builder.AddPlaceholderChunk("expressions");
1845 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1846 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001847
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001848 // delete expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001849 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001850 Builder.AddTypedTextChunk("delete");
1851 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1852 Builder.AddPlaceholderChunk("expression");
1853 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001854
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001855 // delete [] expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001856 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001857 Builder.AddTypedTextChunk("delete");
1858 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1859 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1860 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1861 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1862 Builder.AddPlaceholderChunk("expression");
1863 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001864
Douglas Gregorec3310a2011-04-12 02:47:21 +00001865 if (SemaRef.getLangOptions().CXXExceptions) {
1866 // throw expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001867 Builder.AddResultTypeChunk("void");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001868 Builder.AddTypedTextChunk("throw");
1869 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1870 Builder.AddPlaceholderChunk("expression");
1871 Results.AddResult(Result(Builder.TakeString()));
1872 }
Douglas Gregora50216c2011-10-18 16:29:03 +00001873
Douglas Gregor12e13132010-05-26 22:00:08 +00001874 // FIXME: Rethrow?
Douglas Gregora50216c2011-10-18 16:29:03 +00001875
1876 if (SemaRef.getLangOptions().CPlusPlus0x) {
1877 // nullptr
Douglas Gregor8ca72082011-10-18 21:20:17 +00001878 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001879 Builder.AddTypedTextChunk("nullptr");
1880 Results.AddResult(Result(Builder.TakeString()));
1881
1882 // alignof
Douglas Gregor8ca72082011-10-18 21:20:17 +00001883 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001884 Builder.AddTypedTextChunk("alignof");
1885 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1886 Builder.AddPlaceholderChunk("type");
1887 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1888 Results.AddResult(Result(Builder.TakeString()));
1889
1890 // noexcept
Douglas Gregor8ca72082011-10-18 21:20:17 +00001891 Builder.AddResultTypeChunk("bool");
Douglas Gregora50216c2011-10-18 16:29:03 +00001892 Builder.AddTypedTextChunk("noexcept");
1893 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1894 Builder.AddPlaceholderChunk("expression");
1895 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1896 Results.AddResult(Result(Builder.TakeString()));
1897
1898 // sizeof... expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001899 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001900 Builder.AddTypedTextChunk("sizeof...");
1901 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1902 Builder.AddPlaceholderChunk("parameter-pack");
1903 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1904 Results.AddResult(Result(Builder.TakeString()));
1905 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001906 }
1907
1908 if (SemaRef.getLangOptions().ObjC1) {
1909 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001910 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1911 // The interface can be NULL.
1912 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregor8ca72082011-10-18 21:20:17 +00001913 if (ID->getSuperClass()) {
1914 std::string SuperType;
1915 SuperType = ID->getSuperClass()->getNameAsString();
1916 if (Method->isInstanceMethod())
1917 SuperType += " *";
1918
1919 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
1920 Builder.AddTypedTextChunk("super");
1921 Results.AddResult(Result(Builder.TakeString()));
1922 }
Ted Kremenek681e2562010-05-31 21:43:10 +00001923 }
1924
Douglas Gregorbca403c2010-01-13 23:51:12 +00001925 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001926 }
1927
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001928 // sizeof expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001929 Builder.AddResultTypeChunk("size_t");
Douglas Gregor218937c2011-02-01 19:23:04 +00001930 Builder.AddTypedTextChunk("sizeof");
1931 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1932 Builder.AddPlaceholderChunk("expression-or-type");
1933 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1934 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001935 break;
1936 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001937
John McCallf312b1e2010-08-26 23:41:50 +00001938 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001939 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001940 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001941 }
1942
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001943 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1944 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001945
John McCallf312b1e2010-08-26 23:41:50 +00001946 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001947 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001948}
1949
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001950/// \brief If the given declaration has an associated type, add it as a result
1951/// type chunk.
1952static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001953 const PrintingPolicy &Policy,
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001954 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001955 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001956 if (!ND)
1957 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001958
1959 // Skip constructors and conversion functions, which have their return types
1960 // built into their names.
1961 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1962 return;
1963
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001964 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001965 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001966 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1967 T = Function->getResultType();
1968 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1969 T = Method->getResultType();
1970 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1971 T = FunTmpl->getTemplatedDecl()->getResultType();
1972 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1973 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1974 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1975 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00001976 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001977 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001978 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001979 T = Property->getType();
1980
1981 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1982 return;
1983
Douglas Gregor8987b232011-09-27 23:30:47 +00001984 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00001985 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001986}
1987
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001988static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001989 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001990 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1991 if (Sentinel->getSentinel() == 0) {
1992 if (Context.getLangOptions().ObjC1 &&
1993 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001994 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001995 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001996 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001997 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001998 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001999 }
2000}
2001
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002002static void appendWithSpace(std::string &Result, StringRef Text) {
2003 if (!Result.empty())
2004 Result += ' ';
2005 Result += Text.str();
2006}
2007static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
2008 std::string Result;
2009 if (ObjCQuals & Decl::OBJC_TQ_In)
2010 appendWithSpace(Result, "in");
2011 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2012 appendWithSpace(Result, "inout");
2013 else if (ObjCQuals & Decl::OBJC_TQ_Out)
2014 appendWithSpace(Result, "out");
2015 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2016 appendWithSpace(Result, "bycopy");
2017 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2018 appendWithSpace(Result, "byref");
2019 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2020 appendWithSpace(Result, "oneway");
2021 return Result;
2022}
2023
Douglas Gregor83482d12010-08-24 16:15:59 +00002024static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002025 const PrintingPolicy &Policy,
Douglas Gregoraba48082010-08-29 19:47:46 +00002026 ParmVarDecl *Param,
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002027 bool SuppressName = false,
2028 bool SuppressBlock = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00002029 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2030 if (Param->getType()->isDependentType() ||
2031 !Param->getType()->isBlockPointerType()) {
2032 // The argument for a dependent or non-block parameter is a placeholder
2033 // containing that parameter's type.
2034 std::string Result;
2035
Douglas Gregoraba48082010-08-29 19:47:46 +00002036 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002037 Result = Param->getIdentifier()->getName();
2038
John McCallf85e1932011-06-15 23:02:42 +00002039 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002040
2041 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002042 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2043 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00002044 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002045 Result += Param->getIdentifier()->getName();
2046 }
2047 return Result;
2048 }
2049
2050 // The argument for a block pointer parameter is a block literal with
2051 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00002052 FunctionTypeLoc *Block = 0;
2053 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00002054 TypeLoc TL;
2055 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2056 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2057 while (true) {
2058 // Look through typedefs.
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002059 if (!SuppressBlock) {
2060 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
2061 if (TypeSourceInfo *InnerTSInfo
2062 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
2063 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2064 continue;
2065 }
2066 }
2067
2068 // Look through qualified types
2069 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2070 TL = QualifiedTL->getUnqualifiedLoc();
Douglas Gregor83482d12010-08-24 16:15:59 +00002071 continue;
2072 }
2073 }
2074
Douglas Gregor83482d12010-08-24 16:15:59 +00002075 // Try to get the function prototype behind the block pointer type,
2076 // then we're done.
2077 if (BlockPointerTypeLoc *BlockPtr
2078 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002079 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002080 Block = dyn_cast<FunctionTypeLoc>(&TL);
2081 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002082 }
2083 break;
2084 }
2085 }
2086
2087 if (!Block) {
2088 // We were unable to find a FunctionProtoTypeLoc with parameter names
2089 // for the block; just use the parameter type as a placeholder.
2090 std::string Result;
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002091 if (!ObjCMethodParam && Param->getIdentifier())
2092 Result = Param->getIdentifier()->getName();
2093
John McCallf85e1932011-06-15 23:02:42 +00002094 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002095
2096 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002097 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2098 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002099 if (Param->getIdentifier())
2100 Result += Param->getIdentifier()->getName();
2101 }
2102
2103 return Result;
2104 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002105
Douglas Gregor83482d12010-08-24 16:15:59 +00002106 // We have the function prototype behind the block pointer type, as it was
2107 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002108 std::string Result;
2109 QualType ResultType = Block->getTypePtr()->getResultType();
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002110 if (!ResultType->isVoidType() || SuppressBlock)
John McCallf85e1932011-06-15 23:02:42 +00002111 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002112
2113 // Format the parameter list.
2114 std::string Params;
Douglas Gregor830072c2011-02-15 22:37:09 +00002115 if (!BlockProto || Block->getNumArgs() == 0) {
2116 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002117 Params = "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002118 else
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002119 Params = "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002120 } else {
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002121 Params += "(";
Douglas Gregor38276252010-09-08 22:47:51 +00002122 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2123 if (I)
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002124 Params += ", ";
2125 Params += FormatFunctionParameter(Context, Policy, Block->getArg(I),
2126 /*SuppressName=*/false,
2127 /*SuppressBlock=*/true);
Douglas Gregor38276252010-09-08 22:47:51 +00002128
Douglas Gregor830072c2011-02-15 22:37:09 +00002129 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002130 Params += ", ...";
Douglas Gregor38276252010-09-08 22:47:51 +00002131 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002132 Params += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002133 }
Douglas Gregor38276252010-09-08 22:47:51 +00002134
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002135 if (SuppressBlock) {
2136 // Format as a parameter.
2137 Result = Result + " (^";
2138 if (Param->getIdentifier())
2139 Result += Param->getIdentifier()->getName();
2140 Result += ")";
2141 Result += Params;
2142 } else {
2143 // Format as a block literal argument.
2144 Result = '^' + Result;
2145 Result += Params;
2146
2147 if (Param->getIdentifier())
2148 Result += Param->getIdentifier()->getName();
2149 }
2150
Douglas Gregor83482d12010-08-24 16:15:59 +00002151 return Result;
2152}
2153
Douglas Gregor86d9a522009-09-21 16:56:56 +00002154/// \brief Add function parameter chunks to the given code completion string.
2155static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002156 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002157 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002158 CodeCompletionBuilder &Result,
2159 unsigned Start = 0,
2160 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002161 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002162 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002163
Douglas Gregor218937c2011-02-01 19:23:04 +00002164 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002165 ParmVarDecl *Param = Function->getParamDecl(P);
2166
Douglas Gregor218937c2011-02-01 19:23:04 +00002167 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002168 // When we see an optional default argument, put that argument and
2169 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002170 CodeCompletionBuilder Opt(Result.getAllocator());
2171 if (!FirstParameter)
2172 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002173 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregor218937c2011-02-01 19:23:04 +00002174 Result.AddOptionalChunk(Opt.TakeString());
2175 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002176 }
2177
Douglas Gregor218937c2011-02-01 19:23:04 +00002178 if (FirstParameter)
2179 FirstParameter = false;
2180 else
2181 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2182
2183 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002184
2185 // Format the placeholder string.
Douglas Gregor8987b232011-09-27 23:30:47 +00002186 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2187 Param);
Douglas Gregor83482d12010-08-24 16:15:59 +00002188
Douglas Gregore17794f2010-08-31 05:13:43 +00002189 if (Function->isVariadic() && P == N - 1)
2190 PlaceholderStr += ", ...";
2191
Douglas Gregor86d9a522009-09-21 16:56:56 +00002192 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002193 Result.AddPlaceholderChunk(
2194 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002195 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002196
2197 if (const FunctionProtoType *Proto
2198 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002199 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002200 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002201 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002202
Douglas Gregor218937c2011-02-01 19:23:04 +00002203 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002204 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002205}
2206
2207/// \brief Add template parameter chunks to the given code completion string.
2208static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002209 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002210 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002211 CodeCompletionBuilder &Result,
2212 unsigned MaxParameters = 0,
2213 unsigned Start = 0,
2214 bool InDefaultArg = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002215 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002216 bool FirstParameter = true;
2217
2218 TemplateParameterList *Params = Template->getTemplateParameters();
2219 TemplateParameterList::iterator PEnd = Params->end();
2220 if (MaxParameters)
2221 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002222 for (TemplateParameterList::iterator P = Params->begin() + Start;
2223 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002224 bool HasDefaultArg = false;
2225 std::string PlaceholderStr;
2226 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2227 if (TTP->wasDeclaredWithTypename())
2228 PlaceholderStr = "typename";
2229 else
2230 PlaceholderStr = "class";
2231
2232 if (TTP->getIdentifier()) {
2233 PlaceholderStr += ' ';
2234 PlaceholderStr += TTP->getIdentifier()->getName();
2235 }
2236
2237 HasDefaultArg = TTP->hasDefaultArgument();
2238 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002239 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002240 if (NTTP->getIdentifier())
2241 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002242 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002243 HasDefaultArg = NTTP->hasDefaultArgument();
2244 } else {
2245 assert(isa<TemplateTemplateParmDecl>(*P));
2246 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2247
2248 // Since putting the template argument list into the placeholder would
2249 // be very, very long, we just use an abbreviation.
2250 PlaceholderStr = "template<...> class";
2251 if (TTP->getIdentifier()) {
2252 PlaceholderStr += ' ';
2253 PlaceholderStr += TTP->getIdentifier()->getName();
2254 }
2255
2256 HasDefaultArg = TTP->hasDefaultArgument();
2257 }
2258
Douglas Gregor218937c2011-02-01 19:23:04 +00002259 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002260 // When we see an optional default argument, put that argument and
2261 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002262 CodeCompletionBuilder Opt(Result.getAllocator());
2263 if (!FirstParameter)
2264 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002265 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregor218937c2011-02-01 19:23:04 +00002266 P - Params->begin(), true);
2267 Result.AddOptionalChunk(Opt.TakeString());
2268 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002269 }
2270
Douglas Gregor218937c2011-02-01 19:23:04 +00002271 InDefaultArg = false;
2272
Douglas Gregor86d9a522009-09-21 16:56:56 +00002273 if (FirstParameter)
2274 FirstParameter = false;
2275 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002276 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002277
2278 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002279 Result.AddPlaceholderChunk(
2280 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002281 }
2282}
2283
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002284/// \brief Add a qualifier to the given code-completion string, if the
2285/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002286static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002287AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002288 NestedNameSpecifier *Qualifier,
2289 bool QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002290 ASTContext &Context,
2291 const PrintingPolicy &Policy) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002292 if (!Qualifier)
2293 return;
2294
2295 std::string PrintedNNS;
2296 {
2297 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor8987b232011-09-27 23:30:47 +00002298 Qualifier->print(OS, Policy);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002299 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002300 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002301 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002302 else
Douglas Gregordae68752011-02-01 22:57:45 +00002303 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002304}
2305
Douglas Gregor218937c2011-02-01 19:23:04 +00002306static void
2307AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2308 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002309 const FunctionProtoType *Proto
2310 = Function->getType()->getAs<FunctionProtoType>();
2311 if (!Proto || !Proto->getTypeQuals())
2312 return;
2313
Douglas Gregora63f6de2011-02-01 21:15:40 +00002314 // FIXME: Add ref-qualifier!
2315
2316 // Handle single qualifiers without copying
2317 if (Proto->getTypeQuals() == Qualifiers::Const) {
2318 Result.AddInformativeChunk(" const");
2319 return;
2320 }
2321
2322 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2323 Result.AddInformativeChunk(" volatile");
2324 return;
2325 }
2326
2327 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2328 Result.AddInformativeChunk(" restrict");
2329 return;
2330 }
2331
2332 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002333 std::string QualsStr;
2334 if (Proto->getTypeQuals() & Qualifiers::Const)
2335 QualsStr += " const";
2336 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2337 QualsStr += " volatile";
2338 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2339 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002340 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002341}
2342
Douglas Gregor6f942b22010-09-21 16:06:22 +00002343/// \brief Add the name of the given declaration
Douglas Gregor8987b232011-09-27 23:30:47 +00002344static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2345 NamedDecl *ND, CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002346 typedef CodeCompletionString::Chunk Chunk;
2347
2348 DeclarationName Name = ND->getDeclName();
2349 if (!Name)
2350 return;
2351
2352 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002353 case DeclarationName::CXXOperatorName: {
2354 const char *OperatorName = 0;
2355 switch (Name.getCXXOverloadedOperator()) {
2356 case OO_None:
2357 case OO_Conditional:
2358 case NUM_OVERLOADED_OPERATORS:
2359 OperatorName = "operator";
2360 break;
2361
2362#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2363 case OO_##Name: OperatorName = "operator" Spelling; break;
2364#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2365#include "clang/Basic/OperatorKinds.def"
2366
2367 case OO_New: OperatorName = "operator new"; break;
2368 case OO_Delete: OperatorName = "operator delete"; break;
2369 case OO_Array_New: OperatorName = "operator new[]"; break;
2370 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2371 case OO_Call: OperatorName = "operator()"; break;
2372 case OO_Subscript: OperatorName = "operator[]"; break;
2373 }
2374 Result.AddTypedTextChunk(OperatorName);
2375 break;
2376 }
2377
Douglas Gregor6f942b22010-09-21 16:06:22 +00002378 case DeclarationName::Identifier:
2379 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002380 case DeclarationName::CXXDestructorName:
2381 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002382 Result.AddTypedTextChunk(
2383 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002384 break;
2385
2386 case DeclarationName::CXXUsingDirective:
2387 case DeclarationName::ObjCZeroArgSelector:
2388 case DeclarationName::ObjCOneArgSelector:
2389 case DeclarationName::ObjCMultiArgSelector:
2390 break;
2391
2392 case DeclarationName::CXXConstructorName: {
2393 CXXRecordDecl *Record = 0;
2394 QualType Ty = Name.getCXXNameType();
2395 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2396 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2397 else if (const InjectedClassNameType *InjectedTy
2398 = Ty->getAs<InjectedClassNameType>())
2399 Record = InjectedTy->getDecl();
2400 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002401 Result.AddTypedTextChunk(
2402 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002403 break;
2404 }
2405
Douglas Gregordae68752011-02-01 22:57:45 +00002406 Result.AddTypedTextChunk(
2407 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002408 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002409 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002410 AddTemplateParameterChunks(Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002411 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002412 }
2413 break;
2414 }
2415 }
2416}
2417
Douglas Gregor86d9a522009-09-21 16:56:56 +00002418/// \brief If possible, create a new code completion string for the given
2419/// result.
2420///
2421/// \returns Either a new, heap-allocated code completion string describing
2422/// how to use this result, or NULL to indicate that the string or name of the
2423/// result is all that is needed.
2424CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002425CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002426 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002427 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002428 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002429
Douglas Gregor8987b232011-09-27 23:30:47 +00002430 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregor218937c2011-02-01 19:23:04 +00002431 if (Kind == RK_Pattern) {
2432 Pattern->Priority = Priority;
2433 Pattern->Availability = Availability;
2434 return Pattern;
2435 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002436
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002437 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002438 Result.AddTypedTextChunk(Keyword);
2439 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002440 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002441
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002442 if (Kind == RK_Macro) {
2443 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002444 assert(MI && "Not a macro?");
2445
Douglas Gregordae68752011-02-01 22:57:45 +00002446 Result.AddTypedTextChunk(
2447 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002448
2449 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002450 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002451
2452 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002453 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregore4244702011-07-30 08:17:44 +00002454 bool CombineVariadicArgument = false;
2455 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2456 if (MI->isVariadic() && AEnd - A > 1) {
2457 AEnd -= 2;
2458 CombineVariadicArgument = true;
2459 }
2460 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002461 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002462 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002463
Douglas Gregore4244702011-07-30 08:17:44 +00002464 if (!MI->isVariadic() || A + 1 != AEnd) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002465 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002466 Result.AddPlaceholderChunk(
2467 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002468 continue;
2469 }
2470
Douglas Gregore4244702011-07-30 08:17:44 +00002471 // Variadic argument; cope with the difference between GNU and C99
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002472 // variadic macros, providing a single placeholder for the rest of the
2473 // arguments.
2474 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002475 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002476 else {
2477 std::string Arg = (*A)->getName();
2478 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002479 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002480 }
2481 }
Douglas Gregore4244702011-07-30 08:17:44 +00002482
2483 if (CombineVariadicArgument) {
2484 // Handle the next-to-last argument, combining it with the variadic
2485 // argument.
2486 std::string LastArg = (*A)->getName();
2487 ++A;
2488 if ((*A)->isStr("__VA_ARGS__"))
2489 LastArg += ", ...";
2490 else
2491 LastArg += ", " + (*A)->getName().str() + "...";
2492 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(LastArg));
2493 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002494 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2495 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002496 }
2497
Douglas Gregord8e8a582010-05-25 21:41:55 +00002498 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002499 NamedDecl *ND = Declaration;
2500
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002501 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002502 Result.AddTypedTextChunk(
2503 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002504 Result.AddTextChunk("::");
2505 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002506 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00002507
2508 for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2509 if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2510 Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2511 }
2512 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002513
Douglas Gregor8987b232011-09-27 23:30:47 +00002514 AddResultTypeChunk(S.Context, Policy, ND, Result);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002515
Douglas Gregor86d9a522009-09-21 16:56:56 +00002516 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002517 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002518 S.Context, Policy);
2519 AddTypedNameChunk(S.Context, Policy, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002520 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002521 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002522 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002523 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002524 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002525 }
2526
2527 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002528 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002529 S.Context, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002530 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor8987b232011-09-27 23:30:47 +00002531 AddTypedNameChunk(S.Context, Policy, Function, Result);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002532
Douglas Gregor86d9a522009-09-21 16:56:56 +00002533 // Figure out which template parameters are deduced (or have default
2534 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002535 SmallVector<bool, 16> Deduced;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002536 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2537 unsigned LastDeducibleArgument;
2538 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2539 --LastDeducibleArgument) {
2540 if (!Deduced[LastDeducibleArgument - 1]) {
2541 // C++0x: Figure out if the template argument has a default. If so,
2542 // the user doesn't need to type this argument.
2543 // FIXME: We need to abstract template parameters better!
2544 bool HasDefaultArg = false;
2545 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002546 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002547 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2548 HasDefaultArg = TTP->hasDefaultArgument();
2549 else if (NonTypeTemplateParmDecl *NTTP
2550 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2551 HasDefaultArg = NTTP->hasDefaultArgument();
2552 else {
2553 assert(isa<TemplateTemplateParmDecl>(Param));
2554 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002555 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002556 }
2557
2558 if (!HasDefaultArg)
2559 break;
2560 }
2561 }
2562
2563 if (LastDeducibleArgument) {
2564 // Some of the function template arguments cannot be deduced from a
2565 // function call, so we introduce an explicit template argument list
2566 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002567 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002568 AddTemplateParameterChunks(S.Context, Policy, FunTmpl, Result,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002569 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002570 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002571 }
2572
2573 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002574 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002575 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002576 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002577 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002578 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002579 }
2580
2581 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002582 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002583 S.Context, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002584 Result.AddTypedTextChunk(
2585 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002586 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002587 AddTemplateParameterChunks(S.Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002588 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2589 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002590 }
2591
Douglas Gregor9630eb62009-11-17 16:44:22 +00002592 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002593 Selector Sel = Method->getSelector();
2594 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002595 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002596 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002597 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002598 }
2599
Douglas Gregor813d8342011-02-18 22:29:55 +00002600 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002601 SelName += ':';
2602 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002603 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002604 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002605 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002606
2607 // If there is only one parameter, and we're past it, add an empty
2608 // typed-text chunk since there is nothing to type.
2609 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002610 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002611 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002612 unsigned Idx = 0;
2613 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2614 PEnd = Method->param_end();
2615 P != PEnd; (void)++P, ++Idx) {
2616 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002617 std::string Keyword;
2618 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002619 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002620 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002621 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002622 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002623 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002624 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002625 else
Douglas Gregordae68752011-02-01 22:57:45 +00002626 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002627 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002628
2629 // If we're before the starting parameter, skip the placeholder.
2630 if (Idx < StartParameter)
2631 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002632
2633 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002634
2635 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregor8987b232011-09-27 23:30:47 +00002636 Arg = FormatFunctionParameter(S.Context, Policy, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002637 else {
John McCallf85e1932011-06-15 23:02:42 +00002638 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002639 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2640 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002641 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002642 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002643 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002644 }
2645
Douglas Gregore17794f2010-08-31 05:13:43 +00002646 if (Method->isVariadic() && (P + 1) == PEnd)
2647 Arg += ", ...";
2648
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002649 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002650 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002651 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002652 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002653 else
Douglas Gregordae68752011-02-01 22:57:45 +00002654 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002655 }
2656
Douglas Gregor2a17af02009-12-23 00:21:46 +00002657 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002658 if (Method->param_size() == 0) {
2659 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002660 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002661 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002662 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002663 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002664 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002665 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002666
2667 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002668 }
2669
Douglas Gregor218937c2011-02-01 19:23:04 +00002670 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002671 }
2672
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002673 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002674 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002675 S.Context, Policy);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002676
Douglas Gregordae68752011-02-01 22:57:45 +00002677 Result.AddTypedTextChunk(
2678 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002679 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002680}
2681
Douglas Gregor86d802e2009-09-23 00:34:09 +00002682CodeCompletionString *
2683CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2684 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002685 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002686 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002687 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor8987b232011-09-27 23:30:47 +00002688 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCallf85e1932011-06-15 23:02:42 +00002689
Douglas Gregor218937c2011-02-01 19:23:04 +00002690 // FIXME: Set priority, availability appropriately.
2691 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002692 FunctionDecl *FDecl = getFunction();
Douglas Gregor8987b232011-09-27 23:30:47 +00002693 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002694 const FunctionProtoType *Proto
2695 = dyn_cast<FunctionProtoType>(getFunctionType());
2696 if (!FDecl && !Proto) {
2697 // Function without a prototype. Just give the return type and a
2698 // highlighted ellipsis.
2699 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002700 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
Douglas Gregor8987b232011-09-27 23:30:47 +00002701 S.Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002702 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002703 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2704 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2705 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2706 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002707 }
2708
2709 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002710 Result.AddTextChunk(
2711 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002712 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002713 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002714 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002715 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002716
Douglas Gregor218937c2011-02-01 19:23:04 +00002717 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002718 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2719 for (unsigned I = 0; I != NumParams; ++I) {
2720 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002721 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002722
2723 std::string ArgString;
2724 QualType ArgType;
2725
2726 if (FDecl) {
2727 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2728 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2729 } else {
2730 ArgType = Proto->getArgType(I);
2731 }
2732
John McCallf85e1932011-06-15 23:02:42 +00002733 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002734
2735 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002736 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002737 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002738 else
Douglas Gregordae68752011-02-01 22:57:45 +00002739 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002740 }
2741
2742 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002743 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002744 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002745 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002746 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002747 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002748 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002749 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002750
Douglas Gregor218937c2011-02-01 19:23:04 +00002751 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002752}
2753
Chris Lattner5f9e2722011-07-23 10:55:15 +00002754unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002755 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002756 bool PreferredTypeIsPointer) {
2757 unsigned Priority = CCP_Macro;
2758
Douglas Gregorb05496d2010-09-20 21:11:48 +00002759 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2760 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2761 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002762 Priority = CCP_Constant;
2763 if (PreferredTypeIsPointer)
2764 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002765 }
2766 // Treat "YES", "NO", "true", and "false" as constants.
2767 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2768 MacroName.equals("true") || MacroName.equals("false"))
2769 Priority = CCP_Constant;
2770 // Treat "bool" as a type.
2771 else if (MacroName.equals("bool"))
2772 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2773
Douglas Gregor1827e102010-08-16 16:18:59 +00002774
2775 return Priority;
2776}
2777
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002778CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2779 if (!D)
2780 return CXCursor_UnexposedDecl;
2781
2782 switch (D->getKind()) {
2783 case Decl::Enum: return CXCursor_EnumDecl;
2784 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2785 case Decl::Field: return CXCursor_FieldDecl;
2786 case Decl::Function:
2787 return CXCursor_FunctionDecl;
2788 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2789 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2790 case Decl::ObjCClass:
2791 // FIXME
2792 return CXCursor_UnexposedDecl;
2793 case Decl::ObjCForwardProtocol:
2794 // FIXME
2795 return CXCursor_UnexposedDecl;
2796 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2797 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2798 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2799 case Decl::ObjCMethod:
2800 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2801 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2802 case Decl::CXXMethod: return CXCursor_CXXMethod;
2803 case Decl::CXXConstructor: return CXCursor_Constructor;
2804 case Decl::CXXDestructor: return CXCursor_Destructor;
2805 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2806 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2807 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2808 case Decl::ParmVar: return CXCursor_ParmDecl;
2809 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002810 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002811 case Decl::Var: return CXCursor_VarDecl;
2812 case Decl::Namespace: return CXCursor_Namespace;
2813 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2814 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2815 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2816 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2817 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2818 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00002819 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002820 case Decl::ClassTemplatePartialSpecialization:
2821 return CXCursor_ClassTemplatePartialSpecialization;
2822 case Decl::UsingDirective: return CXCursor_UsingDirective;
2823
2824 case Decl::Using:
2825 case Decl::UnresolvedUsingValue:
2826 case Decl::UnresolvedUsingTypename:
2827 return CXCursor_UsingDeclaration;
2828
Douglas Gregor352697a2011-06-03 23:08:58 +00002829 case Decl::ObjCPropertyImpl:
2830 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2831 case ObjCPropertyImplDecl::Dynamic:
2832 return CXCursor_ObjCDynamicDecl;
2833
2834 case ObjCPropertyImplDecl::Synthesize:
2835 return CXCursor_ObjCSynthesizeDecl;
2836 }
2837 break;
2838
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002839 default:
2840 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2841 switch (TD->getTagKind()) {
2842 case TTK_Struct: return CXCursor_StructDecl;
2843 case TTK_Class: return CXCursor_ClassDecl;
2844 case TTK_Union: return CXCursor_UnionDecl;
2845 case TTK_Enum: return CXCursor_EnumDecl;
2846 }
2847 }
2848 }
2849
2850 return CXCursor_UnexposedDecl;
2851}
2852
Douglas Gregor590c7d52010-07-08 20:55:51 +00002853static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2854 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002855 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002856
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002857 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002858
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002859 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2860 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002861 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002862 Results.AddResult(Result(M->first,
2863 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002864 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002865 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002866 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002867
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002868 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002869
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002870}
2871
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002872static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2873 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002874 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002875
2876 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002877
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002878 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2879 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2880 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2881 Results.AddResult(Result("__func__", CCP_Constant));
2882 Results.ExitScope();
2883}
2884
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002885static void HandleCodeCompleteResults(Sema *S,
2886 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002887 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002888 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002889 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002890 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002891 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002892}
2893
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002894static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2895 Sema::ParserCompletionContext PCC) {
2896 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002897 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002898 return CodeCompletionContext::CCC_TopLevel;
2899
John McCallf312b1e2010-08-26 23:41:50 +00002900 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002901 return CodeCompletionContext::CCC_ClassStructUnion;
2902
John McCallf312b1e2010-08-26 23:41:50 +00002903 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002904 return CodeCompletionContext::CCC_ObjCInterface;
2905
John McCallf312b1e2010-08-26 23:41:50 +00002906 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002907 return CodeCompletionContext::CCC_ObjCImplementation;
2908
John McCallf312b1e2010-08-26 23:41:50 +00002909 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002910 return CodeCompletionContext::CCC_ObjCIvarList;
2911
John McCallf312b1e2010-08-26 23:41:50 +00002912 case Sema::PCC_Template:
2913 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002914 if (S.CurContext->isFileContext())
2915 return CodeCompletionContext::CCC_TopLevel;
2916 else if (S.CurContext->isRecord())
2917 return CodeCompletionContext::CCC_ClassStructUnion;
2918 else
2919 return CodeCompletionContext::CCC_Other;
2920
John McCallf312b1e2010-08-26 23:41:50 +00002921 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002922 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002923
John McCallf312b1e2010-08-26 23:41:50 +00002924 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002925 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2926 S.getLangOptions().ObjC1)
2927 return CodeCompletionContext::CCC_ParenthesizedExpression;
2928 else
2929 return CodeCompletionContext::CCC_Expression;
2930
2931 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002932 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002933 return CodeCompletionContext::CCC_Expression;
2934
John McCallf312b1e2010-08-26 23:41:50 +00002935 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002936 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002937
John McCallf312b1e2010-08-26 23:41:50 +00002938 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002939 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002940
2941 case Sema::PCC_ParenthesizedExpression:
2942 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002943
2944 case Sema::PCC_LocalDeclarationSpecifiers:
2945 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002946 }
2947
2948 return CodeCompletionContext::CCC_Other;
2949}
2950
Douglas Gregorf6961522010-08-27 21:18:54 +00002951/// \brief If we're in a C++ virtual member function, add completion results
2952/// that invoke the functions we override, since it's common to invoke the
2953/// overridden function as well as adding new functionality.
2954///
2955/// \param S The semantic analysis object for which we are generating results.
2956///
2957/// \param InContext This context in which the nested-name-specifier preceding
2958/// the code-completion point
2959static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2960 ResultBuilder &Results) {
2961 // Look through blocks.
2962 DeclContext *CurContext = S.CurContext;
2963 while (isa<BlockDecl>(CurContext))
2964 CurContext = CurContext->getParent();
2965
2966
2967 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2968 if (!Method || !Method->isVirtual())
2969 return;
2970
2971 // We need to have names for all of the parameters, if we're going to
2972 // generate a forwarding call.
2973 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2974 PEnd = Method->param_end();
2975 P != PEnd;
2976 ++P) {
2977 if (!(*P)->getDeclName())
2978 return;
2979 }
2980
Douglas Gregor8987b232011-09-27 23:30:47 +00002981 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorf6961522010-08-27 21:18:54 +00002982 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2983 MEnd = Method->end_overridden_methods();
2984 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002985 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002986 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2987 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2988 continue;
2989
2990 // If we need a nested-name-specifier, add one now.
2991 if (!InContext) {
2992 NestedNameSpecifier *NNS
2993 = getRequiredQualification(S.Context, CurContext,
2994 Overridden->getDeclContext());
2995 if (NNS) {
2996 std::string Str;
2997 llvm::raw_string_ostream OS(Str);
Douglas Gregor8987b232011-09-27 23:30:47 +00002998 NNS->print(OS, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002999 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003000 }
3001 } else if (!InContext->Equals(Overridden->getDeclContext()))
3002 continue;
3003
Douglas Gregordae68752011-02-01 22:57:45 +00003004 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003005 Overridden->getNameAsString()));
3006 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00003007 bool FirstParam = true;
3008 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3009 PEnd = Method->param_end();
3010 P != PEnd; ++P) {
3011 if (FirstParam)
3012 FirstParam = false;
3013 else
Douglas Gregor218937c2011-02-01 19:23:04 +00003014 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00003015
Douglas Gregordae68752011-02-01 22:57:45 +00003016 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003017 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003018 }
Douglas Gregor218937c2011-02-01 19:23:04 +00003019 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3020 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00003021 CCP_SuperCompletion,
3022 CXCursor_CXXMethod));
3023 Results.Ignore(Overridden);
3024 }
3025}
3026
Douglas Gregor01dfea02010-01-10 23:08:15 +00003027void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003028 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00003029 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003030 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003031 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00003032 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003033
Douglas Gregor01dfea02010-01-10 23:08:15 +00003034 // Determine how to filter results, e.g., so that the names of
3035 // values (functions, enumerators, function templates, etc.) are
3036 // only allowed where we can have an expression.
3037 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003038 case PCC_Namespace:
3039 case PCC_Class:
3040 case PCC_ObjCInterface:
3041 case PCC_ObjCImplementation:
3042 case PCC_ObjCInstanceVariableList:
3043 case PCC_Template:
3044 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00003045 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003046 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00003047 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3048 break;
3049
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003050 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00003051 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00003052 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003053 case PCC_ForInit:
3054 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00003055 if (WantTypesInContext(CompletionContext, getLangOptions()))
3056 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3057 else
3058 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00003059
3060 if (getLangOptions().CPlusPlus)
3061 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00003062 break;
Douglas Gregordc845342010-05-25 05:58:43 +00003063
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003064 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00003065 // Unfiltered
3066 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00003067 }
3068
Douglas Gregor3cdee122010-08-26 16:36:48 +00003069 // If we are in a C++ non-static member function, check the qualifiers on
3070 // the member function to filter/prioritize the results list.
3071 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3072 if (CurMethod->isInstance())
3073 Results.setObjectTypeQualifiers(
3074 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3075
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00003076 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003077 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3078 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003079
Douglas Gregorbca403c2010-01-13 23:51:12 +00003080 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003081 Results.ExitScope();
3082
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003083 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00003084 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00003085 case PCC_Expression:
3086 case PCC_Statement:
3087 case PCC_RecoveryInFunction:
3088 if (S->getFnParent())
3089 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3090 break;
3091
3092 case PCC_Namespace:
3093 case PCC_Class:
3094 case PCC_ObjCInterface:
3095 case PCC_ObjCImplementation:
3096 case PCC_ObjCInstanceVariableList:
3097 case PCC_Template:
3098 case PCC_MemberTemplate:
3099 case PCC_ForInit:
3100 case PCC_Condition:
3101 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003102 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003103 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003104 }
3105
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003106 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003107 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003108
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003109 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003110 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003111}
3112
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003113static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3114 ParsedType Receiver,
3115 IdentifierInfo **SelIdents,
3116 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003117 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003118 bool IsSuper,
3119 ResultBuilder &Results);
3120
3121void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3122 bool AllowNonIdentifiers,
3123 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003124 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003125 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003126 AllowNestedNameSpecifiers
3127 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3128 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003129 Results.EnterNewScope();
3130
3131 // Type qualifiers can come after names.
3132 Results.AddResult(Result("const"));
3133 Results.AddResult(Result("volatile"));
3134 if (getLangOptions().C99)
3135 Results.AddResult(Result("restrict"));
3136
3137 if (getLangOptions().CPlusPlus) {
3138 if (AllowNonIdentifiers) {
3139 Results.AddResult(Result("operator"));
3140 }
3141
3142 // Add nested-name-specifiers.
3143 if (AllowNestedNameSpecifiers) {
3144 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003145 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003146 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3147 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3148 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003149 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003150 }
3151 }
3152 Results.ExitScope();
3153
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003154 // If we're in a context where we might have an expression (rather than a
3155 // declaration), and what we've seen so far is an Objective-C type that could
3156 // be a receiver of a class message, this may be a class message send with
3157 // the initial opening bracket '[' missing. Add appropriate completions.
3158 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3159 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3160 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3161 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3162 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3163 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3164 DS.getTypeQualifiers() == 0 &&
3165 S &&
3166 (S->getFlags() & Scope::DeclScope) != 0 &&
3167 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3168 Scope::FunctionPrototypeScope |
3169 Scope::AtCatchScope)) == 0) {
3170 ParsedType T = DS.getRepAsType();
3171 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003172 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003173 }
3174
Douglas Gregor4497dd42010-08-24 04:59:56 +00003175 // Note that we intentionally suppress macro results here, since we do not
3176 // encourage using macros to produce the names of entities.
3177
Douglas Gregor52779fb2010-09-23 23:01:17 +00003178 HandleCodeCompleteResults(this, CodeCompleter,
3179 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003180 Results.data(), Results.size());
3181}
3182
Douglas Gregorfb629412010-08-23 21:17:50 +00003183struct Sema::CodeCompleteExpressionData {
3184 CodeCompleteExpressionData(QualType PreferredType = QualType())
3185 : PreferredType(PreferredType), IntegralConstantExpression(false),
3186 ObjCCollection(false) { }
3187
3188 QualType PreferredType;
3189 bool IntegralConstantExpression;
3190 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003191 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003192};
3193
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003194/// \brief Perform code-completion in an expression context when we know what
3195/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003196///
3197/// \param IntegralConstantExpression Only permit integral constant
3198/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003199void Sema::CodeCompleteExpression(Scope *S,
3200 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003201 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003202 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3203 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003204 if (Data.ObjCCollection)
3205 Results.setFilter(&ResultBuilder::IsObjCCollection);
3206 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003207 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003208 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003209 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3210 else
3211 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003212
3213 if (!Data.PreferredType.isNull())
3214 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3215
3216 // Ignore any declarations that we were told that we don't care about.
3217 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3218 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003219
3220 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003221 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3222 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003223
3224 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003225 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003226 Results.ExitScope();
3227
Douglas Gregor590c7d52010-07-08 20:55:51 +00003228 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003229 if (!Data.PreferredType.isNull())
3230 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3231 || Data.PreferredType->isMemberPointerType()
3232 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003233
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003234 if (S->getFnParent() &&
3235 !Data.ObjCCollection &&
3236 !Data.IntegralConstantExpression)
3237 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3238
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003239 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003240 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003241 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003242 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3243 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003244 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003245}
3246
Douglas Gregorac5fd842010-09-18 01:28:11 +00003247void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3248 if (E.isInvalid())
3249 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3250 else if (getLangOptions().ObjC1)
3251 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003252}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003253
Douglas Gregor73449212010-12-09 23:01:55 +00003254/// \brief The set of properties that have already been added, referenced by
3255/// property name.
3256typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3257
Douglas Gregor95ac6552009-11-18 01:29:26 +00003258static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003259 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003260 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003261 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003262 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003263 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003264 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003265
3266 // Add properties in this container.
3267 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3268 PEnd = Container->prop_end();
3269 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003270 ++P) {
3271 if (AddedProperties.insert(P->getIdentifier()))
3272 Results.MaybeAddResult(Result(*P, 0), CurContext);
3273 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003274
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003275 // Add nullary methods
3276 if (AllowNullaryMethods) {
3277 ASTContext &Context = Container->getASTContext();
Douglas Gregor8987b232011-09-27 23:30:47 +00003278 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003279 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3280 MEnd = Container->meth_end();
3281 M != MEnd; ++M) {
3282 if (M->getSelector().isUnarySelector())
3283 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3284 if (AddedProperties.insert(Name)) {
3285 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor8987b232011-09-27 23:30:47 +00003286 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003287 Builder.AddTypedTextChunk(
3288 Results.getAllocator().CopyString(Name->getName()));
3289
3290 CXAvailabilityKind Availability = CXAvailability_Available;
3291 switch (M->getAvailability()) {
3292 case AR_Available:
3293 case AR_NotYetIntroduced:
3294 Availability = CXAvailability_Available;
3295 break;
3296
3297 case AR_Deprecated:
3298 Availability = CXAvailability_Deprecated;
3299 break;
3300
3301 case AR_Unavailable:
3302 Availability = CXAvailability_NotAvailable;
3303 break;
3304 }
3305
3306 Results.MaybeAddResult(Result(Builder.TakeString(),
3307 CCP_MemberDeclaration + CCD_MethodAsProperty,
3308 M->isInstanceMethod()
3309 ? CXCursor_ObjCInstanceMethodDecl
3310 : CXCursor_ObjCClassMethodDecl,
3311 Availability),
3312 CurContext);
3313 }
3314 }
3315 }
3316
3317
Douglas Gregor95ac6552009-11-18 01:29:26 +00003318 // Add properties in referenced protocols.
3319 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3320 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3321 PEnd = Protocol->protocol_end();
3322 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003323 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3324 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003325 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003326 if (AllowCategories) {
3327 // Look through categories.
3328 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3329 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003330 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3331 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003332 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003333
3334 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003335 for (ObjCInterfaceDecl::all_protocol_iterator
3336 I = IFace->all_referenced_protocol_begin(),
3337 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003338 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3339 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003340
3341 // Look in the superclass.
3342 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003343 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3344 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003345 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003346 } else if (const ObjCCategoryDecl *Category
3347 = dyn_cast<ObjCCategoryDecl>(Container)) {
3348 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003349 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3350 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003351 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003352 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3353 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003354 }
3355}
3356
Richard Trieuf81e5a92011-09-09 02:00:50 +00003357void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *BaseE,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003358 SourceLocation OpLoc,
3359 bool IsArrow) {
3360 if (!BaseE || !CodeCompleter)
3361 return;
3362
John McCall0a2c5e22010-08-25 06:19:51 +00003363 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003364
Douglas Gregor81b747b2009-09-17 21:32:03 +00003365 Expr *Base = static_cast<Expr *>(BaseE);
3366 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003367
3368 if (IsArrow) {
3369 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3370 BaseType = Ptr->getPointeeType();
3371 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003372 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003373 else
3374 return;
3375 }
3376
Douglas Gregor3da626b2011-07-07 16:03:39 +00003377 enum CodeCompletionContext::Kind contextKind;
3378
3379 if (IsArrow) {
3380 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3381 }
3382 else {
3383 if (BaseType->isObjCObjectPointerType() ||
3384 BaseType->isObjCObjectOrInterfaceType()) {
3385 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3386 }
3387 else {
3388 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3389 }
3390 }
3391
Douglas Gregor218937c2011-02-01 19:23:04 +00003392 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003393 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003394 BaseType),
3395 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003396 Results.EnterNewScope();
3397 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003398 // Indicate that we are performing a member access, and the cv-qualifiers
3399 // for the base object type.
3400 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3401
Douglas Gregor95ac6552009-11-18 01:29:26 +00003402 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003403 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003404 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003405 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3406 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003407
Douglas Gregor95ac6552009-11-18 01:29:26 +00003408 if (getLangOptions().CPlusPlus) {
3409 if (!Results.empty()) {
3410 // The "template" keyword can follow "->" or "." in the grammar.
3411 // However, we only want to suggest the template keyword if something
3412 // is dependent.
3413 bool IsDependent = BaseType->isDependentType();
3414 if (!IsDependent) {
3415 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3416 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3417 IsDependent = Ctx->isDependentContext();
3418 break;
3419 }
3420 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003421
Douglas Gregor95ac6552009-11-18 01:29:26 +00003422 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003423 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003424 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003425 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003426 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3427 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003428 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003429
3430 // Add property results based on our interface.
3431 const ObjCObjectPointerType *ObjCPtr
3432 = BaseType->getAsObjCInterfacePointerType();
3433 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003434 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3435 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003436 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003437
3438 // Add properties from the protocols in a qualified interface.
3439 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3440 E = ObjCPtr->qual_end();
3441 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003442 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3443 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003444 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003445 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003446 // Objective-C instance variable access.
3447 ObjCInterfaceDecl *Class = 0;
3448 if (const ObjCObjectPointerType *ObjCPtr
3449 = BaseType->getAs<ObjCObjectPointerType>())
3450 Class = ObjCPtr->getInterfaceDecl();
3451 else
John McCallc12c5bb2010-05-15 11:32:37 +00003452 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003453
3454 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003455 if (Class) {
3456 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3457 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003458 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3459 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003460 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003461 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003462
3463 // FIXME: How do we cope with isa?
3464
3465 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003466
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003467 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003468 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003469 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003470 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003471}
3472
Douglas Gregor374929f2009-09-18 15:37:17 +00003473void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3474 if (!CodeCompleter)
3475 return;
3476
John McCall0a2c5e22010-08-25 06:19:51 +00003477 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003478 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003479 enum CodeCompletionContext::Kind ContextKind
3480 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003481 switch ((DeclSpec::TST)TagSpec) {
3482 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003483 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003484 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003485 break;
3486
3487 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003488 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003489 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003490 break;
3491
3492 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003493 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003494 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003495 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003496 break;
3497
3498 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003499 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003500 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003501
Douglas Gregor218937c2011-02-01 19:23:04 +00003502 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003503 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003504
3505 // First pass: look for tags.
3506 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003507 LookupVisibleDecls(S, LookupTagName, Consumer,
3508 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003509
Douglas Gregor8071e422010-08-15 06:18:01 +00003510 if (CodeCompleter->includeGlobals()) {
3511 // Second pass: look for nested name specifiers.
3512 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3513 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3514 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003515
Douglas Gregor52779fb2010-09-23 23:01:17 +00003516 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003517 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003518}
3519
Douglas Gregor1a480c42010-08-27 17:35:51 +00003520void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003521 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3522 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003523 Results.EnterNewScope();
3524 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3525 Results.AddResult("const");
3526 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3527 Results.AddResult("volatile");
3528 if (getLangOptions().C99 &&
3529 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3530 Results.AddResult("restrict");
3531 Results.ExitScope();
3532 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003533 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003534 Results.data(), Results.size());
3535}
3536
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003537void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003538 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003539 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003540
John McCall781472f2010-08-25 08:40:02 +00003541 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003542 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3543 if (!type->isEnumeralType()) {
3544 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003545 Data.IntegralConstantExpression = true;
3546 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003547 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003548 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003549
3550 // Code-complete the cases of a switch statement over an enumeration type
3551 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003552 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003553
3554 // Determine which enumerators we have already seen in the switch statement.
3555 // FIXME: Ideally, we would also be able to look *past* the code-completion
3556 // token, in case we are code-completing in the middle of the switch and not
3557 // at the end. However, we aren't able to do so at the moment.
3558 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003559 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003560 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3561 SC = SC->getNextSwitchCase()) {
3562 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3563 if (!Case)
3564 continue;
3565
3566 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3567 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3568 if (EnumConstantDecl *Enumerator
3569 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3570 // We look into the AST of the case statement to determine which
3571 // enumerator was named. Alternatively, we could compute the value of
3572 // the integral constant expression, then compare it against the
3573 // values of each enumerator. However, value-based approach would not
3574 // work as well with C++ templates where enumerators declared within a
3575 // template are type- and value-dependent.
3576 EnumeratorsSeen.insert(Enumerator);
3577
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003578 // If this is a qualified-id, keep track of the nested-name-specifier
3579 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003580 //
3581 // switch (TagD.getKind()) {
3582 // case TagDecl::TK_enum:
3583 // break;
3584 // case XXX
3585 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003586 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003587 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3588 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003589 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003590 }
3591 }
3592
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003593 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3594 // If there are no prior enumerators in C++, check whether we have to
3595 // qualify the names of the enumerators that we suggest, because they
3596 // may not be visible in this scope.
3597 Qualifier = getRequiredQualification(Context, CurContext,
3598 Enum->getDeclContext());
3599
3600 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3601 }
3602
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003603 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003604 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3605 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003606 Results.EnterNewScope();
3607 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3608 EEnd = Enum->enumerator_end();
3609 E != EEnd; ++E) {
3610 if (EnumeratorsSeen.count(*E))
3611 continue;
3612
Douglas Gregor5c722c702011-02-18 23:30:37 +00003613 CodeCompletionResult R(*E, Qualifier);
3614 R.Priority = CCP_EnumInCase;
3615 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003616 }
3617 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003618
Douglas Gregor3da626b2011-07-07 16:03:39 +00003619 //We need to make sure we're setting the right context,
3620 //so only say we include macros if the code completer says we do
3621 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3622 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003623 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003624 kind = CodeCompletionContext::CCC_OtherWithMacros;
3625 }
3626
3627
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003628 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003629 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003630 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003631}
3632
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003633namespace {
3634 struct IsBetterOverloadCandidate {
3635 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003636 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003637
3638 public:
John McCall5769d612010-02-08 23:07:23 +00003639 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3640 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003641
3642 bool
3643 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003644 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003645 }
3646 };
3647}
3648
Douglas Gregord28dcd72010-05-30 06:10:08 +00003649static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3650 if (NumArgs && !Args)
3651 return true;
3652
3653 for (unsigned I = 0; I != NumArgs; ++I)
3654 if (!Args[I])
3655 return true;
3656
3657 return false;
3658}
3659
Richard Trieuf81e5a92011-09-09 02:00:50 +00003660void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3661 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003662 if (!CodeCompleter)
3663 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003664
3665 // When we're code-completing for a call, we fall back to ordinary
3666 // name code-completion whenever we can't produce specific
3667 // results. We may want to revisit this strategy in the future,
3668 // e.g., by merging the two kinds of results.
3669
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003670 Expr *Fn = (Expr *)FnIn;
3671 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003672
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003673 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003674 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003675 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003676 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003677 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003678 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003679
John McCall3b4294e2009-12-16 12:17:52 +00003680 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003681 SourceLocation Loc = Fn->getExprLoc();
3682 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003683
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003684 // FIXME: What if we're calling something that isn't a function declaration?
3685 // FIXME: What if we're calling a pseudo-destructor?
3686 // FIXME: What if we're calling a member function?
3687
Douglas Gregorc0265402010-01-21 15:46:19 +00003688 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003689 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003690
John McCall3b4294e2009-12-16 12:17:52 +00003691 Expr *NakedFn = Fn->IgnoreParenCasts();
3692 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3693 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3694 /*PartialOverloading=*/ true);
3695 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3696 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003697 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003698 if (!getLangOptions().CPlusPlus ||
3699 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003700 Results.push_back(ResultCandidate(FDecl));
3701 else
John McCall86820f52010-01-26 01:37:31 +00003702 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003703 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3704 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003705 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003706 }
John McCall3b4294e2009-12-16 12:17:52 +00003707 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003708
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003709 QualType ParamType;
3710
Douglas Gregorc0265402010-01-21 15:46:19 +00003711 if (!CandidateSet.empty()) {
3712 // Sort the overload candidate set by placing the best overloads first.
3713 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003714 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003715
Douglas Gregorc0265402010-01-21 15:46:19 +00003716 // Add the remaining viable overload candidates as code-completion reslults.
3717 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3718 CandEnd = CandidateSet.end();
3719 Cand != CandEnd; ++Cand) {
3720 if (Cand->Viable)
3721 Results.push_back(ResultCandidate(Cand->Function));
3722 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003723
3724 // From the viable candidates, try to determine the type of this parameter.
3725 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3726 if (const FunctionType *FType = Results[I].getFunctionType())
3727 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3728 if (NumArgs < Proto->getNumArgs()) {
3729 if (ParamType.isNull())
3730 ParamType = Proto->getArgType(NumArgs);
3731 else if (!Context.hasSameUnqualifiedType(
3732 ParamType.getNonReferenceType(),
3733 Proto->getArgType(NumArgs).getNonReferenceType())) {
3734 ParamType = QualType();
3735 break;
3736 }
3737 }
3738 }
3739 } else {
3740 // Try to determine the parameter type from the type of the expression
3741 // being called.
3742 QualType FunctionType = Fn->getType();
3743 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3744 FunctionType = Ptr->getPointeeType();
3745 else if (const BlockPointerType *BlockPtr
3746 = FunctionType->getAs<BlockPointerType>())
3747 FunctionType = BlockPtr->getPointeeType();
3748 else if (const MemberPointerType *MemPtr
3749 = FunctionType->getAs<MemberPointerType>())
3750 FunctionType = MemPtr->getPointeeType();
3751
3752 if (const FunctionProtoType *Proto
3753 = FunctionType->getAs<FunctionProtoType>()) {
3754 if (NumArgs < Proto->getNumArgs())
3755 ParamType = Proto->getArgType(NumArgs);
3756 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003757 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003758
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003759 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003760 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003761 else
3762 CodeCompleteExpression(S, ParamType);
3763
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003764 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003765 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3766 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003767}
3768
John McCalld226f652010-08-21 09:40:31 +00003769void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3770 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003771 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003772 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003773 return;
3774 }
3775
3776 CodeCompleteExpression(S, VD->getType());
3777}
3778
3779void Sema::CodeCompleteReturn(Scope *S) {
3780 QualType ResultType;
3781 if (isa<BlockDecl>(CurContext)) {
3782 if (BlockScopeInfo *BSI = getCurBlock())
3783 ResultType = BSI->ReturnType;
3784 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3785 ResultType = Function->getResultType();
3786 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3787 ResultType = Method->getResultType();
3788
3789 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003790 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003791 else
3792 CodeCompleteExpression(S, ResultType);
3793}
3794
Douglas Gregord2d8be62011-07-30 08:36:53 +00003795void Sema::CodeCompleteAfterIf(Scope *S) {
3796 typedef CodeCompletionResult Result;
3797 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3798 mapCodeCompletionContext(*this, PCC_Statement));
3799 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3800 Results.EnterNewScope();
3801
3802 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3803 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3804 CodeCompleter->includeGlobals());
3805
3806 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3807
3808 // "else" block
3809 CodeCompletionBuilder Builder(Results.getAllocator());
3810 Builder.AddTypedTextChunk("else");
3811 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3812 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3813 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3814 Builder.AddPlaceholderChunk("statements");
3815 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3816 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3817 Results.AddResult(Builder.TakeString());
3818
3819 // "else if" block
3820 Builder.AddTypedTextChunk("else");
3821 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3822 Builder.AddTextChunk("if");
3823 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3824 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3825 if (getLangOptions().CPlusPlus)
3826 Builder.AddPlaceholderChunk("condition");
3827 else
3828 Builder.AddPlaceholderChunk("expression");
3829 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3830 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3831 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3832 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3833 Builder.AddPlaceholderChunk("statements");
3834 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3835 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3836 Results.AddResult(Builder.TakeString());
3837
3838 Results.ExitScope();
3839
3840 if (S->getFnParent())
3841 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3842
3843 if (CodeCompleter->includeMacros())
3844 AddMacroResults(PP, Results);
3845
3846 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3847 Results.data(),Results.size());
3848}
3849
Richard Trieuf81e5a92011-09-09 02:00:50 +00003850void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003851 if (LHS)
3852 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3853 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003854 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003855}
3856
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003857void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003858 bool EnteringContext) {
3859 if (!SS.getScopeRep() || !CodeCompleter)
3860 return;
3861
Douglas Gregor86d9a522009-09-21 16:56:56 +00003862 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3863 if (!Ctx)
3864 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003865
3866 // Try to instantiate any non-dependent declaration contexts before
3867 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003868 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003869 return;
3870
Douglas Gregor218937c2011-02-01 19:23:04 +00003871 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3872 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003873 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003874
Douglas Gregor86d9a522009-09-21 16:56:56 +00003875 // The "template" keyword can follow "::" in the grammar, but only
3876 // put it into the grammar if the nested-name-specifier is dependent.
3877 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3878 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003879 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003880
3881 // Add calls to overridden virtual functions, if there are any.
3882 //
3883 // FIXME: This isn't wonderful, because we don't know whether we're actually
3884 // in a context that permits expressions. This is a general issue with
3885 // qualified-id completions.
3886 if (!EnteringContext)
3887 MaybeAddOverrideCalls(*this, Ctx, Results);
3888 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003889
Douglas Gregorf6961522010-08-27 21:18:54 +00003890 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3891 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3892
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003893 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003894 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003895 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003896}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003897
3898void Sema::CodeCompleteUsing(Scope *S) {
3899 if (!CodeCompleter)
3900 return;
3901
Douglas Gregor218937c2011-02-01 19:23:04 +00003902 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003903 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3904 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003905 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003906
3907 // If we aren't in class scope, we could see the "namespace" keyword.
3908 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003909 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003910
3911 // After "using", we can see anything that would start a
3912 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003913 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003914 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3915 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003916 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003917
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003918 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003919 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003920 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003921}
3922
3923void Sema::CodeCompleteUsingDirective(Scope *S) {
3924 if (!CodeCompleter)
3925 return;
3926
Douglas Gregor86d9a522009-09-21 16:56:56 +00003927 // After "using namespace", we expect to see a namespace name or namespace
3928 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003929 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3930 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003931 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003932 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003933 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003934 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3935 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003936 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003937 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003938 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003939 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003940}
3941
3942void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3943 if (!CodeCompleter)
3944 return;
3945
Douglas Gregor86d9a522009-09-21 16:56:56 +00003946 DeclContext *Ctx = (DeclContext *)S->getEntity();
3947 if (!S->getParent())
3948 Ctx = Context.getTranslationUnitDecl();
3949
Douglas Gregor52779fb2010-09-23 23:01:17 +00003950 bool SuppressedGlobalResults
3951 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3952
Douglas Gregor218937c2011-02-01 19:23:04 +00003953 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003954 SuppressedGlobalResults
3955 ? CodeCompletionContext::CCC_Namespace
3956 : CodeCompletionContext::CCC_Other,
3957 &ResultBuilder::IsNamespace);
3958
3959 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003960 // We only want to see those namespaces that have already been defined
3961 // within this scope, because its likely that the user is creating an
3962 // extended namespace declaration. Keep track of the most recent
3963 // definition of each namespace.
3964 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3965 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3966 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3967 NS != NSEnd; ++NS)
3968 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3969
3970 // Add the most recent definition (or extended definition) of each
3971 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003972 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003973 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3974 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3975 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003976 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003977 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003978 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003979 }
3980
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003981 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003982 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003983 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003984}
3985
3986void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3987 if (!CodeCompleter)
3988 return;
3989
Douglas Gregor86d9a522009-09-21 16:56:56 +00003990 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003991 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3992 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003993 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003994 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003995 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3996 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003997 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003998 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003999 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004000}
4001
Douglas Gregored8d3222009-09-18 20:05:18 +00004002void Sema::CodeCompleteOperatorName(Scope *S) {
4003 if (!CodeCompleter)
4004 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00004005
John McCall0a2c5e22010-08-25 06:19:51 +00004006 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004007 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4008 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004009 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004010 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00004011
Douglas Gregor86d9a522009-09-21 16:56:56 +00004012 // Add the names of overloadable operators.
4013#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4014 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00004015 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00004016#include "clang/Basic/OperatorKinds.def"
4017
4018 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00004019 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004020 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004021 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4022 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00004023
4024 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00004025 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004026 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004027
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004028 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00004029 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004030 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00004031}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004032
Douglas Gregor0133f522010-08-28 00:00:50 +00004033void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00004034 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00004035 unsigned NumInitializers) {
Douglas Gregor8987b232011-09-27 23:30:47 +00004036 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor0133f522010-08-28 00:00:50 +00004037 CXXConstructorDecl *Constructor
4038 = static_cast<CXXConstructorDecl *>(ConstructorD);
4039 if (!Constructor)
4040 return;
4041
Douglas Gregor218937c2011-02-01 19:23:04 +00004042 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004043 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00004044 Results.EnterNewScope();
4045
4046 // Fill in any already-initialized fields or base classes.
4047 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4048 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4049 for (unsigned I = 0; I != NumInitializers; ++I) {
4050 if (Initializers[I]->isBaseInitializer())
4051 InitializedBases.insert(
4052 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4053 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00004054 InitializedFields.insert(cast<FieldDecl>(
4055 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00004056 }
4057
4058 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00004059 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00004060 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00004061 CXXRecordDecl *ClassDecl = Constructor->getParent();
4062 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4063 BaseEnd = ClassDecl->bases_end();
4064 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004065 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4066 SawLastInitializer
4067 = NumInitializers > 0 &&
4068 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4069 Context.hasSameUnqualifiedType(Base->getType(),
4070 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004071 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004072 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004073
Douglas Gregor218937c2011-02-01 19:23:04 +00004074 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004075 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004076 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004077 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4078 Builder.AddPlaceholderChunk("args");
4079 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4080 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004081 SawLastInitializer? CCP_NextInitializer
4082 : CCP_MemberDeclaration));
4083 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004084 }
4085
4086 // Add completions for virtual base classes.
4087 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4088 BaseEnd = ClassDecl->vbases_end();
4089 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004090 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4091 SawLastInitializer
4092 = NumInitializers > 0 &&
4093 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4094 Context.hasSameUnqualifiedType(Base->getType(),
4095 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004096 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004097 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004098
Douglas Gregor218937c2011-02-01 19:23:04 +00004099 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004100 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004101 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004102 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4103 Builder.AddPlaceholderChunk("args");
4104 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4105 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004106 SawLastInitializer? CCP_NextInitializer
4107 : CCP_MemberDeclaration));
4108 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004109 }
4110
4111 // Add completions for members.
4112 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4113 FieldEnd = ClassDecl->field_end();
4114 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004115 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4116 SawLastInitializer
4117 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004118 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4119 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004120 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004121 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004122
4123 if (!Field->getDeclName())
4124 continue;
4125
Douglas Gregordae68752011-02-01 22:57:45 +00004126 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004127 Field->getIdentifier()->getName()));
4128 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4129 Builder.AddPlaceholderChunk("args");
4130 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4131 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004132 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004133 : CCP_MemberDeclaration,
4134 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004135 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004136 }
4137 Results.ExitScope();
4138
Douglas Gregor52779fb2010-09-23 23:01:17 +00004139 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004140 Results.data(), Results.size());
4141}
4142
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004143// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4144// true or false.
4145#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004146static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004147 ResultBuilder &Results,
4148 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004149 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004150 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004151 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004152
Douglas Gregor218937c2011-02-01 19:23:04 +00004153 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004154 if (LangOpts.ObjC2) {
4155 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004156 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4157 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4158 Builder.AddPlaceholderChunk("property");
4159 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004160
4161 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004162 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4163 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4164 Builder.AddPlaceholderChunk("property");
4165 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004166 }
4167}
4168
Douglas Gregorbca403c2010-01-13 23:51:12 +00004169static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004170 ResultBuilder &Results,
4171 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004172 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004173
4174 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004175 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004176
4177 if (LangOpts.ObjC2) {
4178 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004179 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004180
4181 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004182 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004183
4184 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004185 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004186 }
4187}
4188
Douglas Gregorbca403c2010-01-13 23:51:12 +00004189static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004190 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004191 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004192
4193 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004194 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4195 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4196 Builder.AddPlaceholderChunk("name");
4197 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004198
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004199 if (Results.includeCodePatterns()) {
4200 // @interface name
4201 // FIXME: Could introduce the whole pattern, including superclasses and
4202 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004203 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4204 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4205 Builder.AddPlaceholderChunk("class");
4206 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004207
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004208 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004209 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4210 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4211 Builder.AddPlaceholderChunk("protocol");
4212 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004213
4214 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004215 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4216 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4217 Builder.AddPlaceholderChunk("class");
4218 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004219 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004220
4221 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004222 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4223 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4224 Builder.AddPlaceholderChunk("alias");
4225 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4226 Builder.AddPlaceholderChunk("class");
4227 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004228}
4229
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004230void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004231 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004232 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4233 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004234 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004235 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorbca403c2010-01-13 23:51:12 +00004236 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004237 else if (CurContext->isObjCContainer())
Douglas Gregorbca403c2010-01-13 23:51:12 +00004238 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004239 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004240 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004241 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004242 HandleCodeCompleteResults(this, CodeCompleter,
4243 CodeCompletionContext::CCC_Other,
4244 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004245}
4246
Douglas Gregorbca403c2010-01-13 23:51:12 +00004247static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004248 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004249 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004250
4251 // @encode ( type-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004252 const char *EncodeType = "char[]";
4253 if (Results.getSema().getLangOptions().CPlusPlus ||
4254 Results.getSema().getLangOptions().ConstStrings)
4255 EncodeType = " const char[]";
4256 Builder.AddResultTypeChunk(EncodeType);
Douglas Gregor218937c2011-02-01 19:23:04 +00004257 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4258 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4259 Builder.AddPlaceholderChunk("type-name");
4260 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4261 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004262
4263 // @protocol ( protocol-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004264 Builder.AddResultTypeChunk("Protocol *");
Douglas Gregor218937c2011-02-01 19:23:04 +00004265 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4266 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4267 Builder.AddPlaceholderChunk("protocol-name");
4268 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4269 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004270
4271 // @selector ( selector )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004272 Builder.AddResultTypeChunk("SEL");
Douglas Gregor218937c2011-02-01 19:23:04 +00004273 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4274 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4275 Builder.AddPlaceholderChunk("selector");
4276 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4277 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004278}
4279
Douglas Gregorbca403c2010-01-13 23:51:12 +00004280static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004281 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004282 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004283
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004284 if (Results.includeCodePatterns()) {
4285 // @try { statements } @catch ( declaration ) { statements } @finally
4286 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004287 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4288 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4289 Builder.AddPlaceholderChunk("statements");
4290 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4291 Builder.AddTextChunk("@catch");
4292 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4293 Builder.AddPlaceholderChunk("parameter");
4294 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4295 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4296 Builder.AddPlaceholderChunk("statements");
4297 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4298 Builder.AddTextChunk("@finally");
4299 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4300 Builder.AddPlaceholderChunk("statements");
4301 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4302 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004303 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004304
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004305 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004306 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4307 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4308 Builder.AddPlaceholderChunk("expression");
4309 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004310
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004311 if (Results.includeCodePatterns()) {
4312 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004313 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4314 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4315 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4316 Builder.AddPlaceholderChunk("expression");
4317 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4318 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4319 Builder.AddPlaceholderChunk("statements");
4320 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4321 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004322 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004323}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004324
Douglas Gregorbca403c2010-01-13 23:51:12 +00004325static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004326 ResultBuilder &Results,
4327 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004328 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004329 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4330 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4331 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004332 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004333 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004334}
4335
4336void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004337 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4338 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004339 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004340 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004341 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004342 HandleCodeCompleteResults(this, CodeCompleter,
4343 CodeCompletionContext::CCC_Other,
4344 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004345}
4346
4347void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004348 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4349 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004350 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004351 AddObjCStatementResults(Results, false);
4352 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004353 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004354 HandleCodeCompleteResults(this, CodeCompleter,
4355 CodeCompletionContext::CCC_Other,
4356 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004357}
4358
4359void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004360 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4361 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004362 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004363 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004364 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004365 HandleCodeCompleteResults(this, CodeCompleter,
4366 CodeCompletionContext::CCC_Other,
4367 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004368}
4369
Douglas Gregor988358f2009-11-19 00:14:45 +00004370/// \brief Determine whether the addition of the given flag to an Objective-C
4371/// property's attributes will cause a conflict.
4372static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4373 // Check if we've already added this flag.
4374 if (Attributes & NewFlag)
4375 return true;
4376
4377 Attributes |= NewFlag;
4378
4379 // Check for collisions with "readonly".
4380 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4381 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4382 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004383 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004384 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004385 ObjCDeclSpec::DQ_PR_retain |
4386 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004387 return true;
4388
John McCallf85e1932011-06-15 23:02:42 +00004389 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004390 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004391 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004392 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004393 ObjCDeclSpec::DQ_PR_retain|
4394 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004395 if (AssignCopyRetMask &&
4396 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004397 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004398 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004399 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4400 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004401 return true;
4402
4403 return false;
4404}
4405
Douglas Gregora93b1082009-11-18 23:08:07 +00004406void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004407 if (!CodeCompleter)
4408 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004409
Steve Naroffece8e712009-10-08 21:55:05 +00004410 unsigned Attributes = ODS.getPropertyAttributes();
4411
John McCall0a2c5e22010-08-25 06:19:51 +00004412 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004413 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4414 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004415 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004416 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004417 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004418 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004419 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004420 if (!ObjCPropertyFlagConflicts(Attributes,
4421 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4422 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004423 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004424 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004425 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004426 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004427 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4428 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004429 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004430 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004431 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004432 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004433 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4434 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004435 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004436 CodeCompletionBuilder Setter(Results.getAllocator());
4437 Setter.AddTypedTextChunk("setter");
4438 Setter.AddTextChunk(" = ");
4439 Setter.AddPlaceholderChunk("method");
4440 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004441 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004442 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004443 CodeCompletionBuilder Getter(Results.getAllocator());
4444 Getter.AddTypedTextChunk("getter");
4445 Getter.AddTextChunk(" = ");
4446 Getter.AddPlaceholderChunk("method");
4447 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004448 }
Steve Naroffece8e712009-10-08 21:55:05 +00004449 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004450 HandleCodeCompleteResults(this, CodeCompleter,
4451 CodeCompletionContext::CCC_Other,
4452 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004453}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004454
Douglas Gregor4ad96852009-11-19 07:41:15 +00004455/// \brief Descripts the kind of Objective-C method that we want to find
4456/// via code completion.
4457enum ObjCMethodKind {
4458 MK_Any, //< Any kind of method, provided it means other specified criteria.
4459 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4460 MK_OneArgSelector //< One-argument selector.
4461};
4462
Douglas Gregor458433d2010-08-26 15:07:07 +00004463static bool isAcceptableObjCSelector(Selector Sel,
4464 ObjCMethodKind WantKind,
4465 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004466 unsigned NumSelIdents,
4467 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004468 if (NumSelIdents > Sel.getNumArgs())
4469 return false;
4470
4471 switch (WantKind) {
4472 case MK_Any: break;
4473 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4474 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4475 }
4476
Douglas Gregorcf544262010-11-17 21:36:08 +00004477 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4478 return false;
4479
Douglas Gregor458433d2010-08-26 15:07:07 +00004480 for (unsigned I = 0; I != NumSelIdents; ++I)
4481 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4482 return false;
4483
4484 return true;
4485}
4486
Douglas Gregor4ad96852009-11-19 07:41:15 +00004487static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4488 ObjCMethodKind WantKind,
4489 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004490 unsigned NumSelIdents,
4491 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004492 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004493 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004494}
Douglas Gregord36adf52010-09-16 16:06:31 +00004495
4496namespace {
4497 /// \brief A set of selectors, which is used to avoid introducing multiple
4498 /// completions with the same selector into the result set.
4499 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4500}
4501
Douglas Gregor36ecb042009-11-17 23:22:23 +00004502/// \brief Add all of the Objective-C methods in the given Objective-C
4503/// container to the set of results.
4504///
4505/// The container will be a class, protocol, category, or implementation of
4506/// any of the above. This mether will recurse to include methods from
4507/// the superclasses of classes along with their categories, protocols, and
4508/// implementations.
4509///
4510/// \param Container the container in which we'll look to find methods.
4511///
4512/// \param WantInstance whether to add instance methods (only); if false, this
4513/// routine will add factory methods (only).
4514///
4515/// \param CurContext the context in which we're performing the lookup that
4516/// finds methods.
4517///
Douglas Gregorcf544262010-11-17 21:36:08 +00004518/// \param AllowSameLength Whether we allow a method to be added to the list
4519/// when it has the same number of parameters as we have selector identifiers.
4520///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004521/// \param Results the structure into which we'll add results.
4522static void AddObjCMethods(ObjCContainerDecl *Container,
4523 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004524 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004525 IdentifierInfo **SelIdents,
4526 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004527 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004528 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004529 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004530 ResultBuilder &Results,
4531 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004532 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004533 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4534 MEnd = Container->meth_end();
4535 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004536 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4537 // Check whether the selector identifiers we've been given are a
4538 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004539 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4540 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004541 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004542
Douglas Gregord36adf52010-09-16 16:06:31 +00004543 if (!Selectors.insert((*M)->getSelector()))
4544 continue;
4545
Douglas Gregord3c68542009-11-19 01:08:35 +00004546 Result R = Result(*M, 0);
4547 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004548 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004549 if (!InOriginalClass)
4550 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004551 Results.MaybeAddResult(R, CurContext);
4552 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004553 }
4554
Douglas Gregore396c7b2010-09-16 15:34:59 +00004555 // Visit the protocols of protocols.
4556 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4557 const ObjCList<ObjCProtocolDecl> &Protocols
4558 = Protocol->getReferencedProtocols();
4559 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4560 E = Protocols.end();
4561 I != E; ++I)
4562 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004563 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004564 }
4565
Douglas Gregor36ecb042009-11-17 23:22:23 +00004566 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4567 if (!IFace)
4568 return;
4569
4570 // Add methods in protocols.
4571 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4572 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4573 E = Protocols.end();
4574 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004575 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004576 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004577
4578 // Add methods in categories.
4579 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4580 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004581 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004582 NumSelIdents, CurContext, Selectors, AllowSameLength,
4583 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004584
4585 // Add a categories protocol methods.
4586 const ObjCList<ObjCProtocolDecl> &Protocols
4587 = CatDecl->getReferencedProtocols();
4588 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4589 E = Protocols.end();
4590 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004591 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004592 NumSelIdents, CurContext, Selectors, AllowSameLength,
4593 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004594
4595 // Add methods in category implementations.
4596 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004597 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004598 NumSelIdents, CurContext, Selectors, AllowSameLength,
4599 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004600 }
4601
4602 // Add methods in superclass.
4603 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004604 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004605 SelIdents, NumSelIdents, CurContext, Selectors,
4606 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004607
4608 // Add methods in our implementation, if any.
4609 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004610 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004611 NumSelIdents, CurContext, Selectors, AllowSameLength,
4612 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004613}
4614
4615
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004616void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004617 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004618
4619 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004620 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004621 if (!Class) {
4622 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004623 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004624 Class = Category->getClassInterface();
4625
4626 if (!Class)
4627 return;
4628 }
4629
4630 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004631 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4632 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004633 Results.EnterNewScope();
4634
Douglas Gregord36adf52010-09-16 16:06:31 +00004635 VisitedSelectorSet Selectors;
4636 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004637 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004638 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004639 HandleCodeCompleteResults(this, CodeCompleter,
4640 CodeCompletionContext::CCC_Other,
4641 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004642}
4643
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004644void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004645 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004646
4647 // Try to find the interface where setters might live.
4648 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004649 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004650 if (!Class) {
4651 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004652 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004653 Class = Category->getClassInterface();
4654
4655 if (!Class)
4656 return;
4657 }
4658
4659 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004660 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4661 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004662 Results.EnterNewScope();
4663
Douglas Gregord36adf52010-09-16 16:06:31 +00004664 VisitedSelectorSet Selectors;
4665 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004666 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004667
4668 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004669 HandleCodeCompleteResults(this, CodeCompleter,
4670 CodeCompletionContext::CCC_Other,
4671 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004672}
4673
Douglas Gregorafc45782011-02-15 22:19:42 +00004674void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4675 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004676 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004677 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4678 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004679 Results.EnterNewScope();
4680
4681 // Add context-sensitive, Objective-C parameter-passing keywords.
4682 bool AddedInOut = false;
4683 if ((DS.getObjCDeclQualifier() &
4684 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4685 Results.AddResult("in");
4686 Results.AddResult("inout");
4687 AddedInOut = true;
4688 }
4689 if ((DS.getObjCDeclQualifier() &
4690 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4691 Results.AddResult("out");
4692 if (!AddedInOut)
4693 Results.AddResult("inout");
4694 }
4695 if ((DS.getObjCDeclQualifier() &
4696 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4697 ObjCDeclSpec::DQ_Oneway)) == 0) {
4698 Results.AddResult("bycopy");
4699 Results.AddResult("byref");
4700 Results.AddResult("oneway");
4701 }
4702
Douglas Gregorafc45782011-02-15 22:19:42 +00004703 // If we're completing the return type of an Objective-C method and the
4704 // identifier IBAction refers to a macro, provide a completion item for
4705 // an action, e.g.,
4706 // IBAction)<#selector#>:(id)sender
4707 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4708 Context.Idents.get("IBAction").hasMacroDefinition()) {
4709 typedef CodeCompletionString::Chunk Chunk;
4710 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4711 CXAvailability_Available);
4712 Builder.AddTypedTextChunk("IBAction");
4713 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4714 Builder.AddPlaceholderChunk("selector");
4715 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4716 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4717 Builder.AddTextChunk("id");
4718 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4719 Builder.AddTextChunk("sender");
4720 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4721 }
4722
Douglas Gregord32b0222010-08-24 01:06:58 +00004723 // Add various builtin type names and specifiers.
4724 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4725 Results.ExitScope();
4726
4727 // Add the various type names
4728 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4729 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4730 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4731 CodeCompleter->includeGlobals());
4732
4733 if (CodeCompleter->includeMacros())
4734 AddMacroResults(PP, Results);
4735
4736 HandleCodeCompleteResults(this, CodeCompleter,
4737 CodeCompletionContext::CCC_Type,
4738 Results.data(), Results.size());
4739}
4740
Douglas Gregor22f56992010-04-06 19:22:33 +00004741/// \brief When we have an expression with type "id", we may assume
4742/// that it has some more-specific class type based on knowledge of
4743/// common uses of Objective-C. This routine returns that class type,
4744/// or NULL if no better result could be determined.
4745static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004746 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004747 if (!Msg)
4748 return 0;
4749
4750 Selector Sel = Msg->getSelector();
4751 if (Sel.isNull())
4752 return 0;
4753
4754 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4755 if (!Id)
4756 return 0;
4757
4758 ObjCMethodDecl *Method = Msg->getMethodDecl();
4759 if (!Method)
4760 return 0;
4761
4762 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004763 ObjCInterfaceDecl *IFace = 0;
4764 switch (Msg->getReceiverKind()) {
4765 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004766 if (const ObjCObjectType *ObjType
4767 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4768 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004769 break;
4770
4771 case ObjCMessageExpr::Instance: {
4772 QualType T = Msg->getInstanceReceiver()->getType();
4773 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4774 IFace = Ptr->getInterfaceDecl();
4775 break;
4776 }
4777
4778 case ObjCMessageExpr::SuperInstance:
4779 case ObjCMessageExpr::SuperClass:
4780 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004781 }
4782
4783 if (!IFace)
4784 return 0;
4785
4786 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4787 if (Method->isInstanceMethod())
4788 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4789 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004790 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004791 .Case("autorelease", IFace)
4792 .Case("copy", IFace)
4793 .Case("copyWithZone", IFace)
4794 .Case("mutableCopy", IFace)
4795 .Case("mutableCopyWithZone", IFace)
4796 .Case("awakeFromCoder", IFace)
4797 .Case("replacementObjectFromCoder", IFace)
4798 .Case("class", IFace)
4799 .Case("classForCoder", IFace)
4800 .Case("superclass", Super)
4801 .Default(0);
4802
4803 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4804 .Case("new", IFace)
4805 .Case("alloc", IFace)
4806 .Case("allocWithZone", IFace)
4807 .Case("class", IFace)
4808 .Case("superclass", Super)
4809 .Default(0);
4810}
4811
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004812// Add a special completion for a message send to "super", which fills in the
4813// most likely case of forwarding all of our arguments to the superclass
4814// function.
4815///
4816/// \param S The semantic analysis object.
4817///
4818/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4819/// the "super" keyword. Otherwise, we just need to provide the arguments.
4820///
4821/// \param SelIdents The identifiers in the selector that have already been
4822/// provided as arguments for a send to "super".
4823///
4824/// \param NumSelIdents The number of identifiers in \p SelIdents.
4825///
4826/// \param Results The set of results to augment.
4827///
4828/// \returns the Objective-C method declaration that would be invoked by
4829/// this "super" completion. If NULL, no completion was added.
4830static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4831 IdentifierInfo **SelIdents,
4832 unsigned NumSelIdents,
4833 ResultBuilder &Results) {
4834 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4835 if (!CurMethod)
4836 return 0;
4837
4838 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4839 if (!Class)
4840 return 0;
4841
4842 // Try to find a superclass method with the same selector.
4843 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004844 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4845 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004846 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4847 CurMethod->isInstanceMethod());
4848
Douglas Gregor78bcd912011-02-16 00:51:18 +00004849 // Check in categories or class extensions.
4850 if (!SuperMethod) {
4851 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4852 Category = Category->getNextClassCategory())
4853 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4854 CurMethod->isInstanceMethod())))
4855 break;
4856 }
4857 }
4858
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004859 if (!SuperMethod)
4860 return 0;
4861
4862 // Check whether the superclass method has the same signature.
4863 if (CurMethod->param_size() != SuperMethod->param_size() ||
4864 CurMethod->isVariadic() != SuperMethod->isVariadic())
4865 return 0;
4866
4867 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4868 CurPEnd = CurMethod->param_end(),
4869 SuperP = SuperMethod->param_begin();
4870 CurP != CurPEnd; ++CurP, ++SuperP) {
4871 // Make sure the parameter types are compatible.
4872 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4873 (*SuperP)->getType()))
4874 return 0;
4875
4876 // Make sure we have a parameter name to forward!
4877 if (!(*CurP)->getIdentifier())
4878 return 0;
4879 }
4880
4881 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004882 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004883
4884 // Give this completion a return type.
Douglas Gregor8987b232011-09-27 23:30:47 +00004885 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
4886 Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004887
4888 // If we need the "super" keyword, add it (plus some spacing).
4889 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004890 Builder.AddTypedTextChunk("super");
4891 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004892 }
4893
4894 Selector Sel = CurMethod->getSelector();
4895 if (Sel.isUnarySelector()) {
4896 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004897 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004898 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004899 else
Douglas Gregordae68752011-02-01 22:57:45 +00004900 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004901 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004902 } else {
4903 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4904 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4905 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004906 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004907
4908 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004909 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004910 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004911 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004912 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004913 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004914 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004915 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004916 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004917 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004918 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004919 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004920 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004921 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004922 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004923 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004924 }
4925 }
4926 }
4927
Douglas Gregor218937c2011-02-01 19:23:04 +00004928 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004929 SuperMethod->isInstanceMethod()
4930 ? CXCursor_ObjCInstanceMethodDecl
4931 : CXCursor_ObjCClassMethodDecl));
4932 return SuperMethod;
4933}
4934
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004935void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004936 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004937 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4938 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004939 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004940
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004941 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4942 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004943 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4944 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004945
4946 // If we are in an Objective-C method inside a class that has a superclass,
4947 // add "super" as an option.
4948 if (ObjCMethodDecl *Method = getCurMethodDecl())
4949 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004950 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004951 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004952
4953 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4954 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004955
4956 Results.ExitScope();
4957
4958 if (CodeCompleter->includeMacros())
4959 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004960 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004961 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004962
4963}
4964
Douglas Gregor2725ca82010-04-21 19:57:20 +00004965void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4966 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004967 unsigned NumSelIdents,
4968 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004969 ObjCInterfaceDecl *CDecl = 0;
4970 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4971 // Figure out which interface we're in.
4972 CDecl = CurMethod->getClassInterface();
4973 if (!CDecl)
4974 return;
4975
4976 // Find the superclass of this class.
4977 CDecl = CDecl->getSuperClass();
4978 if (!CDecl)
4979 return;
4980
4981 if (CurMethod->isInstanceMethod()) {
4982 // We are inside an instance method, which means that the message
4983 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004984 // current object.
4985 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004986 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004987 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004988 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004989 }
4990
4991 // Fall through to send to the superclass in CDecl.
4992 } else {
4993 // "super" may be the name of a type or variable. Figure out which
4994 // it is.
4995 IdentifierInfo *Super = &Context.Idents.get("super");
4996 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4997 LookupOrdinaryName);
4998 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4999 // "super" names an interface. Use it.
5000 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00005001 if (const ObjCObjectType *Iface
5002 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5003 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00005004 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5005 // "super" names an unresolved type; we can't be more specific.
5006 } else {
5007 // Assume that "super" names some kind of value and parse that way.
5008 CXXScopeSpec SS;
5009 UnqualifiedId id;
5010 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00005011 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005012 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005013 SelIdents, NumSelIdents,
5014 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005015 }
5016
5017 // Fall through
5018 }
5019
John McCallb3d87482010-08-24 05:47:05 +00005020 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00005021 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00005022 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00005023 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005024 NumSelIdents, AtArgumentExpression,
5025 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005026}
5027
Douglas Gregorb9d77572010-09-21 00:03:25 +00005028/// \brief Given a set of code-completion results for the argument of a message
5029/// send, determine the preferred type (if any) for that argument expression.
5030static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5031 unsigned NumSelIdents) {
5032 typedef CodeCompletionResult Result;
5033 ASTContext &Context = Results.getSema().Context;
5034
5035 QualType PreferredType;
5036 unsigned BestPriority = CCP_Unlikely * 2;
5037 Result *ResultsData = Results.data();
5038 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5039 Result &R = ResultsData[I];
5040 if (R.Kind == Result::RK_Declaration &&
5041 isa<ObjCMethodDecl>(R.Declaration)) {
5042 if (R.Priority <= BestPriority) {
5043 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5044 if (NumSelIdents <= Method->param_size()) {
5045 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5046 ->getType();
5047 if (R.Priority < BestPriority || PreferredType.isNull()) {
5048 BestPriority = R.Priority;
5049 PreferredType = MyPreferredType;
5050 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5051 MyPreferredType)) {
5052 PreferredType = QualType();
5053 }
5054 }
5055 }
5056 }
5057 }
5058
5059 return PreferredType;
5060}
5061
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005062static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5063 ParsedType Receiver,
5064 IdentifierInfo **SelIdents,
5065 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005066 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005067 bool IsSuper,
5068 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005069 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00005070 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005071
Douglas Gregor24a069f2009-11-17 17:59:40 +00005072 // If the given name refers to an interface type, retrieve the
5073 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00005074 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005075 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005076 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00005077 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5078 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00005079 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005080
Douglas Gregor36ecb042009-11-17 23:22:23 +00005081 // Add all of the factory methods in this Objective-C class, its protocols,
5082 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00005083 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005084
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005085 // If this is a send-to-super, try to add the special "super" send
5086 // completion.
5087 if (IsSuper) {
5088 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005089 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5090 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005091 Results.Ignore(SuperMethod);
5092 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005093
Douglas Gregor265f7492010-08-27 15:29:55 +00005094 // If we're inside an Objective-C method definition, prefer its selector to
5095 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005096 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005097 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005098
Douglas Gregord36adf52010-09-16 16:06:31 +00005099 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005100 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005101 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005102 SemaRef.CurContext, Selectors, AtArgumentExpression,
5103 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005104 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005105 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005106
Douglas Gregor719770d2010-04-06 17:30:22 +00005107 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005108 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005109 if (SemaRef.ExternalSource) {
5110 for (uint32_t I = 0,
5111 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005112 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005113 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5114 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005115 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005116
5117 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005118 }
5119 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005120
5121 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5122 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005123 M != MEnd; ++M) {
5124 for (ObjCMethodList *MethList = &M->second.second;
5125 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005126 MethList = MethList->Next) {
5127 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5128 NumSelIdents))
5129 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005130
Douglas Gregor13438f92010-04-06 16:40:00 +00005131 Result R(MethList->Method, 0);
5132 R.StartParameter = NumSelIdents;
5133 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005134 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005135 }
5136 }
5137 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005138
5139 Results.ExitScope();
5140}
Douglas Gregor13438f92010-04-06 16:40:00 +00005141
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005142void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5143 IdentifierInfo **SelIdents,
5144 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005145 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005146 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005147
5148 QualType T = this->GetTypeFromParser(Receiver);
5149
Douglas Gregor218937c2011-02-01 19:23:04 +00005150 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005151 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005152 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005153
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005154 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5155 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005156
5157 // If we're actually at the argument expression (rather than prior to the
5158 // selector), we're actually performing code completion for an expression.
5159 // Determine whether we have a single, best method. If so, we can
5160 // code-complete the expression using the corresponding parameter type as
5161 // our preferred type, improving completion results.
5162 if (AtArgumentExpression) {
5163 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005164 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005165 if (PreferredType.isNull())
5166 CodeCompleteOrdinaryName(S, PCC_Expression);
5167 else
5168 CodeCompleteExpression(S, PreferredType);
5169 return;
5170 }
5171
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005172 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005173 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005174 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005175}
5176
Richard Trieuf81e5a92011-09-09 02:00:50 +00005177void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005178 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005179 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005180 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005181 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005182 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005183
5184 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005185
Douglas Gregor36ecb042009-11-17 23:22:23 +00005186 // If necessary, apply function/array conversion to the receiver.
5187 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005188 if (RecExpr) {
5189 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5190 if (Conv.isInvalid()) // conversion failed. bail.
5191 return;
5192 RecExpr = Conv.take();
5193 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005194 QualType ReceiverType = RecExpr? RecExpr->getType()
5195 : Super? Context.getObjCObjectPointerType(
5196 Context.getObjCInterfaceType(Super))
5197 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005198
Douglas Gregorda892642010-11-08 21:12:30 +00005199 // If we're messaging an expression with type "id" or "Class", check
5200 // whether we know something special about the receiver that allows
5201 // us to assume a more-specific receiver type.
5202 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5203 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5204 if (ReceiverType->isObjCClassType())
5205 return CodeCompleteObjCClassMessage(S,
5206 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5207 SelIdents, NumSelIdents,
5208 AtArgumentExpression, Super);
5209
5210 ReceiverType = Context.getObjCObjectPointerType(
5211 Context.getObjCInterfaceType(IFace));
5212 }
5213
Douglas Gregor36ecb042009-11-17 23:22:23 +00005214 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005215 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005216 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005217 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005218
Douglas Gregor36ecb042009-11-17 23:22:23 +00005219 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005220
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005221 // If this is a send-to-super, try to add the special "super" send
5222 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005223 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005224 if (ObjCMethodDecl *SuperMethod
5225 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5226 Results))
5227 Results.Ignore(SuperMethod);
5228 }
5229
Douglas Gregor265f7492010-08-27 15:29:55 +00005230 // If we're inside an Objective-C method definition, prefer its selector to
5231 // others.
5232 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5233 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005234
Douglas Gregord36adf52010-09-16 16:06:31 +00005235 // Keep track of the selectors we've already added.
5236 VisitedSelectorSet Selectors;
5237
Douglas Gregorf74a4192009-11-18 00:06:18 +00005238 // Handle messages to Class. This really isn't a message to an instance
5239 // method, so we treat it the same way we would treat a message send to a
5240 // class method.
5241 if (ReceiverType->isObjCClassType() ||
5242 ReceiverType->isObjCQualifiedClassType()) {
5243 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5244 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005245 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005246 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005247 }
5248 }
5249 // Handle messages to a qualified ID ("id<foo>").
5250 else if (const ObjCObjectPointerType *QualID
5251 = ReceiverType->getAsObjCQualifiedIdType()) {
5252 // Search protocols for instance methods.
5253 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5254 E = QualID->qual_end();
5255 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005256 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005257 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005258 }
5259 // Handle messages to a pointer to interface type.
5260 else if (const ObjCObjectPointerType *IFacePtr
5261 = ReceiverType->getAsObjCInterfacePointerType()) {
5262 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005263 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005264 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5265 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005266
5267 // Search protocols for instance methods.
5268 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5269 E = IFacePtr->qual_end();
5270 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005271 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005272 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005273 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005274 // Handle messages to "id".
5275 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005276 // We're messaging "id", so provide all instance methods we know
5277 // about as code-completion results.
5278
5279 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005280 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005281 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005282 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5283 I != N; ++I) {
5284 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005285 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005286 continue;
5287
Sebastian Redldb9d2142010-08-02 23:18:59 +00005288 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005289 }
5290 }
5291
Sebastian Redldb9d2142010-08-02 23:18:59 +00005292 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5293 MEnd = MethodPool.end();
5294 M != MEnd; ++M) {
5295 for (ObjCMethodList *MethList = &M->second.first;
5296 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005297 MethList = MethList->Next) {
5298 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5299 NumSelIdents))
5300 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005301
5302 if (!Selectors.insert(MethList->Method->getSelector()))
5303 continue;
5304
Douglas Gregor13438f92010-04-06 16:40:00 +00005305 Result R(MethList->Method, 0);
5306 R.StartParameter = NumSelIdents;
5307 R.AllParametersAreInformative = false;
5308 Results.MaybeAddResult(R, CurContext);
5309 }
5310 }
5311 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005312 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005313
5314
5315 // If we're actually at the argument expression (rather than prior to the
5316 // selector), we're actually performing code completion for an expression.
5317 // Determine whether we have a single, best method. If so, we can
5318 // code-complete the expression using the corresponding parameter type as
5319 // our preferred type, improving completion results.
5320 if (AtArgumentExpression) {
5321 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5322 NumSelIdents);
5323 if (PreferredType.isNull())
5324 CodeCompleteOrdinaryName(S, PCC_Expression);
5325 else
5326 CodeCompleteExpression(S, PreferredType);
5327 return;
5328 }
5329
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005330 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005331 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005332 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005333}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005334
Douglas Gregorfb629412010-08-23 21:17:50 +00005335void Sema::CodeCompleteObjCForCollection(Scope *S,
5336 DeclGroupPtrTy IterationVar) {
5337 CodeCompleteExpressionData Data;
5338 Data.ObjCCollection = true;
5339
5340 if (IterationVar.getAsOpaquePtr()) {
5341 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5342 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5343 if (*I)
5344 Data.IgnoreDecls.push_back(*I);
5345 }
5346 }
5347
5348 CodeCompleteExpression(S, Data);
5349}
5350
Douglas Gregor458433d2010-08-26 15:07:07 +00005351void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5352 unsigned NumSelIdents) {
5353 // If we have an external source, load the entire class method
5354 // pool from the AST file.
5355 if (ExternalSource) {
5356 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5357 I != N; ++I) {
5358 Selector Sel = ExternalSource->GetExternalSelector(I);
5359 if (Sel.isNull() || MethodPool.count(Sel))
5360 continue;
5361
5362 ReadMethodPool(Sel);
5363 }
5364 }
5365
Douglas Gregor218937c2011-02-01 19:23:04 +00005366 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5367 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005368 Results.EnterNewScope();
5369 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5370 MEnd = MethodPool.end();
5371 M != MEnd; ++M) {
5372
5373 Selector Sel = M->first;
5374 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5375 continue;
5376
Douglas Gregor218937c2011-02-01 19:23:04 +00005377 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005378 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005379 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005380 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005381 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005382 continue;
5383 }
5384
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005385 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005386 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005387 if (I == NumSelIdents) {
5388 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005389 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005390 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005391 Accumulator.clear();
5392 }
5393 }
5394
Benjamin Kramera0651c52011-07-26 16:59:25 +00005395 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005396 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005397 }
Douglas Gregordae68752011-02-01 22:57:45 +00005398 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005399 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005400 }
5401 Results.ExitScope();
5402
5403 HandleCodeCompleteResults(this, CodeCompleter,
5404 CodeCompletionContext::CCC_SelectorName,
5405 Results.data(), Results.size());
5406}
5407
Douglas Gregor55385fe2009-11-18 04:19:12 +00005408/// \brief Add all of the protocol declarations that we find in the given
5409/// (translation unit) context.
5410static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005411 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005412 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005413 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005414
5415 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5416 DEnd = Ctx->decls_end();
5417 D != DEnd; ++D) {
5418 // Record any protocols we find.
5419 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005420 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005421 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005422
5423 // Record any forward-declared protocols we find.
5424 if (ObjCForwardProtocolDecl *Forward
5425 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5426 for (ObjCForwardProtocolDecl::protocol_iterator
5427 P = Forward->protocol_begin(),
5428 PEnd = Forward->protocol_end();
5429 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005430 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005431 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005432 }
5433 }
5434}
5435
5436void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5437 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005438 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5439 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005440
Douglas Gregor70c23352010-12-09 21:44:02 +00005441 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5442 Results.EnterNewScope();
5443
5444 // Tell the result set to ignore all of the protocols we have
5445 // already seen.
5446 // FIXME: This doesn't work when caching code-completion results.
5447 for (unsigned I = 0; I != NumProtocols; ++I)
5448 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5449 Protocols[I].second))
5450 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005451
Douglas Gregor70c23352010-12-09 21:44:02 +00005452 // Add all protocols.
5453 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5454 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005455
Douglas Gregor70c23352010-12-09 21:44:02 +00005456 Results.ExitScope();
5457 }
5458
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005459 HandleCodeCompleteResults(this, CodeCompleter,
5460 CodeCompletionContext::CCC_ObjCProtocolName,
5461 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005462}
5463
5464void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005465 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5466 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005467
Douglas Gregor70c23352010-12-09 21:44:02 +00005468 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5469 Results.EnterNewScope();
5470
5471 // Add all protocols.
5472 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5473 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005474
Douglas Gregor70c23352010-12-09 21:44:02 +00005475 Results.ExitScope();
5476 }
5477
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005478 HandleCodeCompleteResults(this, CodeCompleter,
5479 CodeCompletionContext::CCC_ObjCProtocolName,
5480 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005481}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005482
5483/// \brief Add all of the Objective-C interface declarations that we find in
5484/// the given (translation unit) context.
5485static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5486 bool OnlyForwardDeclarations,
5487 bool OnlyUnimplemented,
5488 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005489 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005490
5491 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5492 DEnd = Ctx->decls_end();
5493 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005494 // Record any interfaces we find.
5495 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5496 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5497 (!OnlyUnimplemented || !Class->getImplementation()))
5498 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005499
5500 // Record any forward-declared interfaces we find.
5501 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005502 ObjCInterfaceDecl *IDecl = Forward->getForwardInterfaceDecl();
5503 if ((!OnlyForwardDeclarations || IDecl->isForwardDecl()) &&
5504 (!OnlyUnimplemented || !IDecl->getImplementation()))
5505 Results.AddResult(Result(IDecl, 0), CurContext,
5506 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005507 }
5508 }
5509}
5510
5511void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005512 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5513 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005514 Results.EnterNewScope();
5515
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005516 if (CodeCompleter->includeGlobals()) {
5517 // Add all classes.
5518 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5519 false, Results);
5520 }
5521
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005522 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005523
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005524 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005525 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005526 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005527}
5528
Douglas Gregorc83c6872010-04-15 22:33:43 +00005529void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5530 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005531 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005532 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005533 Results.EnterNewScope();
5534
5535 // Make sure that we ignore the class we're currently defining.
5536 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005537 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005538 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005539 Results.Ignore(CurClass);
5540
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005541 if (CodeCompleter->includeGlobals()) {
5542 // Add all classes.
5543 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5544 false, Results);
5545 }
5546
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005547 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005548
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005549 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005550 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005551 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005552}
5553
5554void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005555 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5556 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005557 Results.EnterNewScope();
5558
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005559 if (CodeCompleter->includeGlobals()) {
5560 // Add all unimplemented classes.
5561 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5562 true, Results);
5563 }
5564
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005565 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005566
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005567 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005568 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005569 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005570}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005571
5572void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005573 IdentifierInfo *ClassName,
5574 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005575 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005576
Douglas Gregor218937c2011-02-01 19:23:04 +00005577 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005578 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005579
5580 // Ignore any categories we find that have already been implemented by this
5581 // interface.
5582 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5583 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005584 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005585 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5586 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5587 Category = Category->getNextClassCategory())
5588 CategoryNames.insert(Category->getIdentifier());
5589
5590 // Add all of the categories we know about.
5591 Results.EnterNewScope();
5592 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5593 for (DeclContext::decl_iterator D = TU->decls_begin(),
5594 DEnd = TU->decls_end();
5595 D != DEnd; ++D)
5596 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5597 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005598 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005599 Results.ExitScope();
5600
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005601 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005602 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005603 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005604}
5605
5606void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005607 IdentifierInfo *ClassName,
5608 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005609 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005610
5611 // Find the corresponding interface. If we couldn't find the interface, the
5612 // program itself is ill-formed. However, we'll try to be helpful still by
5613 // providing the list of all of the categories we know about.
5614 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005615 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005616 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5617 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005618 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005619
Douglas Gregor218937c2011-02-01 19:23:04 +00005620 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005621 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005622
5623 // Add all of the categories that have have corresponding interface
5624 // declarations in this class and any of its superclasses, except for
5625 // already-implemented categories in the class itself.
5626 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5627 Results.EnterNewScope();
5628 bool IgnoreImplemented = true;
5629 while (Class) {
5630 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5631 Category = Category->getNextClassCategory())
5632 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5633 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005634 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005635
5636 Class = Class->getSuperClass();
5637 IgnoreImplemented = false;
5638 }
5639 Results.ExitScope();
5640
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005641 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005642 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005643 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005644}
Douglas Gregor322328b2009-11-18 22:32:06 +00005645
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005646void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005647 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005648 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5649 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005650
5651 // Figure out where this @synthesize lives.
5652 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005653 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005654 if (!Container ||
5655 (!isa<ObjCImplementationDecl>(Container) &&
5656 !isa<ObjCCategoryImplDecl>(Container)))
5657 return;
5658
5659 // Ignore any properties that have already been implemented.
5660 for (DeclContext::decl_iterator D = Container->decls_begin(),
5661 DEnd = Container->decls_end();
5662 D != DEnd; ++D)
5663 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5664 Results.Ignore(PropertyImpl->getPropertyDecl());
5665
5666 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005667 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005668 Results.EnterNewScope();
5669 if (ObjCImplementationDecl *ClassImpl
5670 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005671 AddObjCProperties(ClassImpl->getClassInterface(), false,
5672 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005673 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005674 else
5675 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005676 false, /*AllowNullaryMethods=*/false, CurContext,
5677 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005678 Results.ExitScope();
5679
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005680 HandleCodeCompleteResults(this, CodeCompleter,
5681 CodeCompletionContext::CCC_Other,
5682 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005683}
5684
5685void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005686 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005687 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005688 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5689 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005690
5691 // Figure out where this @synthesize lives.
5692 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005693 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005694 if (!Container ||
5695 (!isa<ObjCImplementationDecl>(Container) &&
5696 !isa<ObjCCategoryImplDecl>(Container)))
5697 return;
5698
5699 // Figure out which interface we're looking into.
5700 ObjCInterfaceDecl *Class = 0;
5701 if (ObjCImplementationDecl *ClassImpl
5702 = dyn_cast<ObjCImplementationDecl>(Container))
5703 Class = ClassImpl->getClassInterface();
5704 else
5705 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5706 ->getClassInterface();
5707
Douglas Gregore8426052011-04-18 14:40:46 +00005708 // Determine the type of the property we're synthesizing.
5709 QualType PropertyType = Context.getObjCIdType();
5710 if (Class) {
5711 if (ObjCPropertyDecl *Property
5712 = Class->FindPropertyDeclaration(PropertyName)) {
5713 PropertyType
5714 = Property->getType().getNonReferenceType().getUnqualifiedType();
5715
5716 // Give preference to ivars
5717 Results.setPreferredType(PropertyType);
5718 }
5719 }
5720
Douglas Gregor322328b2009-11-18 22:32:06 +00005721 // Add all of the instance variables in this class and its superclasses.
5722 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005723 bool SawSimilarlyNamedIvar = false;
5724 std::string NameWithPrefix;
5725 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005726 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005727 std::string NameWithSuffix = PropertyName->getName().str();
5728 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005729 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005730 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5731 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005732 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5733
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005734 // Determine whether we've seen an ivar with a name similar to the
5735 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005736 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005737 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005738 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005739 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005740
5741 // Reduce the priority of this result by one, to give it a slight
5742 // advantage over other results whose names don't match so closely.
5743 if (Results.size() &&
5744 Results.data()[Results.size() - 1].Kind
5745 == CodeCompletionResult::RK_Declaration &&
5746 Results.data()[Results.size() - 1].Declaration == Ivar)
5747 Results.data()[Results.size() - 1].Priority--;
5748 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005749 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005750 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005751
5752 if (!SawSimilarlyNamedIvar) {
5753 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005754 // an ivar of the appropriate type.
5755 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005756 typedef CodeCompletionResult Result;
5757 CodeCompletionAllocator &Allocator = Results.getAllocator();
5758 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5759
Douglas Gregor8987b232011-09-27 23:30:47 +00005760 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8426052011-04-18 14:40:46 +00005761 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005762 Policy, Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005763 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5764 Results.AddResult(Result(Builder.TakeString(), Priority,
5765 CXCursor_ObjCIvarDecl));
5766 }
5767
Douglas Gregor322328b2009-11-18 22:32:06 +00005768 Results.ExitScope();
5769
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005770 HandleCodeCompleteResults(this, CodeCompleter,
5771 CodeCompletionContext::CCC_Other,
5772 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005773}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005774
Douglas Gregor408be5a2010-08-25 01:08:01 +00005775// Mapping from selectors to the methods that implement that selector, along
5776// with the "in original class" flag.
5777typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5778 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005779
5780/// \brief Find all of the methods that reside in the given container
5781/// (and its superclasses, protocols, etc.) that meet the given
5782/// criteria. Insert those methods into the map of known methods,
5783/// indexed by selector so they can be easily found.
5784static void FindImplementableMethods(ASTContext &Context,
5785 ObjCContainerDecl *Container,
5786 bool WantInstanceMethods,
5787 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005788 KnownMethodsMap &KnownMethods,
5789 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005790 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5791 // Recurse into protocols.
5792 const ObjCList<ObjCProtocolDecl> &Protocols
5793 = IFace->getReferencedProtocols();
5794 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005795 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005796 I != E; ++I)
5797 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005798 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005799
Douglas Gregorea766182010-10-18 18:21:28 +00005800 // Add methods from any class extensions and categories.
5801 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5802 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005803 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5804 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005805 KnownMethods, false);
5806
5807 // Visit the superclass.
5808 if (IFace->getSuperClass())
5809 FindImplementableMethods(Context, IFace->getSuperClass(),
5810 WantInstanceMethods, ReturnType,
5811 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005812 }
5813
5814 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5815 // Recurse into protocols.
5816 const ObjCList<ObjCProtocolDecl> &Protocols
5817 = Category->getReferencedProtocols();
5818 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005819 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005820 I != E; ++I)
5821 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005822 KnownMethods, InOriginalClass);
5823
5824 // If this category is the original class, jump to the interface.
5825 if (InOriginalClass && Category->getClassInterface())
5826 FindImplementableMethods(Context, Category->getClassInterface(),
5827 WantInstanceMethods, ReturnType, KnownMethods,
5828 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005829 }
5830
5831 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5832 // Recurse into protocols.
5833 const ObjCList<ObjCProtocolDecl> &Protocols
5834 = Protocol->getReferencedProtocols();
5835 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5836 E = Protocols.end();
5837 I != E; ++I)
5838 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005839 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005840 }
5841
5842 // Add methods in this container. This operation occurs last because
5843 // we want the methods from this container to override any methods
5844 // we've previously seen with the same selector.
5845 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5846 MEnd = Container->meth_end();
5847 M != MEnd; ++M) {
5848 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5849 if (!ReturnType.isNull() &&
5850 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5851 continue;
5852
Douglas Gregor408be5a2010-08-25 01:08:01 +00005853 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005854 }
5855 }
5856}
5857
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005858/// \brief Add the parenthesized return or parameter type chunk to a code
5859/// completion string.
5860static void AddObjCPassingTypeChunk(QualType Type,
5861 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005862 const PrintingPolicy &Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005863 CodeCompletionBuilder &Builder) {
5864 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor8987b232011-09-27 23:30:47 +00005865 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005866 Builder.getAllocator()));
5867 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5868}
5869
5870/// \brief Determine whether the given class is or inherits from a class by
5871/// the given name.
5872static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005873 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005874 if (!Class)
5875 return false;
5876
5877 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5878 return true;
5879
5880 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5881}
5882
5883/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5884/// Key-Value Observing (KVO).
5885static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5886 bool IsInstanceMethod,
5887 QualType ReturnType,
5888 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005889 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005890 ResultBuilder &Results) {
5891 IdentifierInfo *PropName = Property->getIdentifier();
5892 if (!PropName || PropName->getLength() == 0)
5893 return;
5894
Douglas Gregor8987b232011-09-27 23:30:47 +00005895 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5896
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005897 // Builder that will create each code completion.
5898 typedef CodeCompletionResult Result;
5899 CodeCompletionAllocator &Allocator = Results.getAllocator();
5900 CodeCompletionBuilder Builder(Allocator);
5901
5902 // The selector table.
5903 SelectorTable &Selectors = Context.Selectors;
5904
5905 // The property name, copied into the code completion allocation region
5906 // on demand.
5907 struct KeyHolder {
5908 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005909 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005910 const char *CopiedKey;
5911
Chris Lattner5f9e2722011-07-23 10:55:15 +00005912 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005913 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5914
5915 operator const char *() {
5916 if (CopiedKey)
5917 return CopiedKey;
5918
5919 return CopiedKey = Allocator.CopyString(Key);
5920 }
5921 } Key(Allocator, PropName->getName());
5922
5923 // The uppercased name of the property name.
5924 std::string UpperKey = PropName->getName();
5925 if (!UpperKey.empty())
5926 UpperKey[0] = toupper(UpperKey[0]);
5927
5928 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5929 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5930 Property->getType());
5931 bool ReturnTypeMatchesVoid
5932 = ReturnType.isNull() || ReturnType->isVoidType();
5933
5934 // Add the normal accessor -(type)key.
5935 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005936 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005937 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5938 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00005939 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005940
5941 Builder.AddTypedTextChunk(Key);
5942 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5943 CXCursor_ObjCInstanceMethodDecl));
5944 }
5945
5946 // If we have an integral or boolean property (or the user has provided
5947 // an integral or boolean return type), add the accessor -(type)isKey.
5948 if (IsInstanceMethod &&
5949 ((!ReturnType.isNull() &&
5950 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5951 (ReturnType.isNull() &&
5952 (Property->getType()->isIntegerType() ||
5953 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005954 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005955 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005956 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005957 if (ReturnType.isNull()) {
5958 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5959 Builder.AddTextChunk("BOOL");
5960 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5961 }
5962
5963 Builder.AddTypedTextChunk(
5964 Allocator.CopyString(SelectorId->getName()));
5965 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5966 CXCursor_ObjCInstanceMethodDecl));
5967 }
5968 }
5969
5970 // Add the normal mutator.
5971 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5972 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005973 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005974 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005975 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005976 if (ReturnType.isNull()) {
5977 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5978 Builder.AddTextChunk("void");
5979 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5980 }
5981
5982 Builder.AddTypedTextChunk(
5983 Allocator.CopyString(SelectorId->getName()));
5984 Builder.AddTypedTextChunk(":");
Douglas Gregor8987b232011-09-27 23:30:47 +00005985 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005986 Builder.AddTextChunk(Key);
5987 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5988 CXCursor_ObjCInstanceMethodDecl));
5989 }
5990 }
5991
5992 // Indexed and unordered accessors
5993 unsigned IndexedGetterPriority = CCP_CodePattern;
5994 unsigned IndexedSetterPriority = CCP_CodePattern;
5995 unsigned UnorderedGetterPriority = CCP_CodePattern;
5996 unsigned UnorderedSetterPriority = CCP_CodePattern;
5997 if (const ObjCObjectPointerType *ObjCPointer
5998 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5999 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6000 // If this interface type is not provably derived from a known
6001 // collection, penalize the corresponding completions.
6002 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6003 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6004 if (!InheritsFromClassNamed(IFace, "NSArray"))
6005 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6006 }
6007
6008 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6009 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6010 if (!InheritsFromClassNamed(IFace, "NSSet"))
6011 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6012 }
6013 }
6014 } else {
6015 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6016 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6017 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6018 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6019 }
6020
6021 // Add -(NSUInteger)countOf<key>
6022 if (IsInstanceMethod &&
6023 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006024 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006025 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006026 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006027 if (ReturnType.isNull()) {
6028 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6029 Builder.AddTextChunk("NSUInteger");
6030 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6031 }
6032
6033 Builder.AddTypedTextChunk(
6034 Allocator.CopyString(SelectorId->getName()));
6035 Results.AddResult(Result(Builder.TakeString(),
6036 std::min(IndexedGetterPriority,
6037 UnorderedGetterPriority),
6038 CXCursor_ObjCInstanceMethodDecl));
6039 }
6040 }
6041
6042 // Indexed getters
6043 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6044 if (IsInstanceMethod &&
6045 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00006046 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006047 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006048 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006049 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006050 if (ReturnType.isNull()) {
6051 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6052 Builder.AddTextChunk("id");
6053 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6054 }
6055
6056 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6057 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6058 Builder.AddTextChunk("NSUInteger");
6059 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6060 Builder.AddTextChunk("index");
6061 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6062 CXCursor_ObjCInstanceMethodDecl));
6063 }
6064 }
6065
6066 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6067 if (IsInstanceMethod &&
6068 (ReturnType.isNull() ||
6069 (ReturnType->isObjCObjectPointerType() &&
6070 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6071 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6072 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006073 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006074 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006075 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006076 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006077 if (ReturnType.isNull()) {
6078 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6079 Builder.AddTextChunk("NSArray *");
6080 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6081 }
6082
6083 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6084 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6085 Builder.AddTextChunk("NSIndexSet *");
6086 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6087 Builder.AddTextChunk("indexes");
6088 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6089 CXCursor_ObjCInstanceMethodDecl));
6090 }
6091 }
6092
6093 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6094 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006095 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006096 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006097 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006098 &Context.Idents.get("range")
6099 };
6100
Douglas Gregore74c25c2011-05-04 23:50:46 +00006101 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006102 if (ReturnType.isNull()) {
6103 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6104 Builder.AddTextChunk("void");
6105 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6106 }
6107
6108 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6109 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6110 Builder.AddPlaceholderChunk("object-type");
6111 Builder.AddTextChunk(" **");
6112 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6113 Builder.AddTextChunk("buffer");
6114 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6115 Builder.AddTypedTextChunk("range:");
6116 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6117 Builder.AddTextChunk("NSRange");
6118 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6119 Builder.AddTextChunk("inRange");
6120 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6121 CXCursor_ObjCInstanceMethodDecl));
6122 }
6123 }
6124
6125 // Mutable indexed accessors
6126
6127 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6128 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006129 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006130 IdentifierInfo *SelectorIds[2] = {
6131 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006132 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006133 };
6134
Douglas Gregore74c25c2011-05-04 23:50:46 +00006135 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006136 if (ReturnType.isNull()) {
6137 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6138 Builder.AddTextChunk("void");
6139 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6140 }
6141
6142 Builder.AddTypedTextChunk("insertObject:");
6143 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6144 Builder.AddPlaceholderChunk("object-type");
6145 Builder.AddTextChunk(" *");
6146 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6147 Builder.AddTextChunk("object");
6148 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6149 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6150 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6151 Builder.AddPlaceholderChunk("NSUInteger");
6152 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6153 Builder.AddTextChunk("index");
6154 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6155 CXCursor_ObjCInstanceMethodDecl));
6156 }
6157 }
6158
6159 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6160 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006161 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006162 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006163 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006164 &Context.Idents.get("atIndexes")
6165 };
6166
Douglas Gregore74c25c2011-05-04 23:50:46 +00006167 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006168 if (ReturnType.isNull()) {
6169 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6170 Builder.AddTextChunk("void");
6171 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6172 }
6173
6174 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6175 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6176 Builder.AddTextChunk("NSArray *");
6177 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6178 Builder.AddTextChunk("array");
6179 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6180 Builder.AddTypedTextChunk("atIndexes:");
6181 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6182 Builder.AddPlaceholderChunk("NSIndexSet *");
6183 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6184 Builder.AddTextChunk("indexes");
6185 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6186 CXCursor_ObjCInstanceMethodDecl));
6187 }
6188 }
6189
6190 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6191 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006192 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006193 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006194 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006195 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006196 if (ReturnType.isNull()) {
6197 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6198 Builder.AddTextChunk("void");
6199 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6200 }
6201
6202 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6203 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6204 Builder.AddTextChunk("NSUInteger");
6205 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6206 Builder.AddTextChunk("index");
6207 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6208 CXCursor_ObjCInstanceMethodDecl));
6209 }
6210 }
6211
6212 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6213 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006214 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006215 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006216 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006217 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006218 if (ReturnType.isNull()) {
6219 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6220 Builder.AddTextChunk("void");
6221 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6222 }
6223
6224 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6225 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6226 Builder.AddTextChunk("NSIndexSet *");
6227 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6228 Builder.AddTextChunk("indexes");
6229 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6230 CXCursor_ObjCInstanceMethodDecl));
6231 }
6232 }
6233
6234 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6235 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006236 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006237 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006238 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006239 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006240 &Context.Idents.get("withObject")
6241 };
6242
Douglas Gregore74c25c2011-05-04 23:50:46 +00006243 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006244 if (ReturnType.isNull()) {
6245 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6246 Builder.AddTextChunk("void");
6247 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6248 }
6249
6250 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6251 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6252 Builder.AddPlaceholderChunk("NSUInteger");
6253 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6254 Builder.AddTextChunk("index");
6255 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6256 Builder.AddTypedTextChunk("withObject:");
6257 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6258 Builder.AddTextChunk("id");
6259 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6260 Builder.AddTextChunk("object");
6261 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6262 CXCursor_ObjCInstanceMethodDecl));
6263 }
6264 }
6265
6266 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6267 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006268 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006269 = (Twine("replace") + UpperKey + "AtIndexes").str();
6270 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006271 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006272 &Context.Idents.get(SelectorName1),
6273 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006274 };
6275
Douglas Gregore74c25c2011-05-04 23:50:46 +00006276 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006277 if (ReturnType.isNull()) {
6278 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6279 Builder.AddTextChunk("void");
6280 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6281 }
6282
6283 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6284 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6285 Builder.AddPlaceholderChunk("NSIndexSet *");
6286 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6287 Builder.AddTextChunk("indexes");
6288 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6289 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6290 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6291 Builder.AddTextChunk("NSArray *");
6292 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6293 Builder.AddTextChunk("array");
6294 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6295 CXCursor_ObjCInstanceMethodDecl));
6296 }
6297 }
6298
6299 // Unordered getters
6300 // - (NSEnumerator *)enumeratorOfKey
6301 if (IsInstanceMethod &&
6302 (ReturnType.isNull() ||
6303 (ReturnType->isObjCObjectPointerType() &&
6304 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6305 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6306 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006307 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006308 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006309 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006310 if (ReturnType.isNull()) {
6311 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6312 Builder.AddTextChunk("NSEnumerator *");
6313 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6314 }
6315
6316 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6317 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6318 CXCursor_ObjCInstanceMethodDecl));
6319 }
6320 }
6321
6322 // - (type *)memberOfKey:(type *)object
6323 if (IsInstanceMethod &&
6324 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006325 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006326 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006327 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006328 if (ReturnType.isNull()) {
6329 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6330 Builder.AddPlaceholderChunk("object-type");
6331 Builder.AddTextChunk(" *");
6332 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6333 }
6334
6335 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6336 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6337 if (ReturnType.isNull()) {
6338 Builder.AddPlaceholderChunk("object-type");
6339 Builder.AddTextChunk(" *");
6340 } else {
6341 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006342 Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006343 Builder.getAllocator()));
6344 }
6345 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6346 Builder.AddTextChunk("object");
6347 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6348 CXCursor_ObjCInstanceMethodDecl));
6349 }
6350 }
6351
6352 // Mutable unordered accessors
6353 // - (void)addKeyObject:(type *)object
6354 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006355 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006356 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006357 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006358 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006359 if (ReturnType.isNull()) {
6360 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6361 Builder.AddTextChunk("void");
6362 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6363 }
6364
6365 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6366 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6367 Builder.AddPlaceholderChunk("object-type");
6368 Builder.AddTextChunk(" *");
6369 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6370 Builder.AddTextChunk("object");
6371 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6372 CXCursor_ObjCInstanceMethodDecl));
6373 }
6374 }
6375
6376 // - (void)addKey:(NSSet *)objects
6377 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006378 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006379 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006380 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006381 if (ReturnType.isNull()) {
6382 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6383 Builder.AddTextChunk("void");
6384 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6385 }
6386
6387 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6388 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6389 Builder.AddTextChunk("NSSet *");
6390 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6391 Builder.AddTextChunk("objects");
6392 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6393 CXCursor_ObjCInstanceMethodDecl));
6394 }
6395 }
6396
6397 // - (void)removeKeyObject:(type *)object
6398 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006399 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006400 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006401 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006402 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006403 if (ReturnType.isNull()) {
6404 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6405 Builder.AddTextChunk("void");
6406 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6407 }
6408
6409 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6410 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6411 Builder.AddPlaceholderChunk("object-type");
6412 Builder.AddTextChunk(" *");
6413 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6414 Builder.AddTextChunk("object");
6415 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6416 CXCursor_ObjCInstanceMethodDecl));
6417 }
6418 }
6419
6420 // - (void)removeKey:(NSSet *)objects
6421 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006422 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006423 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006424 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006425 if (ReturnType.isNull()) {
6426 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6427 Builder.AddTextChunk("void");
6428 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6429 }
6430
6431 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6432 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6433 Builder.AddTextChunk("NSSet *");
6434 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6435 Builder.AddTextChunk("objects");
6436 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6437 CXCursor_ObjCInstanceMethodDecl));
6438 }
6439 }
6440
6441 // - (void)intersectKey:(NSSet *)objects
6442 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006443 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006444 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006445 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006446 if (ReturnType.isNull()) {
6447 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6448 Builder.AddTextChunk("void");
6449 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6450 }
6451
6452 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6453 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6454 Builder.AddTextChunk("NSSet *");
6455 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6456 Builder.AddTextChunk("objects");
6457 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6458 CXCursor_ObjCInstanceMethodDecl));
6459 }
6460 }
6461
6462 // Key-Value Observing
6463 // + (NSSet *)keyPathsForValuesAffectingKey
6464 if (!IsInstanceMethod &&
6465 (ReturnType.isNull() ||
6466 (ReturnType->isObjCObjectPointerType() &&
6467 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6468 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6469 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006470 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006471 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006472 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006473 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006474 if (ReturnType.isNull()) {
6475 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6476 Builder.AddTextChunk("NSSet *");
6477 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6478 }
6479
6480 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6481 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006482 CXCursor_ObjCClassMethodDecl));
6483 }
6484 }
6485
6486 // + (BOOL)automaticallyNotifiesObserversForKey
6487 if (!IsInstanceMethod &&
6488 (ReturnType.isNull() ||
6489 ReturnType->isIntegerType() ||
6490 ReturnType->isBooleanType())) {
6491 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006492 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006493 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6494 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6495 if (ReturnType.isNull()) {
6496 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6497 Builder.AddTextChunk("BOOL");
6498 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6499 }
6500
6501 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6502 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6503 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006504 }
6505 }
6506}
6507
Douglas Gregore8f5a172010-04-07 00:21:17 +00006508void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6509 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006510 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006511 // Determine the return type of the method we're declaring, if
6512 // provided.
6513 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006514 Decl *IDecl = 0;
6515 if (CurContext->isObjCContainer()) {
6516 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6517 IDecl = cast<Decl>(OCD);
6518 }
Douglas Gregorea766182010-10-18 18:21:28 +00006519 // Determine where we should start searching for methods.
6520 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006521 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006522 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006523 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6524 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006525 IsInImplementation = true;
6526 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006527 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006528 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006529 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006530 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006531 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006532 }
6533
6534 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006535 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006536 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006537 }
6538
Douglas Gregorea766182010-10-18 18:21:28 +00006539 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006540 HandleCodeCompleteResults(this, CodeCompleter,
6541 CodeCompletionContext::CCC_Other,
6542 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006543 return;
6544 }
6545
6546 // Find all of the methods that we could declare/implement here.
6547 KnownMethodsMap KnownMethods;
6548 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006549 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006550
Douglas Gregore8f5a172010-04-07 00:21:17 +00006551 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006552 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006553 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6554 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006555 Results.EnterNewScope();
Douglas Gregor8987b232011-09-27 23:30:47 +00006556 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006557 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6558 MEnd = KnownMethods.end();
6559 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006560 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006561 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006562
6563 // If the result type was not already provided, add it to the
6564 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006565 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00006566 AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,
6567 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006568
6569 Selector Sel = Method->getSelector();
6570
6571 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006572 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006573 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006574
6575 // Add parameters to the pattern.
6576 unsigned I = 0;
6577 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6578 PEnd = Method->param_end();
6579 P != PEnd; (void)++P, ++I) {
6580 // Add the part of the selector name.
6581 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006582 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006583 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006584 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6585 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006586 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006587 } else
6588 break;
6589
6590 // Add the parameter type.
Douglas Gregor8987b232011-09-27 23:30:47 +00006591 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,
6592 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006593
6594 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006595 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006596 }
6597
6598 if (Method->isVariadic()) {
6599 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006600 Builder.AddChunk(CodeCompletionString::CK_Comma);
6601 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006602 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006603
Douglas Gregor447107d2010-05-28 00:57:46 +00006604 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006605 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006606 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6607 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6608 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006609 if (!Method->getResultType()->isVoidType()) {
6610 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006611 Builder.AddTextChunk("return");
6612 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6613 Builder.AddPlaceholderChunk("expression");
6614 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006615 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006616 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006617
Douglas Gregor218937c2011-02-01 19:23:04 +00006618 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6619 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006620 }
6621
Douglas Gregor408be5a2010-08-25 01:08:01 +00006622 unsigned Priority = CCP_CodePattern;
6623 if (!M->second.second)
6624 Priority += CCD_InBaseClass;
6625
Douglas Gregor218937c2011-02-01 19:23:04 +00006626 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006627 Method->isInstanceMethod()
6628 ? CXCursor_ObjCInstanceMethodDecl
6629 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006630 }
6631
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006632 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6633 // the properties in this class and its categories.
6634 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006635 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006636 Containers.push_back(SearchDecl);
6637
Douglas Gregore74c25c2011-05-04 23:50:46 +00006638 VisitedSelectorSet KnownSelectors;
6639 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6640 MEnd = KnownMethods.end();
6641 M != MEnd; ++M)
6642 KnownSelectors.insert(M->first);
6643
6644
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006645 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6646 if (!IFace)
6647 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6648 IFace = Category->getClassInterface();
6649
6650 if (IFace) {
6651 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6652 Category = Category->getNextClassCategory())
6653 Containers.push_back(Category);
6654 }
6655
6656 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6657 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6658 PEnd = Containers[I]->prop_end();
6659 P != PEnd; ++P) {
6660 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006661 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006662 }
6663 }
6664 }
6665
Douglas Gregore8f5a172010-04-07 00:21:17 +00006666 Results.ExitScope();
6667
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006668 HandleCodeCompleteResults(this, CodeCompleter,
6669 CodeCompletionContext::CCC_Other,
6670 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006671}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006672
6673void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6674 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006675 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006676 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006677 IdentifierInfo **SelIdents,
6678 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006679 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006680 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006681 if (ExternalSource) {
6682 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6683 I != N; ++I) {
6684 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006685 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006686 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006687
6688 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006689 }
6690 }
6691
6692 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006693 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006694 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6695 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006696
6697 if (ReturnTy)
6698 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006699
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006700 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006701 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6702 MEnd = MethodPool.end();
6703 M != MEnd; ++M) {
6704 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6705 &M->second.second;
6706 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006707 MethList = MethList->Next) {
6708 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6709 NumSelIdents))
6710 continue;
6711
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006712 if (AtParameterName) {
6713 // Suggest parameter names we've seen before.
6714 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6715 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6716 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006717 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006718 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006719 Param->getIdentifier()->getName()));
6720 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006721 }
6722 }
6723
6724 continue;
6725 }
6726
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006727 Result R(MethList->Method, 0);
6728 R.StartParameter = NumSelIdents;
6729 R.AllParametersAreInformative = false;
6730 R.DeclaringEntity = true;
6731 Results.MaybeAddResult(R, CurContext);
6732 }
6733 }
6734
6735 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006736 HandleCodeCompleteResults(this, CodeCompleter,
6737 CodeCompletionContext::CCC_Other,
6738 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006739}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006740
Douglas Gregorf29c5232010-08-24 22:20:20 +00006741void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006742 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006743 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006744 Results.EnterNewScope();
6745
6746 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006747 CodeCompletionBuilder Builder(Results.getAllocator());
6748 Builder.AddTypedTextChunk("if");
6749 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6750 Builder.AddPlaceholderChunk("condition");
6751 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006752
6753 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006754 Builder.AddTypedTextChunk("ifdef");
6755 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6756 Builder.AddPlaceholderChunk("macro");
6757 Results.AddResult(Builder.TakeString());
6758
Douglas Gregorf44e8542010-08-24 19:08:16 +00006759 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006760 Builder.AddTypedTextChunk("ifndef");
6761 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6762 Builder.AddPlaceholderChunk("macro");
6763 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006764
6765 if (InConditional) {
6766 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006767 Builder.AddTypedTextChunk("elif");
6768 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6769 Builder.AddPlaceholderChunk("condition");
6770 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006771
6772 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006773 Builder.AddTypedTextChunk("else");
6774 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006775
6776 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006777 Builder.AddTypedTextChunk("endif");
6778 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006779 }
6780
6781 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006782 Builder.AddTypedTextChunk("include");
6783 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6784 Builder.AddTextChunk("\"");
6785 Builder.AddPlaceholderChunk("header");
6786 Builder.AddTextChunk("\"");
6787 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006788
6789 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006790 Builder.AddTypedTextChunk("include");
6791 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6792 Builder.AddTextChunk("<");
6793 Builder.AddPlaceholderChunk("header");
6794 Builder.AddTextChunk(">");
6795 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006796
6797 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006798 Builder.AddTypedTextChunk("define");
6799 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6800 Builder.AddPlaceholderChunk("macro");
6801 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006802
6803 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006804 Builder.AddTypedTextChunk("define");
6805 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6806 Builder.AddPlaceholderChunk("macro");
6807 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6808 Builder.AddPlaceholderChunk("args");
6809 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6810 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006811
6812 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006813 Builder.AddTypedTextChunk("undef");
6814 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6815 Builder.AddPlaceholderChunk("macro");
6816 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006817
6818 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006819 Builder.AddTypedTextChunk("line");
6820 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6821 Builder.AddPlaceholderChunk("number");
6822 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006823
6824 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006825 Builder.AddTypedTextChunk("line");
6826 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6827 Builder.AddPlaceholderChunk("number");
6828 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6829 Builder.AddTextChunk("\"");
6830 Builder.AddPlaceholderChunk("filename");
6831 Builder.AddTextChunk("\"");
6832 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006833
6834 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006835 Builder.AddTypedTextChunk("error");
6836 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6837 Builder.AddPlaceholderChunk("message");
6838 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006839
6840 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006841 Builder.AddTypedTextChunk("pragma");
6842 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6843 Builder.AddPlaceholderChunk("arguments");
6844 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006845
6846 if (getLangOptions().ObjC1) {
6847 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006848 Builder.AddTypedTextChunk("import");
6849 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6850 Builder.AddTextChunk("\"");
6851 Builder.AddPlaceholderChunk("header");
6852 Builder.AddTextChunk("\"");
6853 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006854
6855 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006856 Builder.AddTypedTextChunk("import");
6857 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6858 Builder.AddTextChunk("<");
6859 Builder.AddPlaceholderChunk("header");
6860 Builder.AddTextChunk(">");
6861 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006862 }
6863
6864 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006865 Builder.AddTypedTextChunk("include_next");
6866 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6867 Builder.AddTextChunk("\"");
6868 Builder.AddPlaceholderChunk("header");
6869 Builder.AddTextChunk("\"");
6870 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006871
6872 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006873 Builder.AddTypedTextChunk("include_next");
6874 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6875 Builder.AddTextChunk("<");
6876 Builder.AddPlaceholderChunk("header");
6877 Builder.AddTextChunk(">");
6878 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006879
6880 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006881 Builder.AddTypedTextChunk("warning");
6882 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6883 Builder.AddPlaceholderChunk("message");
6884 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006885
6886 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6887 // completions for them. And __include_macros is a Clang-internal extension
6888 // that we don't want to encourage anyone to use.
6889
6890 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6891 Results.ExitScope();
6892
Douglas Gregorf44e8542010-08-24 19:08:16 +00006893 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006894 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006895 Results.data(), Results.size());
6896}
6897
6898void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006899 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006900 S->getFnParent()? Sema::PCC_RecoveryInFunction
6901 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006902}
6903
Douglas Gregorf29c5232010-08-24 22:20:20 +00006904void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006905 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006906 IsDefinition? CodeCompletionContext::CCC_MacroName
6907 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006908 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6909 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006910 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006911 Results.EnterNewScope();
6912 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6913 MEnd = PP.macro_end();
6914 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006915 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006916 M->first->getName()));
6917 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006918 }
6919 Results.ExitScope();
6920 } else if (IsDefinition) {
6921 // FIXME: Can we detect when the user just wrote an include guard above?
6922 }
6923
Douglas Gregor52779fb2010-09-23 23:01:17 +00006924 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006925 Results.data(), Results.size());
6926}
6927
Douglas Gregorf29c5232010-08-24 22:20:20 +00006928void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006929 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006930 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006931
6932 if (!CodeCompleter || CodeCompleter->includeMacros())
6933 AddMacroResults(PP, Results);
6934
6935 // defined (<macro>)
6936 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006937 CodeCompletionBuilder Builder(Results.getAllocator());
6938 Builder.AddTypedTextChunk("defined");
6939 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6940 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6941 Builder.AddPlaceholderChunk("macro");
6942 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6943 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006944 Results.ExitScope();
6945
6946 HandleCodeCompleteResults(this, CodeCompleter,
6947 CodeCompletionContext::CCC_PreprocessorExpression,
6948 Results.data(), Results.size());
6949}
6950
6951void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6952 IdentifierInfo *Macro,
6953 MacroInfo *MacroInfo,
6954 unsigned Argument) {
6955 // FIXME: In the future, we could provide "overload" results, much like we
6956 // do for function calls.
6957
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00006958 // Now just ignore this. There will be another code-completion callback
6959 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00006960}
6961
Douglas Gregor55817af2010-08-25 17:04:25 +00006962void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006963 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006964 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006965 0, 0);
6966}
6967
Douglas Gregordae68752011-02-01 22:57:45 +00006968void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006969 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006970 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006971 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6972 CodeCompletionDeclConsumer Consumer(Builder,
6973 Context.getTranslationUnitDecl());
6974 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6975 Consumer);
6976 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006977
6978 if (!CodeCompleter || CodeCompleter->includeMacros())
6979 AddMacroResults(PP, Builder);
6980
6981 Results.clear();
6982 Results.insert(Results.end(),
6983 Builder.data(), Builder.data() + Builder.size());
6984}