blob: 6e2094d77a24706cb273be5ea3f35507146a8c59 [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 Gregor01dfea02010-01-10 23:08:15 +00001379/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001380static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001381 Scope *S,
1382 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001383 ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001384 CodeCompletionBuilder Builder(Results.getAllocator());
1385
John McCall0a2c5e22010-08-25 06:19:51 +00001386 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001387 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001388 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001389 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001390 if (Results.includeCodePatterns()) {
1391 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001392 Builder.AddTypedTextChunk("namespace");
1393 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1394 Builder.AddPlaceholderChunk("identifier");
1395 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1396 Builder.AddPlaceholderChunk("declarations");
1397 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1398 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1399 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001400 }
1401
Douglas Gregor01dfea02010-01-10 23:08:15 +00001402 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001403 Builder.AddTypedTextChunk("namespace");
1404 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1405 Builder.AddPlaceholderChunk("name");
1406 Builder.AddChunk(CodeCompletionString::CK_Equal);
1407 Builder.AddPlaceholderChunk("namespace");
1408 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001409
1410 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001411 Builder.AddTypedTextChunk("using");
1412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1413 Builder.AddTextChunk("namespace");
1414 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1415 Builder.AddPlaceholderChunk("identifier");
1416 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001417
1418 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001419 Builder.AddTypedTextChunk("asm");
1420 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1421 Builder.AddPlaceholderChunk("string-literal");
1422 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1423 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001424
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001425 if (Results.includeCodePatterns()) {
1426 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001427 Builder.AddTypedTextChunk("template");
1428 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1429 Builder.AddPlaceholderChunk("declaration");
1430 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001431 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001432 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001433
1434 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001435 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001436
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001437 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001438 // Fall through
1439
John McCallf312b1e2010-08-26 23:41:50 +00001440 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001441 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001442 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001443 Builder.AddTypedTextChunk("using");
1444 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1445 Builder.AddPlaceholderChunk("qualifier");
1446 Builder.AddTextChunk("::");
1447 Builder.AddPlaceholderChunk("name");
1448 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001449
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001450 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001451 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001452 Builder.AddTypedTextChunk("using");
1453 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1454 Builder.AddTextChunk("typename");
1455 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1456 Builder.AddPlaceholderChunk("qualifier");
1457 Builder.AddTextChunk("::");
1458 Builder.AddPlaceholderChunk("name");
1459 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001460 }
1461
John McCallf312b1e2010-08-26 23:41:50 +00001462 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001463 AddTypedefResult(Results);
1464
Douglas Gregor01dfea02010-01-10 23:08:15 +00001465 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001466 Builder.AddTypedTextChunk("public");
1467 Builder.AddChunk(CodeCompletionString::CK_Colon);
1468 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001469
1470 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001471 Builder.AddTypedTextChunk("protected");
1472 Builder.AddChunk(CodeCompletionString::CK_Colon);
1473 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001474
1475 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001476 Builder.AddTypedTextChunk("private");
1477 Builder.AddChunk(CodeCompletionString::CK_Colon);
1478 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001479 }
1480 }
1481 // Fall through
1482
John McCallf312b1e2010-08-26 23:41:50 +00001483 case Sema::PCC_Template:
1484 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001485 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001486 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001487 Builder.AddTypedTextChunk("template");
1488 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1489 Builder.AddPlaceholderChunk("parameters");
1490 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1491 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001492 }
1493
Douglas Gregorbca403c2010-01-13 23:51:12 +00001494 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1495 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001496 break;
1497
John McCallf312b1e2010-08-26 23:41:50 +00001498 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001499 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1500 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1501 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001502 break;
1503
John McCallf312b1e2010-08-26 23:41:50 +00001504 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001505 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1506 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1507 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001508 break;
1509
John McCallf312b1e2010-08-26 23:41:50 +00001510 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001511 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001512 break;
1513
John McCallf312b1e2010-08-26 23:41:50 +00001514 case Sema::PCC_RecoveryInFunction:
1515 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001516 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001517
Douglas Gregorec3310a2011-04-12 02:47:21 +00001518 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1519 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001520 Builder.AddTypedTextChunk("try");
1521 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1522 Builder.AddPlaceholderChunk("statements");
1523 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1524 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1525 Builder.AddTextChunk("catch");
1526 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1527 Builder.AddPlaceholderChunk("declaration");
1528 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1529 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1530 Builder.AddPlaceholderChunk("statements");
1531 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1532 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1533 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001534 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001535 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001536 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001537
Douglas Gregord8e8a582010-05-25 21:41:55 +00001538 if (Results.includeCodePatterns()) {
1539 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001540 Builder.AddTypedTextChunk("if");
1541 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001542 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001543 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001544 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001545 Builder.AddPlaceholderChunk("expression");
1546 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1547 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1548 Builder.AddPlaceholderChunk("statements");
1549 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1550 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1551 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001552
Douglas Gregord8e8a582010-05-25 21:41:55 +00001553 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001554 Builder.AddTypedTextChunk("switch");
1555 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001556 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001557 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001558 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001559 Builder.AddPlaceholderChunk("expression");
1560 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1561 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1562 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1563 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1564 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001565 }
1566
Douglas Gregor01dfea02010-01-10 23:08:15 +00001567 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001568 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001569 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001570 Builder.AddTypedTextChunk("case");
1571 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1572 Builder.AddPlaceholderChunk("expression");
1573 Builder.AddChunk(CodeCompletionString::CK_Colon);
1574 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001575
1576 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001577 Builder.AddTypedTextChunk("default");
1578 Builder.AddChunk(CodeCompletionString::CK_Colon);
1579 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001580 }
1581
Douglas Gregord8e8a582010-05-25 21:41:55 +00001582 if (Results.includeCodePatterns()) {
1583 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001584 Builder.AddTypedTextChunk("while");
1585 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001586 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001587 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001588 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001589 Builder.AddPlaceholderChunk("expression");
1590 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1591 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1592 Builder.AddPlaceholderChunk("statements");
1593 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1594 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1595 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001596
1597 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001598 Builder.AddTypedTextChunk("do");
1599 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1600 Builder.AddPlaceholderChunk("statements");
1601 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1602 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1603 Builder.AddTextChunk("while");
1604 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1605 Builder.AddPlaceholderChunk("expression");
1606 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1607 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001608
Douglas Gregord8e8a582010-05-25 21:41:55 +00001609 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001610 Builder.AddTypedTextChunk("for");
1611 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001612 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001613 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001614 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001615 Builder.AddPlaceholderChunk("init-expression");
1616 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1617 Builder.AddPlaceholderChunk("condition");
1618 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1619 Builder.AddPlaceholderChunk("inc-expression");
1620 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1621 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1622 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1623 Builder.AddPlaceholderChunk("statements");
1624 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1625 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1626 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001627 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001628
1629 if (S->getContinueParent()) {
1630 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001631 Builder.AddTypedTextChunk("continue");
1632 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001633 }
1634
1635 if (S->getBreakParent()) {
1636 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001637 Builder.AddTypedTextChunk("break");
1638 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001639 }
1640
1641 // "return expression ;" or "return ;", depending on whether we
1642 // know the function is void or not.
1643 bool isVoid = false;
1644 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1645 isVoid = Function->getResultType()->isVoidType();
1646 else if (ObjCMethodDecl *Method
1647 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1648 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001649 else if (SemaRef.getCurBlock() &&
1650 !SemaRef.getCurBlock()->ReturnType.isNull())
1651 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001652 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001653 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001654 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1655 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001656 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001657 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001658
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001659 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001660 Builder.AddTypedTextChunk("goto");
1661 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1662 Builder.AddPlaceholderChunk("label");
1663 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001664
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001665 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001666 Builder.AddTypedTextChunk("using");
1667 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1668 Builder.AddTextChunk("namespace");
1669 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1670 Builder.AddPlaceholderChunk("identifier");
1671 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001672 }
1673
1674 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001675 case Sema::PCC_ForInit:
1676 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001677 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001678 // Fall through: conditions and statements can have expressions.
1679
Douglas Gregor02688102010-09-14 23:59:36 +00001680 case Sema::PCC_ParenthesizedExpression:
John McCallf85e1932011-06-15 23:02:42 +00001681 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1682 CCC == Sema::PCC_ParenthesizedExpression) {
1683 // (__bridge <type>)<expression>
1684 Builder.AddTypedTextChunk("__bridge");
1685 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1686 Builder.AddPlaceholderChunk("type");
1687 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1688 Builder.AddPlaceholderChunk("expression");
1689 Results.AddResult(Result(Builder.TakeString()));
1690
1691 // (__bridge_transfer <Objective-C type>)<expression>
1692 Builder.AddTypedTextChunk("__bridge_transfer");
1693 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1694 Builder.AddPlaceholderChunk("Objective-C type");
1695 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1696 Builder.AddPlaceholderChunk("expression");
1697 Results.AddResult(Result(Builder.TakeString()));
1698
1699 // (__bridge_retained <CF type>)<expression>
1700 Builder.AddTypedTextChunk("__bridge_retained");
1701 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1702 Builder.AddPlaceholderChunk("CF type");
1703 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1704 Builder.AddPlaceholderChunk("expression");
1705 Results.AddResult(Result(Builder.TakeString()));
1706 }
1707 // Fall through
1708
John McCallf312b1e2010-08-26 23:41:50 +00001709 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001710 if (SemaRef.getLangOptions().CPlusPlus) {
1711 // 'this', if we're in a non-static member function.
1712 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1713 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001714 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001715
1716 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001717 Results.AddResult(Result("true"));
1718 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001719
Douglas Gregorec3310a2011-04-12 02:47:21 +00001720 if (SemaRef.getLangOptions().RTTI) {
1721 // dynamic_cast < type-id > ( expression )
1722 Builder.AddTypedTextChunk("dynamic_cast");
1723 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1724 Builder.AddPlaceholderChunk("type");
1725 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1726 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1727 Builder.AddPlaceholderChunk("expression");
1728 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1729 Results.AddResult(Result(Builder.TakeString()));
1730 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001731
1732 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001733 Builder.AddTypedTextChunk("static_cast");
1734 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1735 Builder.AddPlaceholderChunk("type");
1736 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1737 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1738 Builder.AddPlaceholderChunk("expression");
1739 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1740 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001741
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001742 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001743 Builder.AddTypedTextChunk("reinterpret_cast");
1744 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1745 Builder.AddPlaceholderChunk("type");
1746 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1747 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1748 Builder.AddPlaceholderChunk("expression");
1749 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1750 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001751
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001752 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001753 Builder.AddTypedTextChunk("const_cast");
1754 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1755 Builder.AddPlaceholderChunk("type");
1756 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1757 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1758 Builder.AddPlaceholderChunk("expression");
1759 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1760 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001761
Douglas Gregorec3310a2011-04-12 02:47:21 +00001762 if (SemaRef.getLangOptions().RTTI) {
1763 // typeid ( expression-or-type )
1764 Builder.AddTypedTextChunk("typeid");
1765 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1766 Builder.AddPlaceholderChunk("expression-or-type");
1767 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1768 Results.AddResult(Result(Builder.TakeString()));
1769 }
1770
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001771 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001772 Builder.AddTypedTextChunk("new");
1773 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1774 Builder.AddPlaceholderChunk("type");
1775 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1776 Builder.AddPlaceholderChunk("expressions");
1777 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1778 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001779
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001780 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001781 Builder.AddTypedTextChunk("new");
1782 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1783 Builder.AddPlaceholderChunk("type");
1784 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1785 Builder.AddPlaceholderChunk("size");
1786 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1787 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1788 Builder.AddPlaceholderChunk("expressions");
1789 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1790 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001791
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001792 // delete expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001793 Builder.AddTypedTextChunk("delete");
1794 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1795 Builder.AddPlaceholderChunk("expression");
1796 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001797
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001798 // delete [] expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001799 Builder.AddTypedTextChunk("delete");
1800 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1801 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1802 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1803 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1804 Builder.AddPlaceholderChunk("expression");
1805 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001806
Douglas Gregorec3310a2011-04-12 02:47:21 +00001807 if (SemaRef.getLangOptions().CXXExceptions) {
1808 // throw expression
1809 Builder.AddTypedTextChunk("throw");
1810 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1811 Builder.AddPlaceholderChunk("expression");
1812 Results.AddResult(Result(Builder.TakeString()));
1813 }
Douglas Gregora50216c2011-10-18 16:29:03 +00001814
Douglas Gregor12e13132010-05-26 22:00:08 +00001815 // FIXME: Rethrow?
Douglas Gregora50216c2011-10-18 16:29:03 +00001816
1817 if (SemaRef.getLangOptions().CPlusPlus0x) {
1818 // nullptr
1819 Builder.AddTypedTextChunk("nullptr");
1820 Results.AddResult(Result(Builder.TakeString()));
1821
1822 // alignof
1823 Builder.AddTypedTextChunk("alignof");
1824 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1825 Builder.AddPlaceholderChunk("type");
1826 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1827 Results.AddResult(Result(Builder.TakeString()));
1828
1829 // noexcept
1830 Builder.AddTypedTextChunk("noexcept");
1831 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1832 Builder.AddPlaceholderChunk("expression");
1833 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1834 Results.AddResult(Result(Builder.TakeString()));
1835
1836 // sizeof... expression
1837 Builder.AddTypedTextChunk("sizeof...");
1838 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1839 Builder.AddPlaceholderChunk("parameter-pack");
1840 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1841 Results.AddResult(Result(Builder.TakeString()));
1842 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001843 }
1844
1845 if (SemaRef.getLangOptions().ObjC1) {
1846 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001847 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1848 // The interface can be NULL.
1849 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1850 if (ID->getSuperClass())
1851 Results.AddResult(Result("super"));
1852 }
1853
Douglas Gregorbca403c2010-01-13 23:51:12 +00001854 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001855 }
1856
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001857 // sizeof expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001858 Builder.AddTypedTextChunk("sizeof");
1859 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1860 Builder.AddPlaceholderChunk("expression-or-type");
1861 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1862 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001863 break;
1864 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001865
John McCallf312b1e2010-08-26 23:41:50 +00001866 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001867 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001868 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001869 }
1870
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001871 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1872 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001873
John McCallf312b1e2010-08-26 23:41:50 +00001874 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001875 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001876}
1877
Douglas Gregor30c42402011-09-27 22:38:19 +00001878/// \brief Retrieve a printing policy suitable for code completion.
Douglas Gregor8987b232011-09-27 23:30:47 +00001879static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1880 PrintingPolicy Policy = S.getPrintingPolicy();
Douglas Gregor30c42402011-09-27 22:38:19 +00001881 Policy.AnonymousTagLocations = false;
1882 Policy.SuppressStrongLifetime = true;
1883 return Policy;
1884}
1885
Douglas Gregora63f6de2011-02-01 21:15:40 +00001886/// \brief Retrieve the string representation of the given type as a string
1887/// that has the appropriate lifetime for code completion.
1888///
1889/// This routine provides a fast path where we provide constant strings for
1890/// common type names.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001891static const char *GetCompletionTypeString(QualType T,
1892 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001893 const PrintingPolicy &Policy,
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001894 CodeCompletionAllocator &Allocator) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001895 if (!T.getLocalQualifiers()) {
1896 // Built-in type names are constant strings.
1897 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
Douglas Gregor30c42402011-09-27 22:38:19 +00001898 return BT->getName(Policy);
Douglas Gregora63f6de2011-02-01 21:15:40 +00001899
1900 // Anonymous tag types are constant strings.
1901 if (const TagType *TagT = dyn_cast<TagType>(T))
1902 if (TagDecl *Tag = TagT->getDecl())
Richard Smith162e1c12011-04-15 14:24:37 +00001903 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001904 switch (Tag->getTagKind()) {
1905 case TTK_Struct: return "struct <anonymous>";
1906 case TTK_Class: return "class <anonymous>";
1907 case TTK_Union: return "union <anonymous>";
1908 case TTK_Enum: return "enum <anonymous>";
1909 }
1910 }
1911 }
1912
1913 // Slow path: format the type as a string.
1914 std::string Result;
1915 T.getAsStringInternal(Result, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00001916 return Allocator.CopyString(Result);
Douglas Gregora63f6de2011-02-01 21:15:40 +00001917}
1918
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001919/// \brief If the given declaration has an associated type, add it as a result
1920/// type chunk.
1921static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001922 const PrintingPolicy &Policy,
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001923 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001924 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001925 if (!ND)
1926 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001927
1928 // Skip constructors and conversion functions, which have their return types
1929 // built into their names.
1930 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1931 return;
1932
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001933 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001934 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001935 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1936 T = Function->getResultType();
1937 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1938 T = Method->getResultType();
1939 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1940 T = FunTmpl->getTemplatedDecl()->getResultType();
1941 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1942 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1943 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1944 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00001945 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001946 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001947 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001948 T = Property->getType();
1949
1950 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1951 return;
1952
Douglas Gregor8987b232011-09-27 23:30:47 +00001953 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00001954 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001955}
1956
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001957static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001958 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001959 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1960 if (Sentinel->getSentinel() == 0) {
1961 if (Context.getLangOptions().ObjC1 &&
1962 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001963 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001964 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001965 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001966 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001967 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001968 }
1969}
1970
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00001971static void appendWithSpace(std::string &Result, StringRef Text) {
1972 if (!Result.empty())
1973 Result += ' ';
1974 Result += Text.str();
1975}
1976static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
1977 std::string Result;
1978 if (ObjCQuals & Decl::OBJC_TQ_In)
1979 appendWithSpace(Result, "in");
1980 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
1981 appendWithSpace(Result, "inout");
1982 else if (ObjCQuals & Decl::OBJC_TQ_Out)
1983 appendWithSpace(Result, "out");
1984 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
1985 appendWithSpace(Result, "bycopy");
1986 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
1987 appendWithSpace(Result, "byref");
1988 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
1989 appendWithSpace(Result, "oneway");
1990 return Result;
1991}
1992
Douglas Gregor83482d12010-08-24 16:15:59 +00001993static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001994 const PrintingPolicy &Policy,
Douglas Gregoraba48082010-08-29 19:47:46 +00001995 ParmVarDecl *Param,
Douglas Gregoree1c68a2011-10-18 04:23:19 +00001996 bool SuppressName = false,
1997 bool SuppressBlock = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001998 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1999 if (Param->getType()->isDependentType() ||
2000 !Param->getType()->isBlockPointerType()) {
2001 // The argument for a dependent or non-block parameter is a placeholder
2002 // containing that parameter's type.
2003 std::string Result;
2004
Douglas Gregoraba48082010-08-29 19:47:46 +00002005 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002006 Result = Param->getIdentifier()->getName();
2007
John McCallf85e1932011-06-15 23:02:42 +00002008 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002009
2010 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002011 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2012 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00002013 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002014 Result += Param->getIdentifier()->getName();
2015 }
2016 return Result;
2017 }
2018
2019 // The argument for a block pointer parameter is a block literal with
2020 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00002021 FunctionTypeLoc *Block = 0;
2022 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00002023 TypeLoc TL;
2024 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2025 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2026 while (true) {
2027 // Look through typedefs.
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002028 if (!SuppressBlock) {
2029 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
2030 if (TypeSourceInfo *InnerTSInfo
2031 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
2032 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2033 continue;
2034 }
2035 }
2036
2037 // Look through qualified types
2038 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2039 TL = QualifiedTL->getUnqualifiedLoc();
Douglas Gregor83482d12010-08-24 16:15:59 +00002040 continue;
2041 }
2042 }
2043
Douglas Gregor83482d12010-08-24 16:15:59 +00002044 // Try to get the function prototype behind the block pointer type,
2045 // then we're done.
2046 if (BlockPointerTypeLoc *BlockPtr
2047 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002048 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002049 Block = dyn_cast<FunctionTypeLoc>(&TL);
2050 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002051 }
2052 break;
2053 }
2054 }
2055
2056 if (!Block) {
2057 // We were unable to find a FunctionProtoTypeLoc with parameter names
2058 // for the block; just use the parameter type as a placeholder.
2059 std::string Result;
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002060 if (!ObjCMethodParam && Param->getIdentifier())
2061 Result = Param->getIdentifier()->getName();
2062
John McCallf85e1932011-06-15 23:02:42 +00002063 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002064
2065 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002066 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2067 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002068 if (Param->getIdentifier())
2069 Result += Param->getIdentifier()->getName();
2070 }
2071
2072 return Result;
2073 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002074
Douglas Gregor83482d12010-08-24 16:15:59 +00002075 // We have the function prototype behind the block pointer type, as it was
2076 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002077 std::string Result;
2078 QualType ResultType = Block->getTypePtr()->getResultType();
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002079 if (!ResultType->isVoidType() || SuppressBlock)
John McCallf85e1932011-06-15 23:02:42 +00002080 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002081
2082 // Format the parameter list.
2083 std::string Params;
Douglas Gregor830072c2011-02-15 22:37:09 +00002084 if (!BlockProto || Block->getNumArgs() == 0) {
2085 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002086 Params = "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002087 else
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002088 Params = "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002089 } else {
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002090 Params += "(";
Douglas Gregor38276252010-09-08 22:47:51 +00002091 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2092 if (I)
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002093 Params += ", ";
2094 Params += FormatFunctionParameter(Context, Policy, Block->getArg(I),
2095 /*SuppressName=*/false,
2096 /*SuppressBlock=*/true);
Douglas Gregor38276252010-09-08 22:47:51 +00002097
Douglas Gregor830072c2011-02-15 22:37:09 +00002098 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002099 Params += ", ...";
Douglas Gregor38276252010-09-08 22:47:51 +00002100 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002101 Params += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002102 }
Douglas Gregor38276252010-09-08 22:47:51 +00002103
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002104 if (SuppressBlock) {
2105 // Format as a parameter.
2106 Result = Result + " (^";
2107 if (Param->getIdentifier())
2108 Result += Param->getIdentifier()->getName();
2109 Result += ")";
2110 Result += Params;
2111 } else {
2112 // Format as a block literal argument.
2113 Result = '^' + Result;
2114 Result += Params;
2115
2116 if (Param->getIdentifier())
2117 Result += Param->getIdentifier()->getName();
2118 }
2119
Douglas Gregor83482d12010-08-24 16:15:59 +00002120 return Result;
2121}
2122
Douglas Gregor86d9a522009-09-21 16:56:56 +00002123/// \brief Add function parameter chunks to the given code completion string.
2124static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002125 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002126 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002127 CodeCompletionBuilder &Result,
2128 unsigned Start = 0,
2129 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002130 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002131 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002132
Douglas Gregor218937c2011-02-01 19:23:04 +00002133 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002134 ParmVarDecl *Param = Function->getParamDecl(P);
2135
Douglas Gregor218937c2011-02-01 19:23:04 +00002136 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002137 // When we see an optional default argument, put that argument and
2138 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002139 CodeCompletionBuilder Opt(Result.getAllocator());
2140 if (!FirstParameter)
2141 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002142 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregor218937c2011-02-01 19:23:04 +00002143 Result.AddOptionalChunk(Opt.TakeString());
2144 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002145 }
2146
Douglas Gregor218937c2011-02-01 19:23:04 +00002147 if (FirstParameter)
2148 FirstParameter = false;
2149 else
2150 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2151
2152 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002153
2154 // Format the placeholder string.
Douglas Gregor8987b232011-09-27 23:30:47 +00002155 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2156 Param);
Douglas Gregor83482d12010-08-24 16:15:59 +00002157
Douglas Gregore17794f2010-08-31 05:13:43 +00002158 if (Function->isVariadic() && P == N - 1)
2159 PlaceholderStr += ", ...";
2160
Douglas Gregor86d9a522009-09-21 16:56:56 +00002161 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002162 Result.AddPlaceholderChunk(
2163 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002164 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002165
2166 if (const FunctionProtoType *Proto
2167 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002168 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002169 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002170 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002171
Douglas Gregor218937c2011-02-01 19:23:04 +00002172 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002173 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002174}
2175
2176/// \brief Add template parameter chunks to the given code completion string.
2177static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002178 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002179 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002180 CodeCompletionBuilder &Result,
2181 unsigned MaxParameters = 0,
2182 unsigned Start = 0,
2183 bool InDefaultArg = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002184 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002185 bool FirstParameter = true;
2186
2187 TemplateParameterList *Params = Template->getTemplateParameters();
2188 TemplateParameterList::iterator PEnd = Params->end();
2189 if (MaxParameters)
2190 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002191 for (TemplateParameterList::iterator P = Params->begin() + Start;
2192 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002193 bool HasDefaultArg = false;
2194 std::string PlaceholderStr;
2195 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2196 if (TTP->wasDeclaredWithTypename())
2197 PlaceholderStr = "typename";
2198 else
2199 PlaceholderStr = "class";
2200
2201 if (TTP->getIdentifier()) {
2202 PlaceholderStr += ' ';
2203 PlaceholderStr += TTP->getIdentifier()->getName();
2204 }
2205
2206 HasDefaultArg = TTP->hasDefaultArgument();
2207 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002208 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002209 if (NTTP->getIdentifier())
2210 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002211 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002212 HasDefaultArg = NTTP->hasDefaultArgument();
2213 } else {
2214 assert(isa<TemplateTemplateParmDecl>(*P));
2215 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2216
2217 // Since putting the template argument list into the placeholder would
2218 // be very, very long, we just use an abbreviation.
2219 PlaceholderStr = "template<...> class";
2220 if (TTP->getIdentifier()) {
2221 PlaceholderStr += ' ';
2222 PlaceholderStr += TTP->getIdentifier()->getName();
2223 }
2224
2225 HasDefaultArg = TTP->hasDefaultArgument();
2226 }
2227
Douglas Gregor218937c2011-02-01 19:23:04 +00002228 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002229 // When we see an optional default argument, put that argument and
2230 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002231 CodeCompletionBuilder Opt(Result.getAllocator());
2232 if (!FirstParameter)
2233 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002234 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregor218937c2011-02-01 19:23:04 +00002235 P - Params->begin(), true);
2236 Result.AddOptionalChunk(Opt.TakeString());
2237 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002238 }
2239
Douglas Gregor218937c2011-02-01 19:23:04 +00002240 InDefaultArg = false;
2241
Douglas Gregor86d9a522009-09-21 16:56:56 +00002242 if (FirstParameter)
2243 FirstParameter = false;
2244 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002245 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002246
2247 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002248 Result.AddPlaceholderChunk(
2249 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002250 }
2251}
2252
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002253/// \brief Add a qualifier to the given code-completion string, if the
2254/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002255static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002256AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002257 NestedNameSpecifier *Qualifier,
2258 bool QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002259 ASTContext &Context,
2260 const PrintingPolicy &Policy) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002261 if (!Qualifier)
2262 return;
2263
2264 std::string PrintedNNS;
2265 {
2266 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor8987b232011-09-27 23:30:47 +00002267 Qualifier->print(OS, Policy);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002268 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002269 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002270 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002271 else
Douglas Gregordae68752011-02-01 22:57:45 +00002272 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002273}
2274
Douglas Gregor218937c2011-02-01 19:23:04 +00002275static void
2276AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2277 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002278 const FunctionProtoType *Proto
2279 = Function->getType()->getAs<FunctionProtoType>();
2280 if (!Proto || !Proto->getTypeQuals())
2281 return;
2282
Douglas Gregora63f6de2011-02-01 21:15:40 +00002283 // FIXME: Add ref-qualifier!
2284
2285 // Handle single qualifiers without copying
2286 if (Proto->getTypeQuals() == Qualifiers::Const) {
2287 Result.AddInformativeChunk(" const");
2288 return;
2289 }
2290
2291 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2292 Result.AddInformativeChunk(" volatile");
2293 return;
2294 }
2295
2296 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2297 Result.AddInformativeChunk(" restrict");
2298 return;
2299 }
2300
2301 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002302 std::string QualsStr;
2303 if (Proto->getTypeQuals() & Qualifiers::Const)
2304 QualsStr += " const";
2305 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2306 QualsStr += " volatile";
2307 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2308 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002309 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002310}
2311
Douglas Gregor6f942b22010-09-21 16:06:22 +00002312/// \brief Add the name of the given declaration
Douglas Gregor8987b232011-09-27 23:30:47 +00002313static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2314 NamedDecl *ND, CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002315 typedef CodeCompletionString::Chunk Chunk;
2316
2317 DeclarationName Name = ND->getDeclName();
2318 if (!Name)
2319 return;
2320
2321 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002322 case DeclarationName::CXXOperatorName: {
2323 const char *OperatorName = 0;
2324 switch (Name.getCXXOverloadedOperator()) {
2325 case OO_None:
2326 case OO_Conditional:
2327 case NUM_OVERLOADED_OPERATORS:
2328 OperatorName = "operator";
2329 break;
2330
2331#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2332 case OO_##Name: OperatorName = "operator" Spelling; break;
2333#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2334#include "clang/Basic/OperatorKinds.def"
2335
2336 case OO_New: OperatorName = "operator new"; break;
2337 case OO_Delete: OperatorName = "operator delete"; break;
2338 case OO_Array_New: OperatorName = "operator new[]"; break;
2339 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2340 case OO_Call: OperatorName = "operator()"; break;
2341 case OO_Subscript: OperatorName = "operator[]"; break;
2342 }
2343 Result.AddTypedTextChunk(OperatorName);
2344 break;
2345 }
2346
Douglas Gregor6f942b22010-09-21 16:06:22 +00002347 case DeclarationName::Identifier:
2348 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002349 case DeclarationName::CXXDestructorName:
2350 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002351 Result.AddTypedTextChunk(
2352 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002353 break;
2354
2355 case DeclarationName::CXXUsingDirective:
2356 case DeclarationName::ObjCZeroArgSelector:
2357 case DeclarationName::ObjCOneArgSelector:
2358 case DeclarationName::ObjCMultiArgSelector:
2359 break;
2360
2361 case DeclarationName::CXXConstructorName: {
2362 CXXRecordDecl *Record = 0;
2363 QualType Ty = Name.getCXXNameType();
2364 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2365 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2366 else if (const InjectedClassNameType *InjectedTy
2367 = Ty->getAs<InjectedClassNameType>())
2368 Record = InjectedTy->getDecl();
2369 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002370 Result.AddTypedTextChunk(
2371 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002372 break;
2373 }
2374
Douglas Gregordae68752011-02-01 22:57:45 +00002375 Result.AddTypedTextChunk(
2376 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002377 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002378 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002379 AddTemplateParameterChunks(Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002380 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002381 }
2382 break;
2383 }
2384 }
2385}
2386
Douglas Gregor86d9a522009-09-21 16:56:56 +00002387/// \brief If possible, create a new code completion string for the given
2388/// result.
2389///
2390/// \returns Either a new, heap-allocated code completion string describing
2391/// how to use this result, or NULL to indicate that the string or name of the
2392/// result is all that is needed.
2393CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002394CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002395 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002396 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002397 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002398
Douglas Gregor8987b232011-09-27 23:30:47 +00002399 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregor218937c2011-02-01 19:23:04 +00002400 if (Kind == RK_Pattern) {
2401 Pattern->Priority = Priority;
2402 Pattern->Availability = Availability;
2403 return Pattern;
2404 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002405
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002406 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002407 Result.AddTypedTextChunk(Keyword);
2408 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002409 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002410
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002411 if (Kind == RK_Macro) {
2412 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002413 assert(MI && "Not a macro?");
2414
Douglas Gregordae68752011-02-01 22:57:45 +00002415 Result.AddTypedTextChunk(
2416 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002417
2418 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002419 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002420
2421 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002422 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregore4244702011-07-30 08:17:44 +00002423 bool CombineVariadicArgument = false;
2424 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2425 if (MI->isVariadic() && AEnd - A > 1) {
2426 AEnd -= 2;
2427 CombineVariadicArgument = true;
2428 }
2429 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002430 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002431 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002432
Douglas Gregore4244702011-07-30 08:17:44 +00002433 if (!MI->isVariadic() || A + 1 != AEnd) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002434 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002435 Result.AddPlaceholderChunk(
2436 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002437 continue;
2438 }
2439
Douglas Gregore4244702011-07-30 08:17:44 +00002440 // Variadic argument; cope with the difference between GNU and C99
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002441 // variadic macros, providing a single placeholder for the rest of the
2442 // arguments.
2443 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002444 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002445 else {
2446 std::string Arg = (*A)->getName();
2447 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002448 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002449 }
2450 }
Douglas Gregore4244702011-07-30 08:17:44 +00002451
2452 if (CombineVariadicArgument) {
2453 // Handle the next-to-last argument, combining it with the variadic
2454 // argument.
2455 std::string LastArg = (*A)->getName();
2456 ++A;
2457 if ((*A)->isStr("__VA_ARGS__"))
2458 LastArg += ", ...";
2459 else
2460 LastArg += ", " + (*A)->getName().str() + "...";
2461 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(LastArg));
2462 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002463 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2464 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002465 }
2466
Douglas Gregord8e8a582010-05-25 21:41:55 +00002467 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002468 NamedDecl *ND = Declaration;
2469
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002470 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002471 Result.AddTypedTextChunk(
2472 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002473 Result.AddTextChunk("::");
2474 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002475 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00002476
2477 for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2478 if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2479 Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2480 }
2481 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002482
Douglas Gregor8987b232011-09-27 23:30:47 +00002483 AddResultTypeChunk(S.Context, Policy, ND, Result);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002484
Douglas Gregor86d9a522009-09-21 16:56:56 +00002485 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002486 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002487 S.Context, Policy);
2488 AddTypedNameChunk(S.Context, Policy, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002489 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002490 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002491 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002492 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002493 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002494 }
2495
2496 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002497 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002498 S.Context, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002499 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor8987b232011-09-27 23:30:47 +00002500 AddTypedNameChunk(S.Context, Policy, Function, Result);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002501
Douglas Gregor86d9a522009-09-21 16:56:56 +00002502 // Figure out which template parameters are deduced (or have default
2503 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002504 SmallVector<bool, 16> Deduced;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002505 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2506 unsigned LastDeducibleArgument;
2507 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2508 --LastDeducibleArgument) {
2509 if (!Deduced[LastDeducibleArgument - 1]) {
2510 // C++0x: Figure out if the template argument has a default. If so,
2511 // the user doesn't need to type this argument.
2512 // FIXME: We need to abstract template parameters better!
2513 bool HasDefaultArg = false;
2514 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002515 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002516 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2517 HasDefaultArg = TTP->hasDefaultArgument();
2518 else if (NonTypeTemplateParmDecl *NTTP
2519 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2520 HasDefaultArg = NTTP->hasDefaultArgument();
2521 else {
2522 assert(isa<TemplateTemplateParmDecl>(Param));
2523 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002524 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002525 }
2526
2527 if (!HasDefaultArg)
2528 break;
2529 }
2530 }
2531
2532 if (LastDeducibleArgument) {
2533 // Some of the function template arguments cannot be deduced from a
2534 // function call, so we introduce an explicit template argument list
2535 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002536 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002537 AddTemplateParameterChunks(S.Context, Policy, FunTmpl, Result,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002538 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002539 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002540 }
2541
2542 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002543 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002544 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002545 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002546 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002547 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002548 }
2549
2550 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002551 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002552 S.Context, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002553 Result.AddTypedTextChunk(
2554 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002555 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002556 AddTemplateParameterChunks(S.Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002557 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2558 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002559 }
2560
Douglas Gregor9630eb62009-11-17 16:44:22 +00002561 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002562 Selector Sel = Method->getSelector();
2563 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002564 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002565 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002566 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002567 }
2568
Douglas Gregor813d8342011-02-18 22:29:55 +00002569 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002570 SelName += ':';
2571 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002572 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002573 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002574 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002575
2576 // If there is only one parameter, and we're past it, add an empty
2577 // typed-text chunk since there is nothing to type.
2578 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002579 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002580 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002581 unsigned Idx = 0;
2582 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2583 PEnd = Method->param_end();
2584 P != PEnd; (void)++P, ++Idx) {
2585 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002586 std::string Keyword;
2587 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002588 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002589 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002590 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002591 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002592 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002593 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002594 else
Douglas Gregordae68752011-02-01 22:57:45 +00002595 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002596 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002597
2598 // If we're before the starting parameter, skip the placeholder.
2599 if (Idx < StartParameter)
2600 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002601
2602 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002603
2604 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregor8987b232011-09-27 23:30:47 +00002605 Arg = FormatFunctionParameter(S.Context, Policy, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002606 else {
John McCallf85e1932011-06-15 23:02:42 +00002607 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002608 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2609 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002610 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002611 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002612 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002613 }
2614
Douglas Gregore17794f2010-08-31 05:13:43 +00002615 if (Method->isVariadic() && (P + 1) == PEnd)
2616 Arg += ", ...";
2617
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002618 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002619 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002620 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002621 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002622 else
Douglas Gregordae68752011-02-01 22:57:45 +00002623 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002624 }
2625
Douglas Gregor2a17af02009-12-23 00:21:46 +00002626 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002627 if (Method->param_size() == 0) {
2628 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002629 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002630 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002631 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002632 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002633 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002634 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002635
2636 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002637 }
2638
Douglas Gregor218937c2011-02-01 19:23:04 +00002639 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002640 }
2641
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002642 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002643 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002644 S.Context, Policy);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002645
Douglas Gregordae68752011-02-01 22:57:45 +00002646 Result.AddTypedTextChunk(
2647 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002648 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002649}
2650
Douglas Gregor86d802e2009-09-23 00:34:09 +00002651CodeCompletionString *
2652CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2653 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002654 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002655 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002656 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor8987b232011-09-27 23:30:47 +00002657 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCallf85e1932011-06-15 23:02:42 +00002658
Douglas Gregor218937c2011-02-01 19:23:04 +00002659 // FIXME: Set priority, availability appropriately.
2660 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002661 FunctionDecl *FDecl = getFunction();
Douglas Gregor8987b232011-09-27 23:30:47 +00002662 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002663 const FunctionProtoType *Proto
2664 = dyn_cast<FunctionProtoType>(getFunctionType());
2665 if (!FDecl && !Proto) {
2666 // Function without a prototype. Just give the return type and a
2667 // highlighted ellipsis.
2668 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002669 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
Douglas Gregor8987b232011-09-27 23:30:47 +00002670 S.Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002671 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002672 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2673 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2674 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2675 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002676 }
2677
2678 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002679 Result.AddTextChunk(
2680 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002681 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002682 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002683 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002684 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002685
Douglas Gregor218937c2011-02-01 19:23:04 +00002686 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002687 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2688 for (unsigned I = 0; I != NumParams; ++I) {
2689 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002690 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002691
2692 std::string ArgString;
2693 QualType ArgType;
2694
2695 if (FDecl) {
2696 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2697 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2698 } else {
2699 ArgType = Proto->getArgType(I);
2700 }
2701
John McCallf85e1932011-06-15 23:02:42 +00002702 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002703
2704 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002705 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002706 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002707 else
Douglas Gregordae68752011-02-01 22:57:45 +00002708 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002709 }
2710
2711 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002712 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002713 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002714 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002715 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002716 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002717 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002718 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002719
Douglas Gregor218937c2011-02-01 19:23:04 +00002720 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002721}
2722
Chris Lattner5f9e2722011-07-23 10:55:15 +00002723unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002724 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002725 bool PreferredTypeIsPointer) {
2726 unsigned Priority = CCP_Macro;
2727
Douglas Gregorb05496d2010-09-20 21:11:48 +00002728 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2729 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2730 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002731 Priority = CCP_Constant;
2732 if (PreferredTypeIsPointer)
2733 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002734 }
2735 // Treat "YES", "NO", "true", and "false" as constants.
2736 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2737 MacroName.equals("true") || MacroName.equals("false"))
2738 Priority = CCP_Constant;
2739 // Treat "bool" as a type.
2740 else if (MacroName.equals("bool"))
2741 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2742
Douglas Gregor1827e102010-08-16 16:18:59 +00002743
2744 return Priority;
2745}
2746
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002747CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2748 if (!D)
2749 return CXCursor_UnexposedDecl;
2750
2751 switch (D->getKind()) {
2752 case Decl::Enum: return CXCursor_EnumDecl;
2753 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2754 case Decl::Field: return CXCursor_FieldDecl;
2755 case Decl::Function:
2756 return CXCursor_FunctionDecl;
2757 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2758 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2759 case Decl::ObjCClass:
2760 // FIXME
2761 return CXCursor_UnexposedDecl;
2762 case Decl::ObjCForwardProtocol:
2763 // FIXME
2764 return CXCursor_UnexposedDecl;
2765 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2766 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2767 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2768 case Decl::ObjCMethod:
2769 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2770 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2771 case Decl::CXXMethod: return CXCursor_CXXMethod;
2772 case Decl::CXXConstructor: return CXCursor_Constructor;
2773 case Decl::CXXDestructor: return CXCursor_Destructor;
2774 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2775 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2776 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2777 case Decl::ParmVar: return CXCursor_ParmDecl;
2778 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002779 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002780 case Decl::Var: return CXCursor_VarDecl;
2781 case Decl::Namespace: return CXCursor_Namespace;
2782 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2783 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2784 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2785 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2786 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2787 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00002788 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002789 case Decl::ClassTemplatePartialSpecialization:
2790 return CXCursor_ClassTemplatePartialSpecialization;
2791 case Decl::UsingDirective: return CXCursor_UsingDirective;
2792
2793 case Decl::Using:
2794 case Decl::UnresolvedUsingValue:
2795 case Decl::UnresolvedUsingTypename:
2796 return CXCursor_UsingDeclaration;
2797
Douglas Gregor352697a2011-06-03 23:08:58 +00002798 case Decl::ObjCPropertyImpl:
2799 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2800 case ObjCPropertyImplDecl::Dynamic:
2801 return CXCursor_ObjCDynamicDecl;
2802
2803 case ObjCPropertyImplDecl::Synthesize:
2804 return CXCursor_ObjCSynthesizeDecl;
2805 }
2806 break;
2807
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002808 default:
2809 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2810 switch (TD->getTagKind()) {
2811 case TTK_Struct: return CXCursor_StructDecl;
2812 case TTK_Class: return CXCursor_ClassDecl;
2813 case TTK_Union: return CXCursor_UnionDecl;
2814 case TTK_Enum: return CXCursor_EnumDecl;
2815 }
2816 }
2817 }
2818
2819 return CXCursor_UnexposedDecl;
2820}
2821
Douglas Gregor590c7d52010-07-08 20:55:51 +00002822static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2823 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002824 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002825
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002826 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002827
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002828 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2829 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002830 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002831 Results.AddResult(Result(M->first,
2832 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002833 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002834 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002835 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002836
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002837 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002838
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002839}
2840
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002841static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2842 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002843 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002844
2845 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002846
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002847 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2848 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2849 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2850 Results.AddResult(Result("__func__", CCP_Constant));
2851 Results.ExitScope();
2852}
2853
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002854static void HandleCodeCompleteResults(Sema *S,
2855 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002856 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002857 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002858 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002859 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002860 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002861}
2862
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002863static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2864 Sema::ParserCompletionContext PCC) {
2865 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002866 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002867 return CodeCompletionContext::CCC_TopLevel;
2868
John McCallf312b1e2010-08-26 23:41:50 +00002869 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002870 return CodeCompletionContext::CCC_ClassStructUnion;
2871
John McCallf312b1e2010-08-26 23:41:50 +00002872 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002873 return CodeCompletionContext::CCC_ObjCInterface;
2874
John McCallf312b1e2010-08-26 23:41:50 +00002875 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002876 return CodeCompletionContext::CCC_ObjCImplementation;
2877
John McCallf312b1e2010-08-26 23:41:50 +00002878 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002879 return CodeCompletionContext::CCC_ObjCIvarList;
2880
John McCallf312b1e2010-08-26 23:41:50 +00002881 case Sema::PCC_Template:
2882 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002883 if (S.CurContext->isFileContext())
2884 return CodeCompletionContext::CCC_TopLevel;
2885 else if (S.CurContext->isRecord())
2886 return CodeCompletionContext::CCC_ClassStructUnion;
2887 else
2888 return CodeCompletionContext::CCC_Other;
2889
John McCallf312b1e2010-08-26 23:41:50 +00002890 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002891 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002892
John McCallf312b1e2010-08-26 23:41:50 +00002893 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002894 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2895 S.getLangOptions().ObjC1)
2896 return CodeCompletionContext::CCC_ParenthesizedExpression;
2897 else
2898 return CodeCompletionContext::CCC_Expression;
2899
2900 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002901 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002902 return CodeCompletionContext::CCC_Expression;
2903
John McCallf312b1e2010-08-26 23:41:50 +00002904 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002905 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002906
John McCallf312b1e2010-08-26 23:41:50 +00002907 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002908 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002909
2910 case Sema::PCC_ParenthesizedExpression:
2911 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002912
2913 case Sema::PCC_LocalDeclarationSpecifiers:
2914 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002915 }
2916
2917 return CodeCompletionContext::CCC_Other;
2918}
2919
Douglas Gregorf6961522010-08-27 21:18:54 +00002920/// \brief If we're in a C++ virtual member function, add completion results
2921/// that invoke the functions we override, since it's common to invoke the
2922/// overridden function as well as adding new functionality.
2923///
2924/// \param S The semantic analysis object for which we are generating results.
2925///
2926/// \param InContext This context in which the nested-name-specifier preceding
2927/// the code-completion point
2928static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2929 ResultBuilder &Results) {
2930 // Look through blocks.
2931 DeclContext *CurContext = S.CurContext;
2932 while (isa<BlockDecl>(CurContext))
2933 CurContext = CurContext->getParent();
2934
2935
2936 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2937 if (!Method || !Method->isVirtual())
2938 return;
2939
2940 // We need to have names for all of the parameters, if we're going to
2941 // generate a forwarding call.
2942 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2943 PEnd = Method->param_end();
2944 P != PEnd;
2945 ++P) {
2946 if (!(*P)->getDeclName())
2947 return;
2948 }
2949
Douglas Gregor8987b232011-09-27 23:30:47 +00002950 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorf6961522010-08-27 21:18:54 +00002951 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2952 MEnd = Method->end_overridden_methods();
2953 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002954 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002955 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2956 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2957 continue;
2958
2959 // If we need a nested-name-specifier, add one now.
2960 if (!InContext) {
2961 NestedNameSpecifier *NNS
2962 = getRequiredQualification(S.Context, CurContext,
2963 Overridden->getDeclContext());
2964 if (NNS) {
2965 std::string Str;
2966 llvm::raw_string_ostream OS(Str);
Douglas Gregor8987b232011-09-27 23:30:47 +00002967 NNS->print(OS, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002968 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002969 }
2970 } else if (!InContext->Equals(Overridden->getDeclContext()))
2971 continue;
2972
Douglas Gregordae68752011-02-01 22:57:45 +00002973 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002974 Overridden->getNameAsString()));
2975 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00002976 bool FirstParam = true;
2977 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2978 PEnd = Method->param_end();
2979 P != PEnd; ++P) {
2980 if (FirstParam)
2981 FirstParam = false;
2982 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002983 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00002984
Douglas Gregordae68752011-02-01 22:57:45 +00002985 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002986 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002987 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002988 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2989 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00002990 CCP_SuperCompletion,
2991 CXCursor_CXXMethod));
2992 Results.Ignore(Overridden);
2993 }
2994}
2995
Douglas Gregor01dfea02010-01-10 23:08:15 +00002996void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002997 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002998 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002999 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003000 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00003001 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003002
Douglas Gregor01dfea02010-01-10 23:08:15 +00003003 // Determine how to filter results, e.g., so that the names of
3004 // values (functions, enumerators, function templates, etc.) are
3005 // only allowed where we can have an expression.
3006 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003007 case PCC_Namespace:
3008 case PCC_Class:
3009 case PCC_ObjCInterface:
3010 case PCC_ObjCImplementation:
3011 case PCC_ObjCInstanceVariableList:
3012 case PCC_Template:
3013 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00003014 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003015 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00003016 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3017 break;
3018
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003019 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00003020 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00003021 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003022 case PCC_ForInit:
3023 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00003024 if (WantTypesInContext(CompletionContext, getLangOptions()))
3025 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3026 else
3027 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00003028
3029 if (getLangOptions().CPlusPlus)
3030 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00003031 break;
Douglas Gregordc845342010-05-25 05:58:43 +00003032
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003033 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00003034 // Unfiltered
3035 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00003036 }
3037
Douglas Gregor3cdee122010-08-26 16:36:48 +00003038 // If we are in a C++ non-static member function, check the qualifiers on
3039 // the member function to filter/prioritize the results list.
3040 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3041 if (CurMethod->isInstance())
3042 Results.setObjectTypeQualifiers(
3043 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3044
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00003045 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003046 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3047 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003048
Douglas Gregorbca403c2010-01-13 23:51:12 +00003049 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003050 Results.ExitScope();
3051
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003052 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00003053 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00003054 case PCC_Expression:
3055 case PCC_Statement:
3056 case PCC_RecoveryInFunction:
3057 if (S->getFnParent())
3058 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3059 break;
3060
3061 case PCC_Namespace:
3062 case PCC_Class:
3063 case PCC_ObjCInterface:
3064 case PCC_ObjCImplementation:
3065 case PCC_ObjCInstanceVariableList:
3066 case PCC_Template:
3067 case PCC_MemberTemplate:
3068 case PCC_ForInit:
3069 case PCC_Condition:
3070 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003071 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003072 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003073 }
3074
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003075 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003076 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003077
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003078 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003079 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003080}
3081
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003082static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3083 ParsedType Receiver,
3084 IdentifierInfo **SelIdents,
3085 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003086 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003087 bool IsSuper,
3088 ResultBuilder &Results);
3089
3090void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3091 bool AllowNonIdentifiers,
3092 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003093 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003094 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003095 AllowNestedNameSpecifiers
3096 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3097 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003098 Results.EnterNewScope();
3099
3100 // Type qualifiers can come after names.
3101 Results.AddResult(Result("const"));
3102 Results.AddResult(Result("volatile"));
3103 if (getLangOptions().C99)
3104 Results.AddResult(Result("restrict"));
3105
3106 if (getLangOptions().CPlusPlus) {
3107 if (AllowNonIdentifiers) {
3108 Results.AddResult(Result("operator"));
3109 }
3110
3111 // Add nested-name-specifiers.
3112 if (AllowNestedNameSpecifiers) {
3113 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003114 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003115 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3116 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3117 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003118 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003119 }
3120 }
3121 Results.ExitScope();
3122
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003123 // If we're in a context where we might have an expression (rather than a
3124 // declaration), and what we've seen so far is an Objective-C type that could
3125 // be a receiver of a class message, this may be a class message send with
3126 // the initial opening bracket '[' missing. Add appropriate completions.
3127 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3128 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3129 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3130 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3131 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3132 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3133 DS.getTypeQualifiers() == 0 &&
3134 S &&
3135 (S->getFlags() & Scope::DeclScope) != 0 &&
3136 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3137 Scope::FunctionPrototypeScope |
3138 Scope::AtCatchScope)) == 0) {
3139 ParsedType T = DS.getRepAsType();
3140 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003141 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003142 }
3143
Douglas Gregor4497dd42010-08-24 04:59:56 +00003144 // Note that we intentionally suppress macro results here, since we do not
3145 // encourage using macros to produce the names of entities.
3146
Douglas Gregor52779fb2010-09-23 23:01:17 +00003147 HandleCodeCompleteResults(this, CodeCompleter,
3148 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003149 Results.data(), Results.size());
3150}
3151
Douglas Gregorfb629412010-08-23 21:17:50 +00003152struct Sema::CodeCompleteExpressionData {
3153 CodeCompleteExpressionData(QualType PreferredType = QualType())
3154 : PreferredType(PreferredType), IntegralConstantExpression(false),
3155 ObjCCollection(false) { }
3156
3157 QualType PreferredType;
3158 bool IntegralConstantExpression;
3159 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003160 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003161};
3162
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003163/// \brief Perform code-completion in an expression context when we know what
3164/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003165///
3166/// \param IntegralConstantExpression Only permit integral constant
3167/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003168void Sema::CodeCompleteExpression(Scope *S,
3169 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003170 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003171 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3172 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003173 if (Data.ObjCCollection)
3174 Results.setFilter(&ResultBuilder::IsObjCCollection);
3175 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003176 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003177 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003178 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3179 else
3180 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003181
3182 if (!Data.PreferredType.isNull())
3183 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3184
3185 // Ignore any declarations that we were told that we don't care about.
3186 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3187 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003188
3189 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003190 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3191 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003192
3193 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003194 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003195 Results.ExitScope();
3196
Douglas Gregor590c7d52010-07-08 20:55:51 +00003197 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003198 if (!Data.PreferredType.isNull())
3199 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3200 || Data.PreferredType->isMemberPointerType()
3201 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003202
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003203 if (S->getFnParent() &&
3204 !Data.ObjCCollection &&
3205 !Data.IntegralConstantExpression)
3206 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3207
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003208 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003209 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003210 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003211 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3212 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003213 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003214}
3215
Douglas Gregorac5fd842010-09-18 01:28:11 +00003216void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3217 if (E.isInvalid())
3218 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3219 else if (getLangOptions().ObjC1)
3220 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003221}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003222
Douglas Gregor73449212010-12-09 23:01:55 +00003223/// \brief The set of properties that have already been added, referenced by
3224/// property name.
3225typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3226
Douglas Gregor95ac6552009-11-18 01:29:26 +00003227static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003228 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003229 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003230 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003231 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003232 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003233 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003234
3235 // Add properties in this container.
3236 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3237 PEnd = Container->prop_end();
3238 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003239 ++P) {
3240 if (AddedProperties.insert(P->getIdentifier()))
3241 Results.MaybeAddResult(Result(*P, 0), CurContext);
3242 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003243
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003244 // Add nullary methods
3245 if (AllowNullaryMethods) {
3246 ASTContext &Context = Container->getASTContext();
Douglas Gregor8987b232011-09-27 23:30:47 +00003247 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003248 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3249 MEnd = Container->meth_end();
3250 M != MEnd; ++M) {
3251 if (M->getSelector().isUnarySelector())
3252 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3253 if (AddedProperties.insert(Name)) {
3254 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor8987b232011-09-27 23:30:47 +00003255 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003256 Builder.AddTypedTextChunk(
3257 Results.getAllocator().CopyString(Name->getName()));
3258
3259 CXAvailabilityKind Availability = CXAvailability_Available;
3260 switch (M->getAvailability()) {
3261 case AR_Available:
3262 case AR_NotYetIntroduced:
3263 Availability = CXAvailability_Available;
3264 break;
3265
3266 case AR_Deprecated:
3267 Availability = CXAvailability_Deprecated;
3268 break;
3269
3270 case AR_Unavailable:
3271 Availability = CXAvailability_NotAvailable;
3272 break;
3273 }
3274
3275 Results.MaybeAddResult(Result(Builder.TakeString(),
3276 CCP_MemberDeclaration + CCD_MethodAsProperty,
3277 M->isInstanceMethod()
3278 ? CXCursor_ObjCInstanceMethodDecl
3279 : CXCursor_ObjCClassMethodDecl,
3280 Availability),
3281 CurContext);
3282 }
3283 }
3284 }
3285
3286
Douglas Gregor95ac6552009-11-18 01:29:26 +00003287 // Add properties in referenced protocols.
3288 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3289 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3290 PEnd = Protocol->protocol_end();
3291 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003292 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3293 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003294 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003295 if (AllowCategories) {
3296 // Look through categories.
3297 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3298 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003299 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3300 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003301 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003302
3303 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003304 for (ObjCInterfaceDecl::all_protocol_iterator
3305 I = IFace->all_referenced_protocol_begin(),
3306 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003307 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3308 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003309
3310 // Look in the superclass.
3311 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003312 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3313 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003314 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003315 } else if (const ObjCCategoryDecl *Category
3316 = dyn_cast<ObjCCategoryDecl>(Container)) {
3317 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003318 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3319 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003320 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003321 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3322 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003323 }
3324}
3325
Richard Trieuf81e5a92011-09-09 02:00:50 +00003326void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *BaseE,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003327 SourceLocation OpLoc,
3328 bool IsArrow) {
3329 if (!BaseE || !CodeCompleter)
3330 return;
3331
John McCall0a2c5e22010-08-25 06:19:51 +00003332 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003333
Douglas Gregor81b747b2009-09-17 21:32:03 +00003334 Expr *Base = static_cast<Expr *>(BaseE);
3335 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003336
3337 if (IsArrow) {
3338 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3339 BaseType = Ptr->getPointeeType();
3340 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003341 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003342 else
3343 return;
3344 }
3345
Douglas Gregor3da626b2011-07-07 16:03:39 +00003346 enum CodeCompletionContext::Kind contextKind;
3347
3348 if (IsArrow) {
3349 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3350 }
3351 else {
3352 if (BaseType->isObjCObjectPointerType() ||
3353 BaseType->isObjCObjectOrInterfaceType()) {
3354 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3355 }
3356 else {
3357 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3358 }
3359 }
3360
Douglas Gregor218937c2011-02-01 19:23:04 +00003361 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003362 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003363 BaseType),
3364 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003365 Results.EnterNewScope();
3366 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003367 // Indicate that we are performing a member access, and the cv-qualifiers
3368 // for the base object type.
3369 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3370
Douglas Gregor95ac6552009-11-18 01:29:26 +00003371 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003372 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003373 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003374 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3375 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003376
Douglas Gregor95ac6552009-11-18 01:29:26 +00003377 if (getLangOptions().CPlusPlus) {
3378 if (!Results.empty()) {
3379 // The "template" keyword can follow "->" or "." in the grammar.
3380 // However, we only want to suggest the template keyword if something
3381 // is dependent.
3382 bool IsDependent = BaseType->isDependentType();
3383 if (!IsDependent) {
3384 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3385 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3386 IsDependent = Ctx->isDependentContext();
3387 break;
3388 }
3389 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003390
Douglas Gregor95ac6552009-11-18 01:29:26 +00003391 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003392 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003393 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003394 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003395 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3396 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003397 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003398
3399 // Add property results based on our interface.
3400 const ObjCObjectPointerType *ObjCPtr
3401 = BaseType->getAsObjCInterfacePointerType();
3402 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003403 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3404 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003405 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003406
3407 // Add properties from the protocols in a qualified interface.
3408 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3409 E = ObjCPtr->qual_end();
3410 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003411 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3412 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003413 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003414 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003415 // Objective-C instance variable access.
3416 ObjCInterfaceDecl *Class = 0;
3417 if (const ObjCObjectPointerType *ObjCPtr
3418 = BaseType->getAs<ObjCObjectPointerType>())
3419 Class = ObjCPtr->getInterfaceDecl();
3420 else
John McCallc12c5bb2010-05-15 11:32:37 +00003421 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003422
3423 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003424 if (Class) {
3425 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3426 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003427 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3428 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003429 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003430 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003431
3432 // FIXME: How do we cope with isa?
3433
3434 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003435
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003436 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003437 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003438 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003439 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003440}
3441
Douglas Gregor374929f2009-09-18 15:37:17 +00003442void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3443 if (!CodeCompleter)
3444 return;
3445
John McCall0a2c5e22010-08-25 06:19:51 +00003446 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003447 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003448 enum CodeCompletionContext::Kind ContextKind
3449 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003450 switch ((DeclSpec::TST)TagSpec) {
3451 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003452 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003453 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003454 break;
3455
3456 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003457 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003458 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003459 break;
3460
3461 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003462 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003463 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003464 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003465 break;
3466
3467 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003468 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003469 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003470
Douglas Gregor218937c2011-02-01 19:23:04 +00003471 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003472 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003473
3474 // First pass: look for tags.
3475 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003476 LookupVisibleDecls(S, LookupTagName, Consumer,
3477 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003478
Douglas Gregor8071e422010-08-15 06:18:01 +00003479 if (CodeCompleter->includeGlobals()) {
3480 // Second pass: look for nested name specifiers.
3481 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3482 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3483 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003484
Douglas Gregor52779fb2010-09-23 23:01:17 +00003485 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003486 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003487}
3488
Douglas Gregor1a480c42010-08-27 17:35:51 +00003489void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003490 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3491 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003492 Results.EnterNewScope();
3493 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3494 Results.AddResult("const");
3495 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3496 Results.AddResult("volatile");
3497 if (getLangOptions().C99 &&
3498 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3499 Results.AddResult("restrict");
3500 Results.ExitScope();
3501 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003502 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003503 Results.data(), Results.size());
3504}
3505
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003506void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003507 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003508 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003509
John McCall781472f2010-08-25 08:40:02 +00003510 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003511 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3512 if (!type->isEnumeralType()) {
3513 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003514 Data.IntegralConstantExpression = true;
3515 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003516 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003517 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003518
3519 // Code-complete the cases of a switch statement over an enumeration type
3520 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003521 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003522
3523 // Determine which enumerators we have already seen in the switch statement.
3524 // FIXME: Ideally, we would also be able to look *past* the code-completion
3525 // token, in case we are code-completing in the middle of the switch and not
3526 // at the end. However, we aren't able to do so at the moment.
3527 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003528 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003529 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3530 SC = SC->getNextSwitchCase()) {
3531 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3532 if (!Case)
3533 continue;
3534
3535 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3536 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3537 if (EnumConstantDecl *Enumerator
3538 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3539 // We look into the AST of the case statement to determine which
3540 // enumerator was named. Alternatively, we could compute the value of
3541 // the integral constant expression, then compare it against the
3542 // values of each enumerator. However, value-based approach would not
3543 // work as well with C++ templates where enumerators declared within a
3544 // template are type- and value-dependent.
3545 EnumeratorsSeen.insert(Enumerator);
3546
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003547 // If this is a qualified-id, keep track of the nested-name-specifier
3548 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003549 //
3550 // switch (TagD.getKind()) {
3551 // case TagDecl::TK_enum:
3552 // break;
3553 // case XXX
3554 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003555 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003556 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3557 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003558 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003559 }
3560 }
3561
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003562 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3563 // If there are no prior enumerators in C++, check whether we have to
3564 // qualify the names of the enumerators that we suggest, because they
3565 // may not be visible in this scope.
3566 Qualifier = getRequiredQualification(Context, CurContext,
3567 Enum->getDeclContext());
3568
3569 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3570 }
3571
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003572 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003573 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3574 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003575 Results.EnterNewScope();
3576 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3577 EEnd = Enum->enumerator_end();
3578 E != EEnd; ++E) {
3579 if (EnumeratorsSeen.count(*E))
3580 continue;
3581
Douglas Gregor5c722c702011-02-18 23:30:37 +00003582 CodeCompletionResult R(*E, Qualifier);
3583 R.Priority = CCP_EnumInCase;
3584 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003585 }
3586 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003587
Douglas Gregor3da626b2011-07-07 16:03:39 +00003588 //We need to make sure we're setting the right context,
3589 //so only say we include macros if the code completer says we do
3590 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3591 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003592 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003593 kind = CodeCompletionContext::CCC_OtherWithMacros;
3594 }
3595
3596
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003597 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003598 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003599 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003600}
3601
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003602namespace {
3603 struct IsBetterOverloadCandidate {
3604 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003605 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003606
3607 public:
John McCall5769d612010-02-08 23:07:23 +00003608 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3609 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003610
3611 bool
3612 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003613 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003614 }
3615 };
3616}
3617
Douglas Gregord28dcd72010-05-30 06:10:08 +00003618static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3619 if (NumArgs && !Args)
3620 return true;
3621
3622 for (unsigned I = 0; I != NumArgs; ++I)
3623 if (!Args[I])
3624 return true;
3625
3626 return false;
3627}
3628
Richard Trieuf81e5a92011-09-09 02:00:50 +00003629void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3630 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003631 if (!CodeCompleter)
3632 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003633
3634 // When we're code-completing for a call, we fall back to ordinary
3635 // name code-completion whenever we can't produce specific
3636 // results. We may want to revisit this strategy in the future,
3637 // e.g., by merging the two kinds of results.
3638
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003639 Expr *Fn = (Expr *)FnIn;
3640 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003641
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003642 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003643 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003644 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003645 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003646 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003647 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003648
John McCall3b4294e2009-12-16 12:17:52 +00003649 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003650 SourceLocation Loc = Fn->getExprLoc();
3651 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003652
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003653 // FIXME: What if we're calling something that isn't a function declaration?
3654 // FIXME: What if we're calling a pseudo-destructor?
3655 // FIXME: What if we're calling a member function?
3656
Douglas Gregorc0265402010-01-21 15:46:19 +00003657 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003658 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003659
John McCall3b4294e2009-12-16 12:17:52 +00003660 Expr *NakedFn = Fn->IgnoreParenCasts();
3661 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3662 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3663 /*PartialOverloading=*/ true);
3664 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3665 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003666 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003667 if (!getLangOptions().CPlusPlus ||
3668 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003669 Results.push_back(ResultCandidate(FDecl));
3670 else
John McCall86820f52010-01-26 01:37:31 +00003671 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003672 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3673 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003674 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003675 }
John McCall3b4294e2009-12-16 12:17:52 +00003676 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003677
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003678 QualType ParamType;
3679
Douglas Gregorc0265402010-01-21 15:46:19 +00003680 if (!CandidateSet.empty()) {
3681 // Sort the overload candidate set by placing the best overloads first.
3682 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003683 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003684
Douglas Gregorc0265402010-01-21 15:46:19 +00003685 // Add the remaining viable overload candidates as code-completion reslults.
3686 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3687 CandEnd = CandidateSet.end();
3688 Cand != CandEnd; ++Cand) {
3689 if (Cand->Viable)
3690 Results.push_back(ResultCandidate(Cand->Function));
3691 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003692
3693 // From the viable candidates, try to determine the type of this parameter.
3694 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3695 if (const FunctionType *FType = Results[I].getFunctionType())
3696 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3697 if (NumArgs < Proto->getNumArgs()) {
3698 if (ParamType.isNull())
3699 ParamType = Proto->getArgType(NumArgs);
3700 else if (!Context.hasSameUnqualifiedType(
3701 ParamType.getNonReferenceType(),
3702 Proto->getArgType(NumArgs).getNonReferenceType())) {
3703 ParamType = QualType();
3704 break;
3705 }
3706 }
3707 }
3708 } else {
3709 // Try to determine the parameter type from the type of the expression
3710 // being called.
3711 QualType FunctionType = Fn->getType();
3712 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3713 FunctionType = Ptr->getPointeeType();
3714 else if (const BlockPointerType *BlockPtr
3715 = FunctionType->getAs<BlockPointerType>())
3716 FunctionType = BlockPtr->getPointeeType();
3717 else if (const MemberPointerType *MemPtr
3718 = FunctionType->getAs<MemberPointerType>())
3719 FunctionType = MemPtr->getPointeeType();
3720
3721 if (const FunctionProtoType *Proto
3722 = FunctionType->getAs<FunctionProtoType>()) {
3723 if (NumArgs < Proto->getNumArgs())
3724 ParamType = Proto->getArgType(NumArgs);
3725 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003726 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003727
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003728 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003729 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003730 else
3731 CodeCompleteExpression(S, ParamType);
3732
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003733 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003734 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3735 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003736}
3737
John McCalld226f652010-08-21 09:40:31 +00003738void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3739 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003740 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003741 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003742 return;
3743 }
3744
3745 CodeCompleteExpression(S, VD->getType());
3746}
3747
3748void Sema::CodeCompleteReturn(Scope *S) {
3749 QualType ResultType;
3750 if (isa<BlockDecl>(CurContext)) {
3751 if (BlockScopeInfo *BSI = getCurBlock())
3752 ResultType = BSI->ReturnType;
3753 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3754 ResultType = Function->getResultType();
3755 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3756 ResultType = Method->getResultType();
3757
3758 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003759 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003760 else
3761 CodeCompleteExpression(S, ResultType);
3762}
3763
Douglas Gregord2d8be62011-07-30 08:36:53 +00003764void Sema::CodeCompleteAfterIf(Scope *S) {
3765 typedef CodeCompletionResult Result;
3766 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3767 mapCodeCompletionContext(*this, PCC_Statement));
3768 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3769 Results.EnterNewScope();
3770
3771 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3772 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3773 CodeCompleter->includeGlobals());
3774
3775 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3776
3777 // "else" block
3778 CodeCompletionBuilder Builder(Results.getAllocator());
3779 Builder.AddTypedTextChunk("else");
3780 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3781 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3782 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3783 Builder.AddPlaceholderChunk("statements");
3784 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3785 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3786 Results.AddResult(Builder.TakeString());
3787
3788 // "else if" block
3789 Builder.AddTypedTextChunk("else");
3790 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3791 Builder.AddTextChunk("if");
3792 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3793 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3794 if (getLangOptions().CPlusPlus)
3795 Builder.AddPlaceholderChunk("condition");
3796 else
3797 Builder.AddPlaceholderChunk("expression");
3798 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3799 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3800 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3801 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3802 Builder.AddPlaceholderChunk("statements");
3803 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3804 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3805 Results.AddResult(Builder.TakeString());
3806
3807 Results.ExitScope();
3808
3809 if (S->getFnParent())
3810 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3811
3812 if (CodeCompleter->includeMacros())
3813 AddMacroResults(PP, Results);
3814
3815 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3816 Results.data(),Results.size());
3817}
3818
Richard Trieuf81e5a92011-09-09 02:00:50 +00003819void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003820 if (LHS)
3821 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3822 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003823 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003824}
3825
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003826void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003827 bool EnteringContext) {
3828 if (!SS.getScopeRep() || !CodeCompleter)
3829 return;
3830
Douglas Gregor86d9a522009-09-21 16:56:56 +00003831 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3832 if (!Ctx)
3833 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003834
3835 // Try to instantiate any non-dependent declaration contexts before
3836 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003837 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003838 return;
3839
Douglas Gregor218937c2011-02-01 19:23:04 +00003840 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3841 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003842 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003843
Douglas Gregor86d9a522009-09-21 16:56:56 +00003844 // The "template" keyword can follow "::" in the grammar, but only
3845 // put it into the grammar if the nested-name-specifier is dependent.
3846 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3847 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003848 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003849
3850 // Add calls to overridden virtual functions, if there are any.
3851 //
3852 // FIXME: This isn't wonderful, because we don't know whether we're actually
3853 // in a context that permits expressions. This is a general issue with
3854 // qualified-id completions.
3855 if (!EnteringContext)
3856 MaybeAddOverrideCalls(*this, Ctx, Results);
3857 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003858
Douglas Gregorf6961522010-08-27 21:18:54 +00003859 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3860 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3861
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003862 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003863 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003864 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003865}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003866
3867void Sema::CodeCompleteUsing(Scope *S) {
3868 if (!CodeCompleter)
3869 return;
3870
Douglas Gregor218937c2011-02-01 19:23:04 +00003871 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003872 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3873 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003874 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003875
3876 // If we aren't in class scope, we could see the "namespace" keyword.
3877 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003878 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003879
3880 // After "using", we can see anything that would start a
3881 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003882 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003883 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3884 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003885 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003886
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003887 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003888 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003889 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003890}
3891
3892void Sema::CodeCompleteUsingDirective(Scope *S) {
3893 if (!CodeCompleter)
3894 return;
3895
Douglas Gregor86d9a522009-09-21 16:56:56 +00003896 // After "using namespace", we expect to see a namespace name or namespace
3897 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003898 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3899 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003900 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003901 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003902 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003903 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3904 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003905 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003906 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003907 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003908 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003909}
3910
3911void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3912 if (!CodeCompleter)
3913 return;
3914
Douglas Gregor86d9a522009-09-21 16:56:56 +00003915 DeclContext *Ctx = (DeclContext *)S->getEntity();
3916 if (!S->getParent())
3917 Ctx = Context.getTranslationUnitDecl();
3918
Douglas Gregor52779fb2010-09-23 23:01:17 +00003919 bool SuppressedGlobalResults
3920 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3921
Douglas Gregor218937c2011-02-01 19:23:04 +00003922 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003923 SuppressedGlobalResults
3924 ? CodeCompletionContext::CCC_Namespace
3925 : CodeCompletionContext::CCC_Other,
3926 &ResultBuilder::IsNamespace);
3927
3928 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003929 // We only want to see those namespaces that have already been defined
3930 // within this scope, because its likely that the user is creating an
3931 // extended namespace declaration. Keep track of the most recent
3932 // definition of each namespace.
3933 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3934 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3935 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3936 NS != NSEnd; ++NS)
3937 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3938
3939 // Add the most recent definition (or extended definition) of each
3940 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003941 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003942 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3943 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3944 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003945 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003946 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003947 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003948 }
3949
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003950 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003951 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003952 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003953}
3954
3955void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3956 if (!CodeCompleter)
3957 return;
3958
Douglas Gregor86d9a522009-09-21 16:56:56 +00003959 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003960 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3961 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003962 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003963 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003964 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3965 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003966 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003967 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003968 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003969}
3970
Douglas Gregored8d3222009-09-18 20:05:18 +00003971void Sema::CodeCompleteOperatorName(Scope *S) {
3972 if (!CodeCompleter)
3973 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003974
John McCall0a2c5e22010-08-25 06:19:51 +00003975 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003976 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3977 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003978 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003979 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003980
Douglas Gregor86d9a522009-09-21 16:56:56 +00003981 // Add the names of overloadable operators.
3982#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3983 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003984 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003985#include "clang/Basic/OperatorKinds.def"
3986
3987 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003988 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003989 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003990 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3991 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003992
3993 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003994 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003995 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003996
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003997 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003998 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003999 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00004000}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004001
Douglas Gregor0133f522010-08-28 00:00:50 +00004002void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00004003 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00004004 unsigned NumInitializers) {
Douglas Gregor8987b232011-09-27 23:30:47 +00004005 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor0133f522010-08-28 00:00:50 +00004006 CXXConstructorDecl *Constructor
4007 = static_cast<CXXConstructorDecl *>(ConstructorD);
4008 if (!Constructor)
4009 return;
4010
Douglas Gregor218937c2011-02-01 19:23:04 +00004011 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004012 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00004013 Results.EnterNewScope();
4014
4015 // Fill in any already-initialized fields or base classes.
4016 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4017 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4018 for (unsigned I = 0; I != NumInitializers; ++I) {
4019 if (Initializers[I]->isBaseInitializer())
4020 InitializedBases.insert(
4021 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4022 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00004023 InitializedFields.insert(cast<FieldDecl>(
4024 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00004025 }
4026
4027 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00004028 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00004029 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00004030 CXXRecordDecl *ClassDecl = Constructor->getParent();
4031 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4032 BaseEnd = ClassDecl->bases_end();
4033 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004034 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4035 SawLastInitializer
4036 = NumInitializers > 0 &&
4037 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4038 Context.hasSameUnqualifiedType(Base->getType(),
4039 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004040 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004041 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004042
Douglas Gregor218937c2011-02-01 19:23:04 +00004043 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004044 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004045 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004046 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4047 Builder.AddPlaceholderChunk("args");
4048 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4049 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004050 SawLastInitializer? CCP_NextInitializer
4051 : CCP_MemberDeclaration));
4052 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004053 }
4054
4055 // Add completions for virtual base classes.
4056 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4057 BaseEnd = ClassDecl->vbases_end();
4058 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004059 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4060 SawLastInitializer
4061 = NumInitializers > 0 &&
4062 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4063 Context.hasSameUnqualifiedType(Base->getType(),
4064 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004065 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004066 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004067
Douglas Gregor218937c2011-02-01 19:23:04 +00004068 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004069 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004070 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004071 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4072 Builder.AddPlaceholderChunk("args");
4073 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4074 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004075 SawLastInitializer? CCP_NextInitializer
4076 : CCP_MemberDeclaration));
4077 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004078 }
4079
4080 // Add completions for members.
4081 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4082 FieldEnd = ClassDecl->field_end();
4083 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004084 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4085 SawLastInitializer
4086 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004087 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4088 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004089 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004090 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004091
4092 if (!Field->getDeclName())
4093 continue;
4094
Douglas Gregordae68752011-02-01 22:57:45 +00004095 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004096 Field->getIdentifier()->getName()));
4097 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4098 Builder.AddPlaceholderChunk("args");
4099 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4100 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004101 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004102 : CCP_MemberDeclaration,
4103 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004104 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004105 }
4106 Results.ExitScope();
4107
Douglas Gregor52779fb2010-09-23 23:01:17 +00004108 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004109 Results.data(), Results.size());
4110}
4111
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004112// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4113// true or false.
4114#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004115static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004116 ResultBuilder &Results,
4117 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004118 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004119 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004120 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004121
Douglas Gregor218937c2011-02-01 19:23:04 +00004122 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004123 if (LangOpts.ObjC2) {
4124 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004125 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4126 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4127 Builder.AddPlaceholderChunk("property");
4128 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004129
4130 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004131 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4132 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4133 Builder.AddPlaceholderChunk("property");
4134 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004135 }
4136}
4137
Douglas Gregorbca403c2010-01-13 23:51:12 +00004138static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004139 ResultBuilder &Results,
4140 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004141 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004142
4143 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004144 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004145
4146 if (LangOpts.ObjC2) {
4147 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004148 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004149
4150 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004151 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004152
4153 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004154 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004155 }
4156}
4157
Douglas Gregorbca403c2010-01-13 23:51:12 +00004158static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004159 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004160 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004161
4162 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004163 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4164 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4165 Builder.AddPlaceholderChunk("name");
4166 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004167
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004168 if (Results.includeCodePatterns()) {
4169 // @interface name
4170 // FIXME: Could introduce the whole pattern, including superclasses and
4171 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004172 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4173 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4174 Builder.AddPlaceholderChunk("class");
4175 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004176
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004177 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004178 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4179 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4180 Builder.AddPlaceholderChunk("protocol");
4181 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004182
4183 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004184 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4185 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4186 Builder.AddPlaceholderChunk("class");
4187 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004188 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004189
4190 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004191 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4192 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4193 Builder.AddPlaceholderChunk("alias");
4194 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4195 Builder.AddPlaceholderChunk("class");
4196 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004197}
4198
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004199void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004200 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004201 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4202 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004203 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004204 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorbca403c2010-01-13 23:51:12 +00004205 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004206 else if (CurContext->isObjCContainer())
Douglas Gregorbca403c2010-01-13 23:51:12 +00004207 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004208 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004209 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004210 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004211 HandleCodeCompleteResults(this, CodeCompleter,
4212 CodeCompletionContext::CCC_Other,
4213 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004214}
4215
Douglas Gregorbca403c2010-01-13 23:51:12 +00004216static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004217 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004218 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004219
4220 // @encode ( type-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004221 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4222 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4223 Builder.AddPlaceholderChunk("type-name");
4224 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4225 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004226
4227 // @protocol ( protocol-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004228 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4229 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4230 Builder.AddPlaceholderChunk("protocol-name");
4231 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4232 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004233
4234 // @selector ( selector )
Douglas Gregor218937c2011-02-01 19:23:04 +00004235 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4236 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4237 Builder.AddPlaceholderChunk("selector");
4238 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4239 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004240}
4241
Douglas Gregorbca403c2010-01-13 23:51:12 +00004242static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004243 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004244 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004245
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004246 if (Results.includeCodePatterns()) {
4247 // @try { statements } @catch ( declaration ) { statements } @finally
4248 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004249 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4250 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4251 Builder.AddPlaceholderChunk("statements");
4252 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4253 Builder.AddTextChunk("@catch");
4254 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4255 Builder.AddPlaceholderChunk("parameter");
4256 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4257 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4258 Builder.AddPlaceholderChunk("statements");
4259 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4260 Builder.AddTextChunk("@finally");
4261 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4262 Builder.AddPlaceholderChunk("statements");
4263 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4264 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004265 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004266
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004267 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004268 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4269 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4270 Builder.AddPlaceholderChunk("expression");
4271 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004272
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004273 if (Results.includeCodePatterns()) {
4274 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004275 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4276 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4277 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4278 Builder.AddPlaceholderChunk("expression");
4279 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4280 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4281 Builder.AddPlaceholderChunk("statements");
4282 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4283 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004284 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004285}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004286
Douglas Gregorbca403c2010-01-13 23:51:12 +00004287static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004288 ResultBuilder &Results,
4289 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004290 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004291 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4292 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4293 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004294 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004295 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004296}
4297
4298void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004299 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4300 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004301 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004302 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004303 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004304 HandleCodeCompleteResults(this, CodeCompleter,
4305 CodeCompletionContext::CCC_Other,
4306 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004307}
4308
4309void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004310 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4311 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004312 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004313 AddObjCStatementResults(Results, false);
4314 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004315 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004316 HandleCodeCompleteResults(this, CodeCompleter,
4317 CodeCompletionContext::CCC_Other,
4318 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004319}
4320
4321void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004322 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4323 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004324 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004325 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004326 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004327 HandleCodeCompleteResults(this, CodeCompleter,
4328 CodeCompletionContext::CCC_Other,
4329 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004330}
4331
Douglas Gregor988358f2009-11-19 00:14:45 +00004332/// \brief Determine whether the addition of the given flag to an Objective-C
4333/// property's attributes will cause a conflict.
4334static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4335 // Check if we've already added this flag.
4336 if (Attributes & NewFlag)
4337 return true;
4338
4339 Attributes |= NewFlag;
4340
4341 // Check for collisions with "readonly".
4342 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4343 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4344 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004345 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004346 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004347 ObjCDeclSpec::DQ_PR_retain |
4348 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004349 return true;
4350
John McCallf85e1932011-06-15 23:02:42 +00004351 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004352 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004353 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004354 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004355 ObjCDeclSpec::DQ_PR_retain|
4356 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004357 if (AssignCopyRetMask &&
4358 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004359 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004360 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004361 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4362 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004363 return true;
4364
4365 return false;
4366}
4367
Douglas Gregora93b1082009-11-18 23:08:07 +00004368void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004369 if (!CodeCompleter)
4370 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004371
Steve Naroffece8e712009-10-08 21:55:05 +00004372 unsigned Attributes = ODS.getPropertyAttributes();
4373
John McCall0a2c5e22010-08-25 06:19:51 +00004374 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004375 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4376 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004377 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004378 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004379 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004380 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004381 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004382 if (!ObjCPropertyFlagConflicts(Attributes,
4383 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4384 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004385 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004386 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004387 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004388 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004389 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4390 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004391 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004392 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004393 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004394 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004395 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4396 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004397 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004398 CodeCompletionBuilder Setter(Results.getAllocator());
4399 Setter.AddTypedTextChunk("setter");
4400 Setter.AddTextChunk(" = ");
4401 Setter.AddPlaceholderChunk("method");
4402 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004403 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004404 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004405 CodeCompletionBuilder Getter(Results.getAllocator());
4406 Getter.AddTypedTextChunk("getter");
4407 Getter.AddTextChunk(" = ");
4408 Getter.AddPlaceholderChunk("method");
4409 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004410 }
Steve Naroffece8e712009-10-08 21:55:05 +00004411 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004412 HandleCodeCompleteResults(this, CodeCompleter,
4413 CodeCompletionContext::CCC_Other,
4414 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004415}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004416
Douglas Gregor4ad96852009-11-19 07:41:15 +00004417/// \brief Descripts the kind of Objective-C method that we want to find
4418/// via code completion.
4419enum ObjCMethodKind {
4420 MK_Any, //< Any kind of method, provided it means other specified criteria.
4421 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4422 MK_OneArgSelector //< One-argument selector.
4423};
4424
Douglas Gregor458433d2010-08-26 15:07:07 +00004425static bool isAcceptableObjCSelector(Selector Sel,
4426 ObjCMethodKind WantKind,
4427 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004428 unsigned NumSelIdents,
4429 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004430 if (NumSelIdents > Sel.getNumArgs())
4431 return false;
4432
4433 switch (WantKind) {
4434 case MK_Any: break;
4435 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4436 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4437 }
4438
Douglas Gregorcf544262010-11-17 21:36:08 +00004439 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4440 return false;
4441
Douglas Gregor458433d2010-08-26 15:07:07 +00004442 for (unsigned I = 0; I != NumSelIdents; ++I)
4443 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4444 return false;
4445
4446 return true;
4447}
4448
Douglas Gregor4ad96852009-11-19 07:41:15 +00004449static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4450 ObjCMethodKind WantKind,
4451 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004452 unsigned NumSelIdents,
4453 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004454 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004455 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004456}
Douglas Gregord36adf52010-09-16 16:06:31 +00004457
4458namespace {
4459 /// \brief A set of selectors, which is used to avoid introducing multiple
4460 /// completions with the same selector into the result set.
4461 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4462}
4463
Douglas Gregor36ecb042009-11-17 23:22:23 +00004464/// \brief Add all of the Objective-C methods in the given Objective-C
4465/// container to the set of results.
4466///
4467/// The container will be a class, protocol, category, or implementation of
4468/// any of the above. This mether will recurse to include methods from
4469/// the superclasses of classes along with their categories, protocols, and
4470/// implementations.
4471///
4472/// \param Container the container in which we'll look to find methods.
4473///
4474/// \param WantInstance whether to add instance methods (only); if false, this
4475/// routine will add factory methods (only).
4476///
4477/// \param CurContext the context in which we're performing the lookup that
4478/// finds methods.
4479///
Douglas Gregorcf544262010-11-17 21:36:08 +00004480/// \param AllowSameLength Whether we allow a method to be added to the list
4481/// when it has the same number of parameters as we have selector identifiers.
4482///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004483/// \param Results the structure into which we'll add results.
4484static void AddObjCMethods(ObjCContainerDecl *Container,
4485 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004486 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004487 IdentifierInfo **SelIdents,
4488 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004489 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004490 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004491 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004492 ResultBuilder &Results,
4493 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004494 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004495 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4496 MEnd = Container->meth_end();
4497 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004498 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4499 // Check whether the selector identifiers we've been given are a
4500 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004501 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4502 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004503 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004504
Douglas Gregord36adf52010-09-16 16:06:31 +00004505 if (!Selectors.insert((*M)->getSelector()))
4506 continue;
4507
Douglas Gregord3c68542009-11-19 01:08:35 +00004508 Result R = Result(*M, 0);
4509 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004510 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004511 if (!InOriginalClass)
4512 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004513 Results.MaybeAddResult(R, CurContext);
4514 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004515 }
4516
Douglas Gregore396c7b2010-09-16 15:34:59 +00004517 // Visit the protocols of protocols.
4518 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4519 const ObjCList<ObjCProtocolDecl> &Protocols
4520 = Protocol->getReferencedProtocols();
4521 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4522 E = Protocols.end();
4523 I != E; ++I)
4524 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004525 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004526 }
4527
Douglas Gregor36ecb042009-11-17 23:22:23 +00004528 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4529 if (!IFace)
4530 return;
4531
4532 // Add methods in protocols.
4533 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4534 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4535 E = Protocols.end();
4536 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004537 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004538 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004539
4540 // Add methods in categories.
4541 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4542 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004543 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004544 NumSelIdents, CurContext, Selectors, AllowSameLength,
4545 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004546
4547 // Add a categories protocol methods.
4548 const ObjCList<ObjCProtocolDecl> &Protocols
4549 = CatDecl->getReferencedProtocols();
4550 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4551 E = Protocols.end();
4552 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004553 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004554 NumSelIdents, CurContext, Selectors, AllowSameLength,
4555 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004556
4557 // Add methods in category implementations.
4558 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004559 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004560 NumSelIdents, CurContext, Selectors, AllowSameLength,
4561 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004562 }
4563
4564 // Add methods in superclass.
4565 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004566 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004567 SelIdents, NumSelIdents, CurContext, Selectors,
4568 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004569
4570 // Add methods in our implementation, if any.
4571 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004572 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004573 NumSelIdents, CurContext, Selectors, AllowSameLength,
4574 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004575}
4576
4577
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004578void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004579 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004580
4581 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004582 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004583 if (!Class) {
4584 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004585 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004586 Class = Category->getClassInterface();
4587
4588 if (!Class)
4589 return;
4590 }
4591
4592 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004593 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4594 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004595 Results.EnterNewScope();
4596
Douglas Gregord36adf52010-09-16 16:06:31 +00004597 VisitedSelectorSet Selectors;
4598 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004599 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004600 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004601 HandleCodeCompleteResults(this, CodeCompleter,
4602 CodeCompletionContext::CCC_Other,
4603 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004604}
4605
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004606void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004607 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004608
4609 // Try to find the interface where setters might live.
4610 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004611 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004612 if (!Class) {
4613 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004614 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004615 Class = Category->getClassInterface();
4616
4617 if (!Class)
4618 return;
4619 }
4620
4621 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004622 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4623 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004624 Results.EnterNewScope();
4625
Douglas Gregord36adf52010-09-16 16:06:31 +00004626 VisitedSelectorSet Selectors;
4627 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004628 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004629
4630 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004631 HandleCodeCompleteResults(this, CodeCompleter,
4632 CodeCompletionContext::CCC_Other,
4633 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004634}
4635
Douglas Gregorafc45782011-02-15 22:19:42 +00004636void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4637 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004638 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004639 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4640 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004641 Results.EnterNewScope();
4642
4643 // Add context-sensitive, Objective-C parameter-passing keywords.
4644 bool AddedInOut = false;
4645 if ((DS.getObjCDeclQualifier() &
4646 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4647 Results.AddResult("in");
4648 Results.AddResult("inout");
4649 AddedInOut = true;
4650 }
4651 if ((DS.getObjCDeclQualifier() &
4652 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4653 Results.AddResult("out");
4654 if (!AddedInOut)
4655 Results.AddResult("inout");
4656 }
4657 if ((DS.getObjCDeclQualifier() &
4658 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4659 ObjCDeclSpec::DQ_Oneway)) == 0) {
4660 Results.AddResult("bycopy");
4661 Results.AddResult("byref");
4662 Results.AddResult("oneway");
4663 }
4664
Douglas Gregorafc45782011-02-15 22:19:42 +00004665 // If we're completing the return type of an Objective-C method and the
4666 // identifier IBAction refers to a macro, provide a completion item for
4667 // an action, e.g.,
4668 // IBAction)<#selector#>:(id)sender
4669 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4670 Context.Idents.get("IBAction").hasMacroDefinition()) {
4671 typedef CodeCompletionString::Chunk Chunk;
4672 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4673 CXAvailability_Available);
4674 Builder.AddTypedTextChunk("IBAction");
4675 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4676 Builder.AddPlaceholderChunk("selector");
4677 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4678 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4679 Builder.AddTextChunk("id");
4680 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4681 Builder.AddTextChunk("sender");
4682 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4683 }
4684
Douglas Gregord32b0222010-08-24 01:06:58 +00004685 // Add various builtin type names and specifiers.
4686 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4687 Results.ExitScope();
4688
4689 // Add the various type names
4690 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4691 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4692 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4693 CodeCompleter->includeGlobals());
4694
4695 if (CodeCompleter->includeMacros())
4696 AddMacroResults(PP, Results);
4697
4698 HandleCodeCompleteResults(this, CodeCompleter,
4699 CodeCompletionContext::CCC_Type,
4700 Results.data(), Results.size());
4701}
4702
Douglas Gregor22f56992010-04-06 19:22:33 +00004703/// \brief When we have an expression with type "id", we may assume
4704/// that it has some more-specific class type based on knowledge of
4705/// common uses of Objective-C. This routine returns that class type,
4706/// or NULL if no better result could be determined.
4707static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004708 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004709 if (!Msg)
4710 return 0;
4711
4712 Selector Sel = Msg->getSelector();
4713 if (Sel.isNull())
4714 return 0;
4715
4716 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4717 if (!Id)
4718 return 0;
4719
4720 ObjCMethodDecl *Method = Msg->getMethodDecl();
4721 if (!Method)
4722 return 0;
4723
4724 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004725 ObjCInterfaceDecl *IFace = 0;
4726 switch (Msg->getReceiverKind()) {
4727 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004728 if (const ObjCObjectType *ObjType
4729 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4730 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004731 break;
4732
4733 case ObjCMessageExpr::Instance: {
4734 QualType T = Msg->getInstanceReceiver()->getType();
4735 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4736 IFace = Ptr->getInterfaceDecl();
4737 break;
4738 }
4739
4740 case ObjCMessageExpr::SuperInstance:
4741 case ObjCMessageExpr::SuperClass:
4742 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004743 }
4744
4745 if (!IFace)
4746 return 0;
4747
4748 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4749 if (Method->isInstanceMethod())
4750 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4751 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004752 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004753 .Case("autorelease", IFace)
4754 .Case("copy", IFace)
4755 .Case("copyWithZone", IFace)
4756 .Case("mutableCopy", IFace)
4757 .Case("mutableCopyWithZone", IFace)
4758 .Case("awakeFromCoder", IFace)
4759 .Case("replacementObjectFromCoder", IFace)
4760 .Case("class", IFace)
4761 .Case("classForCoder", IFace)
4762 .Case("superclass", Super)
4763 .Default(0);
4764
4765 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4766 .Case("new", IFace)
4767 .Case("alloc", IFace)
4768 .Case("allocWithZone", IFace)
4769 .Case("class", IFace)
4770 .Case("superclass", Super)
4771 .Default(0);
4772}
4773
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004774// Add a special completion for a message send to "super", which fills in the
4775// most likely case of forwarding all of our arguments to the superclass
4776// function.
4777///
4778/// \param S The semantic analysis object.
4779///
4780/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4781/// the "super" keyword. Otherwise, we just need to provide the arguments.
4782///
4783/// \param SelIdents The identifiers in the selector that have already been
4784/// provided as arguments for a send to "super".
4785///
4786/// \param NumSelIdents The number of identifiers in \p SelIdents.
4787///
4788/// \param Results The set of results to augment.
4789///
4790/// \returns the Objective-C method declaration that would be invoked by
4791/// this "super" completion. If NULL, no completion was added.
4792static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4793 IdentifierInfo **SelIdents,
4794 unsigned NumSelIdents,
4795 ResultBuilder &Results) {
4796 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4797 if (!CurMethod)
4798 return 0;
4799
4800 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4801 if (!Class)
4802 return 0;
4803
4804 // Try to find a superclass method with the same selector.
4805 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004806 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4807 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004808 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4809 CurMethod->isInstanceMethod());
4810
Douglas Gregor78bcd912011-02-16 00:51:18 +00004811 // Check in categories or class extensions.
4812 if (!SuperMethod) {
4813 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4814 Category = Category->getNextClassCategory())
4815 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4816 CurMethod->isInstanceMethod())))
4817 break;
4818 }
4819 }
4820
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004821 if (!SuperMethod)
4822 return 0;
4823
4824 // Check whether the superclass method has the same signature.
4825 if (CurMethod->param_size() != SuperMethod->param_size() ||
4826 CurMethod->isVariadic() != SuperMethod->isVariadic())
4827 return 0;
4828
4829 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4830 CurPEnd = CurMethod->param_end(),
4831 SuperP = SuperMethod->param_begin();
4832 CurP != CurPEnd; ++CurP, ++SuperP) {
4833 // Make sure the parameter types are compatible.
4834 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4835 (*SuperP)->getType()))
4836 return 0;
4837
4838 // Make sure we have a parameter name to forward!
4839 if (!(*CurP)->getIdentifier())
4840 return 0;
4841 }
4842
4843 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004844 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004845
4846 // Give this completion a return type.
Douglas Gregor8987b232011-09-27 23:30:47 +00004847 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
4848 Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004849
4850 // If we need the "super" keyword, add it (plus some spacing).
4851 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004852 Builder.AddTypedTextChunk("super");
4853 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004854 }
4855
4856 Selector Sel = CurMethod->getSelector();
4857 if (Sel.isUnarySelector()) {
4858 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004859 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004860 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004861 else
Douglas Gregordae68752011-02-01 22:57:45 +00004862 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004863 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004864 } else {
4865 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4866 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4867 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004868 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004869
4870 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004871 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004872 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004873 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004874 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004875 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004876 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004877 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004878 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004879 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004880 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004881 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004882 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004883 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004884 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004885 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004886 }
4887 }
4888 }
4889
Douglas Gregor218937c2011-02-01 19:23:04 +00004890 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004891 SuperMethod->isInstanceMethod()
4892 ? CXCursor_ObjCInstanceMethodDecl
4893 : CXCursor_ObjCClassMethodDecl));
4894 return SuperMethod;
4895}
4896
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004897void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004898 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004899 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4900 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004901 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004902
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004903 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4904 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004905 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4906 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004907
4908 // If we are in an Objective-C method inside a class that has a superclass,
4909 // add "super" as an option.
4910 if (ObjCMethodDecl *Method = getCurMethodDecl())
4911 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004912 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004913 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004914
4915 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4916 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004917
4918 Results.ExitScope();
4919
4920 if (CodeCompleter->includeMacros())
4921 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004922 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004923 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004924
4925}
4926
Douglas Gregor2725ca82010-04-21 19:57:20 +00004927void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4928 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004929 unsigned NumSelIdents,
4930 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004931 ObjCInterfaceDecl *CDecl = 0;
4932 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4933 // Figure out which interface we're in.
4934 CDecl = CurMethod->getClassInterface();
4935 if (!CDecl)
4936 return;
4937
4938 // Find the superclass of this class.
4939 CDecl = CDecl->getSuperClass();
4940 if (!CDecl)
4941 return;
4942
4943 if (CurMethod->isInstanceMethod()) {
4944 // We are inside an instance method, which means that the message
4945 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004946 // current object.
4947 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004948 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004949 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004950 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004951 }
4952
4953 // Fall through to send to the superclass in CDecl.
4954 } else {
4955 // "super" may be the name of a type or variable. Figure out which
4956 // it is.
4957 IdentifierInfo *Super = &Context.Idents.get("super");
4958 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4959 LookupOrdinaryName);
4960 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4961 // "super" names an interface. Use it.
4962 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004963 if (const ObjCObjectType *Iface
4964 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4965 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004966 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4967 // "super" names an unresolved type; we can't be more specific.
4968 } else {
4969 // Assume that "super" names some kind of value and parse that way.
4970 CXXScopeSpec SS;
4971 UnqualifiedId id;
4972 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004973 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004974 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004975 SelIdents, NumSelIdents,
4976 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004977 }
4978
4979 // Fall through
4980 }
4981
John McCallb3d87482010-08-24 05:47:05 +00004982 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004983 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004984 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004985 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004986 NumSelIdents, AtArgumentExpression,
4987 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004988}
4989
Douglas Gregorb9d77572010-09-21 00:03:25 +00004990/// \brief Given a set of code-completion results for the argument of a message
4991/// send, determine the preferred type (if any) for that argument expression.
4992static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4993 unsigned NumSelIdents) {
4994 typedef CodeCompletionResult Result;
4995 ASTContext &Context = Results.getSema().Context;
4996
4997 QualType PreferredType;
4998 unsigned BestPriority = CCP_Unlikely * 2;
4999 Result *ResultsData = Results.data();
5000 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5001 Result &R = ResultsData[I];
5002 if (R.Kind == Result::RK_Declaration &&
5003 isa<ObjCMethodDecl>(R.Declaration)) {
5004 if (R.Priority <= BestPriority) {
5005 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5006 if (NumSelIdents <= Method->param_size()) {
5007 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5008 ->getType();
5009 if (R.Priority < BestPriority || PreferredType.isNull()) {
5010 BestPriority = R.Priority;
5011 PreferredType = MyPreferredType;
5012 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5013 MyPreferredType)) {
5014 PreferredType = QualType();
5015 }
5016 }
5017 }
5018 }
5019 }
5020
5021 return PreferredType;
5022}
5023
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005024static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5025 ParsedType Receiver,
5026 IdentifierInfo **SelIdents,
5027 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005028 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005029 bool IsSuper,
5030 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005031 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00005032 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005033
Douglas Gregor24a069f2009-11-17 17:59:40 +00005034 // If the given name refers to an interface type, retrieve the
5035 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00005036 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005037 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005038 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00005039 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5040 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00005041 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005042
Douglas Gregor36ecb042009-11-17 23:22:23 +00005043 // Add all of the factory methods in this Objective-C class, its protocols,
5044 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00005045 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005046
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005047 // If this is a send-to-super, try to add the special "super" send
5048 // completion.
5049 if (IsSuper) {
5050 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005051 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5052 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005053 Results.Ignore(SuperMethod);
5054 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005055
Douglas Gregor265f7492010-08-27 15:29:55 +00005056 // If we're inside an Objective-C method definition, prefer its selector to
5057 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005058 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005059 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005060
Douglas Gregord36adf52010-09-16 16:06:31 +00005061 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005062 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005063 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005064 SemaRef.CurContext, Selectors, AtArgumentExpression,
5065 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005066 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005067 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005068
Douglas Gregor719770d2010-04-06 17:30:22 +00005069 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005070 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005071 if (SemaRef.ExternalSource) {
5072 for (uint32_t I = 0,
5073 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005074 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005075 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5076 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005077 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005078
5079 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005080 }
5081 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005082
5083 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5084 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005085 M != MEnd; ++M) {
5086 for (ObjCMethodList *MethList = &M->second.second;
5087 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005088 MethList = MethList->Next) {
5089 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5090 NumSelIdents))
5091 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005092
Douglas Gregor13438f92010-04-06 16:40:00 +00005093 Result R(MethList->Method, 0);
5094 R.StartParameter = NumSelIdents;
5095 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005096 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005097 }
5098 }
5099 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005100
5101 Results.ExitScope();
5102}
Douglas Gregor13438f92010-04-06 16:40:00 +00005103
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005104void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5105 IdentifierInfo **SelIdents,
5106 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005107 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005108 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005109
5110 QualType T = this->GetTypeFromParser(Receiver);
5111
Douglas Gregor218937c2011-02-01 19:23:04 +00005112 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005113 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005114 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005115
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005116 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5117 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005118
5119 // If we're actually at the argument expression (rather than prior to the
5120 // selector), we're actually performing code completion for an expression.
5121 // Determine whether we have a single, best method. If so, we can
5122 // code-complete the expression using the corresponding parameter type as
5123 // our preferred type, improving completion results.
5124 if (AtArgumentExpression) {
5125 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005126 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005127 if (PreferredType.isNull())
5128 CodeCompleteOrdinaryName(S, PCC_Expression);
5129 else
5130 CodeCompleteExpression(S, PreferredType);
5131 return;
5132 }
5133
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005134 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005135 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005136 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005137}
5138
Richard Trieuf81e5a92011-09-09 02:00:50 +00005139void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005140 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005141 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005142 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005143 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005144 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005145
5146 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005147
Douglas Gregor36ecb042009-11-17 23:22:23 +00005148 // If necessary, apply function/array conversion to the receiver.
5149 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005150 if (RecExpr) {
5151 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5152 if (Conv.isInvalid()) // conversion failed. bail.
5153 return;
5154 RecExpr = Conv.take();
5155 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005156 QualType ReceiverType = RecExpr? RecExpr->getType()
5157 : Super? Context.getObjCObjectPointerType(
5158 Context.getObjCInterfaceType(Super))
5159 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005160
Douglas Gregorda892642010-11-08 21:12:30 +00005161 // If we're messaging an expression with type "id" or "Class", check
5162 // whether we know something special about the receiver that allows
5163 // us to assume a more-specific receiver type.
5164 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5165 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5166 if (ReceiverType->isObjCClassType())
5167 return CodeCompleteObjCClassMessage(S,
5168 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5169 SelIdents, NumSelIdents,
5170 AtArgumentExpression, Super);
5171
5172 ReceiverType = Context.getObjCObjectPointerType(
5173 Context.getObjCInterfaceType(IFace));
5174 }
5175
Douglas Gregor36ecb042009-11-17 23:22:23 +00005176 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005177 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005178 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005179 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005180
Douglas Gregor36ecb042009-11-17 23:22:23 +00005181 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005182
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005183 // If this is a send-to-super, try to add the special "super" send
5184 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005185 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005186 if (ObjCMethodDecl *SuperMethod
5187 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5188 Results))
5189 Results.Ignore(SuperMethod);
5190 }
5191
Douglas Gregor265f7492010-08-27 15:29:55 +00005192 // If we're inside an Objective-C method definition, prefer its selector to
5193 // others.
5194 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5195 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005196
Douglas Gregord36adf52010-09-16 16:06:31 +00005197 // Keep track of the selectors we've already added.
5198 VisitedSelectorSet Selectors;
5199
Douglas Gregorf74a4192009-11-18 00:06:18 +00005200 // Handle messages to Class. This really isn't a message to an instance
5201 // method, so we treat it the same way we would treat a message send to a
5202 // class method.
5203 if (ReceiverType->isObjCClassType() ||
5204 ReceiverType->isObjCQualifiedClassType()) {
5205 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5206 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005207 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005208 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005209 }
5210 }
5211 // Handle messages to a qualified ID ("id<foo>").
5212 else if (const ObjCObjectPointerType *QualID
5213 = ReceiverType->getAsObjCQualifiedIdType()) {
5214 // Search protocols for instance methods.
5215 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5216 E = QualID->qual_end();
5217 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005218 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005219 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005220 }
5221 // Handle messages to a pointer to interface type.
5222 else if (const ObjCObjectPointerType *IFacePtr
5223 = ReceiverType->getAsObjCInterfacePointerType()) {
5224 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005225 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005226 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5227 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005228
5229 // Search protocols for instance methods.
5230 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5231 E = IFacePtr->qual_end();
5232 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005233 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005234 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005235 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005236 // Handle messages to "id".
5237 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005238 // We're messaging "id", so provide all instance methods we know
5239 // about as code-completion results.
5240
5241 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005242 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005243 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005244 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5245 I != N; ++I) {
5246 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005247 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005248 continue;
5249
Sebastian Redldb9d2142010-08-02 23:18:59 +00005250 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005251 }
5252 }
5253
Sebastian Redldb9d2142010-08-02 23:18:59 +00005254 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5255 MEnd = MethodPool.end();
5256 M != MEnd; ++M) {
5257 for (ObjCMethodList *MethList = &M->second.first;
5258 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005259 MethList = MethList->Next) {
5260 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5261 NumSelIdents))
5262 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005263
5264 if (!Selectors.insert(MethList->Method->getSelector()))
5265 continue;
5266
Douglas Gregor13438f92010-04-06 16:40:00 +00005267 Result R(MethList->Method, 0);
5268 R.StartParameter = NumSelIdents;
5269 R.AllParametersAreInformative = false;
5270 Results.MaybeAddResult(R, CurContext);
5271 }
5272 }
5273 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005274 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005275
5276
5277 // If we're actually at the argument expression (rather than prior to the
5278 // selector), we're actually performing code completion for an expression.
5279 // Determine whether we have a single, best method. If so, we can
5280 // code-complete the expression using the corresponding parameter type as
5281 // our preferred type, improving completion results.
5282 if (AtArgumentExpression) {
5283 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5284 NumSelIdents);
5285 if (PreferredType.isNull())
5286 CodeCompleteOrdinaryName(S, PCC_Expression);
5287 else
5288 CodeCompleteExpression(S, PreferredType);
5289 return;
5290 }
5291
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005292 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005293 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005294 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005295}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005296
Douglas Gregorfb629412010-08-23 21:17:50 +00005297void Sema::CodeCompleteObjCForCollection(Scope *S,
5298 DeclGroupPtrTy IterationVar) {
5299 CodeCompleteExpressionData Data;
5300 Data.ObjCCollection = true;
5301
5302 if (IterationVar.getAsOpaquePtr()) {
5303 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5304 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5305 if (*I)
5306 Data.IgnoreDecls.push_back(*I);
5307 }
5308 }
5309
5310 CodeCompleteExpression(S, Data);
5311}
5312
Douglas Gregor458433d2010-08-26 15:07:07 +00005313void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5314 unsigned NumSelIdents) {
5315 // If we have an external source, load the entire class method
5316 // pool from the AST file.
5317 if (ExternalSource) {
5318 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5319 I != N; ++I) {
5320 Selector Sel = ExternalSource->GetExternalSelector(I);
5321 if (Sel.isNull() || MethodPool.count(Sel))
5322 continue;
5323
5324 ReadMethodPool(Sel);
5325 }
5326 }
5327
Douglas Gregor218937c2011-02-01 19:23:04 +00005328 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5329 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005330 Results.EnterNewScope();
5331 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5332 MEnd = MethodPool.end();
5333 M != MEnd; ++M) {
5334
5335 Selector Sel = M->first;
5336 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5337 continue;
5338
Douglas Gregor218937c2011-02-01 19:23:04 +00005339 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005340 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005341 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005342 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005343 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005344 continue;
5345 }
5346
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005347 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005348 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005349 if (I == NumSelIdents) {
5350 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005351 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005352 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005353 Accumulator.clear();
5354 }
5355 }
5356
Benjamin Kramera0651c52011-07-26 16:59:25 +00005357 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005358 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005359 }
Douglas Gregordae68752011-02-01 22:57:45 +00005360 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005361 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005362 }
5363 Results.ExitScope();
5364
5365 HandleCodeCompleteResults(this, CodeCompleter,
5366 CodeCompletionContext::CCC_SelectorName,
5367 Results.data(), Results.size());
5368}
5369
Douglas Gregor55385fe2009-11-18 04:19:12 +00005370/// \brief Add all of the protocol declarations that we find in the given
5371/// (translation unit) context.
5372static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005373 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005374 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005375 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005376
5377 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5378 DEnd = Ctx->decls_end();
5379 D != DEnd; ++D) {
5380 // Record any protocols we find.
5381 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005382 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005383 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005384
5385 // Record any forward-declared protocols we find.
5386 if (ObjCForwardProtocolDecl *Forward
5387 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5388 for (ObjCForwardProtocolDecl::protocol_iterator
5389 P = Forward->protocol_begin(),
5390 PEnd = Forward->protocol_end();
5391 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005392 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005393 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005394 }
5395 }
5396}
5397
5398void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5399 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005400 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5401 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005402
Douglas Gregor70c23352010-12-09 21:44:02 +00005403 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5404 Results.EnterNewScope();
5405
5406 // Tell the result set to ignore all of the protocols we have
5407 // already seen.
5408 // FIXME: This doesn't work when caching code-completion results.
5409 for (unsigned I = 0; I != NumProtocols; ++I)
5410 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5411 Protocols[I].second))
5412 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005413
Douglas Gregor70c23352010-12-09 21:44:02 +00005414 // Add all protocols.
5415 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5416 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005417
Douglas Gregor70c23352010-12-09 21:44:02 +00005418 Results.ExitScope();
5419 }
5420
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005421 HandleCodeCompleteResults(this, CodeCompleter,
5422 CodeCompletionContext::CCC_ObjCProtocolName,
5423 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005424}
5425
5426void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005427 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5428 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005429
Douglas Gregor70c23352010-12-09 21:44:02 +00005430 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5431 Results.EnterNewScope();
5432
5433 // Add all protocols.
5434 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5435 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005436
Douglas Gregor70c23352010-12-09 21:44:02 +00005437 Results.ExitScope();
5438 }
5439
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005440 HandleCodeCompleteResults(this, CodeCompleter,
5441 CodeCompletionContext::CCC_ObjCProtocolName,
5442 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005443}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005444
5445/// \brief Add all of the Objective-C interface declarations that we find in
5446/// the given (translation unit) context.
5447static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5448 bool OnlyForwardDeclarations,
5449 bool OnlyUnimplemented,
5450 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005451 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005452
5453 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5454 DEnd = Ctx->decls_end();
5455 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005456 // Record any interfaces we find.
5457 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5458 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5459 (!OnlyUnimplemented || !Class->getImplementation()))
5460 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005461
5462 // Record any forward-declared interfaces we find.
5463 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005464 ObjCInterfaceDecl *IDecl = Forward->getForwardInterfaceDecl();
5465 if ((!OnlyForwardDeclarations || IDecl->isForwardDecl()) &&
5466 (!OnlyUnimplemented || !IDecl->getImplementation()))
5467 Results.AddResult(Result(IDecl, 0), CurContext,
5468 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005469 }
5470 }
5471}
5472
5473void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005474 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5475 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005476 Results.EnterNewScope();
5477
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005478 if (CodeCompleter->includeGlobals()) {
5479 // Add all classes.
5480 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5481 false, Results);
5482 }
5483
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005484 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005485
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005486 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005487 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005488 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005489}
5490
Douglas Gregorc83c6872010-04-15 22:33:43 +00005491void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5492 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005493 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005494 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005495 Results.EnterNewScope();
5496
5497 // Make sure that we ignore the class we're currently defining.
5498 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005499 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005500 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005501 Results.Ignore(CurClass);
5502
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005503 if (CodeCompleter->includeGlobals()) {
5504 // Add all classes.
5505 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5506 false, Results);
5507 }
5508
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005509 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005510
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005511 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005512 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005513 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005514}
5515
5516void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005517 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5518 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005519 Results.EnterNewScope();
5520
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005521 if (CodeCompleter->includeGlobals()) {
5522 // Add all unimplemented classes.
5523 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5524 true, Results);
5525 }
5526
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005527 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005528
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005529 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005530 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005531 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005532}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005533
5534void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005535 IdentifierInfo *ClassName,
5536 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005537 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005538
Douglas Gregor218937c2011-02-01 19:23:04 +00005539 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005540 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005541
5542 // Ignore any categories we find that have already been implemented by this
5543 // interface.
5544 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5545 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005546 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005547 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5548 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5549 Category = Category->getNextClassCategory())
5550 CategoryNames.insert(Category->getIdentifier());
5551
5552 // Add all of the categories we know about.
5553 Results.EnterNewScope();
5554 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5555 for (DeclContext::decl_iterator D = TU->decls_begin(),
5556 DEnd = TU->decls_end();
5557 D != DEnd; ++D)
5558 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5559 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005560 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005561 Results.ExitScope();
5562
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005563 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005564 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005565 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005566}
5567
5568void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005569 IdentifierInfo *ClassName,
5570 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005571 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005572
5573 // Find the corresponding interface. If we couldn't find the interface, the
5574 // program itself is ill-formed. However, we'll try to be helpful still by
5575 // providing the list of all of the categories we know about.
5576 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005577 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005578 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5579 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005580 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005581
Douglas Gregor218937c2011-02-01 19:23:04 +00005582 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005583 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005584
5585 // Add all of the categories that have have corresponding interface
5586 // declarations in this class and any of its superclasses, except for
5587 // already-implemented categories in the class itself.
5588 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5589 Results.EnterNewScope();
5590 bool IgnoreImplemented = true;
5591 while (Class) {
5592 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5593 Category = Category->getNextClassCategory())
5594 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5595 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005596 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005597
5598 Class = Class->getSuperClass();
5599 IgnoreImplemented = false;
5600 }
5601 Results.ExitScope();
5602
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005603 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005604 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005605 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005606}
Douglas Gregor322328b2009-11-18 22:32:06 +00005607
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005608void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005609 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005610 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5611 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005612
5613 // Figure out where this @synthesize lives.
5614 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005615 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005616 if (!Container ||
5617 (!isa<ObjCImplementationDecl>(Container) &&
5618 !isa<ObjCCategoryImplDecl>(Container)))
5619 return;
5620
5621 // Ignore any properties that have already been implemented.
5622 for (DeclContext::decl_iterator D = Container->decls_begin(),
5623 DEnd = Container->decls_end();
5624 D != DEnd; ++D)
5625 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5626 Results.Ignore(PropertyImpl->getPropertyDecl());
5627
5628 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005629 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005630 Results.EnterNewScope();
5631 if (ObjCImplementationDecl *ClassImpl
5632 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005633 AddObjCProperties(ClassImpl->getClassInterface(), false,
5634 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005635 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005636 else
5637 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005638 false, /*AllowNullaryMethods=*/false, CurContext,
5639 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005640 Results.ExitScope();
5641
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005642 HandleCodeCompleteResults(this, CodeCompleter,
5643 CodeCompletionContext::CCC_Other,
5644 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005645}
5646
5647void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005648 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005649 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005650 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5651 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005652
5653 // Figure out where this @synthesize lives.
5654 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005655 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005656 if (!Container ||
5657 (!isa<ObjCImplementationDecl>(Container) &&
5658 !isa<ObjCCategoryImplDecl>(Container)))
5659 return;
5660
5661 // Figure out which interface we're looking into.
5662 ObjCInterfaceDecl *Class = 0;
5663 if (ObjCImplementationDecl *ClassImpl
5664 = dyn_cast<ObjCImplementationDecl>(Container))
5665 Class = ClassImpl->getClassInterface();
5666 else
5667 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5668 ->getClassInterface();
5669
Douglas Gregore8426052011-04-18 14:40:46 +00005670 // Determine the type of the property we're synthesizing.
5671 QualType PropertyType = Context.getObjCIdType();
5672 if (Class) {
5673 if (ObjCPropertyDecl *Property
5674 = Class->FindPropertyDeclaration(PropertyName)) {
5675 PropertyType
5676 = Property->getType().getNonReferenceType().getUnqualifiedType();
5677
5678 // Give preference to ivars
5679 Results.setPreferredType(PropertyType);
5680 }
5681 }
5682
Douglas Gregor322328b2009-11-18 22:32:06 +00005683 // Add all of the instance variables in this class and its superclasses.
5684 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005685 bool SawSimilarlyNamedIvar = false;
5686 std::string NameWithPrefix;
5687 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005688 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005689 std::string NameWithSuffix = PropertyName->getName().str();
5690 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005691 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005692 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5693 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005694 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5695
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005696 // Determine whether we've seen an ivar with a name similar to the
5697 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005698 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005699 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005700 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005701 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005702
5703 // Reduce the priority of this result by one, to give it a slight
5704 // advantage over other results whose names don't match so closely.
5705 if (Results.size() &&
5706 Results.data()[Results.size() - 1].Kind
5707 == CodeCompletionResult::RK_Declaration &&
5708 Results.data()[Results.size() - 1].Declaration == Ivar)
5709 Results.data()[Results.size() - 1].Priority--;
5710 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005711 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005712 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005713
5714 if (!SawSimilarlyNamedIvar) {
5715 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005716 // an ivar of the appropriate type.
5717 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005718 typedef CodeCompletionResult Result;
5719 CodeCompletionAllocator &Allocator = Results.getAllocator();
5720 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5721
Douglas Gregor8987b232011-09-27 23:30:47 +00005722 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8426052011-04-18 14:40:46 +00005723 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005724 Policy, Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005725 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5726 Results.AddResult(Result(Builder.TakeString(), Priority,
5727 CXCursor_ObjCIvarDecl));
5728 }
5729
Douglas Gregor322328b2009-11-18 22:32:06 +00005730 Results.ExitScope();
5731
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005732 HandleCodeCompleteResults(this, CodeCompleter,
5733 CodeCompletionContext::CCC_Other,
5734 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005735}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005736
Douglas Gregor408be5a2010-08-25 01:08:01 +00005737// Mapping from selectors to the methods that implement that selector, along
5738// with the "in original class" flag.
5739typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5740 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005741
5742/// \brief Find all of the methods that reside in the given container
5743/// (and its superclasses, protocols, etc.) that meet the given
5744/// criteria. Insert those methods into the map of known methods,
5745/// indexed by selector so they can be easily found.
5746static void FindImplementableMethods(ASTContext &Context,
5747 ObjCContainerDecl *Container,
5748 bool WantInstanceMethods,
5749 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005750 KnownMethodsMap &KnownMethods,
5751 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005752 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5753 // Recurse into protocols.
5754 const ObjCList<ObjCProtocolDecl> &Protocols
5755 = IFace->getReferencedProtocols();
5756 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005757 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005758 I != E; ++I)
5759 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005760 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005761
Douglas Gregorea766182010-10-18 18:21:28 +00005762 // Add methods from any class extensions and categories.
5763 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5764 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005765 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5766 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005767 KnownMethods, false);
5768
5769 // Visit the superclass.
5770 if (IFace->getSuperClass())
5771 FindImplementableMethods(Context, IFace->getSuperClass(),
5772 WantInstanceMethods, ReturnType,
5773 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005774 }
5775
5776 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5777 // Recurse into protocols.
5778 const ObjCList<ObjCProtocolDecl> &Protocols
5779 = Category->getReferencedProtocols();
5780 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005781 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005782 I != E; ++I)
5783 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005784 KnownMethods, InOriginalClass);
5785
5786 // If this category is the original class, jump to the interface.
5787 if (InOriginalClass && Category->getClassInterface())
5788 FindImplementableMethods(Context, Category->getClassInterface(),
5789 WantInstanceMethods, ReturnType, KnownMethods,
5790 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005791 }
5792
5793 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5794 // Recurse into protocols.
5795 const ObjCList<ObjCProtocolDecl> &Protocols
5796 = Protocol->getReferencedProtocols();
5797 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5798 E = Protocols.end();
5799 I != E; ++I)
5800 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005801 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005802 }
5803
5804 // Add methods in this container. This operation occurs last because
5805 // we want the methods from this container to override any methods
5806 // we've previously seen with the same selector.
5807 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5808 MEnd = Container->meth_end();
5809 M != MEnd; ++M) {
5810 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5811 if (!ReturnType.isNull() &&
5812 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5813 continue;
5814
Douglas Gregor408be5a2010-08-25 01:08:01 +00005815 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005816 }
5817 }
5818}
5819
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005820/// \brief Add the parenthesized return or parameter type chunk to a code
5821/// completion string.
5822static void AddObjCPassingTypeChunk(QualType Type,
5823 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005824 const PrintingPolicy &Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005825 CodeCompletionBuilder &Builder) {
5826 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor8987b232011-09-27 23:30:47 +00005827 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005828 Builder.getAllocator()));
5829 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5830}
5831
5832/// \brief Determine whether the given class is or inherits from a class by
5833/// the given name.
5834static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005835 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005836 if (!Class)
5837 return false;
5838
5839 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5840 return true;
5841
5842 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5843}
5844
5845/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5846/// Key-Value Observing (KVO).
5847static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5848 bool IsInstanceMethod,
5849 QualType ReturnType,
5850 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005851 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005852 ResultBuilder &Results) {
5853 IdentifierInfo *PropName = Property->getIdentifier();
5854 if (!PropName || PropName->getLength() == 0)
5855 return;
5856
Douglas Gregor8987b232011-09-27 23:30:47 +00005857 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5858
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005859 // Builder that will create each code completion.
5860 typedef CodeCompletionResult Result;
5861 CodeCompletionAllocator &Allocator = Results.getAllocator();
5862 CodeCompletionBuilder Builder(Allocator);
5863
5864 // The selector table.
5865 SelectorTable &Selectors = Context.Selectors;
5866
5867 // The property name, copied into the code completion allocation region
5868 // on demand.
5869 struct KeyHolder {
5870 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005871 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005872 const char *CopiedKey;
5873
Chris Lattner5f9e2722011-07-23 10:55:15 +00005874 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005875 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5876
5877 operator const char *() {
5878 if (CopiedKey)
5879 return CopiedKey;
5880
5881 return CopiedKey = Allocator.CopyString(Key);
5882 }
5883 } Key(Allocator, PropName->getName());
5884
5885 // The uppercased name of the property name.
5886 std::string UpperKey = PropName->getName();
5887 if (!UpperKey.empty())
5888 UpperKey[0] = toupper(UpperKey[0]);
5889
5890 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5891 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5892 Property->getType());
5893 bool ReturnTypeMatchesVoid
5894 = ReturnType.isNull() || ReturnType->isVoidType();
5895
5896 // Add the normal accessor -(type)key.
5897 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005898 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005899 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5900 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00005901 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005902
5903 Builder.AddTypedTextChunk(Key);
5904 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5905 CXCursor_ObjCInstanceMethodDecl));
5906 }
5907
5908 // If we have an integral or boolean property (or the user has provided
5909 // an integral or boolean return type), add the accessor -(type)isKey.
5910 if (IsInstanceMethod &&
5911 ((!ReturnType.isNull() &&
5912 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5913 (ReturnType.isNull() &&
5914 (Property->getType()->isIntegerType() ||
5915 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005916 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005917 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005918 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005919 if (ReturnType.isNull()) {
5920 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5921 Builder.AddTextChunk("BOOL");
5922 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5923 }
5924
5925 Builder.AddTypedTextChunk(
5926 Allocator.CopyString(SelectorId->getName()));
5927 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5928 CXCursor_ObjCInstanceMethodDecl));
5929 }
5930 }
5931
5932 // Add the normal mutator.
5933 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5934 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005935 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005936 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005937 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005938 if (ReturnType.isNull()) {
5939 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5940 Builder.AddTextChunk("void");
5941 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5942 }
5943
5944 Builder.AddTypedTextChunk(
5945 Allocator.CopyString(SelectorId->getName()));
5946 Builder.AddTypedTextChunk(":");
Douglas Gregor8987b232011-09-27 23:30:47 +00005947 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005948 Builder.AddTextChunk(Key);
5949 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5950 CXCursor_ObjCInstanceMethodDecl));
5951 }
5952 }
5953
5954 // Indexed and unordered accessors
5955 unsigned IndexedGetterPriority = CCP_CodePattern;
5956 unsigned IndexedSetterPriority = CCP_CodePattern;
5957 unsigned UnorderedGetterPriority = CCP_CodePattern;
5958 unsigned UnorderedSetterPriority = CCP_CodePattern;
5959 if (const ObjCObjectPointerType *ObjCPointer
5960 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5961 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5962 // If this interface type is not provably derived from a known
5963 // collection, penalize the corresponding completions.
5964 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5965 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5966 if (!InheritsFromClassNamed(IFace, "NSArray"))
5967 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5968 }
5969
5970 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5971 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5972 if (!InheritsFromClassNamed(IFace, "NSSet"))
5973 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5974 }
5975 }
5976 } else {
5977 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5978 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5979 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5980 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5981 }
5982
5983 // Add -(NSUInteger)countOf<key>
5984 if (IsInstanceMethod &&
5985 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005986 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005987 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005988 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005989 if (ReturnType.isNull()) {
5990 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5991 Builder.AddTextChunk("NSUInteger");
5992 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5993 }
5994
5995 Builder.AddTypedTextChunk(
5996 Allocator.CopyString(SelectorId->getName()));
5997 Results.AddResult(Result(Builder.TakeString(),
5998 std::min(IndexedGetterPriority,
5999 UnorderedGetterPriority),
6000 CXCursor_ObjCInstanceMethodDecl));
6001 }
6002 }
6003
6004 // Indexed getters
6005 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6006 if (IsInstanceMethod &&
6007 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00006008 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006009 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006010 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006011 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006012 if (ReturnType.isNull()) {
6013 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6014 Builder.AddTextChunk("id");
6015 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6016 }
6017
6018 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6019 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6020 Builder.AddTextChunk("NSUInteger");
6021 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6022 Builder.AddTextChunk("index");
6023 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6024 CXCursor_ObjCInstanceMethodDecl));
6025 }
6026 }
6027
6028 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6029 if (IsInstanceMethod &&
6030 (ReturnType.isNull() ||
6031 (ReturnType->isObjCObjectPointerType() &&
6032 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6033 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6034 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006035 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006036 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006037 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006038 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006039 if (ReturnType.isNull()) {
6040 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6041 Builder.AddTextChunk("NSArray *");
6042 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6043 }
6044
6045 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6046 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6047 Builder.AddTextChunk("NSIndexSet *");
6048 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6049 Builder.AddTextChunk("indexes");
6050 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6051 CXCursor_ObjCInstanceMethodDecl));
6052 }
6053 }
6054
6055 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6056 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006057 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006058 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006059 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006060 &Context.Idents.get("range")
6061 };
6062
Douglas Gregore74c25c2011-05-04 23:50:46 +00006063 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006064 if (ReturnType.isNull()) {
6065 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6066 Builder.AddTextChunk("void");
6067 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6068 }
6069
6070 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6071 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6072 Builder.AddPlaceholderChunk("object-type");
6073 Builder.AddTextChunk(" **");
6074 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6075 Builder.AddTextChunk("buffer");
6076 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6077 Builder.AddTypedTextChunk("range:");
6078 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6079 Builder.AddTextChunk("NSRange");
6080 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6081 Builder.AddTextChunk("inRange");
6082 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6083 CXCursor_ObjCInstanceMethodDecl));
6084 }
6085 }
6086
6087 // Mutable indexed accessors
6088
6089 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6090 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006091 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006092 IdentifierInfo *SelectorIds[2] = {
6093 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006094 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006095 };
6096
Douglas Gregore74c25c2011-05-04 23:50:46 +00006097 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006098 if (ReturnType.isNull()) {
6099 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6100 Builder.AddTextChunk("void");
6101 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6102 }
6103
6104 Builder.AddTypedTextChunk("insertObject:");
6105 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6106 Builder.AddPlaceholderChunk("object-type");
6107 Builder.AddTextChunk(" *");
6108 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6109 Builder.AddTextChunk("object");
6110 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6111 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6112 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6113 Builder.AddPlaceholderChunk("NSUInteger");
6114 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6115 Builder.AddTextChunk("index");
6116 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6117 CXCursor_ObjCInstanceMethodDecl));
6118 }
6119 }
6120
6121 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6122 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006123 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006124 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006125 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006126 &Context.Idents.get("atIndexes")
6127 };
6128
Douglas Gregore74c25c2011-05-04 23:50:46 +00006129 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006130 if (ReturnType.isNull()) {
6131 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6132 Builder.AddTextChunk("void");
6133 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6134 }
6135
6136 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6137 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6138 Builder.AddTextChunk("NSArray *");
6139 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6140 Builder.AddTextChunk("array");
6141 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6142 Builder.AddTypedTextChunk("atIndexes:");
6143 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6144 Builder.AddPlaceholderChunk("NSIndexSet *");
6145 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6146 Builder.AddTextChunk("indexes");
6147 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6148 CXCursor_ObjCInstanceMethodDecl));
6149 }
6150 }
6151
6152 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6153 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006154 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006155 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006156 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006157 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006158 if (ReturnType.isNull()) {
6159 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6160 Builder.AddTextChunk("void");
6161 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6162 }
6163
6164 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6165 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6166 Builder.AddTextChunk("NSUInteger");
6167 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6168 Builder.AddTextChunk("index");
6169 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6170 CXCursor_ObjCInstanceMethodDecl));
6171 }
6172 }
6173
6174 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6175 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006176 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006177 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006178 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006179 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006180 if (ReturnType.isNull()) {
6181 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6182 Builder.AddTextChunk("void");
6183 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6184 }
6185
6186 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6187 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6188 Builder.AddTextChunk("NSIndexSet *");
6189 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6190 Builder.AddTextChunk("indexes");
6191 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6192 CXCursor_ObjCInstanceMethodDecl));
6193 }
6194 }
6195
6196 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6197 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006198 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006199 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006200 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006201 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006202 &Context.Idents.get("withObject")
6203 };
6204
Douglas Gregore74c25c2011-05-04 23:50:46 +00006205 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006206 if (ReturnType.isNull()) {
6207 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6208 Builder.AddTextChunk("void");
6209 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6210 }
6211
6212 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6213 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6214 Builder.AddPlaceholderChunk("NSUInteger");
6215 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6216 Builder.AddTextChunk("index");
6217 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6218 Builder.AddTypedTextChunk("withObject:");
6219 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6220 Builder.AddTextChunk("id");
6221 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6222 Builder.AddTextChunk("object");
6223 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6224 CXCursor_ObjCInstanceMethodDecl));
6225 }
6226 }
6227
6228 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6229 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006230 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006231 = (Twine("replace") + UpperKey + "AtIndexes").str();
6232 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006233 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006234 &Context.Idents.get(SelectorName1),
6235 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006236 };
6237
Douglas Gregore74c25c2011-05-04 23:50:46 +00006238 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006239 if (ReturnType.isNull()) {
6240 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6241 Builder.AddTextChunk("void");
6242 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6243 }
6244
6245 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6246 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6247 Builder.AddPlaceholderChunk("NSIndexSet *");
6248 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6249 Builder.AddTextChunk("indexes");
6250 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6251 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6252 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6253 Builder.AddTextChunk("NSArray *");
6254 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6255 Builder.AddTextChunk("array");
6256 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6257 CXCursor_ObjCInstanceMethodDecl));
6258 }
6259 }
6260
6261 // Unordered getters
6262 // - (NSEnumerator *)enumeratorOfKey
6263 if (IsInstanceMethod &&
6264 (ReturnType.isNull() ||
6265 (ReturnType->isObjCObjectPointerType() &&
6266 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6267 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6268 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006269 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006270 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006271 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006272 if (ReturnType.isNull()) {
6273 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6274 Builder.AddTextChunk("NSEnumerator *");
6275 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6276 }
6277
6278 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6279 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6280 CXCursor_ObjCInstanceMethodDecl));
6281 }
6282 }
6283
6284 // - (type *)memberOfKey:(type *)object
6285 if (IsInstanceMethod &&
6286 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006287 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006288 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006289 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006290 if (ReturnType.isNull()) {
6291 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6292 Builder.AddPlaceholderChunk("object-type");
6293 Builder.AddTextChunk(" *");
6294 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6295 }
6296
6297 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6298 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6299 if (ReturnType.isNull()) {
6300 Builder.AddPlaceholderChunk("object-type");
6301 Builder.AddTextChunk(" *");
6302 } else {
6303 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006304 Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006305 Builder.getAllocator()));
6306 }
6307 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6308 Builder.AddTextChunk("object");
6309 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6310 CXCursor_ObjCInstanceMethodDecl));
6311 }
6312 }
6313
6314 // Mutable unordered accessors
6315 // - (void)addKeyObject:(type *)object
6316 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006317 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006318 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006319 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006320 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006321 if (ReturnType.isNull()) {
6322 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6323 Builder.AddTextChunk("void");
6324 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6325 }
6326
6327 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6328 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6329 Builder.AddPlaceholderChunk("object-type");
6330 Builder.AddTextChunk(" *");
6331 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6332 Builder.AddTextChunk("object");
6333 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6334 CXCursor_ObjCInstanceMethodDecl));
6335 }
6336 }
6337
6338 // - (void)addKey:(NSSet *)objects
6339 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006340 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006341 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006342 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006343 if (ReturnType.isNull()) {
6344 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6345 Builder.AddTextChunk("void");
6346 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6347 }
6348
6349 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6350 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6351 Builder.AddTextChunk("NSSet *");
6352 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6353 Builder.AddTextChunk("objects");
6354 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6355 CXCursor_ObjCInstanceMethodDecl));
6356 }
6357 }
6358
6359 // - (void)removeKeyObject:(type *)object
6360 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006361 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006362 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006363 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006364 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006365 if (ReturnType.isNull()) {
6366 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6367 Builder.AddTextChunk("void");
6368 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6369 }
6370
6371 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6372 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6373 Builder.AddPlaceholderChunk("object-type");
6374 Builder.AddTextChunk(" *");
6375 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6376 Builder.AddTextChunk("object");
6377 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6378 CXCursor_ObjCInstanceMethodDecl));
6379 }
6380 }
6381
6382 // - (void)removeKey:(NSSet *)objects
6383 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006384 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006385 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006386 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006387 if (ReturnType.isNull()) {
6388 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6389 Builder.AddTextChunk("void");
6390 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6391 }
6392
6393 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6394 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6395 Builder.AddTextChunk("NSSet *");
6396 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6397 Builder.AddTextChunk("objects");
6398 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6399 CXCursor_ObjCInstanceMethodDecl));
6400 }
6401 }
6402
6403 // - (void)intersectKey:(NSSet *)objects
6404 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006405 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006406 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006407 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006408 if (ReturnType.isNull()) {
6409 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6410 Builder.AddTextChunk("void");
6411 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6412 }
6413
6414 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6415 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6416 Builder.AddTextChunk("NSSet *");
6417 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6418 Builder.AddTextChunk("objects");
6419 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6420 CXCursor_ObjCInstanceMethodDecl));
6421 }
6422 }
6423
6424 // Key-Value Observing
6425 // + (NSSet *)keyPathsForValuesAffectingKey
6426 if (!IsInstanceMethod &&
6427 (ReturnType.isNull() ||
6428 (ReturnType->isObjCObjectPointerType() &&
6429 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6430 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6431 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006432 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006433 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006434 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006435 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006436 if (ReturnType.isNull()) {
6437 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6438 Builder.AddTextChunk("NSSet *");
6439 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6440 }
6441
6442 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6443 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006444 CXCursor_ObjCClassMethodDecl));
6445 }
6446 }
6447
6448 // + (BOOL)automaticallyNotifiesObserversForKey
6449 if (!IsInstanceMethod &&
6450 (ReturnType.isNull() ||
6451 ReturnType->isIntegerType() ||
6452 ReturnType->isBooleanType())) {
6453 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006454 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006455 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6456 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6457 if (ReturnType.isNull()) {
6458 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6459 Builder.AddTextChunk("BOOL");
6460 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6461 }
6462
6463 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6464 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6465 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006466 }
6467 }
6468}
6469
Douglas Gregore8f5a172010-04-07 00:21:17 +00006470void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6471 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006472 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006473 // Determine the return type of the method we're declaring, if
6474 // provided.
6475 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006476 Decl *IDecl = 0;
6477 if (CurContext->isObjCContainer()) {
6478 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6479 IDecl = cast<Decl>(OCD);
6480 }
Douglas Gregorea766182010-10-18 18:21:28 +00006481 // Determine where we should start searching for methods.
6482 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006483 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006484 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006485 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6486 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006487 IsInImplementation = true;
6488 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006489 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006490 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006491 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006492 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006493 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006494 }
6495
6496 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006497 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006498 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006499 }
6500
Douglas Gregorea766182010-10-18 18:21:28 +00006501 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006502 HandleCodeCompleteResults(this, CodeCompleter,
6503 CodeCompletionContext::CCC_Other,
6504 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006505 return;
6506 }
6507
6508 // Find all of the methods that we could declare/implement here.
6509 KnownMethodsMap KnownMethods;
6510 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006511 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006512
Douglas Gregore8f5a172010-04-07 00:21:17 +00006513 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006514 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006515 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6516 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006517 Results.EnterNewScope();
Douglas Gregor8987b232011-09-27 23:30:47 +00006518 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006519 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6520 MEnd = KnownMethods.end();
6521 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006522 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006523 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006524
6525 // If the result type was not already provided, add it to the
6526 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006527 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00006528 AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,
6529 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006530
6531 Selector Sel = Method->getSelector();
6532
6533 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006534 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006535 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006536
6537 // Add parameters to the pattern.
6538 unsigned I = 0;
6539 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6540 PEnd = Method->param_end();
6541 P != PEnd; (void)++P, ++I) {
6542 // Add the part of the selector name.
6543 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006544 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006545 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006546 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6547 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006548 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006549 } else
6550 break;
6551
6552 // Add the parameter type.
Douglas Gregor8987b232011-09-27 23:30:47 +00006553 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,
6554 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006555
6556 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006557 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006558 }
6559
6560 if (Method->isVariadic()) {
6561 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006562 Builder.AddChunk(CodeCompletionString::CK_Comma);
6563 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006564 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006565
Douglas Gregor447107d2010-05-28 00:57:46 +00006566 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006567 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006568 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6569 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6570 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006571 if (!Method->getResultType()->isVoidType()) {
6572 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006573 Builder.AddTextChunk("return");
6574 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6575 Builder.AddPlaceholderChunk("expression");
6576 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006577 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006578 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006579
Douglas Gregor218937c2011-02-01 19:23:04 +00006580 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6581 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006582 }
6583
Douglas Gregor408be5a2010-08-25 01:08:01 +00006584 unsigned Priority = CCP_CodePattern;
6585 if (!M->second.second)
6586 Priority += CCD_InBaseClass;
6587
Douglas Gregor218937c2011-02-01 19:23:04 +00006588 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006589 Method->isInstanceMethod()
6590 ? CXCursor_ObjCInstanceMethodDecl
6591 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006592 }
6593
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006594 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6595 // the properties in this class and its categories.
6596 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006597 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006598 Containers.push_back(SearchDecl);
6599
Douglas Gregore74c25c2011-05-04 23:50:46 +00006600 VisitedSelectorSet KnownSelectors;
6601 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6602 MEnd = KnownMethods.end();
6603 M != MEnd; ++M)
6604 KnownSelectors.insert(M->first);
6605
6606
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006607 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6608 if (!IFace)
6609 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6610 IFace = Category->getClassInterface();
6611
6612 if (IFace) {
6613 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6614 Category = Category->getNextClassCategory())
6615 Containers.push_back(Category);
6616 }
6617
6618 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6619 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6620 PEnd = Containers[I]->prop_end();
6621 P != PEnd; ++P) {
6622 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006623 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006624 }
6625 }
6626 }
6627
Douglas Gregore8f5a172010-04-07 00:21:17 +00006628 Results.ExitScope();
6629
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006630 HandleCodeCompleteResults(this, CodeCompleter,
6631 CodeCompletionContext::CCC_Other,
6632 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006633}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006634
6635void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6636 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006637 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006638 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006639 IdentifierInfo **SelIdents,
6640 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006641 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006642 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006643 if (ExternalSource) {
6644 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6645 I != N; ++I) {
6646 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006647 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006648 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006649
6650 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006651 }
6652 }
6653
6654 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006655 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006656 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6657 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006658
6659 if (ReturnTy)
6660 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006661
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006662 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006663 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6664 MEnd = MethodPool.end();
6665 M != MEnd; ++M) {
6666 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6667 &M->second.second;
6668 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006669 MethList = MethList->Next) {
6670 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6671 NumSelIdents))
6672 continue;
6673
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006674 if (AtParameterName) {
6675 // Suggest parameter names we've seen before.
6676 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6677 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6678 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006679 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006680 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006681 Param->getIdentifier()->getName()));
6682 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006683 }
6684 }
6685
6686 continue;
6687 }
6688
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006689 Result R(MethList->Method, 0);
6690 R.StartParameter = NumSelIdents;
6691 R.AllParametersAreInformative = false;
6692 R.DeclaringEntity = true;
6693 Results.MaybeAddResult(R, CurContext);
6694 }
6695 }
6696
6697 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006698 HandleCodeCompleteResults(this, CodeCompleter,
6699 CodeCompletionContext::CCC_Other,
6700 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006701}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006702
Douglas Gregorf29c5232010-08-24 22:20:20 +00006703void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006704 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006705 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006706 Results.EnterNewScope();
6707
6708 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006709 CodeCompletionBuilder Builder(Results.getAllocator());
6710 Builder.AddTypedTextChunk("if");
6711 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6712 Builder.AddPlaceholderChunk("condition");
6713 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006714
6715 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006716 Builder.AddTypedTextChunk("ifdef");
6717 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6718 Builder.AddPlaceholderChunk("macro");
6719 Results.AddResult(Builder.TakeString());
6720
Douglas Gregorf44e8542010-08-24 19:08:16 +00006721 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006722 Builder.AddTypedTextChunk("ifndef");
6723 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6724 Builder.AddPlaceholderChunk("macro");
6725 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006726
6727 if (InConditional) {
6728 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006729 Builder.AddTypedTextChunk("elif");
6730 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6731 Builder.AddPlaceholderChunk("condition");
6732 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006733
6734 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006735 Builder.AddTypedTextChunk("else");
6736 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006737
6738 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006739 Builder.AddTypedTextChunk("endif");
6740 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006741 }
6742
6743 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006744 Builder.AddTypedTextChunk("include");
6745 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6746 Builder.AddTextChunk("\"");
6747 Builder.AddPlaceholderChunk("header");
6748 Builder.AddTextChunk("\"");
6749 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006750
6751 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006752 Builder.AddTypedTextChunk("include");
6753 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6754 Builder.AddTextChunk("<");
6755 Builder.AddPlaceholderChunk("header");
6756 Builder.AddTextChunk(">");
6757 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006758
6759 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006760 Builder.AddTypedTextChunk("define");
6761 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6762 Builder.AddPlaceholderChunk("macro");
6763 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006764
6765 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006766 Builder.AddTypedTextChunk("define");
6767 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6768 Builder.AddPlaceholderChunk("macro");
6769 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6770 Builder.AddPlaceholderChunk("args");
6771 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6772 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006773
6774 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006775 Builder.AddTypedTextChunk("undef");
6776 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6777 Builder.AddPlaceholderChunk("macro");
6778 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006779
6780 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006781 Builder.AddTypedTextChunk("line");
6782 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6783 Builder.AddPlaceholderChunk("number");
6784 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006785
6786 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006787 Builder.AddTypedTextChunk("line");
6788 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6789 Builder.AddPlaceholderChunk("number");
6790 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6791 Builder.AddTextChunk("\"");
6792 Builder.AddPlaceholderChunk("filename");
6793 Builder.AddTextChunk("\"");
6794 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006795
6796 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006797 Builder.AddTypedTextChunk("error");
6798 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6799 Builder.AddPlaceholderChunk("message");
6800 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006801
6802 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006803 Builder.AddTypedTextChunk("pragma");
6804 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6805 Builder.AddPlaceholderChunk("arguments");
6806 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006807
6808 if (getLangOptions().ObjC1) {
6809 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006810 Builder.AddTypedTextChunk("import");
6811 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6812 Builder.AddTextChunk("\"");
6813 Builder.AddPlaceholderChunk("header");
6814 Builder.AddTextChunk("\"");
6815 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006816
6817 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006818 Builder.AddTypedTextChunk("import");
6819 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6820 Builder.AddTextChunk("<");
6821 Builder.AddPlaceholderChunk("header");
6822 Builder.AddTextChunk(">");
6823 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006824 }
6825
6826 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006827 Builder.AddTypedTextChunk("include_next");
6828 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6829 Builder.AddTextChunk("\"");
6830 Builder.AddPlaceholderChunk("header");
6831 Builder.AddTextChunk("\"");
6832 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006833
6834 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006835 Builder.AddTypedTextChunk("include_next");
6836 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6837 Builder.AddTextChunk("<");
6838 Builder.AddPlaceholderChunk("header");
6839 Builder.AddTextChunk(">");
6840 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006841
6842 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006843 Builder.AddTypedTextChunk("warning");
6844 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6845 Builder.AddPlaceholderChunk("message");
6846 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006847
6848 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6849 // completions for them. And __include_macros is a Clang-internal extension
6850 // that we don't want to encourage anyone to use.
6851
6852 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6853 Results.ExitScope();
6854
Douglas Gregorf44e8542010-08-24 19:08:16 +00006855 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006856 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006857 Results.data(), Results.size());
6858}
6859
6860void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006861 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006862 S->getFnParent()? Sema::PCC_RecoveryInFunction
6863 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006864}
6865
Douglas Gregorf29c5232010-08-24 22:20:20 +00006866void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006867 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006868 IsDefinition? CodeCompletionContext::CCC_MacroName
6869 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006870 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6871 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006872 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006873 Results.EnterNewScope();
6874 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6875 MEnd = PP.macro_end();
6876 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006877 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006878 M->first->getName()));
6879 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006880 }
6881 Results.ExitScope();
6882 } else if (IsDefinition) {
6883 // FIXME: Can we detect when the user just wrote an include guard above?
6884 }
6885
Douglas Gregor52779fb2010-09-23 23:01:17 +00006886 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006887 Results.data(), Results.size());
6888}
6889
Douglas Gregorf29c5232010-08-24 22:20:20 +00006890void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006891 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006892 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006893
6894 if (!CodeCompleter || CodeCompleter->includeMacros())
6895 AddMacroResults(PP, Results);
6896
6897 // defined (<macro>)
6898 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006899 CodeCompletionBuilder Builder(Results.getAllocator());
6900 Builder.AddTypedTextChunk("defined");
6901 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6902 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6903 Builder.AddPlaceholderChunk("macro");
6904 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6905 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006906 Results.ExitScope();
6907
6908 HandleCodeCompleteResults(this, CodeCompleter,
6909 CodeCompletionContext::CCC_PreprocessorExpression,
6910 Results.data(), Results.size());
6911}
6912
6913void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6914 IdentifierInfo *Macro,
6915 MacroInfo *MacroInfo,
6916 unsigned Argument) {
6917 // FIXME: In the future, we could provide "overload" results, much like we
6918 // do for function calls.
6919
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00006920 // Now just ignore this. There will be another code-completion callback
6921 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00006922}
6923
Douglas Gregor55817af2010-08-25 17:04:25 +00006924void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006925 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006926 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006927 0, 0);
6928}
6929
Douglas Gregordae68752011-02-01 22:57:45 +00006930void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006931 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006932 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006933 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6934 CodeCompletionDeclConsumer Consumer(Builder,
6935 Context.getTranslationUnitDecl());
6936 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6937 Consumer);
6938 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006939
6940 if (!CodeCompleter || CodeCompleter->includeMacros())
6941 AddMacroResults(PP, Builder);
6942
6943 Results.clear();
6944 Results.insert(Results.end(),
6945 Builder.data(), Builder.data() + Builder.size());
6946}