blob: 5589245d1a728cce1e74ba4eb0456566782231d0 [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 Gregor12e13132010-05-26 22:00:08 +00001814
1815 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001816 }
1817
1818 if (SemaRef.getLangOptions().ObjC1) {
1819 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001820 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1821 // The interface can be NULL.
1822 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1823 if (ID->getSuperClass())
1824 Results.AddResult(Result("super"));
1825 }
1826
Douglas Gregorbca403c2010-01-13 23:51:12 +00001827 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001828 }
1829
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001830 // sizeof expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001831 Builder.AddTypedTextChunk("sizeof");
1832 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1833 Builder.AddPlaceholderChunk("expression-or-type");
1834 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1835 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001836 break;
1837 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001838
John McCallf312b1e2010-08-26 23:41:50 +00001839 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001840 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001841 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001842 }
1843
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001844 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1845 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001846
John McCallf312b1e2010-08-26 23:41:50 +00001847 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001848 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001849}
1850
Douglas Gregor30c42402011-09-27 22:38:19 +00001851/// \brief Retrieve a printing policy suitable for code completion.
Douglas Gregor8987b232011-09-27 23:30:47 +00001852static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1853 PrintingPolicy Policy = S.getPrintingPolicy();
Douglas Gregor30c42402011-09-27 22:38:19 +00001854 Policy.AnonymousTagLocations = false;
1855 Policy.SuppressStrongLifetime = true;
1856 return Policy;
1857}
1858
Douglas Gregora63f6de2011-02-01 21:15:40 +00001859/// \brief Retrieve the string representation of the given type as a string
1860/// that has the appropriate lifetime for code completion.
1861///
1862/// This routine provides a fast path where we provide constant strings for
1863/// common type names.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001864static const char *GetCompletionTypeString(QualType T,
1865 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001866 const PrintingPolicy &Policy,
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001867 CodeCompletionAllocator &Allocator) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001868 if (!T.getLocalQualifiers()) {
1869 // Built-in type names are constant strings.
1870 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
Douglas Gregor30c42402011-09-27 22:38:19 +00001871 return BT->getName(Policy);
Douglas Gregora63f6de2011-02-01 21:15:40 +00001872
1873 // Anonymous tag types are constant strings.
1874 if (const TagType *TagT = dyn_cast<TagType>(T))
1875 if (TagDecl *Tag = TagT->getDecl())
Richard Smith162e1c12011-04-15 14:24:37 +00001876 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001877 switch (Tag->getTagKind()) {
1878 case TTK_Struct: return "struct <anonymous>";
1879 case TTK_Class: return "class <anonymous>";
1880 case TTK_Union: return "union <anonymous>";
1881 case TTK_Enum: return "enum <anonymous>";
1882 }
1883 }
1884 }
1885
1886 // Slow path: format the type as a string.
1887 std::string Result;
1888 T.getAsStringInternal(Result, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00001889 return Allocator.CopyString(Result);
Douglas Gregora63f6de2011-02-01 21:15:40 +00001890}
1891
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001892/// \brief If the given declaration has an associated type, add it as a result
1893/// type chunk.
1894static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001895 const PrintingPolicy &Policy,
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001896 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001897 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001898 if (!ND)
1899 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001900
1901 // Skip constructors and conversion functions, which have their return types
1902 // built into their names.
1903 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1904 return;
1905
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001906 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001907 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001908 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1909 T = Function->getResultType();
1910 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1911 T = Method->getResultType();
1912 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1913 T = FunTmpl->getTemplatedDecl()->getResultType();
1914 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1915 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1916 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1917 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00001918 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001919 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001920 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001921 T = Property->getType();
1922
1923 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1924 return;
1925
Douglas Gregor8987b232011-09-27 23:30:47 +00001926 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00001927 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001928}
1929
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001930static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001931 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001932 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1933 if (Sentinel->getSentinel() == 0) {
1934 if (Context.getLangOptions().ObjC1 &&
1935 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001936 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001937 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001938 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001939 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001940 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001941 }
1942}
1943
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00001944static void appendWithSpace(std::string &Result, StringRef Text) {
1945 if (!Result.empty())
1946 Result += ' ';
1947 Result += Text.str();
1948}
1949static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
1950 std::string Result;
1951 if (ObjCQuals & Decl::OBJC_TQ_In)
1952 appendWithSpace(Result, "in");
1953 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
1954 appendWithSpace(Result, "inout");
1955 else if (ObjCQuals & Decl::OBJC_TQ_Out)
1956 appendWithSpace(Result, "out");
1957 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
1958 appendWithSpace(Result, "bycopy");
1959 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
1960 appendWithSpace(Result, "byref");
1961 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
1962 appendWithSpace(Result, "oneway");
1963 return Result;
1964}
1965
Douglas Gregor83482d12010-08-24 16:15:59 +00001966static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001967 const PrintingPolicy &Policy,
Douglas Gregoraba48082010-08-29 19:47:46 +00001968 ParmVarDecl *Param,
Douglas Gregoree1c68a2011-10-18 04:23:19 +00001969 bool SuppressName = false,
1970 bool SuppressBlock = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001971 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1972 if (Param->getType()->isDependentType() ||
1973 !Param->getType()->isBlockPointerType()) {
1974 // The argument for a dependent or non-block parameter is a placeholder
1975 // containing that parameter's type.
1976 std::string Result;
1977
Douglas Gregoraba48082010-08-29 19:47:46 +00001978 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001979 Result = Param->getIdentifier()->getName();
1980
John McCallf85e1932011-06-15 23:02:42 +00001981 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00001982
1983 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00001984 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
1985 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001986 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001987 Result += Param->getIdentifier()->getName();
1988 }
1989 return Result;
1990 }
1991
1992 // The argument for a block pointer parameter is a block literal with
1993 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00001994 FunctionTypeLoc *Block = 0;
1995 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00001996 TypeLoc TL;
1997 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1998 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1999 while (true) {
2000 // Look through typedefs.
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002001 if (!SuppressBlock) {
2002 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
2003 if (TypeSourceInfo *InnerTSInfo
2004 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
2005 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2006 continue;
2007 }
2008 }
2009
2010 // Look through qualified types
2011 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2012 TL = QualifiedTL->getUnqualifiedLoc();
Douglas Gregor83482d12010-08-24 16:15:59 +00002013 continue;
2014 }
2015 }
2016
Douglas Gregor83482d12010-08-24 16:15:59 +00002017 // Try to get the function prototype behind the block pointer type,
2018 // then we're done.
2019 if (BlockPointerTypeLoc *BlockPtr
2020 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002021 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002022 Block = dyn_cast<FunctionTypeLoc>(&TL);
2023 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002024 }
2025 break;
2026 }
2027 }
2028
2029 if (!Block) {
2030 // We were unable to find a FunctionProtoTypeLoc with parameter names
2031 // for the block; just use the parameter type as a placeholder.
2032 std::string Result;
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002033 if (!ObjCMethodParam && Param->getIdentifier())
2034 Result = Param->getIdentifier()->getName();
2035
John McCallf85e1932011-06-15 23:02:42 +00002036 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002037
2038 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002039 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2040 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002041 if (Param->getIdentifier())
2042 Result += Param->getIdentifier()->getName();
2043 }
2044
2045 return Result;
2046 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002047
Douglas Gregor83482d12010-08-24 16:15:59 +00002048 // We have the function prototype behind the block pointer type, as it was
2049 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002050 std::string Result;
2051 QualType ResultType = Block->getTypePtr()->getResultType();
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002052 if (!ResultType->isVoidType() || SuppressBlock)
John McCallf85e1932011-06-15 23:02:42 +00002053 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002054
2055 // Format the parameter list.
2056 std::string Params;
Douglas Gregor830072c2011-02-15 22:37:09 +00002057 if (!BlockProto || Block->getNumArgs() == 0) {
2058 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002059 Params = "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002060 else
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002061 Params = "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002062 } else {
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002063 Params += "(";
Douglas Gregor38276252010-09-08 22:47:51 +00002064 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2065 if (I)
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002066 Params += ", ";
2067 Params += FormatFunctionParameter(Context, Policy, Block->getArg(I),
2068 /*SuppressName=*/false,
2069 /*SuppressBlock=*/true);
Douglas Gregor38276252010-09-08 22:47:51 +00002070
Douglas Gregor830072c2011-02-15 22:37:09 +00002071 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002072 Params += ", ...";
Douglas Gregor38276252010-09-08 22:47:51 +00002073 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002074 Params += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002075 }
Douglas Gregor38276252010-09-08 22:47:51 +00002076
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002077 if (SuppressBlock) {
2078 // Format as a parameter.
2079 Result = Result + " (^";
2080 if (Param->getIdentifier())
2081 Result += Param->getIdentifier()->getName();
2082 Result += ")";
2083 Result += Params;
2084 } else {
2085 // Format as a block literal argument.
2086 Result = '^' + Result;
2087 Result += Params;
2088
2089 if (Param->getIdentifier())
2090 Result += Param->getIdentifier()->getName();
2091 }
2092
Douglas Gregor83482d12010-08-24 16:15:59 +00002093 return Result;
2094}
2095
Douglas Gregor86d9a522009-09-21 16:56:56 +00002096/// \brief Add function parameter chunks to the given code completion string.
2097static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002098 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002099 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002100 CodeCompletionBuilder &Result,
2101 unsigned Start = 0,
2102 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002103 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002104 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002105
Douglas Gregor218937c2011-02-01 19:23:04 +00002106 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002107 ParmVarDecl *Param = Function->getParamDecl(P);
2108
Douglas Gregor218937c2011-02-01 19:23:04 +00002109 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002110 // When we see an optional default argument, put that argument and
2111 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002112 CodeCompletionBuilder Opt(Result.getAllocator());
2113 if (!FirstParameter)
2114 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002115 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregor218937c2011-02-01 19:23:04 +00002116 Result.AddOptionalChunk(Opt.TakeString());
2117 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002118 }
2119
Douglas Gregor218937c2011-02-01 19:23:04 +00002120 if (FirstParameter)
2121 FirstParameter = false;
2122 else
2123 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2124
2125 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002126
2127 // Format the placeholder string.
Douglas Gregor8987b232011-09-27 23:30:47 +00002128 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2129 Param);
Douglas Gregor83482d12010-08-24 16:15:59 +00002130
Douglas Gregore17794f2010-08-31 05:13:43 +00002131 if (Function->isVariadic() && P == N - 1)
2132 PlaceholderStr += ", ...";
2133
Douglas Gregor86d9a522009-09-21 16:56:56 +00002134 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002135 Result.AddPlaceholderChunk(
2136 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002137 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002138
2139 if (const FunctionProtoType *Proto
2140 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002141 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002142 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002143 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002144
Douglas Gregor218937c2011-02-01 19:23:04 +00002145 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002146 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002147}
2148
2149/// \brief Add template parameter chunks to the given code completion string.
2150static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002151 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002152 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002153 CodeCompletionBuilder &Result,
2154 unsigned MaxParameters = 0,
2155 unsigned Start = 0,
2156 bool InDefaultArg = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002157 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002158 bool FirstParameter = true;
2159
2160 TemplateParameterList *Params = Template->getTemplateParameters();
2161 TemplateParameterList::iterator PEnd = Params->end();
2162 if (MaxParameters)
2163 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002164 for (TemplateParameterList::iterator P = Params->begin() + Start;
2165 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002166 bool HasDefaultArg = false;
2167 std::string PlaceholderStr;
2168 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2169 if (TTP->wasDeclaredWithTypename())
2170 PlaceholderStr = "typename";
2171 else
2172 PlaceholderStr = "class";
2173
2174 if (TTP->getIdentifier()) {
2175 PlaceholderStr += ' ';
2176 PlaceholderStr += TTP->getIdentifier()->getName();
2177 }
2178
2179 HasDefaultArg = TTP->hasDefaultArgument();
2180 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002181 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002182 if (NTTP->getIdentifier())
2183 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002184 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002185 HasDefaultArg = NTTP->hasDefaultArgument();
2186 } else {
2187 assert(isa<TemplateTemplateParmDecl>(*P));
2188 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2189
2190 // Since putting the template argument list into the placeholder would
2191 // be very, very long, we just use an abbreviation.
2192 PlaceholderStr = "template<...> class";
2193 if (TTP->getIdentifier()) {
2194 PlaceholderStr += ' ';
2195 PlaceholderStr += TTP->getIdentifier()->getName();
2196 }
2197
2198 HasDefaultArg = TTP->hasDefaultArgument();
2199 }
2200
Douglas Gregor218937c2011-02-01 19:23:04 +00002201 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002202 // When we see an optional default argument, put that argument and
2203 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002204 CodeCompletionBuilder Opt(Result.getAllocator());
2205 if (!FirstParameter)
2206 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002207 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregor218937c2011-02-01 19:23:04 +00002208 P - Params->begin(), true);
2209 Result.AddOptionalChunk(Opt.TakeString());
2210 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002211 }
2212
Douglas Gregor218937c2011-02-01 19:23:04 +00002213 InDefaultArg = false;
2214
Douglas Gregor86d9a522009-09-21 16:56:56 +00002215 if (FirstParameter)
2216 FirstParameter = false;
2217 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002218 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002219
2220 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002221 Result.AddPlaceholderChunk(
2222 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002223 }
2224}
2225
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002226/// \brief Add a qualifier to the given code-completion string, if the
2227/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002228static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002229AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002230 NestedNameSpecifier *Qualifier,
2231 bool QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002232 ASTContext &Context,
2233 const PrintingPolicy &Policy) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002234 if (!Qualifier)
2235 return;
2236
2237 std::string PrintedNNS;
2238 {
2239 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor8987b232011-09-27 23:30:47 +00002240 Qualifier->print(OS, Policy);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002241 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002242 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002243 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002244 else
Douglas Gregordae68752011-02-01 22:57:45 +00002245 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002246}
2247
Douglas Gregor218937c2011-02-01 19:23:04 +00002248static void
2249AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2250 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002251 const FunctionProtoType *Proto
2252 = Function->getType()->getAs<FunctionProtoType>();
2253 if (!Proto || !Proto->getTypeQuals())
2254 return;
2255
Douglas Gregora63f6de2011-02-01 21:15:40 +00002256 // FIXME: Add ref-qualifier!
2257
2258 // Handle single qualifiers without copying
2259 if (Proto->getTypeQuals() == Qualifiers::Const) {
2260 Result.AddInformativeChunk(" const");
2261 return;
2262 }
2263
2264 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2265 Result.AddInformativeChunk(" volatile");
2266 return;
2267 }
2268
2269 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2270 Result.AddInformativeChunk(" restrict");
2271 return;
2272 }
2273
2274 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002275 std::string QualsStr;
2276 if (Proto->getTypeQuals() & Qualifiers::Const)
2277 QualsStr += " const";
2278 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2279 QualsStr += " volatile";
2280 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2281 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002282 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002283}
2284
Douglas Gregor6f942b22010-09-21 16:06:22 +00002285/// \brief Add the name of the given declaration
Douglas Gregor8987b232011-09-27 23:30:47 +00002286static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2287 NamedDecl *ND, CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002288 typedef CodeCompletionString::Chunk Chunk;
2289
2290 DeclarationName Name = ND->getDeclName();
2291 if (!Name)
2292 return;
2293
2294 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002295 case DeclarationName::CXXOperatorName: {
2296 const char *OperatorName = 0;
2297 switch (Name.getCXXOverloadedOperator()) {
2298 case OO_None:
2299 case OO_Conditional:
2300 case NUM_OVERLOADED_OPERATORS:
2301 OperatorName = "operator";
2302 break;
2303
2304#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2305 case OO_##Name: OperatorName = "operator" Spelling; break;
2306#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2307#include "clang/Basic/OperatorKinds.def"
2308
2309 case OO_New: OperatorName = "operator new"; break;
2310 case OO_Delete: OperatorName = "operator delete"; break;
2311 case OO_Array_New: OperatorName = "operator new[]"; break;
2312 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2313 case OO_Call: OperatorName = "operator()"; break;
2314 case OO_Subscript: OperatorName = "operator[]"; break;
2315 }
2316 Result.AddTypedTextChunk(OperatorName);
2317 break;
2318 }
2319
Douglas Gregor6f942b22010-09-21 16:06:22 +00002320 case DeclarationName::Identifier:
2321 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002322 case DeclarationName::CXXDestructorName:
2323 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002324 Result.AddTypedTextChunk(
2325 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002326 break;
2327
2328 case DeclarationName::CXXUsingDirective:
2329 case DeclarationName::ObjCZeroArgSelector:
2330 case DeclarationName::ObjCOneArgSelector:
2331 case DeclarationName::ObjCMultiArgSelector:
2332 break;
2333
2334 case DeclarationName::CXXConstructorName: {
2335 CXXRecordDecl *Record = 0;
2336 QualType Ty = Name.getCXXNameType();
2337 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2338 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2339 else if (const InjectedClassNameType *InjectedTy
2340 = Ty->getAs<InjectedClassNameType>())
2341 Record = InjectedTy->getDecl();
2342 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002343 Result.AddTypedTextChunk(
2344 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002345 break;
2346 }
2347
Douglas Gregordae68752011-02-01 22:57:45 +00002348 Result.AddTypedTextChunk(
2349 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002350 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002351 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002352 AddTemplateParameterChunks(Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002353 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002354 }
2355 break;
2356 }
2357 }
2358}
2359
Douglas Gregor86d9a522009-09-21 16:56:56 +00002360/// \brief If possible, create a new code completion string for the given
2361/// result.
2362///
2363/// \returns Either a new, heap-allocated code completion string describing
2364/// how to use this result, or NULL to indicate that the string or name of the
2365/// result is all that is needed.
2366CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002367CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002368 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002369 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002370 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002371
Douglas Gregor8987b232011-09-27 23:30:47 +00002372 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregor218937c2011-02-01 19:23:04 +00002373 if (Kind == RK_Pattern) {
2374 Pattern->Priority = Priority;
2375 Pattern->Availability = Availability;
2376 return Pattern;
2377 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002378
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002379 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002380 Result.AddTypedTextChunk(Keyword);
2381 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002382 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002383
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002384 if (Kind == RK_Macro) {
2385 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002386 assert(MI && "Not a macro?");
2387
Douglas Gregordae68752011-02-01 22:57:45 +00002388 Result.AddTypedTextChunk(
2389 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002390
2391 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002392 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002393
2394 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002395 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregore4244702011-07-30 08:17:44 +00002396 bool CombineVariadicArgument = false;
2397 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2398 if (MI->isVariadic() && AEnd - A > 1) {
2399 AEnd -= 2;
2400 CombineVariadicArgument = true;
2401 }
2402 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002403 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002404 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002405
Douglas Gregore4244702011-07-30 08:17:44 +00002406 if (!MI->isVariadic() || A + 1 != AEnd) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002407 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002408 Result.AddPlaceholderChunk(
2409 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002410 continue;
2411 }
2412
Douglas Gregore4244702011-07-30 08:17:44 +00002413 // Variadic argument; cope with the difference between GNU and C99
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002414 // variadic macros, providing a single placeholder for the rest of the
2415 // arguments.
2416 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002417 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002418 else {
2419 std::string Arg = (*A)->getName();
2420 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002421 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002422 }
2423 }
Douglas Gregore4244702011-07-30 08:17:44 +00002424
2425 if (CombineVariadicArgument) {
2426 // Handle the next-to-last argument, combining it with the variadic
2427 // argument.
2428 std::string LastArg = (*A)->getName();
2429 ++A;
2430 if ((*A)->isStr("__VA_ARGS__"))
2431 LastArg += ", ...";
2432 else
2433 LastArg += ", " + (*A)->getName().str() + "...";
2434 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(LastArg));
2435 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002436 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2437 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002438 }
2439
Douglas Gregord8e8a582010-05-25 21:41:55 +00002440 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002441 NamedDecl *ND = Declaration;
2442
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002443 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002444 Result.AddTypedTextChunk(
2445 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002446 Result.AddTextChunk("::");
2447 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002448 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00002449
2450 for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2451 if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2452 Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2453 }
2454 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002455
Douglas Gregor8987b232011-09-27 23:30:47 +00002456 AddResultTypeChunk(S.Context, Policy, ND, Result);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002457
Douglas Gregor86d9a522009-09-21 16:56:56 +00002458 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002459 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002460 S.Context, Policy);
2461 AddTypedNameChunk(S.Context, Policy, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002462 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002463 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002464 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002465 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002466 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002467 }
2468
2469 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002470 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002471 S.Context, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002472 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor8987b232011-09-27 23:30:47 +00002473 AddTypedNameChunk(S.Context, Policy, Function, Result);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002474
Douglas Gregor86d9a522009-09-21 16:56:56 +00002475 // Figure out which template parameters are deduced (or have default
2476 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002477 SmallVector<bool, 16> Deduced;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002478 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2479 unsigned LastDeducibleArgument;
2480 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2481 --LastDeducibleArgument) {
2482 if (!Deduced[LastDeducibleArgument - 1]) {
2483 // C++0x: Figure out if the template argument has a default. If so,
2484 // the user doesn't need to type this argument.
2485 // FIXME: We need to abstract template parameters better!
2486 bool HasDefaultArg = false;
2487 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002488 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002489 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2490 HasDefaultArg = TTP->hasDefaultArgument();
2491 else if (NonTypeTemplateParmDecl *NTTP
2492 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2493 HasDefaultArg = NTTP->hasDefaultArgument();
2494 else {
2495 assert(isa<TemplateTemplateParmDecl>(Param));
2496 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002497 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002498 }
2499
2500 if (!HasDefaultArg)
2501 break;
2502 }
2503 }
2504
2505 if (LastDeducibleArgument) {
2506 // Some of the function template arguments cannot be deduced from a
2507 // function call, so we introduce an explicit template argument list
2508 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002509 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002510 AddTemplateParameterChunks(S.Context, Policy, FunTmpl, Result,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002511 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002512 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002513 }
2514
2515 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002516 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002517 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002518 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002519 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002520 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002521 }
2522
2523 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002524 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002525 S.Context, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002526 Result.AddTypedTextChunk(
2527 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002528 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002529 AddTemplateParameterChunks(S.Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002530 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2531 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002532 }
2533
Douglas Gregor9630eb62009-11-17 16:44:22 +00002534 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002535 Selector Sel = Method->getSelector();
2536 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002537 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002538 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002539 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002540 }
2541
Douglas Gregor813d8342011-02-18 22:29:55 +00002542 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002543 SelName += ':';
2544 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002545 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002546 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002547 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002548
2549 // If there is only one parameter, and we're past it, add an empty
2550 // typed-text chunk since there is nothing to type.
2551 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002552 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002553 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002554 unsigned Idx = 0;
2555 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2556 PEnd = Method->param_end();
2557 P != PEnd; (void)++P, ++Idx) {
2558 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002559 std::string Keyword;
2560 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002561 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002562 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002563 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002564 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002565 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002566 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002567 else
Douglas Gregordae68752011-02-01 22:57:45 +00002568 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002569 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002570
2571 // If we're before the starting parameter, skip the placeholder.
2572 if (Idx < StartParameter)
2573 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002574
2575 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002576
2577 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregor8987b232011-09-27 23:30:47 +00002578 Arg = FormatFunctionParameter(S.Context, Policy, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002579 else {
John McCallf85e1932011-06-15 23:02:42 +00002580 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002581 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2582 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002583 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002584 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002585 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002586 }
2587
Douglas Gregore17794f2010-08-31 05:13:43 +00002588 if (Method->isVariadic() && (P + 1) == PEnd)
2589 Arg += ", ...";
2590
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002591 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002592 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002593 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002594 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002595 else
Douglas Gregordae68752011-02-01 22:57:45 +00002596 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002597 }
2598
Douglas Gregor2a17af02009-12-23 00:21:46 +00002599 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002600 if (Method->param_size() == 0) {
2601 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002602 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002603 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002604 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002605 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002606 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002607 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002608
2609 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002610 }
2611
Douglas Gregor218937c2011-02-01 19:23:04 +00002612 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002613 }
2614
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002615 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002616 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002617 S.Context, Policy);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002618
Douglas Gregordae68752011-02-01 22:57:45 +00002619 Result.AddTypedTextChunk(
2620 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002621 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002622}
2623
Douglas Gregor86d802e2009-09-23 00:34:09 +00002624CodeCompletionString *
2625CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2626 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002627 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002628 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002629 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor8987b232011-09-27 23:30:47 +00002630 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCallf85e1932011-06-15 23:02:42 +00002631
Douglas Gregor218937c2011-02-01 19:23:04 +00002632 // FIXME: Set priority, availability appropriately.
2633 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002634 FunctionDecl *FDecl = getFunction();
Douglas Gregor8987b232011-09-27 23:30:47 +00002635 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002636 const FunctionProtoType *Proto
2637 = dyn_cast<FunctionProtoType>(getFunctionType());
2638 if (!FDecl && !Proto) {
2639 // Function without a prototype. Just give the return type and a
2640 // highlighted ellipsis.
2641 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002642 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
Douglas Gregor8987b232011-09-27 23:30:47 +00002643 S.Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002644 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002645 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2646 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2647 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2648 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002649 }
2650
2651 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002652 Result.AddTextChunk(
2653 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002654 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002655 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002656 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002657 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002658
Douglas Gregor218937c2011-02-01 19:23:04 +00002659 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002660 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2661 for (unsigned I = 0; I != NumParams; ++I) {
2662 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002663 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002664
2665 std::string ArgString;
2666 QualType ArgType;
2667
2668 if (FDecl) {
2669 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2670 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2671 } else {
2672 ArgType = Proto->getArgType(I);
2673 }
2674
John McCallf85e1932011-06-15 23:02:42 +00002675 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002676
2677 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002678 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002679 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002680 else
Douglas Gregordae68752011-02-01 22:57:45 +00002681 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002682 }
2683
2684 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002685 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002686 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002687 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002688 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002689 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002690 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002691 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002692
Douglas Gregor218937c2011-02-01 19:23:04 +00002693 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002694}
2695
Chris Lattner5f9e2722011-07-23 10:55:15 +00002696unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002697 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002698 bool PreferredTypeIsPointer) {
2699 unsigned Priority = CCP_Macro;
2700
Douglas Gregorb05496d2010-09-20 21:11:48 +00002701 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2702 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2703 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002704 Priority = CCP_Constant;
2705 if (PreferredTypeIsPointer)
2706 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002707 }
2708 // Treat "YES", "NO", "true", and "false" as constants.
2709 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2710 MacroName.equals("true") || MacroName.equals("false"))
2711 Priority = CCP_Constant;
2712 // Treat "bool" as a type.
2713 else if (MacroName.equals("bool"))
2714 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2715
Douglas Gregor1827e102010-08-16 16:18:59 +00002716
2717 return Priority;
2718}
2719
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002720CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2721 if (!D)
2722 return CXCursor_UnexposedDecl;
2723
2724 switch (D->getKind()) {
2725 case Decl::Enum: return CXCursor_EnumDecl;
2726 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2727 case Decl::Field: return CXCursor_FieldDecl;
2728 case Decl::Function:
2729 return CXCursor_FunctionDecl;
2730 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2731 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2732 case Decl::ObjCClass:
2733 // FIXME
2734 return CXCursor_UnexposedDecl;
2735 case Decl::ObjCForwardProtocol:
2736 // FIXME
2737 return CXCursor_UnexposedDecl;
2738 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2739 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2740 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2741 case Decl::ObjCMethod:
2742 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2743 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2744 case Decl::CXXMethod: return CXCursor_CXXMethod;
2745 case Decl::CXXConstructor: return CXCursor_Constructor;
2746 case Decl::CXXDestructor: return CXCursor_Destructor;
2747 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2748 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2749 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2750 case Decl::ParmVar: return CXCursor_ParmDecl;
2751 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002752 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002753 case Decl::Var: return CXCursor_VarDecl;
2754 case Decl::Namespace: return CXCursor_Namespace;
2755 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2756 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2757 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2758 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2759 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2760 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00002761 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002762 case Decl::ClassTemplatePartialSpecialization:
2763 return CXCursor_ClassTemplatePartialSpecialization;
2764 case Decl::UsingDirective: return CXCursor_UsingDirective;
2765
2766 case Decl::Using:
2767 case Decl::UnresolvedUsingValue:
2768 case Decl::UnresolvedUsingTypename:
2769 return CXCursor_UsingDeclaration;
2770
Douglas Gregor352697a2011-06-03 23:08:58 +00002771 case Decl::ObjCPropertyImpl:
2772 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2773 case ObjCPropertyImplDecl::Dynamic:
2774 return CXCursor_ObjCDynamicDecl;
2775
2776 case ObjCPropertyImplDecl::Synthesize:
2777 return CXCursor_ObjCSynthesizeDecl;
2778 }
2779 break;
2780
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002781 default:
2782 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2783 switch (TD->getTagKind()) {
2784 case TTK_Struct: return CXCursor_StructDecl;
2785 case TTK_Class: return CXCursor_ClassDecl;
2786 case TTK_Union: return CXCursor_UnionDecl;
2787 case TTK_Enum: return CXCursor_EnumDecl;
2788 }
2789 }
2790 }
2791
2792 return CXCursor_UnexposedDecl;
2793}
2794
Douglas Gregor590c7d52010-07-08 20:55:51 +00002795static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2796 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002797 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002798
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002799 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002800
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002801 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2802 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002803 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002804 Results.AddResult(Result(M->first,
2805 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002806 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002807 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002808 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002809
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002810 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002811
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002812}
2813
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002814static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2815 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002816 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002817
2818 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002819
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002820 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2821 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2822 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2823 Results.AddResult(Result("__func__", CCP_Constant));
2824 Results.ExitScope();
2825}
2826
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002827static void HandleCodeCompleteResults(Sema *S,
2828 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002829 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002830 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002831 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002832 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002833 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002834}
2835
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002836static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2837 Sema::ParserCompletionContext PCC) {
2838 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002839 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002840 return CodeCompletionContext::CCC_TopLevel;
2841
John McCallf312b1e2010-08-26 23:41:50 +00002842 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002843 return CodeCompletionContext::CCC_ClassStructUnion;
2844
John McCallf312b1e2010-08-26 23:41:50 +00002845 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002846 return CodeCompletionContext::CCC_ObjCInterface;
2847
John McCallf312b1e2010-08-26 23:41:50 +00002848 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002849 return CodeCompletionContext::CCC_ObjCImplementation;
2850
John McCallf312b1e2010-08-26 23:41:50 +00002851 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002852 return CodeCompletionContext::CCC_ObjCIvarList;
2853
John McCallf312b1e2010-08-26 23:41:50 +00002854 case Sema::PCC_Template:
2855 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002856 if (S.CurContext->isFileContext())
2857 return CodeCompletionContext::CCC_TopLevel;
2858 else if (S.CurContext->isRecord())
2859 return CodeCompletionContext::CCC_ClassStructUnion;
2860 else
2861 return CodeCompletionContext::CCC_Other;
2862
John McCallf312b1e2010-08-26 23:41:50 +00002863 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002864 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002865
John McCallf312b1e2010-08-26 23:41:50 +00002866 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002867 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2868 S.getLangOptions().ObjC1)
2869 return CodeCompletionContext::CCC_ParenthesizedExpression;
2870 else
2871 return CodeCompletionContext::CCC_Expression;
2872
2873 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002874 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002875 return CodeCompletionContext::CCC_Expression;
2876
John McCallf312b1e2010-08-26 23:41:50 +00002877 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002878 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002879
John McCallf312b1e2010-08-26 23:41:50 +00002880 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002881 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002882
2883 case Sema::PCC_ParenthesizedExpression:
2884 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002885
2886 case Sema::PCC_LocalDeclarationSpecifiers:
2887 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002888 }
2889
2890 return CodeCompletionContext::CCC_Other;
2891}
2892
Douglas Gregorf6961522010-08-27 21:18:54 +00002893/// \brief If we're in a C++ virtual member function, add completion results
2894/// that invoke the functions we override, since it's common to invoke the
2895/// overridden function as well as adding new functionality.
2896///
2897/// \param S The semantic analysis object for which we are generating results.
2898///
2899/// \param InContext This context in which the nested-name-specifier preceding
2900/// the code-completion point
2901static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2902 ResultBuilder &Results) {
2903 // Look through blocks.
2904 DeclContext *CurContext = S.CurContext;
2905 while (isa<BlockDecl>(CurContext))
2906 CurContext = CurContext->getParent();
2907
2908
2909 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2910 if (!Method || !Method->isVirtual())
2911 return;
2912
2913 // We need to have names for all of the parameters, if we're going to
2914 // generate a forwarding call.
2915 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2916 PEnd = Method->param_end();
2917 P != PEnd;
2918 ++P) {
2919 if (!(*P)->getDeclName())
2920 return;
2921 }
2922
Douglas Gregor8987b232011-09-27 23:30:47 +00002923 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorf6961522010-08-27 21:18:54 +00002924 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2925 MEnd = Method->end_overridden_methods();
2926 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002927 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002928 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2929 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2930 continue;
2931
2932 // If we need a nested-name-specifier, add one now.
2933 if (!InContext) {
2934 NestedNameSpecifier *NNS
2935 = getRequiredQualification(S.Context, CurContext,
2936 Overridden->getDeclContext());
2937 if (NNS) {
2938 std::string Str;
2939 llvm::raw_string_ostream OS(Str);
Douglas Gregor8987b232011-09-27 23:30:47 +00002940 NNS->print(OS, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002941 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002942 }
2943 } else if (!InContext->Equals(Overridden->getDeclContext()))
2944 continue;
2945
Douglas Gregordae68752011-02-01 22:57:45 +00002946 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002947 Overridden->getNameAsString()));
2948 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00002949 bool FirstParam = true;
2950 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2951 PEnd = Method->param_end();
2952 P != PEnd; ++P) {
2953 if (FirstParam)
2954 FirstParam = false;
2955 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002956 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00002957
Douglas Gregordae68752011-02-01 22:57:45 +00002958 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002959 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002960 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002961 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2962 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00002963 CCP_SuperCompletion,
2964 CXCursor_CXXMethod));
2965 Results.Ignore(Overridden);
2966 }
2967}
2968
Douglas Gregor01dfea02010-01-10 23:08:15 +00002969void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002970 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002971 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002972 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002973 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002974 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002975
Douglas Gregor01dfea02010-01-10 23:08:15 +00002976 // Determine how to filter results, e.g., so that the names of
2977 // values (functions, enumerators, function templates, etc.) are
2978 // only allowed where we can have an expression.
2979 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002980 case PCC_Namespace:
2981 case PCC_Class:
2982 case PCC_ObjCInterface:
2983 case PCC_ObjCImplementation:
2984 case PCC_ObjCInstanceVariableList:
2985 case PCC_Template:
2986 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002987 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002988 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002989 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2990 break;
2991
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002992 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002993 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002994 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002995 case PCC_ForInit:
2996 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002997 if (WantTypesInContext(CompletionContext, getLangOptions()))
2998 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2999 else
3000 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00003001
3002 if (getLangOptions().CPlusPlus)
3003 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00003004 break;
Douglas Gregordc845342010-05-25 05:58:43 +00003005
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003006 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00003007 // Unfiltered
3008 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00003009 }
3010
Douglas Gregor3cdee122010-08-26 16:36:48 +00003011 // If we are in a C++ non-static member function, check the qualifiers on
3012 // the member function to filter/prioritize the results list.
3013 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3014 if (CurMethod->isInstance())
3015 Results.setObjectTypeQualifiers(
3016 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3017
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00003018 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003019 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3020 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003021
Douglas Gregorbca403c2010-01-13 23:51:12 +00003022 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003023 Results.ExitScope();
3024
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003025 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00003026 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00003027 case PCC_Expression:
3028 case PCC_Statement:
3029 case PCC_RecoveryInFunction:
3030 if (S->getFnParent())
3031 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3032 break;
3033
3034 case PCC_Namespace:
3035 case PCC_Class:
3036 case PCC_ObjCInterface:
3037 case PCC_ObjCImplementation:
3038 case PCC_ObjCInstanceVariableList:
3039 case PCC_Template:
3040 case PCC_MemberTemplate:
3041 case PCC_ForInit:
3042 case PCC_Condition:
3043 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003044 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003045 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003046 }
3047
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003048 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003049 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003050
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003051 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003052 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003053}
3054
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003055static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3056 ParsedType Receiver,
3057 IdentifierInfo **SelIdents,
3058 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003059 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003060 bool IsSuper,
3061 ResultBuilder &Results);
3062
3063void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3064 bool AllowNonIdentifiers,
3065 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003066 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003067 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003068 AllowNestedNameSpecifiers
3069 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3070 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003071 Results.EnterNewScope();
3072
3073 // Type qualifiers can come after names.
3074 Results.AddResult(Result("const"));
3075 Results.AddResult(Result("volatile"));
3076 if (getLangOptions().C99)
3077 Results.AddResult(Result("restrict"));
3078
3079 if (getLangOptions().CPlusPlus) {
3080 if (AllowNonIdentifiers) {
3081 Results.AddResult(Result("operator"));
3082 }
3083
3084 // Add nested-name-specifiers.
3085 if (AllowNestedNameSpecifiers) {
3086 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003087 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003088 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3089 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3090 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003091 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003092 }
3093 }
3094 Results.ExitScope();
3095
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003096 // If we're in a context where we might have an expression (rather than a
3097 // declaration), and what we've seen so far is an Objective-C type that could
3098 // be a receiver of a class message, this may be a class message send with
3099 // the initial opening bracket '[' missing. Add appropriate completions.
3100 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3101 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3102 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3103 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3104 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3105 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3106 DS.getTypeQualifiers() == 0 &&
3107 S &&
3108 (S->getFlags() & Scope::DeclScope) != 0 &&
3109 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3110 Scope::FunctionPrototypeScope |
3111 Scope::AtCatchScope)) == 0) {
3112 ParsedType T = DS.getRepAsType();
3113 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003114 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003115 }
3116
Douglas Gregor4497dd42010-08-24 04:59:56 +00003117 // Note that we intentionally suppress macro results here, since we do not
3118 // encourage using macros to produce the names of entities.
3119
Douglas Gregor52779fb2010-09-23 23:01:17 +00003120 HandleCodeCompleteResults(this, CodeCompleter,
3121 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003122 Results.data(), Results.size());
3123}
3124
Douglas Gregorfb629412010-08-23 21:17:50 +00003125struct Sema::CodeCompleteExpressionData {
3126 CodeCompleteExpressionData(QualType PreferredType = QualType())
3127 : PreferredType(PreferredType), IntegralConstantExpression(false),
3128 ObjCCollection(false) { }
3129
3130 QualType PreferredType;
3131 bool IntegralConstantExpression;
3132 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003133 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003134};
3135
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003136/// \brief Perform code-completion in an expression context when we know what
3137/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003138///
3139/// \param IntegralConstantExpression Only permit integral constant
3140/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003141void Sema::CodeCompleteExpression(Scope *S,
3142 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003143 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003144 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3145 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003146 if (Data.ObjCCollection)
3147 Results.setFilter(&ResultBuilder::IsObjCCollection);
3148 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003149 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003150 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003151 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3152 else
3153 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003154
3155 if (!Data.PreferredType.isNull())
3156 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3157
3158 // Ignore any declarations that we were told that we don't care about.
3159 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3160 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003161
3162 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003163 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3164 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003165
3166 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003167 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003168 Results.ExitScope();
3169
Douglas Gregor590c7d52010-07-08 20:55:51 +00003170 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003171 if (!Data.PreferredType.isNull())
3172 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3173 || Data.PreferredType->isMemberPointerType()
3174 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003175
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003176 if (S->getFnParent() &&
3177 !Data.ObjCCollection &&
3178 !Data.IntegralConstantExpression)
3179 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3180
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003181 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003182 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003183 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003184 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3185 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003186 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003187}
3188
Douglas Gregorac5fd842010-09-18 01:28:11 +00003189void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3190 if (E.isInvalid())
3191 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3192 else if (getLangOptions().ObjC1)
3193 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003194}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003195
Douglas Gregor73449212010-12-09 23:01:55 +00003196/// \brief The set of properties that have already been added, referenced by
3197/// property name.
3198typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3199
Douglas Gregor95ac6552009-11-18 01:29:26 +00003200static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003201 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003202 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003203 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003204 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003205 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003206 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003207
3208 // Add properties in this container.
3209 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3210 PEnd = Container->prop_end();
3211 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003212 ++P) {
3213 if (AddedProperties.insert(P->getIdentifier()))
3214 Results.MaybeAddResult(Result(*P, 0), CurContext);
3215 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003216
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003217 // Add nullary methods
3218 if (AllowNullaryMethods) {
3219 ASTContext &Context = Container->getASTContext();
Douglas Gregor8987b232011-09-27 23:30:47 +00003220 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003221 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3222 MEnd = Container->meth_end();
3223 M != MEnd; ++M) {
3224 if (M->getSelector().isUnarySelector())
3225 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3226 if (AddedProperties.insert(Name)) {
3227 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor8987b232011-09-27 23:30:47 +00003228 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003229 Builder.AddTypedTextChunk(
3230 Results.getAllocator().CopyString(Name->getName()));
3231
3232 CXAvailabilityKind Availability = CXAvailability_Available;
3233 switch (M->getAvailability()) {
3234 case AR_Available:
3235 case AR_NotYetIntroduced:
3236 Availability = CXAvailability_Available;
3237 break;
3238
3239 case AR_Deprecated:
3240 Availability = CXAvailability_Deprecated;
3241 break;
3242
3243 case AR_Unavailable:
3244 Availability = CXAvailability_NotAvailable;
3245 break;
3246 }
3247
3248 Results.MaybeAddResult(Result(Builder.TakeString(),
3249 CCP_MemberDeclaration + CCD_MethodAsProperty,
3250 M->isInstanceMethod()
3251 ? CXCursor_ObjCInstanceMethodDecl
3252 : CXCursor_ObjCClassMethodDecl,
3253 Availability),
3254 CurContext);
3255 }
3256 }
3257 }
3258
3259
Douglas Gregor95ac6552009-11-18 01:29:26 +00003260 // Add properties in referenced protocols.
3261 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3262 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3263 PEnd = Protocol->protocol_end();
3264 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003265 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3266 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003267 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003268 if (AllowCategories) {
3269 // Look through categories.
3270 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3271 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003272 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3273 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003274 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003275
3276 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003277 for (ObjCInterfaceDecl::all_protocol_iterator
3278 I = IFace->all_referenced_protocol_begin(),
3279 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003280 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3281 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003282
3283 // Look in the superclass.
3284 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003285 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3286 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003287 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003288 } else if (const ObjCCategoryDecl *Category
3289 = dyn_cast<ObjCCategoryDecl>(Container)) {
3290 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003291 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3292 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003293 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003294 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3295 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003296 }
3297}
3298
Richard Trieuf81e5a92011-09-09 02:00:50 +00003299void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *BaseE,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003300 SourceLocation OpLoc,
3301 bool IsArrow) {
3302 if (!BaseE || !CodeCompleter)
3303 return;
3304
John McCall0a2c5e22010-08-25 06:19:51 +00003305 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003306
Douglas Gregor81b747b2009-09-17 21:32:03 +00003307 Expr *Base = static_cast<Expr *>(BaseE);
3308 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003309
3310 if (IsArrow) {
3311 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3312 BaseType = Ptr->getPointeeType();
3313 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003314 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003315 else
3316 return;
3317 }
3318
Douglas Gregor3da626b2011-07-07 16:03:39 +00003319 enum CodeCompletionContext::Kind contextKind;
3320
3321 if (IsArrow) {
3322 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3323 }
3324 else {
3325 if (BaseType->isObjCObjectPointerType() ||
3326 BaseType->isObjCObjectOrInterfaceType()) {
3327 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3328 }
3329 else {
3330 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3331 }
3332 }
3333
Douglas Gregor218937c2011-02-01 19:23:04 +00003334 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003335 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003336 BaseType),
3337 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003338 Results.EnterNewScope();
3339 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003340 // Indicate that we are performing a member access, and the cv-qualifiers
3341 // for the base object type.
3342 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3343
Douglas Gregor95ac6552009-11-18 01:29:26 +00003344 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003345 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003346 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003347 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3348 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003349
Douglas Gregor95ac6552009-11-18 01:29:26 +00003350 if (getLangOptions().CPlusPlus) {
3351 if (!Results.empty()) {
3352 // The "template" keyword can follow "->" or "." in the grammar.
3353 // However, we only want to suggest the template keyword if something
3354 // is dependent.
3355 bool IsDependent = BaseType->isDependentType();
3356 if (!IsDependent) {
3357 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3358 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3359 IsDependent = Ctx->isDependentContext();
3360 break;
3361 }
3362 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003363
Douglas Gregor95ac6552009-11-18 01:29:26 +00003364 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003365 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003366 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003367 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003368 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3369 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003370 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003371
3372 // Add property results based on our interface.
3373 const ObjCObjectPointerType *ObjCPtr
3374 = BaseType->getAsObjCInterfacePointerType();
3375 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003376 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3377 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003378 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003379
3380 // Add properties from the protocols in a qualified interface.
3381 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3382 E = ObjCPtr->qual_end();
3383 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003384 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3385 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003386 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003387 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003388 // Objective-C instance variable access.
3389 ObjCInterfaceDecl *Class = 0;
3390 if (const ObjCObjectPointerType *ObjCPtr
3391 = BaseType->getAs<ObjCObjectPointerType>())
3392 Class = ObjCPtr->getInterfaceDecl();
3393 else
John McCallc12c5bb2010-05-15 11:32:37 +00003394 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003395
3396 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003397 if (Class) {
3398 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3399 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003400 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3401 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003402 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003403 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003404
3405 // FIXME: How do we cope with isa?
3406
3407 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003408
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003409 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003410 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003411 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003412 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003413}
3414
Douglas Gregor374929f2009-09-18 15:37:17 +00003415void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3416 if (!CodeCompleter)
3417 return;
3418
John McCall0a2c5e22010-08-25 06:19:51 +00003419 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003420 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003421 enum CodeCompletionContext::Kind ContextKind
3422 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003423 switch ((DeclSpec::TST)TagSpec) {
3424 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003425 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003426 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003427 break;
3428
3429 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003430 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003431 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003432 break;
3433
3434 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003435 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003436 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003437 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003438 break;
3439
3440 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003441 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003442 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003443
Douglas Gregor218937c2011-02-01 19:23:04 +00003444 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003445 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003446
3447 // First pass: look for tags.
3448 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003449 LookupVisibleDecls(S, LookupTagName, Consumer,
3450 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003451
Douglas Gregor8071e422010-08-15 06:18:01 +00003452 if (CodeCompleter->includeGlobals()) {
3453 // Second pass: look for nested name specifiers.
3454 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3455 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3456 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003457
Douglas Gregor52779fb2010-09-23 23:01:17 +00003458 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003459 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003460}
3461
Douglas Gregor1a480c42010-08-27 17:35:51 +00003462void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003463 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3464 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003465 Results.EnterNewScope();
3466 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3467 Results.AddResult("const");
3468 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3469 Results.AddResult("volatile");
3470 if (getLangOptions().C99 &&
3471 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3472 Results.AddResult("restrict");
3473 Results.ExitScope();
3474 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003475 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003476 Results.data(), Results.size());
3477}
3478
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003479void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003480 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003481 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003482
John McCall781472f2010-08-25 08:40:02 +00003483 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003484 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3485 if (!type->isEnumeralType()) {
3486 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003487 Data.IntegralConstantExpression = true;
3488 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003489 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003490 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003491
3492 // Code-complete the cases of a switch statement over an enumeration type
3493 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003494 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003495
3496 // Determine which enumerators we have already seen in the switch statement.
3497 // FIXME: Ideally, we would also be able to look *past* the code-completion
3498 // token, in case we are code-completing in the middle of the switch and not
3499 // at the end. However, we aren't able to do so at the moment.
3500 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003501 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003502 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3503 SC = SC->getNextSwitchCase()) {
3504 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3505 if (!Case)
3506 continue;
3507
3508 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3509 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3510 if (EnumConstantDecl *Enumerator
3511 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3512 // We look into the AST of the case statement to determine which
3513 // enumerator was named. Alternatively, we could compute the value of
3514 // the integral constant expression, then compare it against the
3515 // values of each enumerator. However, value-based approach would not
3516 // work as well with C++ templates where enumerators declared within a
3517 // template are type- and value-dependent.
3518 EnumeratorsSeen.insert(Enumerator);
3519
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003520 // If this is a qualified-id, keep track of the nested-name-specifier
3521 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003522 //
3523 // switch (TagD.getKind()) {
3524 // case TagDecl::TK_enum:
3525 // break;
3526 // case XXX
3527 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003528 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003529 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3530 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003531 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003532 }
3533 }
3534
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003535 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3536 // If there are no prior enumerators in C++, check whether we have to
3537 // qualify the names of the enumerators that we suggest, because they
3538 // may not be visible in this scope.
3539 Qualifier = getRequiredQualification(Context, CurContext,
3540 Enum->getDeclContext());
3541
3542 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3543 }
3544
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003545 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003546 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3547 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003548 Results.EnterNewScope();
3549 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3550 EEnd = Enum->enumerator_end();
3551 E != EEnd; ++E) {
3552 if (EnumeratorsSeen.count(*E))
3553 continue;
3554
Douglas Gregor5c722c702011-02-18 23:30:37 +00003555 CodeCompletionResult R(*E, Qualifier);
3556 R.Priority = CCP_EnumInCase;
3557 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003558 }
3559 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003560
Douglas Gregor3da626b2011-07-07 16:03:39 +00003561 //We need to make sure we're setting the right context,
3562 //so only say we include macros if the code completer says we do
3563 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3564 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003565 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003566 kind = CodeCompletionContext::CCC_OtherWithMacros;
3567 }
3568
3569
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003570 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003571 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003572 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003573}
3574
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003575namespace {
3576 struct IsBetterOverloadCandidate {
3577 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003578 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003579
3580 public:
John McCall5769d612010-02-08 23:07:23 +00003581 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3582 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003583
3584 bool
3585 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003586 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003587 }
3588 };
3589}
3590
Douglas Gregord28dcd72010-05-30 06:10:08 +00003591static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3592 if (NumArgs && !Args)
3593 return true;
3594
3595 for (unsigned I = 0; I != NumArgs; ++I)
3596 if (!Args[I])
3597 return true;
3598
3599 return false;
3600}
3601
Richard Trieuf81e5a92011-09-09 02:00:50 +00003602void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3603 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003604 if (!CodeCompleter)
3605 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003606
3607 // When we're code-completing for a call, we fall back to ordinary
3608 // name code-completion whenever we can't produce specific
3609 // results. We may want to revisit this strategy in the future,
3610 // e.g., by merging the two kinds of results.
3611
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003612 Expr *Fn = (Expr *)FnIn;
3613 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003614
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003615 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003616 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003617 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003618 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003619 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003620 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003621
John McCall3b4294e2009-12-16 12:17:52 +00003622 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003623 SourceLocation Loc = Fn->getExprLoc();
3624 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003625
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003626 // FIXME: What if we're calling something that isn't a function declaration?
3627 // FIXME: What if we're calling a pseudo-destructor?
3628 // FIXME: What if we're calling a member function?
3629
Douglas Gregorc0265402010-01-21 15:46:19 +00003630 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003631 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003632
John McCall3b4294e2009-12-16 12:17:52 +00003633 Expr *NakedFn = Fn->IgnoreParenCasts();
3634 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3635 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3636 /*PartialOverloading=*/ true);
3637 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3638 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003639 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003640 if (!getLangOptions().CPlusPlus ||
3641 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003642 Results.push_back(ResultCandidate(FDecl));
3643 else
John McCall86820f52010-01-26 01:37:31 +00003644 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003645 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3646 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003647 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003648 }
John McCall3b4294e2009-12-16 12:17:52 +00003649 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003650
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003651 QualType ParamType;
3652
Douglas Gregorc0265402010-01-21 15:46:19 +00003653 if (!CandidateSet.empty()) {
3654 // Sort the overload candidate set by placing the best overloads first.
3655 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003656 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003657
Douglas Gregorc0265402010-01-21 15:46:19 +00003658 // Add the remaining viable overload candidates as code-completion reslults.
3659 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3660 CandEnd = CandidateSet.end();
3661 Cand != CandEnd; ++Cand) {
3662 if (Cand->Viable)
3663 Results.push_back(ResultCandidate(Cand->Function));
3664 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003665
3666 // From the viable candidates, try to determine the type of this parameter.
3667 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3668 if (const FunctionType *FType = Results[I].getFunctionType())
3669 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3670 if (NumArgs < Proto->getNumArgs()) {
3671 if (ParamType.isNull())
3672 ParamType = Proto->getArgType(NumArgs);
3673 else if (!Context.hasSameUnqualifiedType(
3674 ParamType.getNonReferenceType(),
3675 Proto->getArgType(NumArgs).getNonReferenceType())) {
3676 ParamType = QualType();
3677 break;
3678 }
3679 }
3680 }
3681 } else {
3682 // Try to determine the parameter type from the type of the expression
3683 // being called.
3684 QualType FunctionType = Fn->getType();
3685 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3686 FunctionType = Ptr->getPointeeType();
3687 else if (const BlockPointerType *BlockPtr
3688 = FunctionType->getAs<BlockPointerType>())
3689 FunctionType = BlockPtr->getPointeeType();
3690 else if (const MemberPointerType *MemPtr
3691 = FunctionType->getAs<MemberPointerType>())
3692 FunctionType = MemPtr->getPointeeType();
3693
3694 if (const FunctionProtoType *Proto
3695 = FunctionType->getAs<FunctionProtoType>()) {
3696 if (NumArgs < Proto->getNumArgs())
3697 ParamType = Proto->getArgType(NumArgs);
3698 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003699 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003700
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003701 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003702 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003703 else
3704 CodeCompleteExpression(S, ParamType);
3705
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003706 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003707 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3708 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003709}
3710
John McCalld226f652010-08-21 09:40:31 +00003711void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3712 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003713 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003714 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003715 return;
3716 }
3717
3718 CodeCompleteExpression(S, VD->getType());
3719}
3720
3721void Sema::CodeCompleteReturn(Scope *S) {
3722 QualType ResultType;
3723 if (isa<BlockDecl>(CurContext)) {
3724 if (BlockScopeInfo *BSI = getCurBlock())
3725 ResultType = BSI->ReturnType;
3726 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3727 ResultType = Function->getResultType();
3728 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3729 ResultType = Method->getResultType();
3730
3731 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003732 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003733 else
3734 CodeCompleteExpression(S, ResultType);
3735}
3736
Douglas Gregord2d8be62011-07-30 08:36:53 +00003737void Sema::CodeCompleteAfterIf(Scope *S) {
3738 typedef CodeCompletionResult Result;
3739 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3740 mapCodeCompletionContext(*this, PCC_Statement));
3741 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3742 Results.EnterNewScope();
3743
3744 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3745 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3746 CodeCompleter->includeGlobals());
3747
3748 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3749
3750 // "else" block
3751 CodeCompletionBuilder Builder(Results.getAllocator());
3752 Builder.AddTypedTextChunk("else");
3753 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3754 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3755 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3756 Builder.AddPlaceholderChunk("statements");
3757 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3758 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3759 Results.AddResult(Builder.TakeString());
3760
3761 // "else if" block
3762 Builder.AddTypedTextChunk("else");
3763 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3764 Builder.AddTextChunk("if");
3765 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3766 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3767 if (getLangOptions().CPlusPlus)
3768 Builder.AddPlaceholderChunk("condition");
3769 else
3770 Builder.AddPlaceholderChunk("expression");
3771 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3772 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3773 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3774 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3775 Builder.AddPlaceholderChunk("statements");
3776 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3777 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3778 Results.AddResult(Builder.TakeString());
3779
3780 Results.ExitScope();
3781
3782 if (S->getFnParent())
3783 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3784
3785 if (CodeCompleter->includeMacros())
3786 AddMacroResults(PP, Results);
3787
3788 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3789 Results.data(),Results.size());
3790}
3791
Richard Trieuf81e5a92011-09-09 02:00:50 +00003792void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003793 if (LHS)
3794 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3795 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003796 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003797}
3798
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003799void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003800 bool EnteringContext) {
3801 if (!SS.getScopeRep() || !CodeCompleter)
3802 return;
3803
Douglas Gregor86d9a522009-09-21 16:56:56 +00003804 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3805 if (!Ctx)
3806 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003807
3808 // Try to instantiate any non-dependent declaration contexts before
3809 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003810 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003811 return;
3812
Douglas Gregor218937c2011-02-01 19:23:04 +00003813 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3814 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003815 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003816
Douglas Gregor86d9a522009-09-21 16:56:56 +00003817 // The "template" keyword can follow "::" in the grammar, but only
3818 // put it into the grammar if the nested-name-specifier is dependent.
3819 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3820 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003821 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003822
3823 // Add calls to overridden virtual functions, if there are any.
3824 //
3825 // FIXME: This isn't wonderful, because we don't know whether we're actually
3826 // in a context that permits expressions. This is a general issue with
3827 // qualified-id completions.
3828 if (!EnteringContext)
3829 MaybeAddOverrideCalls(*this, Ctx, Results);
3830 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003831
Douglas Gregorf6961522010-08-27 21:18:54 +00003832 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3833 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3834
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003835 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003836 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003837 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003838}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003839
3840void Sema::CodeCompleteUsing(Scope *S) {
3841 if (!CodeCompleter)
3842 return;
3843
Douglas Gregor218937c2011-02-01 19:23:04 +00003844 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003845 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3846 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003847 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003848
3849 // If we aren't in class scope, we could see the "namespace" keyword.
3850 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003851 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003852
3853 // After "using", we can see anything that would start a
3854 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003855 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003856 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3857 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003858 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003859
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003860 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003861 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003862 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003863}
3864
3865void Sema::CodeCompleteUsingDirective(Scope *S) {
3866 if (!CodeCompleter)
3867 return;
3868
Douglas Gregor86d9a522009-09-21 16:56:56 +00003869 // After "using namespace", we expect to see a namespace name or namespace
3870 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003871 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3872 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003873 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003874 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003875 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003876 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3877 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003878 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003879 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003880 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003881 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003882}
3883
3884void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3885 if (!CodeCompleter)
3886 return;
3887
Douglas Gregor86d9a522009-09-21 16:56:56 +00003888 DeclContext *Ctx = (DeclContext *)S->getEntity();
3889 if (!S->getParent())
3890 Ctx = Context.getTranslationUnitDecl();
3891
Douglas Gregor52779fb2010-09-23 23:01:17 +00003892 bool SuppressedGlobalResults
3893 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3894
Douglas Gregor218937c2011-02-01 19:23:04 +00003895 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003896 SuppressedGlobalResults
3897 ? CodeCompletionContext::CCC_Namespace
3898 : CodeCompletionContext::CCC_Other,
3899 &ResultBuilder::IsNamespace);
3900
3901 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003902 // We only want to see those namespaces that have already been defined
3903 // within this scope, because its likely that the user is creating an
3904 // extended namespace declaration. Keep track of the most recent
3905 // definition of each namespace.
3906 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3907 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3908 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3909 NS != NSEnd; ++NS)
3910 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3911
3912 // Add the most recent definition (or extended definition) of each
3913 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003914 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003915 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3916 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3917 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003918 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003919 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003920 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003921 }
3922
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003923 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003924 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003925 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003926}
3927
3928void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3929 if (!CodeCompleter)
3930 return;
3931
Douglas Gregor86d9a522009-09-21 16:56:56 +00003932 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003933 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3934 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003935 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003936 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003937 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3938 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003939 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003940 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003941 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003942}
3943
Douglas Gregored8d3222009-09-18 20:05:18 +00003944void Sema::CodeCompleteOperatorName(Scope *S) {
3945 if (!CodeCompleter)
3946 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003947
John McCall0a2c5e22010-08-25 06:19:51 +00003948 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003949 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3950 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003951 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003952 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003953
Douglas Gregor86d9a522009-09-21 16:56:56 +00003954 // Add the names of overloadable operators.
3955#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3956 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003957 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003958#include "clang/Basic/OperatorKinds.def"
3959
3960 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003961 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003962 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003963 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3964 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003965
3966 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003967 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003968 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003969
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003970 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003971 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003972 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003973}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003974
Douglas Gregor0133f522010-08-28 00:00:50 +00003975void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00003976 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00003977 unsigned NumInitializers) {
Douglas Gregor8987b232011-09-27 23:30:47 +00003978 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor0133f522010-08-28 00:00:50 +00003979 CXXConstructorDecl *Constructor
3980 = static_cast<CXXConstructorDecl *>(ConstructorD);
3981 if (!Constructor)
3982 return;
3983
Douglas Gregor218937c2011-02-01 19:23:04 +00003984 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003985 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003986 Results.EnterNewScope();
3987
3988 // Fill in any already-initialized fields or base classes.
3989 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3990 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3991 for (unsigned I = 0; I != NumInitializers; ++I) {
3992 if (Initializers[I]->isBaseInitializer())
3993 InitializedBases.insert(
3994 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3995 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003996 InitializedFields.insert(cast<FieldDecl>(
3997 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00003998 }
3999
4000 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00004001 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00004002 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00004003 CXXRecordDecl *ClassDecl = Constructor->getParent();
4004 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4005 BaseEnd = ClassDecl->bases_end();
4006 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004007 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4008 SawLastInitializer
4009 = NumInitializers > 0 &&
4010 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4011 Context.hasSameUnqualifiedType(Base->getType(),
4012 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004013 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004014 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004015
Douglas Gregor218937c2011-02-01 19:23:04 +00004016 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004017 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004018 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004019 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4020 Builder.AddPlaceholderChunk("args");
4021 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4022 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004023 SawLastInitializer? CCP_NextInitializer
4024 : CCP_MemberDeclaration));
4025 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004026 }
4027
4028 // Add completions for virtual base classes.
4029 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4030 BaseEnd = ClassDecl->vbases_end();
4031 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004032 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4033 SawLastInitializer
4034 = NumInitializers > 0 &&
4035 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4036 Context.hasSameUnqualifiedType(Base->getType(),
4037 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004038 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004039 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004040
Douglas Gregor218937c2011-02-01 19:23:04 +00004041 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004042 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004043 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004044 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4045 Builder.AddPlaceholderChunk("args");
4046 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4047 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004048 SawLastInitializer? CCP_NextInitializer
4049 : CCP_MemberDeclaration));
4050 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004051 }
4052
4053 // Add completions for members.
4054 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4055 FieldEnd = ClassDecl->field_end();
4056 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004057 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4058 SawLastInitializer
4059 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004060 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4061 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004062 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004063 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004064
4065 if (!Field->getDeclName())
4066 continue;
4067
Douglas Gregordae68752011-02-01 22:57:45 +00004068 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004069 Field->getIdentifier()->getName()));
4070 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4071 Builder.AddPlaceholderChunk("args");
4072 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4073 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004074 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004075 : CCP_MemberDeclaration,
4076 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004077 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004078 }
4079 Results.ExitScope();
4080
Douglas Gregor52779fb2010-09-23 23:01:17 +00004081 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004082 Results.data(), Results.size());
4083}
4084
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004085// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4086// true or false.
4087#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004088static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004089 ResultBuilder &Results,
4090 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004091 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004092 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004093 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004094
Douglas Gregor218937c2011-02-01 19:23:04 +00004095 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004096 if (LangOpts.ObjC2) {
4097 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004098 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4099 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4100 Builder.AddPlaceholderChunk("property");
4101 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004102
4103 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004104 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4105 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4106 Builder.AddPlaceholderChunk("property");
4107 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004108 }
4109}
4110
Douglas Gregorbca403c2010-01-13 23:51:12 +00004111static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004112 ResultBuilder &Results,
4113 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004114 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004115
4116 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004117 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004118
4119 if (LangOpts.ObjC2) {
4120 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004121 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004122
4123 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004124 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004125
4126 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004127 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004128 }
4129}
4130
Douglas Gregorbca403c2010-01-13 23:51:12 +00004131static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004132 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004133 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004134
4135 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004136 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4137 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4138 Builder.AddPlaceholderChunk("name");
4139 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004140
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004141 if (Results.includeCodePatterns()) {
4142 // @interface name
4143 // FIXME: Could introduce the whole pattern, including superclasses and
4144 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004145 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4146 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4147 Builder.AddPlaceholderChunk("class");
4148 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004149
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004150 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004151 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4152 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4153 Builder.AddPlaceholderChunk("protocol");
4154 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004155
4156 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004157 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4158 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4159 Builder.AddPlaceholderChunk("class");
4160 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004161 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004162
4163 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004164 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4165 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4166 Builder.AddPlaceholderChunk("alias");
4167 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4168 Builder.AddPlaceholderChunk("class");
4169 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004170}
4171
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004172void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004173 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004174 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4175 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004176 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004177 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorbca403c2010-01-13 23:51:12 +00004178 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004179 else if (CurContext->isObjCContainer())
Douglas Gregorbca403c2010-01-13 23:51:12 +00004180 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004181 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004182 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004183 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004184 HandleCodeCompleteResults(this, CodeCompleter,
4185 CodeCompletionContext::CCC_Other,
4186 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004187}
4188
Douglas Gregorbca403c2010-01-13 23:51:12 +00004189static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004190 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004191 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004192
4193 // @encode ( type-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004194 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4195 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4196 Builder.AddPlaceholderChunk("type-name");
4197 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4198 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004199
4200 // @protocol ( protocol-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004201 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4202 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4203 Builder.AddPlaceholderChunk("protocol-name");
4204 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4205 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004206
4207 // @selector ( selector )
Douglas Gregor218937c2011-02-01 19:23:04 +00004208 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4209 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4210 Builder.AddPlaceholderChunk("selector");
4211 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4212 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004213}
4214
Douglas Gregorbca403c2010-01-13 23:51:12 +00004215static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004216 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004217 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004218
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004219 if (Results.includeCodePatterns()) {
4220 // @try { statements } @catch ( declaration ) { statements } @finally
4221 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004222 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4223 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4224 Builder.AddPlaceholderChunk("statements");
4225 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4226 Builder.AddTextChunk("@catch");
4227 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4228 Builder.AddPlaceholderChunk("parameter");
4229 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4230 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4231 Builder.AddPlaceholderChunk("statements");
4232 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4233 Builder.AddTextChunk("@finally");
4234 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4235 Builder.AddPlaceholderChunk("statements");
4236 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4237 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004238 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004239
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004240 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004241 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4242 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4243 Builder.AddPlaceholderChunk("expression");
4244 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004245
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004246 if (Results.includeCodePatterns()) {
4247 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004248 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4249 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4250 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4251 Builder.AddPlaceholderChunk("expression");
4252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4253 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4254 Builder.AddPlaceholderChunk("statements");
4255 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4256 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004257 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004258}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004259
Douglas Gregorbca403c2010-01-13 23:51:12 +00004260static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004261 ResultBuilder &Results,
4262 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004263 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004264 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4265 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4266 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004267 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004268 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004269}
4270
4271void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004272 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4273 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004274 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004275 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004276 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004277 HandleCodeCompleteResults(this, CodeCompleter,
4278 CodeCompletionContext::CCC_Other,
4279 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004280}
4281
4282void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004283 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4284 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004285 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004286 AddObjCStatementResults(Results, false);
4287 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004288 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004289 HandleCodeCompleteResults(this, CodeCompleter,
4290 CodeCompletionContext::CCC_Other,
4291 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004292}
4293
4294void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004295 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4296 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004297 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004298 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004299 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004300 HandleCodeCompleteResults(this, CodeCompleter,
4301 CodeCompletionContext::CCC_Other,
4302 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004303}
4304
Douglas Gregor988358f2009-11-19 00:14:45 +00004305/// \brief Determine whether the addition of the given flag to an Objective-C
4306/// property's attributes will cause a conflict.
4307static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4308 // Check if we've already added this flag.
4309 if (Attributes & NewFlag)
4310 return true;
4311
4312 Attributes |= NewFlag;
4313
4314 // Check for collisions with "readonly".
4315 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4316 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4317 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004318 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004319 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004320 ObjCDeclSpec::DQ_PR_retain |
4321 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004322 return true;
4323
John McCallf85e1932011-06-15 23:02:42 +00004324 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004325 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004326 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004327 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004328 ObjCDeclSpec::DQ_PR_retain|
4329 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004330 if (AssignCopyRetMask &&
4331 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004332 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004333 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004334 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4335 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004336 return true;
4337
4338 return false;
4339}
4340
Douglas Gregora93b1082009-11-18 23:08:07 +00004341void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004342 if (!CodeCompleter)
4343 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004344
Steve Naroffece8e712009-10-08 21:55:05 +00004345 unsigned Attributes = ODS.getPropertyAttributes();
4346
John McCall0a2c5e22010-08-25 06:19:51 +00004347 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004348 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4349 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004350 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004351 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004352 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004353 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004354 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004355 if (!ObjCPropertyFlagConflicts(Attributes,
4356 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4357 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004358 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004359 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004360 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004361 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004362 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4363 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004364 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004365 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004366 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004367 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004368 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4369 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004370 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004371 CodeCompletionBuilder Setter(Results.getAllocator());
4372 Setter.AddTypedTextChunk("setter");
4373 Setter.AddTextChunk(" = ");
4374 Setter.AddPlaceholderChunk("method");
4375 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004376 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004377 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004378 CodeCompletionBuilder Getter(Results.getAllocator());
4379 Getter.AddTypedTextChunk("getter");
4380 Getter.AddTextChunk(" = ");
4381 Getter.AddPlaceholderChunk("method");
4382 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004383 }
Steve Naroffece8e712009-10-08 21:55:05 +00004384 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004385 HandleCodeCompleteResults(this, CodeCompleter,
4386 CodeCompletionContext::CCC_Other,
4387 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004388}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004389
Douglas Gregor4ad96852009-11-19 07:41:15 +00004390/// \brief Descripts the kind of Objective-C method that we want to find
4391/// via code completion.
4392enum ObjCMethodKind {
4393 MK_Any, //< Any kind of method, provided it means other specified criteria.
4394 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4395 MK_OneArgSelector //< One-argument selector.
4396};
4397
Douglas Gregor458433d2010-08-26 15:07:07 +00004398static bool isAcceptableObjCSelector(Selector Sel,
4399 ObjCMethodKind WantKind,
4400 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004401 unsigned NumSelIdents,
4402 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004403 if (NumSelIdents > Sel.getNumArgs())
4404 return false;
4405
4406 switch (WantKind) {
4407 case MK_Any: break;
4408 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4409 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4410 }
4411
Douglas Gregorcf544262010-11-17 21:36:08 +00004412 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4413 return false;
4414
Douglas Gregor458433d2010-08-26 15:07:07 +00004415 for (unsigned I = 0; I != NumSelIdents; ++I)
4416 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4417 return false;
4418
4419 return true;
4420}
4421
Douglas Gregor4ad96852009-11-19 07:41:15 +00004422static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4423 ObjCMethodKind WantKind,
4424 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004425 unsigned NumSelIdents,
4426 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004427 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004428 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004429}
Douglas Gregord36adf52010-09-16 16:06:31 +00004430
4431namespace {
4432 /// \brief A set of selectors, which is used to avoid introducing multiple
4433 /// completions with the same selector into the result set.
4434 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4435}
4436
Douglas Gregor36ecb042009-11-17 23:22:23 +00004437/// \brief Add all of the Objective-C methods in the given Objective-C
4438/// container to the set of results.
4439///
4440/// The container will be a class, protocol, category, or implementation of
4441/// any of the above. This mether will recurse to include methods from
4442/// the superclasses of classes along with their categories, protocols, and
4443/// implementations.
4444///
4445/// \param Container the container in which we'll look to find methods.
4446///
4447/// \param WantInstance whether to add instance methods (only); if false, this
4448/// routine will add factory methods (only).
4449///
4450/// \param CurContext the context in which we're performing the lookup that
4451/// finds methods.
4452///
Douglas Gregorcf544262010-11-17 21:36:08 +00004453/// \param AllowSameLength Whether we allow a method to be added to the list
4454/// when it has the same number of parameters as we have selector identifiers.
4455///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004456/// \param Results the structure into which we'll add results.
4457static void AddObjCMethods(ObjCContainerDecl *Container,
4458 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004459 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004460 IdentifierInfo **SelIdents,
4461 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004462 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004463 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004464 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004465 ResultBuilder &Results,
4466 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004467 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004468 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4469 MEnd = Container->meth_end();
4470 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004471 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4472 // Check whether the selector identifiers we've been given are a
4473 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004474 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4475 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004476 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004477
Douglas Gregord36adf52010-09-16 16:06:31 +00004478 if (!Selectors.insert((*M)->getSelector()))
4479 continue;
4480
Douglas Gregord3c68542009-11-19 01:08:35 +00004481 Result R = Result(*M, 0);
4482 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004483 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004484 if (!InOriginalClass)
4485 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004486 Results.MaybeAddResult(R, CurContext);
4487 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004488 }
4489
Douglas Gregore396c7b2010-09-16 15:34:59 +00004490 // Visit the protocols of protocols.
4491 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4492 const ObjCList<ObjCProtocolDecl> &Protocols
4493 = Protocol->getReferencedProtocols();
4494 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4495 E = Protocols.end();
4496 I != E; ++I)
4497 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004498 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004499 }
4500
Douglas Gregor36ecb042009-11-17 23:22:23 +00004501 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4502 if (!IFace)
4503 return;
4504
4505 // Add methods in protocols.
4506 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4507 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4508 E = Protocols.end();
4509 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004510 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004511 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004512
4513 // Add methods in categories.
4514 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4515 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004516 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004517 NumSelIdents, CurContext, Selectors, AllowSameLength,
4518 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004519
4520 // Add a categories protocol methods.
4521 const ObjCList<ObjCProtocolDecl> &Protocols
4522 = CatDecl->getReferencedProtocols();
4523 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4524 E = Protocols.end();
4525 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004526 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004527 NumSelIdents, CurContext, Selectors, AllowSameLength,
4528 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004529
4530 // Add methods in category implementations.
4531 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004532 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004533 NumSelIdents, CurContext, Selectors, AllowSameLength,
4534 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004535 }
4536
4537 // Add methods in superclass.
4538 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004539 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004540 SelIdents, NumSelIdents, CurContext, Selectors,
4541 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004542
4543 // Add methods in our implementation, if any.
4544 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004545 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004546 NumSelIdents, CurContext, Selectors, AllowSameLength,
4547 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004548}
4549
4550
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004551void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004552 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004553
4554 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004555 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004556 if (!Class) {
4557 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004558 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004559 Class = Category->getClassInterface();
4560
4561 if (!Class)
4562 return;
4563 }
4564
4565 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004566 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4567 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004568 Results.EnterNewScope();
4569
Douglas Gregord36adf52010-09-16 16:06:31 +00004570 VisitedSelectorSet Selectors;
4571 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004572 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004573 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004574 HandleCodeCompleteResults(this, CodeCompleter,
4575 CodeCompletionContext::CCC_Other,
4576 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004577}
4578
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004579void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004580 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004581
4582 // Try to find the interface where setters might live.
4583 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004584 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004585 if (!Class) {
4586 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004587 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004588 Class = Category->getClassInterface();
4589
4590 if (!Class)
4591 return;
4592 }
4593
4594 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004595 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4596 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004597 Results.EnterNewScope();
4598
Douglas Gregord36adf52010-09-16 16:06:31 +00004599 VisitedSelectorSet Selectors;
4600 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004601 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004602
4603 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004604 HandleCodeCompleteResults(this, CodeCompleter,
4605 CodeCompletionContext::CCC_Other,
4606 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004607}
4608
Douglas Gregorafc45782011-02-15 22:19:42 +00004609void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4610 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004611 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004612 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4613 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004614 Results.EnterNewScope();
4615
4616 // Add context-sensitive, Objective-C parameter-passing keywords.
4617 bool AddedInOut = false;
4618 if ((DS.getObjCDeclQualifier() &
4619 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4620 Results.AddResult("in");
4621 Results.AddResult("inout");
4622 AddedInOut = true;
4623 }
4624 if ((DS.getObjCDeclQualifier() &
4625 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4626 Results.AddResult("out");
4627 if (!AddedInOut)
4628 Results.AddResult("inout");
4629 }
4630 if ((DS.getObjCDeclQualifier() &
4631 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4632 ObjCDeclSpec::DQ_Oneway)) == 0) {
4633 Results.AddResult("bycopy");
4634 Results.AddResult("byref");
4635 Results.AddResult("oneway");
4636 }
4637
Douglas Gregorafc45782011-02-15 22:19:42 +00004638 // If we're completing the return type of an Objective-C method and the
4639 // identifier IBAction refers to a macro, provide a completion item for
4640 // an action, e.g.,
4641 // IBAction)<#selector#>:(id)sender
4642 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4643 Context.Idents.get("IBAction").hasMacroDefinition()) {
4644 typedef CodeCompletionString::Chunk Chunk;
4645 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4646 CXAvailability_Available);
4647 Builder.AddTypedTextChunk("IBAction");
4648 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4649 Builder.AddPlaceholderChunk("selector");
4650 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4651 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4652 Builder.AddTextChunk("id");
4653 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4654 Builder.AddTextChunk("sender");
4655 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4656 }
4657
Douglas Gregord32b0222010-08-24 01:06:58 +00004658 // Add various builtin type names and specifiers.
4659 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4660 Results.ExitScope();
4661
4662 // Add the various type names
4663 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4664 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4665 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4666 CodeCompleter->includeGlobals());
4667
4668 if (CodeCompleter->includeMacros())
4669 AddMacroResults(PP, Results);
4670
4671 HandleCodeCompleteResults(this, CodeCompleter,
4672 CodeCompletionContext::CCC_Type,
4673 Results.data(), Results.size());
4674}
4675
Douglas Gregor22f56992010-04-06 19:22:33 +00004676/// \brief When we have an expression with type "id", we may assume
4677/// that it has some more-specific class type based on knowledge of
4678/// common uses of Objective-C. This routine returns that class type,
4679/// or NULL if no better result could be determined.
4680static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004681 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004682 if (!Msg)
4683 return 0;
4684
4685 Selector Sel = Msg->getSelector();
4686 if (Sel.isNull())
4687 return 0;
4688
4689 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4690 if (!Id)
4691 return 0;
4692
4693 ObjCMethodDecl *Method = Msg->getMethodDecl();
4694 if (!Method)
4695 return 0;
4696
4697 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004698 ObjCInterfaceDecl *IFace = 0;
4699 switch (Msg->getReceiverKind()) {
4700 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004701 if (const ObjCObjectType *ObjType
4702 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4703 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004704 break;
4705
4706 case ObjCMessageExpr::Instance: {
4707 QualType T = Msg->getInstanceReceiver()->getType();
4708 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4709 IFace = Ptr->getInterfaceDecl();
4710 break;
4711 }
4712
4713 case ObjCMessageExpr::SuperInstance:
4714 case ObjCMessageExpr::SuperClass:
4715 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004716 }
4717
4718 if (!IFace)
4719 return 0;
4720
4721 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4722 if (Method->isInstanceMethod())
4723 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4724 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004725 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004726 .Case("autorelease", IFace)
4727 .Case("copy", IFace)
4728 .Case("copyWithZone", IFace)
4729 .Case("mutableCopy", IFace)
4730 .Case("mutableCopyWithZone", IFace)
4731 .Case("awakeFromCoder", IFace)
4732 .Case("replacementObjectFromCoder", IFace)
4733 .Case("class", IFace)
4734 .Case("classForCoder", IFace)
4735 .Case("superclass", Super)
4736 .Default(0);
4737
4738 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4739 .Case("new", IFace)
4740 .Case("alloc", IFace)
4741 .Case("allocWithZone", IFace)
4742 .Case("class", IFace)
4743 .Case("superclass", Super)
4744 .Default(0);
4745}
4746
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004747// Add a special completion for a message send to "super", which fills in the
4748// most likely case of forwarding all of our arguments to the superclass
4749// function.
4750///
4751/// \param S The semantic analysis object.
4752///
4753/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4754/// the "super" keyword. Otherwise, we just need to provide the arguments.
4755///
4756/// \param SelIdents The identifiers in the selector that have already been
4757/// provided as arguments for a send to "super".
4758///
4759/// \param NumSelIdents The number of identifiers in \p SelIdents.
4760///
4761/// \param Results The set of results to augment.
4762///
4763/// \returns the Objective-C method declaration that would be invoked by
4764/// this "super" completion. If NULL, no completion was added.
4765static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4766 IdentifierInfo **SelIdents,
4767 unsigned NumSelIdents,
4768 ResultBuilder &Results) {
4769 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4770 if (!CurMethod)
4771 return 0;
4772
4773 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4774 if (!Class)
4775 return 0;
4776
4777 // Try to find a superclass method with the same selector.
4778 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004779 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4780 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004781 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4782 CurMethod->isInstanceMethod());
4783
Douglas Gregor78bcd912011-02-16 00:51:18 +00004784 // Check in categories or class extensions.
4785 if (!SuperMethod) {
4786 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4787 Category = Category->getNextClassCategory())
4788 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4789 CurMethod->isInstanceMethod())))
4790 break;
4791 }
4792 }
4793
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004794 if (!SuperMethod)
4795 return 0;
4796
4797 // Check whether the superclass method has the same signature.
4798 if (CurMethod->param_size() != SuperMethod->param_size() ||
4799 CurMethod->isVariadic() != SuperMethod->isVariadic())
4800 return 0;
4801
4802 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4803 CurPEnd = CurMethod->param_end(),
4804 SuperP = SuperMethod->param_begin();
4805 CurP != CurPEnd; ++CurP, ++SuperP) {
4806 // Make sure the parameter types are compatible.
4807 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4808 (*SuperP)->getType()))
4809 return 0;
4810
4811 // Make sure we have a parameter name to forward!
4812 if (!(*CurP)->getIdentifier())
4813 return 0;
4814 }
4815
4816 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004817 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004818
4819 // Give this completion a return type.
Douglas Gregor8987b232011-09-27 23:30:47 +00004820 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
4821 Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004822
4823 // If we need the "super" keyword, add it (plus some spacing).
4824 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004825 Builder.AddTypedTextChunk("super");
4826 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004827 }
4828
4829 Selector Sel = CurMethod->getSelector();
4830 if (Sel.isUnarySelector()) {
4831 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004832 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004833 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004834 else
Douglas Gregordae68752011-02-01 22:57:45 +00004835 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004836 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004837 } else {
4838 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4839 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4840 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004841 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004842
4843 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004844 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004845 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004846 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004847 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004848 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004849 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004850 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004851 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004852 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004853 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004854 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004855 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004856 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004857 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004858 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004859 }
4860 }
4861 }
4862
Douglas Gregor218937c2011-02-01 19:23:04 +00004863 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004864 SuperMethod->isInstanceMethod()
4865 ? CXCursor_ObjCInstanceMethodDecl
4866 : CXCursor_ObjCClassMethodDecl));
4867 return SuperMethod;
4868}
4869
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004870void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004871 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004872 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4873 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004874 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004875
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004876 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4877 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004878 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4879 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004880
4881 // If we are in an Objective-C method inside a class that has a superclass,
4882 // add "super" as an option.
4883 if (ObjCMethodDecl *Method = getCurMethodDecl())
4884 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004885 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004886 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004887
4888 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4889 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004890
4891 Results.ExitScope();
4892
4893 if (CodeCompleter->includeMacros())
4894 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004895 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004896 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004897
4898}
4899
Douglas Gregor2725ca82010-04-21 19:57:20 +00004900void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4901 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004902 unsigned NumSelIdents,
4903 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004904 ObjCInterfaceDecl *CDecl = 0;
4905 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4906 // Figure out which interface we're in.
4907 CDecl = CurMethod->getClassInterface();
4908 if (!CDecl)
4909 return;
4910
4911 // Find the superclass of this class.
4912 CDecl = CDecl->getSuperClass();
4913 if (!CDecl)
4914 return;
4915
4916 if (CurMethod->isInstanceMethod()) {
4917 // We are inside an instance method, which means that the message
4918 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004919 // current object.
4920 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004921 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004922 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004923 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004924 }
4925
4926 // Fall through to send to the superclass in CDecl.
4927 } else {
4928 // "super" may be the name of a type or variable. Figure out which
4929 // it is.
4930 IdentifierInfo *Super = &Context.Idents.get("super");
4931 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4932 LookupOrdinaryName);
4933 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4934 // "super" names an interface. Use it.
4935 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004936 if (const ObjCObjectType *Iface
4937 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4938 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004939 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4940 // "super" names an unresolved type; we can't be more specific.
4941 } else {
4942 // Assume that "super" names some kind of value and parse that way.
4943 CXXScopeSpec SS;
4944 UnqualifiedId id;
4945 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004946 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004947 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004948 SelIdents, NumSelIdents,
4949 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004950 }
4951
4952 // Fall through
4953 }
4954
John McCallb3d87482010-08-24 05:47:05 +00004955 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004956 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004957 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004958 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004959 NumSelIdents, AtArgumentExpression,
4960 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004961}
4962
Douglas Gregorb9d77572010-09-21 00:03:25 +00004963/// \brief Given a set of code-completion results for the argument of a message
4964/// send, determine the preferred type (if any) for that argument expression.
4965static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4966 unsigned NumSelIdents) {
4967 typedef CodeCompletionResult Result;
4968 ASTContext &Context = Results.getSema().Context;
4969
4970 QualType PreferredType;
4971 unsigned BestPriority = CCP_Unlikely * 2;
4972 Result *ResultsData = Results.data();
4973 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4974 Result &R = ResultsData[I];
4975 if (R.Kind == Result::RK_Declaration &&
4976 isa<ObjCMethodDecl>(R.Declaration)) {
4977 if (R.Priority <= BestPriority) {
4978 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4979 if (NumSelIdents <= Method->param_size()) {
4980 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4981 ->getType();
4982 if (R.Priority < BestPriority || PreferredType.isNull()) {
4983 BestPriority = R.Priority;
4984 PreferredType = MyPreferredType;
4985 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4986 MyPreferredType)) {
4987 PreferredType = QualType();
4988 }
4989 }
4990 }
4991 }
4992 }
4993
4994 return PreferredType;
4995}
4996
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004997static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4998 ParsedType Receiver,
4999 IdentifierInfo **SelIdents,
5000 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005001 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005002 bool IsSuper,
5003 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005004 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00005005 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005006
Douglas Gregor24a069f2009-11-17 17:59:40 +00005007 // If the given name refers to an interface type, retrieve the
5008 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00005009 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005010 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005011 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00005012 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5013 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00005014 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005015
Douglas Gregor36ecb042009-11-17 23:22:23 +00005016 // Add all of the factory methods in this Objective-C class, its protocols,
5017 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00005018 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005019
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005020 // If this is a send-to-super, try to add the special "super" send
5021 // completion.
5022 if (IsSuper) {
5023 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005024 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5025 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005026 Results.Ignore(SuperMethod);
5027 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005028
Douglas Gregor265f7492010-08-27 15:29:55 +00005029 // If we're inside an Objective-C method definition, prefer its selector to
5030 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005031 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005032 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005033
Douglas Gregord36adf52010-09-16 16:06:31 +00005034 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005035 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005036 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005037 SemaRef.CurContext, Selectors, AtArgumentExpression,
5038 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005039 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005040 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005041
Douglas Gregor719770d2010-04-06 17:30:22 +00005042 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005043 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005044 if (SemaRef.ExternalSource) {
5045 for (uint32_t I = 0,
5046 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005047 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005048 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5049 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005050 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005051
5052 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005053 }
5054 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005055
5056 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5057 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005058 M != MEnd; ++M) {
5059 for (ObjCMethodList *MethList = &M->second.second;
5060 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005061 MethList = MethList->Next) {
5062 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5063 NumSelIdents))
5064 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005065
Douglas Gregor13438f92010-04-06 16:40:00 +00005066 Result R(MethList->Method, 0);
5067 R.StartParameter = NumSelIdents;
5068 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005069 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005070 }
5071 }
5072 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005073
5074 Results.ExitScope();
5075}
Douglas Gregor13438f92010-04-06 16:40:00 +00005076
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005077void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5078 IdentifierInfo **SelIdents,
5079 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005080 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005081 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005082
5083 QualType T = this->GetTypeFromParser(Receiver);
5084
Douglas Gregor218937c2011-02-01 19:23:04 +00005085 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005086 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005087 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005088
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005089 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5090 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005091
5092 // If we're actually at the argument expression (rather than prior to the
5093 // selector), we're actually performing code completion for an expression.
5094 // Determine whether we have a single, best method. If so, we can
5095 // code-complete the expression using the corresponding parameter type as
5096 // our preferred type, improving completion results.
5097 if (AtArgumentExpression) {
5098 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005099 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005100 if (PreferredType.isNull())
5101 CodeCompleteOrdinaryName(S, PCC_Expression);
5102 else
5103 CodeCompleteExpression(S, PreferredType);
5104 return;
5105 }
5106
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005107 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005108 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005109 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005110}
5111
Richard Trieuf81e5a92011-09-09 02:00:50 +00005112void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005113 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005114 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005115 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005116 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005117 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005118
5119 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005120
Douglas Gregor36ecb042009-11-17 23:22:23 +00005121 // If necessary, apply function/array conversion to the receiver.
5122 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005123 if (RecExpr) {
5124 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5125 if (Conv.isInvalid()) // conversion failed. bail.
5126 return;
5127 RecExpr = Conv.take();
5128 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005129 QualType ReceiverType = RecExpr? RecExpr->getType()
5130 : Super? Context.getObjCObjectPointerType(
5131 Context.getObjCInterfaceType(Super))
5132 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005133
Douglas Gregorda892642010-11-08 21:12:30 +00005134 // If we're messaging an expression with type "id" or "Class", check
5135 // whether we know something special about the receiver that allows
5136 // us to assume a more-specific receiver type.
5137 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5138 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5139 if (ReceiverType->isObjCClassType())
5140 return CodeCompleteObjCClassMessage(S,
5141 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5142 SelIdents, NumSelIdents,
5143 AtArgumentExpression, Super);
5144
5145 ReceiverType = Context.getObjCObjectPointerType(
5146 Context.getObjCInterfaceType(IFace));
5147 }
5148
Douglas Gregor36ecb042009-11-17 23:22:23 +00005149 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005150 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005151 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005152 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005153
Douglas Gregor36ecb042009-11-17 23:22:23 +00005154 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005155
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005156 // If this is a send-to-super, try to add the special "super" send
5157 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005158 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005159 if (ObjCMethodDecl *SuperMethod
5160 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5161 Results))
5162 Results.Ignore(SuperMethod);
5163 }
5164
Douglas Gregor265f7492010-08-27 15:29:55 +00005165 // If we're inside an Objective-C method definition, prefer its selector to
5166 // others.
5167 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5168 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005169
Douglas Gregord36adf52010-09-16 16:06:31 +00005170 // Keep track of the selectors we've already added.
5171 VisitedSelectorSet Selectors;
5172
Douglas Gregorf74a4192009-11-18 00:06:18 +00005173 // Handle messages to Class. This really isn't a message to an instance
5174 // method, so we treat it the same way we would treat a message send to a
5175 // class method.
5176 if (ReceiverType->isObjCClassType() ||
5177 ReceiverType->isObjCQualifiedClassType()) {
5178 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5179 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005180 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005181 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005182 }
5183 }
5184 // Handle messages to a qualified ID ("id<foo>").
5185 else if (const ObjCObjectPointerType *QualID
5186 = ReceiverType->getAsObjCQualifiedIdType()) {
5187 // Search protocols for instance methods.
5188 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5189 E = QualID->qual_end();
5190 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005191 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005192 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005193 }
5194 // Handle messages to a pointer to interface type.
5195 else if (const ObjCObjectPointerType *IFacePtr
5196 = ReceiverType->getAsObjCInterfacePointerType()) {
5197 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005198 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005199 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5200 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005201
5202 // Search protocols for instance methods.
5203 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5204 E = IFacePtr->qual_end();
5205 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005206 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005207 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005208 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005209 // Handle messages to "id".
5210 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005211 // We're messaging "id", so provide all instance methods we know
5212 // about as code-completion results.
5213
5214 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005215 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005216 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005217 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5218 I != N; ++I) {
5219 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005220 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005221 continue;
5222
Sebastian Redldb9d2142010-08-02 23:18:59 +00005223 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005224 }
5225 }
5226
Sebastian Redldb9d2142010-08-02 23:18:59 +00005227 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5228 MEnd = MethodPool.end();
5229 M != MEnd; ++M) {
5230 for (ObjCMethodList *MethList = &M->second.first;
5231 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005232 MethList = MethList->Next) {
5233 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5234 NumSelIdents))
5235 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005236
5237 if (!Selectors.insert(MethList->Method->getSelector()))
5238 continue;
5239
Douglas Gregor13438f92010-04-06 16:40:00 +00005240 Result R(MethList->Method, 0);
5241 R.StartParameter = NumSelIdents;
5242 R.AllParametersAreInformative = false;
5243 Results.MaybeAddResult(R, CurContext);
5244 }
5245 }
5246 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005247 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005248
5249
5250 // If we're actually at the argument expression (rather than prior to the
5251 // selector), we're actually performing code completion for an expression.
5252 // Determine whether we have a single, best method. If so, we can
5253 // code-complete the expression using the corresponding parameter type as
5254 // our preferred type, improving completion results.
5255 if (AtArgumentExpression) {
5256 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5257 NumSelIdents);
5258 if (PreferredType.isNull())
5259 CodeCompleteOrdinaryName(S, PCC_Expression);
5260 else
5261 CodeCompleteExpression(S, PreferredType);
5262 return;
5263 }
5264
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005265 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005266 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005267 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005268}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005269
Douglas Gregorfb629412010-08-23 21:17:50 +00005270void Sema::CodeCompleteObjCForCollection(Scope *S,
5271 DeclGroupPtrTy IterationVar) {
5272 CodeCompleteExpressionData Data;
5273 Data.ObjCCollection = true;
5274
5275 if (IterationVar.getAsOpaquePtr()) {
5276 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5277 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5278 if (*I)
5279 Data.IgnoreDecls.push_back(*I);
5280 }
5281 }
5282
5283 CodeCompleteExpression(S, Data);
5284}
5285
Douglas Gregor458433d2010-08-26 15:07:07 +00005286void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5287 unsigned NumSelIdents) {
5288 // If we have an external source, load the entire class method
5289 // pool from the AST file.
5290 if (ExternalSource) {
5291 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5292 I != N; ++I) {
5293 Selector Sel = ExternalSource->GetExternalSelector(I);
5294 if (Sel.isNull() || MethodPool.count(Sel))
5295 continue;
5296
5297 ReadMethodPool(Sel);
5298 }
5299 }
5300
Douglas Gregor218937c2011-02-01 19:23:04 +00005301 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5302 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005303 Results.EnterNewScope();
5304 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5305 MEnd = MethodPool.end();
5306 M != MEnd; ++M) {
5307
5308 Selector Sel = M->first;
5309 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5310 continue;
5311
Douglas Gregor218937c2011-02-01 19:23:04 +00005312 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005313 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005314 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005315 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005316 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005317 continue;
5318 }
5319
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005320 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005321 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005322 if (I == NumSelIdents) {
5323 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005324 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005325 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005326 Accumulator.clear();
5327 }
5328 }
5329
Benjamin Kramera0651c52011-07-26 16:59:25 +00005330 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005331 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005332 }
Douglas Gregordae68752011-02-01 22:57:45 +00005333 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005334 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005335 }
5336 Results.ExitScope();
5337
5338 HandleCodeCompleteResults(this, CodeCompleter,
5339 CodeCompletionContext::CCC_SelectorName,
5340 Results.data(), Results.size());
5341}
5342
Douglas Gregor55385fe2009-11-18 04:19:12 +00005343/// \brief Add all of the protocol declarations that we find in the given
5344/// (translation unit) context.
5345static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005346 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005347 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005348 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005349
5350 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5351 DEnd = Ctx->decls_end();
5352 D != DEnd; ++D) {
5353 // Record any protocols we find.
5354 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005355 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005356 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005357
5358 // Record any forward-declared protocols we find.
5359 if (ObjCForwardProtocolDecl *Forward
5360 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5361 for (ObjCForwardProtocolDecl::protocol_iterator
5362 P = Forward->protocol_begin(),
5363 PEnd = Forward->protocol_end();
5364 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005365 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005366 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005367 }
5368 }
5369}
5370
5371void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5372 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005373 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5374 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005375
Douglas Gregor70c23352010-12-09 21:44:02 +00005376 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5377 Results.EnterNewScope();
5378
5379 // Tell the result set to ignore all of the protocols we have
5380 // already seen.
5381 // FIXME: This doesn't work when caching code-completion results.
5382 for (unsigned I = 0; I != NumProtocols; ++I)
5383 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5384 Protocols[I].second))
5385 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005386
Douglas Gregor70c23352010-12-09 21:44:02 +00005387 // Add all protocols.
5388 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5389 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005390
Douglas Gregor70c23352010-12-09 21:44:02 +00005391 Results.ExitScope();
5392 }
5393
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005394 HandleCodeCompleteResults(this, CodeCompleter,
5395 CodeCompletionContext::CCC_ObjCProtocolName,
5396 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005397}
5398
5399void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005400 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5401 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005402
Douglas Gregor70c23352010-12-09 21:44:02 +00005403 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5404 Results.EnterNewScope();
5405
5406 // Add all protocols.
5407 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5408 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005409
Douglas Gregor70c23352010-12-09 21:44:02 +00005410 Results.ExitScope();
5411 }
5412
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005413 HandleCodeCompleteResults(this, CodeCompleter,
5414 CodeCompletionContext::CCC_ObjCProtocolName,
5415 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005416}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005417
5418/// \brief Add all of the Objective-C interface declarations that we find in
5419/// the given (translation unit) context.
5420static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5421 bool OnlyForwardDeclarations,
5422 bool OnlyUnimplemented,
5423 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005424 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005425
5426 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5427 DEnd = Ctx->decls_end();
5428 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005429 // Record any interfaces we find.
5430 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5431 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5432 (!OnlyUnimplemented || !Class->getImplementation()))
5433 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005434
5435 // Record any forward-declared interfaces we find.
5436 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005437 ObjCInterfaceDecl *IDecl = Forward->getForwardInterfaceDecl();
5438 if ((!OnlyForwardDeclarations || IDecl->isForwardDecl()) &&
5439 (!OnlyUnimplemented || !IDecl->getImplementation()))
5440 Results.AddResult(Result(IDecl, 0), CurContext,
5441 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005442 }
5443 }
5444}
5445
5446void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005447 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5448 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005449 Results.EnterNewScope();
5450
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005451 if (CodeCompleter->includeGlobals()) {
5452 // Add all classes.
5453 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5454 false, Results);
5455 }
5456
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005457 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005458
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005459 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005460 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005461 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005462}
5463
Douglas Gregorc83c6872010-04-15 22:33:43 +00005464void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5465 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005466 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005467 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005468 Results.EnterNewScope();
5469
5470 // Make sure that we ignore the class we're currently defining.
5471 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005472 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005473 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005474 Results.Ignore(CurClass);
5475
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005476 if (CodeCompleter->includeGlobals()) {
5477 // Add all classes.
5478 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5479 false, Results);
5480 }
5481
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005482 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005483
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005484 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005485 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005486 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005487}
5488
5489void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005490 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5491 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005492 Results.EnterNewScope();
5493
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005494 if (CodeCompleter->includeGlobals()) {
5495 // Add all unimplemented classes.
5496 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5497 true, Results);
5498 }
5499
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005500 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005501
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005502 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005503 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005504 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005505}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005506
5507void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005508 IdentifierInfo *ClassName,
5509 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005510 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005511
Douglas Gregor218937c2011-02-01 19:23:04 +00005512 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005513 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005514
5515 // Ignore any categories we find that have already been implemented by this
5516 // interface.
5517 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5518 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005519 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005520 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5521 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5522 Category = Category->getNextClassCategory())
5523 CategoryNames.insert(Category->getIdentifier());
5524
5525 // Add all of the categories we know about.
5526 Results.EnterNewScope();
5527 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5528 for (DeclContext::decl_iterator D = TU->decls_begin(),
5529 DEnd = TU->decls_end();
5530 D != DEnd; ++D)
5531 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5532 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005533 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005534 Results.ExitScope();
5535
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005536 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005537 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005538 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005539}
5540
5541void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005542 IdentifierInfo *ClassName,
5543 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005544 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005545
5546 // Find the corresponding interface. If we couldn't find the interface, the
5547 // program itself is ill-formed. However, we'll try to be helpful still by
5548 // providing the list of all of the categories we know about.
5549 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005550 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005551 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5552 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005553 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005554
Douglas Gregor218937c2011-02-01 19:23:04 +00005555 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005556 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005557
5558 // Add all of the categories that have have corresponding interface
5559 // declarations in this class and any of its superclasses, except for
5560 // already-implemented categories in the class itself.
5561 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5562 Results.EnterNewScope();
5563 bool IgnoreImplemented = true;
5564 while (Class) {
5565 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5566 Category = Category->getNextClassCategory())
5567 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5568 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005569 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005570
5571 Class = Class->getSuperClass();
5572 IgnoreImplemented = false;
5573 }
5574 Results.ExitScope();
5575
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005576 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005577 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005578 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005579}
Douglas Gregor322328b2009-11-18 22:32:06 +00005580
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005581void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005582 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005583 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5584 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005585
5586 // Figure out where this @synthesize lives.
5587 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005588 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005589 if (!Container ||
5590 (!isa<ObjCImplementationDecl>(Container) &&
5591 !isa<ObjCCategoryImplDecl>(Container)))
5592 return;
5593
5594 // Ignore any properties that have already been implemented.
5595 for (DeclContext::decl_iterator D = Container->decls_begin(),
5596 DEnd = Container->decls_end();
5597 D != DEnd; ++D)
5598 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5599 Results.Ignore(PropertyImpl->getPropertyDecl());
5600
5601 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005602 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005603 Results.EnterNewScope();
5604 if (ObjCImplementationDecl *ClassImpl
5605 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005606 AddObjCProperties(ClassImpl->getClassInterface(), false,
5607 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005608 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005609 else
5610 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005611 false, /*AllowNullaryMethods=*/false, CurContext,
5612 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005613 Results.ExitScope();
5614
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005615 HandleCodeCompleteResults(this, CodeCompleter,
5616 CodeCompletionContext::CCC_Other,
5617 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005618}
5619
5620void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005621 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005622 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005623 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5624 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005625
5626 // Figure out where this @synthesize lives.
5627 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005628 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005629 if (!Container ||
5630 (!isa<ObjCImplementationDecl>(Container) &&
5631 !isa<ObjCCategoryImplDecl>(Container)))
5632 return;
5633
5634 // Figure out which interface we're looking into.
5635 ObjCInterfaceDecl *Class = 0;
5636 if (ObjCImplementationDecl *ClassImpl
5637 = dyn_cast<ObjCImplementationDecl>(Container))
5638 Class = ClassImpl->getClassInterface();
5639 else
5640 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5641 ->getClassInterface();
5642
Douglas Gregore8426052011-04-18 14:40:46 +00005643 // Determine the type of the property we're synthesizing.
5644 QualType PropertyType = Context.getObjCIdType();
5645 if (Class) {
5646 if (ObjCPropertyDecl *Property
5647 = Class->FindPropertyDeclaration(PropertyName)) {
5648 PropertyType
5649 = Property->getType().getNonReferenceType().getUnqualifiedType();
5650
5651 // Give preference to ivars
5652 Results.setPreferredType(PropertyType);
5653 }
5654 }
5655
Douglas Gregor322328b2009-11-18 22:32:06 +00005656 // Add all of the instance variables in this class and its superclasses.
5657 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005658 bool SawSimilarlyNamedIvar = false;
5659 std::string NameWithPrefix;
5660 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005661 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005662 std::string NameWithSuffix = PropertyName->getName().str();
5663 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005664 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005665 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5666 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005667 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5668
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005669 // Determine whether we've seen an ivar with a name similar to the
5670 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005671 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005672 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005673 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005674 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005675
5676 // Reduce the priority of this result by one, to give it a slight
5677 // advantage over other results whose names don't match so closely.
5678 if (Results.size() &&
5679 Results.data()[Results.size() - 1].Kind
5680 == CodeCompletionResult::RK_Declaration &&
5681 Results.data()[Results.size() - 1].Declaration == Ivar)
5682 Results.data()[Results.size() - 1].Priority--;
5683 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005684 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005685 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005686
5687 if (!SawSimilarlyNamedIvar) {
5688 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005689 // an ivar of the appropriate type.
5690 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005691 typedef CodeCompletionResult Result;
5692 CodeCompletionAllocator &Allocator = Results.getAllocator();
5693 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5694
Douglas Gregor8987b232011-09-27 23:30:47 +00005695 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8426052011-04-18 14:40:46 +00005696 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005697 Policy, Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005698 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5699 Results.AddResult(Result(Builder.TakeString(), Priority,
5700 CXCursor_ObjCIvarDecl));
5701 }
5702
Douglas Gregor322328b2009-11-18 22:32:06 +00005703 Results.ExitScope();
5704
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005705 HandleCodeCompleteResults(this, CodeCompleter,
5706 CodeCompletionContext::CCC_Other,
5707 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005708}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005709
Douglas Gregor408be5a2010-08-25 01:08:01 +00005710// Mapping from selectors to the methods that implement that selector, along
5711// with the "in original class" flag.
5712typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5713 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005714
5715/// \brief Find all of the methods that reside in the given container
5716/// (and its superclasses, protocols, etc.) that meet the given
5717/// criteria. Insert those methods into the map of known methods,
5718/// indexed by selector so they can be easily found.
5719static void FindImplementableMethods(ASTContext &Context,
5720 ObjCContainerDecl *Container,
5721 bool WantInstanceMethods,
5722 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005723 KnownMethodsMap &KnownMethods,
5724 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005725 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5726 // Recurse into protocols.
5727 const ObjCList<ObjCProtocolDecl> &Protocols
5728 = IFace->getReferencedProtocols();
5729 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005730 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005731 I != E; ++I)
5732 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005733 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005734
Douglas Gregorea766182010-10-18 18:21:28 +00005735 // Add methods from any class extensions and categories.
5736 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5737 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005738 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5739 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005740 KnownMethods, false);
5741
5742 // Visit the superclass.
5743 if (IFace->getSuperClass())
5744 FindImplementableMethods(Context, IFace->getSuperClass(),
5745 WantInstanceMethods, ReturnType,
5746 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005747 }
5748
5749 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5750 // Recurse into protocols.
5751 const ObjCList<ObjCProtocolDecl> &Protocols
5752 = Category->getReferencedProtocols();
5753 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005754 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005755 I != E; ++I)
5756 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005757 KnownMethods, InOriginalClass);
5758
5759 // If this category is the original class, jump to the interface.
5760 if (InOriginalClass && Category->getClassInterface())
5761 FindImplementableMethods(Context, Category->getClassInterface(),
5762 WantInstanceMethods, ReturnType, KnownMethods,
5763 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005764 }
5765
5766 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5767 // Recurse into protocols.
5768 const ObjCList<ObjCProtocolDecl> &Protocols
5769 = Protocol->getReferencedProtocols();
5770 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5771 E = Protocols.end();
5772 I != E; ++I)
5773 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005774 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005775 }
5776
5777 // Add methods in this container. This operation occurs last because
5778 // we want the methods from this container to override any methods
5779 // we've previously seen with the same selector.
5780 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5781 MEnd = Container->meth_end();
5782 M != MEnd; ++M) {
5783 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5784 if (!ReturnType.isNull() &&
5785 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5786 continue;
5787
Douglas Gregor408be5a2010-08-25 01:08:01 +00005788 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005789 }
5790 }
5791}
5792
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005793/// \brief Add the parenthesized return or parameter type chunk to a code
5794/// completion string.
5795static void AddObjCPassingTypeChunk(QualType Type,
5796 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005797 const PrintingPolicy &Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005798 CodeCompletionBuilder &Builder) {
5799 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor8987b232011-09-27 23:30:47 +00005800 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005801 Builder.getAllocator()));
5802 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5803}
5804
5805/// \brief Determine whether the given class is or inherits from a class by
5806/// the given name.
5807static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005808 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005809 if (!Class)
5810 return false;
5811
5812 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5813 return true;
5814
5815 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5816}
5817
5818/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5819/// Key-Value Observing (KVO).
5820static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5821 bool IsInstanceMethod,
5822 QualType ReturnType,
5823 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005824 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005825 ResultBuilder &Results) {
5826 IdentifierInfo *PropName = Property->getIdentifier();
5827 if (!PropName || PropName->getLength() == 0)
5828 return;
5829
Douglas Gregor8987b232011-09-27 23:30:47 +00005830 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5831
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005832 // Builder that will create each code completion.
5833 typedef CodeCompletionResult Result;
5834 CodeCompletionAllocator &Allocator = Results.getAllocator();
5835 CodeCompletionBuilder Builder(Allocator);
5836
5837 // The selector table.
5838 SelectorTable &Selectors = Context.Selectors;
5839
5840 // The property name, copied into the code completion allocation region
5841 // on demand.
5842 struct KeyHolder {
5843 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005844 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005845 const char *CopiedKey;
5846
Chris Lattner5f9e2722011-07-23 10:55:15 +00005847 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005848 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5849
5850 operator const char *() {
5851 if (CopiedKey)
5852 return CopiedKey;
5853
5854 return CopiedKey = Allocator.CopyString(Key);
5855 }
5856 } Key(Allocator, PropName->getName());
5857
5858 // The uppercased name of the property name.
5859 std::string UpperKey = PropName->getName();
5860 if (!UpperKey.empty())
5861 UpperKey[0] = toupper(UpperKey[0]);
5862
5863 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5864 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5865 Property->getType());
5866 bool ReturnTypeMatchesVoid
5867 = ReturnType.isNull() || ReturnType->isVoidType();
5868
5869 // Add the normal accessor -(type)key.
5870 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005871 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005872 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5873 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00005874 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005875
5876 Builder.AddTypedTextChunk(Key);
5877 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5878 CXCursor_ObjCInstanceMethodDecl));
5879 }
5880
5881 // If we have an integral or boolean property (or the user has provided
5882 // an integral or boolean return type), add the accessor -(type)isKey.
5883 if (IsInstanceMethod &&
5884 ((!ReturnType.isNull() &&
5885 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5886 (ReturnType.isNull() &&
5887 (Property->getType()->isIntegerType() ||
5888 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005889 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005890 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005891 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005892 if (ReturnType.isNull()) {
5893 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5894 Builder.AddTextChunk("BOOL");
5895 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5896 }
5897
5898 Builder.AddTypedTextChunk(
5899 Allocator.CopyString(SelectorId->getName()));
5900 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5901 CXCursor_ObjCInstanceMethodDecl));
5902 }
5903 }
5904
5905 // Add the normal mutator.
5906 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5907 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005908 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005909 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005910 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005911 if (ReturnType.isNull()) {
5912 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5913 Builder.AddTextChunk("void");
5914 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5915 }
5916
5917 Builder.AddTypedTextChunk(
5918 Allocator.CopyString(SelectorId->getName()));
5919 Builder.AddTypedTextChunk(":");
Douglas Gregor8987b232011-09-27 23:30:47 +00005920 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005921 Builder.AddTextChunk(Key);
5922 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5923 CXCursor_ObjCInstanceMethodDecl));
5924 }
5925 }
5926
5927 // Indexed and unordered accessors
5928 unsigned IndexedGetterPriority = CCP_CodePattern;
5929 unsigned IndexedSetterPriority = CCP_CodePattern;
5930 unsigned UnorderedGetterPriority = CCP_CodePattern;
5931 unsigned UnorderedSetterPriority = CCP_CodePattern;
5932 if (const ObjCObjectPointerType *ObjCPointer
5933 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5934 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5935 // If this interface type is not provably derived from a known
5936 // collection, penalize the corresponding completions.
5937 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5938 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5939 if (!InheritsFromClassNamed(IFace, "NSArray"))
5940 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5941 }
5942
5943 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5944 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5945 if (!InheritsFromClassNamed(IFace, "NSSet"))
5946 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5947 }
5948 }
5949 } else {
5950 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5951 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5952 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5953 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5954 }
5955
5956 // Add -(NSUInteger)countOf<key>
5957 if (IsInstanceMethod &&
5958 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005959 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005960 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005961 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005962 if (ReturnType.isNull()) {
5963 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5964 Builder.AddTextChunk("NSUInteger");
5965 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5966 }
5967
5968 Builder.AddTypedTextChunk(
5969 Allocator.CopyString(SelectorId->getName()));
5970 Results.AddResult(Result(Builder.TakeString(),
5971 std::min(IndexedGetterPriority,
5972 UnorderedGetterPriority),
5973 CXCursor_ObjCInstanceMethodDecl));
5974 }
5975 }
5976
5977 // Indexed getters
5978 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
5979 if (IsInstanceMethod &&
5980 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005981 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005982 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005983 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005984 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005985 if (ReturnType.isNull()) {
5986 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5987 Builder.AddTextChunk("id");
5988 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5989 }
5990
5991 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5992 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5993 Builder.AddTextChunk("NSUInteger");
5994 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5995 Builder.AddTextChunk("index");
5996 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5997 CXCursor_ObjCInstanceMethodDecl));
5998 }
5999 }
6000
6001 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6002 if (IsInstanceMethod &&
6003 (ReturnType.isNull() ||
6004 (ReturnType->isObjCObjectPointerType() &&
6005 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6006 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6007 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006008 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006009 = (Twine(Property->getName()) + "AtIndexes").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("NSArray *");
6015 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6016 }
6017
6018 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6019 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6020 Builder.AddTextChunk("NSIndexSet *");
6021 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6022 Builder.AddTextChunk("indexes");
6023 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6024 CXCursor_ObjCInstanceMethodDecl));
6025 }
6026 }
6027
6028 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6029 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006030 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006031 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006032 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006033 &Context.Idents.get("range")
6034 };
6035
Douglas Gregore74c25c2011-05-04 23:50:46 +00006036 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006037 if (ReturnType.isNull()) {
6038 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6039 Builder.AddTextChunk("void");
6040 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6041 }
6042
6043 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6044 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6045 Builder.AddPlaceholderChunk("object-type");
6046 Builder.AddTextChunk(" **");
6047 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6048 Builder.AddTextChunk("buffer");
6049 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6050 Builder.AddTypedTextChunk("range:");
6051 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6052 Builder.AddTextChunk("NSRange");
6053 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6054 Builder.AddTextChunk("inRange");
6055 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6056 CXCursor_ObjCInstanceMethodDecl));
6057 }
6058 }
6059
6060 // Mutable indexed accessors
6061
6062 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6063 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006064 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006065 IdentifierInfo *SelectorIds[2] = {
6066 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006067 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006068 };
6069
Douglas Gregore74c25c2011-05-04 23:50:46 +00006070 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006071 if (ReturnType.isNull()) {
6072 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6073 Builder.AddTextChunk("void");
6074 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6075 }
6076
6077 Builder.AddTypedTextChunk("insertObject:");
6078 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6079 Builder.AddPlaceholderChunk("object-type");
6080 Builder.AddTextChunk(" *");
6081 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6082 Builder.AddTextChunk("object");
6083 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6084 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6085 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6086 Builder.AddPlaceholderChunk("NSUInteger");
6087 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6088 Builder.AddTextChunk("index");
6089 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6090 CXCursor_ObjCInstanceMethodDecl));
6091 }
6092 }
6093
6094 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6095 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006096 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006097 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006098 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006099 &Context.Idents.get("atIndexes")
6100 };
6101
Douglas Gregore74c25c2011-05-04 23:50:46 +00006102 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006103 if (ReturnType.isNull()) {
6104 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6105 Builder.AddTextChunk("void");
6106 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6107 }
6108
6109 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6110 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6111 Builder.AddTextChunk("NSArray *");
6112 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6113 Builder.AddTextChunk("array");
6114 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6115 Builder.AddTypedTextChunk("atIndexes:");
6116 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6117 Builder.AddPlaceholderChunk("NSIndexSet *");
6118 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6119 Builder.AddTextChunk("indexes");
6120 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6121 CXCursor_ObjCInstanceMethodDecl));
6122 }
6123 }
6124
6125 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6126 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006127 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006128 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006129 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006130 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006131 if (ReturnType.isNull()) {
6132 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6133 Builder.AddTextChunk("void");
6134 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6135 }
6136
6137 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6138 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6139 Builder.AddTextChunk("NSUInteger");
6140 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6141 Builder.AddTextChunk("index");
6142 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6143 CXCursor_ObjCInstanceMethodDecl));
6144 }
6145 }
6146
6147 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6148 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006149 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006150 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006151 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006152 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006153 if (ReturnType.isNull()) {
6154 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6155 Builder.AddTextChunk("void");
6156 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6157 }
6158
6159 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6160 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6161 Builder.AddTextChunk("NSIndexSet *");
6162 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6163 Builder.AddTextChunk("indexes");
6164 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6165 CXCursor_ObjCInstanceMethodDecl));
6166 }
6167 }
6168
6169 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6170 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006171 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006172 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006173 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006174 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006175 &Context.Idents.get("withObject")
6176 };
6177
Douglas Gregore74c25c2011-05-04 23:50:46 +00006178 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006179 if (ReturnType.isNull()) {
6180 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6181 Builder.AddTextChunk("void");
6182 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6183 }
6184
6185 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6186 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6187 Builder.AddPlaceholderChunk("NSUInteger");
6188 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6189 Builder.AddTextChunk("index");
6190 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6191 Builder.AddTypedTextChunk("withObject:");
6192 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6193 Builder.AddTextChunk("id");
6194 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6195 Builder.AddTextChunk("object");
6196 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6197 CXCursor_ObjCInstanceMethodDecl));
6198 }
6199 }
6200
6201 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6202 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006203 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006204 = (Twine("replace") + UpperKey + "AtIndexes").str();
6205 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006206 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006207 &Context.Idents.get(SelectorName1),
6208 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006209 };
6210
Douglas Gregore74c25c2011-05-04 23:50:46 +00006211 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006212 if (ReturnType.isNull()) {
6213 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6214 Builder.AddTextChunk("void");
6215 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6216 }
6217
6218 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6219 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6220 Builder.AddPlaceholderChunk("NSIndexSet *");
6221 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6222 Builder.AddTextChunk("indexes");
6223 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6224 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6225 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6226 Builder.AddTextChunk("NSArray *");
6227 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6228 Builder.AddTextChunk("array");
6229 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6230 CXCursor_ObjCInstanceMethodDecl));
6231 }
6232 }
6233
6234 // Unordered getters
6235 // - (NSEnumerator *)enumeratorOfKey
6236 if (IsInstanceMethod &&
6237 (ReturnType.isNull() ||
6238 (ReturnType->isObjCObjectPointerType() &&
6239 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6240 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6241 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006242 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006243 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006244 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006245 if (ReturnType.isNull()) {
6246 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6247 Builder.AddTextChunk("NSEnumerator *");
6248 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6249 }
6250
6251 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6252 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6253 CXCursor_ObjCInstanceMethodDecl));
6254 }
6255 }
6256
6257 // - (type *)memberOfKey:(type *)object
6258 if (IsInstanceMethod &&
6259 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006260 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006261 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006262 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006263 if (ReturnType.isNull()) {
6264 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6265 Builder.AddPlaceholderChunk("object-type");
6266 Builder.AddTextChunk(" *");
6267 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6268 }
6269
6270 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6271 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6272 if (ReturnType.isNull()) {
6273 Builder.AddPlaceholderChunk("object-type");
6274 Builder.AddTextChunk(" *");
6275 } else {
6276 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006277 Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006278 Builder.getAllocator()));
6279 }
6280 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6281 Builder.AddTextChunk("object");
6282 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6283 CXCursor_ObjCInstanceMethodDecl));
6284 }
6285 }
6286
6287 // Mutable unordered accessors
6288 // - (void)addKeyObject:(type *)object
6289 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006290 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006291 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006292 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006293 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006294 if (ReturnType.isNull()) {
6295 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6296 Builder.AddTextChunk("void");
6297 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6298 }
6299
6300 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6301 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6302 Builder.AddPlaceholderChunk("object-type");
6303 Builder.AddTextChunk(" *");
6304 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6305 Builder.AddTextChunk("object");
6306 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6307 CXCursor_ObjCInstanceMethodDecl));
6308 }
6309 }
6310
6311 // - (void)addKey:(NSSet *)objects
6312 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006313 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006314 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006315 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006316 if (ReturnType.isNull()) {
6317 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6318 Builder.AddTextChunk("void");
6319 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6320 }
6321
6322 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6323 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6324 Builder.AddTextChunk("NSSet *");
6325 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6326 Builder.AddTextChunk("objects");
6327 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6328 CXCursor_ObjCInstanceMethodDecl));
6329 }
6330 }
6331
6332 // - (void)removeKeyObject:(type *)object
6333 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006334 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006335 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006336 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006337 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006338 if (ReturnType.isNull()) {
6339 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6340 Builder.AddTextChunk("void");
6341 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6342 }
6343
6344 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6345 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6346 Builder.AddPlaceholderChunk("object-type");
6347 Builder.AddTextChunk(" *");
6348 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6349 Builder.AddTextChunk("object");
6350 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6351 CXCursor_ObjCInstanceMethodDecl));
6352 }
6353 }
6354
6355 // - (void)removeKey:(NSSet *)objects
6356 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006357 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006358 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006359 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006360 if (ReturnType.isNull()) {
6361 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6362 Builder.AddTextChunk("void");
6363 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6364 }
6365
6366 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6367 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6368 Builder.AddTextChunk("NSSet *");
6369 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6370 Builder.AddTextChunk("objects");
6371 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6372 CXCursor_ObjCInstanceMethodDecl));
6373 }
6374 }
6375
6376 // - (void)intersectKey:(NSSet *)objects
6377 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006378 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006379 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006380 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006381 if (ReturnType.isNull()) {
6382 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6383 Builder.AddTextChunk("void");
6384 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6385 }
6386
6387 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6388 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6389 Builder.AddTextChunk("NSSet *");
6390 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6391 Builder.AddTextChunk("objects");
6392 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6393 CXCursor_ObjCInstanceMethodDecl));
6394 }
6395 }
6396
6397 // Key-Value Observing
6398 // + (NSSet *)keyPathsForValuesAffectingKey
6399 if (!IsInstanceMethod &&
6400 (ReturnType.isNull() ||
6401 (ReturnType->isObjCObjectPointerType() &&
6402 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6403 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6404 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006405 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006406 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006407 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006408 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006409 if (ReturnType.isNull()) {
6410 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6411 Builder.AddTextChunk("NSSet *");
6412 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6413 }
6414
6415 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6416 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006417 CXCursor_ObjCClassMethodDecl));
6418 }
6419 }
6420
6421 // + (BOOL)automaticallyNotifiesObserversForKey
6422 if (!IsInstanceMethod &&
6423 (ReturnType.isNull() ||
6424 ReturnType->isIntegerType() ||
6425 ReturnType->isBooleanType())) {
6426 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006427 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006428 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6429 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6430 if (ReturnType.isNull()) {
6431 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6432 Builder.AddTextChunk("BOOL");
6433 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6434 }
6435
6436 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6437 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6438 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006439 }
6440 }
6441}
6442
Douglas Gregore8f5a172010-04-07 00:21:17 +00006443void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6444 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006445 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006446 // Determine the return type of the method we're declaring, if
6447 // provided.
6448 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006449 Decl *IDecl = 0;
6450 if (CurContext->isObjCContainer()) {
6451 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6452 IDecl = cast<Decl>(OCD);
6453 }
Douglas Gregorea766182010-10-18 18:21:28 +00006454 // Determine where we should start searching for methods.
6455 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006456 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006457 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006458 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6459 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006460 IsInImplementation = true;
6461 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006462 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006463 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006464 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006465 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006466 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006467 }
6468
6469 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006470 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006471 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006472 }
6473
Douglas Gregorea766182010-10-18 18:21:28 +00006474 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006475 HandleCodeCompleteResults(this, CodeCompleter,
6476 CodeCompletionContext::CCC_Other,
6477 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006478 return;
6479 }
6480
6481 // Find all of the methods that we could declare/implement here.
6482 KnownMethodsMap KnownMethods;
6483 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006484 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006485
Douglas Gregore8f5a172010-04-07 00:21:17 +00006486 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006487 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006488 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6489 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006490 Results.EnterNewScope();
Douglas Gregor8987b232011-09-27 23:30:47 +00006491 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006492 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6493 MEnd = KnownMethods.end();
6494 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006495 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006496 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006497
6498 // If the result type was not already provided, add it to the
6499 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006500 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00006501 AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,
6502 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006503
6504 Selector Sel = Method->getSelector();
6505
6506 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006507 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006508 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006509
6510 // Add parameters to the pattern.
6511 unsigned I = 0;
6512 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6513 PEnd = Method->param_end();
6514 P != PEnd; (void)++P, ++I) {
6515 // Add the part of the selector name.
6516 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006517 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006518 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006519 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6520 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006521 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006522 } else
6523 break;
6524
6525 // Add the parameter type.
Douglas Gregor8987b232011-09-27 23:30:47 +00006526 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,
6527 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006528
6529 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006530 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006531 }
6532
6533 if (Method->isVariadic()) {
6534 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006535 Builder.AddChunk(CodeCompletionString::CK_Comma);
6536 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006537 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006538
Douglas Gregor447107d2010-05-28 00:57:46 +00006539 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006540 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006541 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6542 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6543 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006544 if (!Method->getResultType()->isVoidType()) {
6545 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006546 Builder.AddTextChunk("return");
6547 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6548 Builder.AddPlaceholderChunk("expression");
6549 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006550 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006551 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006552
Douglas Gregor218937c2011-02-01 19:23:04 +00006553 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6554 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006555 }
6556
Douglas Gregor408be5a2010-08-25 01:08:01 +00006557 unsigned Priority = CCP_CodePattern;
6558 if (!M->second.second)
6559 Priority += CCD_InBaseClass;
6560
Douglas Gregor218937c2011-02-01 19:23:04 +00006561 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006562 Method->isInstanceMethod()
6563 ? CXCursor_ObjCInstanceMethodDecl
6564 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006565 }
6566
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006567 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6568 // the properties in this class and its categories.
6569 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006570 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006571 Containers.push_back(SearchDecl);
6572
Douglas Gregore74c25c2011-05-04 23:50:46 +00006573 VisitedSelectorSet KnownSelectors;
6574 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6575 MEnd = KnownMethods.end();
6576 M != MEnd; ++M)
6577 KnownSelectors.insert(M->first);
6578
6579
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006580 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6581 if (!IFace)
6582 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6583 IFace = Category->getClassInterface();
6584
6585 if (IFace) {
6586 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6587 Category = Category->getNextClassCategory())
6588 Containers.push_back(Category);
6589 }
6590
6591 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6592 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6593 PEnd = Containers[I]->prop_end();
6594 P != PEnd; ++P) {
6595 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006596 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006597 }
6598 }
6599 }
6600
Douglas Gregore8f5a172010-04-07 00:21:17 +00006601 Results.ExitScope();
6602
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006603 HandleCodeCompleteResults(this, CodeCompleter,
6604 CodeCompletionContext::CCC_Other,
6605 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006606}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006607
6608void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6609 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006610 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006611 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006612 IdentifierInfo **SelIdents,
6613 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006614 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006615 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006616 if (ExternalSource) {
6617 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6618 I != N; ++I) {
6619 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006620 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006621 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006622
6623 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006624 }
6625 }
6626
6627 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006628 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006629 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6630 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006631
6632 if (ReturnTy)
6633 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006634
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006635 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006636 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6637 MEnd = MethodPool.end();
6638 M != MEnd; ++M) {
6639 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6640 &M->second.second;
6641 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006642 MethList = MethList->Next) {
6643 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6644 NumSelIdents))
6645 continue;
6646
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006647 if (AtParameterName) {
6648 // Suggest parameter names we've seen before.
6649 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6650 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6651 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006652 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006653 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006654 Param->getIdentifier()->getName()));
6655 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006656 }
6657 }
6658
6659 continue;
6660 }
6661
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006662 Result R(MethList->Method, 0);
6663 R.StartParameter = NumSelIdents;
6664 R.AllParametersAreInformative = false;
6665 R.DeclaringEntity = true;
6666 Results.MaybeAddResult(R, CurContext);
6667 }
6668 }
6669
6670 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006671 HandleCodeCompleteResults(this, CodeCompleter,
6672 CodeCompletionContext::CCC_Other,
6673 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006674}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006675
Douglas Gregorf29c5232010-08-24 22:20:20 +00006676void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006677 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006678 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006679 Results.EnterNewScope();
6680
6681 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006682 CodeCompletionBuilder Builder(Results.getAllocator());
6683 Builder.AddTypedTextChunk("if");
6684 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6685 Builder.AddPlaceholderChunk("condition");
6686 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006687
6688 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006689 Builder.AddTypedTextChunk("ifdef");
6690 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6691 Builder.AddPlaceholderChunk("macro");
6692 Results.AddResult(Builder.TakeString());
6693
Douglas Gregorf44e8542010-08-24 19:08:16 +00006694 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006695 Builder.AddTypedTextChunk("ifndef");
6696 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6697 Builder.AddPlaceholderChunk("macro");
6698 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006699
6700 if (InConditional) {
6701 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006702 Builder.AddTypedTextChunk("elif");
6703 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6704 Builder.AddPlaceholderChunk("condition");
6705 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006706
6707 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006708 Builder.AddTypedTextChunk("else");
6709 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006710
6711 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006712 Builder.AddTypedTextChunk("endif");
6713 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006714 }
6715
6716 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006717 Builder.AddTypedTextChunk("include");
6718 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6719 Builder.AddTextChunk("\"");
6720 Builder.AddPlaceholderChunk("header");
6721 Builder.AddTextChunk("\"");
6722 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006723
6724 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006725 Builder.AddTypedTextChunk("include");
6726 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6727 Builder.AddTextChunk("<");
6728 Builder.AddPlaceholderChunk("header");
6729 Builder.AddTextChunk(">");
6730 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006731
6732 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006733 Builder.AddTypedTextChunk("define");
6734 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6735 Builder.AddPlaceholderChunk("macro");
6736 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006737
6738 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006739 Builder.AddTypedTextChunk("define");
6740 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6741 Builder.AddPlaceholderChunk("macro");
6742 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6743 Builder.AddPlaceholderChunk("args");
6744 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6745 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006746
6747 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006748 Builder.AddTypedTextChunk("undef");
6749 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6750 Builder.AddPlaceholderChunk("macro");
6751 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006752
6753 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006754 Builder.AddTypedTextChunk("line");
6755 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6756 Builder.AddPlaceholderChunk("number");
6757 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006758
6759 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006760 Builder.AddTypedTextChunk("line");
6761 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6762 Builder.AddPlaceholderChunk("number");
6763 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6764 Builder.AddTextChunk("\"");
6765 Builder.AddPlaceholderChunk("filename");
6766 Builder.AddTextChunk("\"");
6767 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006768
6769 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006770 Builder.AddTypedTextChunk("error");
6771 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6772 Builder.AddPlaceholderChunk("message");
6773 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006774
6775 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006776 Builder.AddTypedTextChunk("pragma");
6777 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6778 Builder.AddPlaceholderChunk("arguments");
6779 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006780
6781 if (getLangOptions().ObjC1) {
6782 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006783 Builder.AddTypedTextChunk("import");
6784 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6785 Builder.AddTextChunk("\"");
6786 Builder.AddPlaceholderChunk("header");
6787 Builder.AddTextChunk("\"");
6788 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006789
6790 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006791 Builder.AddTypedTextChunk("import");
6792 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6793 Builder.AddTextChunk("<");
6794 Builder.AddPlaceholderChunk("header");
6795 Builder.AddTextChunk(">");
6796 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006797 }
6798
6799 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006800 Builder.AddTypedTextChunk("include_next");
6801 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6802 Builder.AddTextChunk("\"");
6803 Builder.AddPlaceholderChunk("header");
6804 Builder.AddTextChunk("\"");
6805 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006806
6807 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006808 Builder.AddTypedTextChunk("include_next");
6809 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6810 Builder.AddTextChunk("<");
6811 Builder.AddPlaceholderChunk("header");
6812 Builder.AddTextChunk(">");
6813 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006814
6815 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006816 Builder.AddTypedTextChunk("warning");
6817 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6818 Builder.AddPlaceholderChunk("message");
6819 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006820
6821 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6822 // completions for them. And __include_macros is a Clang-internal extension
6823 // that we don't want to encourage anyone to use.
6824
6825 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6826 Results.ExitScope();
6827
Douglas Gregorf44e8542010-08-24 19:08:16 +00006828 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006829 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006830 Results.data(), Results.size());
6831}
6832
6833void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006834 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006835 S->getFnParent()? Sema::PCC_RecoveryInFunction
6836 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006837}
6838
Douglas Gregorf29c5232010-08-24 22:20:20 +00006839void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006840 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006841 IsDefinition? CodeCompletionContext::CCC_MacroName
6842 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006843 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6844 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006845 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006846 Results.EnterNewScope();
6847 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6848 MEnd = PP.macro_end();
6849 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006850 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006851 M->first->getName()));
6852 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006853 }
6854 Results.ExitScope();
6855 } else if (IsDefinition) {
6856 // FIXME: Can we detect when the user just wrote an include guard above?
6857 }
6858
Douglas Gregor52779fb2010-09-23 23:01:17 +00006859 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006860 Results.data(), Results.size());
6861}
6862
Douglas Gregorf29c5232010-08-24 22:20:20 +00006863void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006864 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006865 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006866
6867 if (!CodeCompleter || CodeCompleter->includeMacros())
6868 AddMacroResults(PP, Results);
6869
6870 // defined (<macro>)
6871 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006872 CodeCompletionBuilder Builder(Results.getAllocator());
6873 Builder.AddTypedTextChunk("defined");
6874 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6875 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6876 Builder.AddPlaceholderChunk("macro");
6877 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6878 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006879 Results.ExitScope();
6880
6881 HandleCodeCompleteResults(this, CodeCompleter,
6882 CodeCompletionContext::CCC_PreprocessorExpression,
6883 Results.data(), Results.size());
6884}
6885
6886void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6887 IdentifierInfo *Macro,
6888 MacroInfo *MacroInfo,
6889 unsigned Argument) {
6890 // FIXME: In the future, we could provide "overload" results, much like we
6891 // do for function calls.
6892
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00006893 // Now just ignore this. There will be another code-completion callback
6894 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00006895}
6896
Douglas Gregor55817af2010-08-25 17:04:25 +00006897void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006898 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006899 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006900 0, 0);
6901}
6902
Douglas Gregordae68752011-02-01 22:57:45 +00006903void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006904 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006905 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006906 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6907 CodeCompletionDeclConsumer Consumer(Builder,
6908 Context.getTranslationUnitDecl());
6909 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6910 Consumer);
6911 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006912
6913 if (!CodeCompleter || CodeCompleter->includeMacros())
6914 AddMacroResults(PP, Builder);
6915
6916 Results.clear();
6917 Results.insert(Results.end(),
6918 Builder.data(), Builder.data() + Builder.size());
6919}