blob: 405d626ae9ba89b65dcef9acca1e1385fb9679c8 [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,
1969 bool SuppressName = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001970 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1971 if (Param->getType()->isDependentType() ||
1972 !Param->getType()->isBlockPointerType()) {
1973 // The argument for a dependent or non-block parameter is a placeholder
1974 // containing that parameter's type.
1975 std::string Result;
1976
Douglas Gregoraba48082010-08-29 19:47:46 +00001977 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001978 Result = Param->getIdentifier()->getName();
1979
John McCallf85e1932011-06-15 23:02:42 +00001980 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00001981
1982 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00001983 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
1984 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001985 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001986 Result += Param->getIdentifier()->getName();
1987 }
1988 return Result;
1989 }
1990
1991 // The argument for a block pointer parameter is a block literal with
1992 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00001993 FunctionTypeLoc *Block = 0;
1994 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00001995 TypeLoc TL;
1996 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1997 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1998 while (true) {
1999 // Look through typedefs.
2000 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
2001 if (TypeSourceInfo *InnerTSInfo
Richard Smith162e1c12011-04-15 14:24:37 +00002002 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregor83482d12010-08-24 16:15:59 +00002003 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2004 continue;
2005 }
2006 }
2007
2008 // Look through qualified types
2009 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2010 TL = QualifiedTL->getUnqualifiedLoc();
2011 continue;
2012 }
2013
2014 // Try to get the function prototype behind the block pointer type,
2015 // then we're done.
2016 if (BlockPointerTypeLoc *BlockPtr
2017 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002018 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002019 Block = dyn_cast<FunctionTypeLoc>(&TL);
2020 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002021 }
2022 break;
2023 }
2024 }
2025
2026 if (!Block) {
2027 // We were unable to find a FunctionProtoTypeLoc with parameter names
2028 // for the block; just use the parameter type as a placeholder.
2029 std::string Result;
John McCallf85e1932011-06-15 23:02:42 +00002030 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002031
2032 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002033 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2034 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002035 if (Param->getIdentifier())
2036 Result += Param->getIdentifier()->getName();
2037 }
2038
2039 return Result;
2040 }
2041
2042 // We have the function prototype behind the block pointer type, as it was
2043 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002044 std::string Result;
2045 QualType ResultType = Block->getTypePtr()->getResultType();
2046 if (!ResultType->isVoidType())
John McCallf85e1932011-06-15 23:02:42 +00002047 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregor38276252010-09-08 22:47:51 +00002048
2049 Result = '^' + Result;
Douglas Gregor830072c2011-02-15 22:37:09 +00002050 if (!BlockProto || Block->getNumArgs() == 0) {
2051 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002052 Result += "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002053 else
2054 Result += "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002055 } else {
2056 Result += "(";
2057 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2058 if (I)
2059 Result += ", ";
Douglas Gregor8987b232011-09-27 23:30:47 +00002060 Result += FormatFunctionParameter(Context, Policy, Block->getArg(I));
Douglas Gregor38276252010-09-08 22:47:51 +00002061
Douglas Gregor830072c2011-02-15 22:37:09 +00002062 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002063 Result += ", ...";
2064 }
2065 Result += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002066 }
Douglas Gregor38276252010-09-08 22:47:51 +00002067
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002068 if (Param->getIdentifier())
2069 Result += Param->getIdentifier()->getName();
2070
Douglas Gregor83482d12010-08-24 16:15:59 +00002071 return Result;
2072}
2073
Douglas Gregor86d9a522009-09-21 16:56:56 +00002074/// \brief Add function parameter chunks to the given code completion string.
2075static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002076 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002077 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002078 CodeCompletionBuilder &Result,
2079 unsigned Start = 0,
2080 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002081 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002082 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002083
Douglas Gregor218937c2011-02-01 19:23:04 +00002084 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002085 ParmVarDecl *Param = Function->getParamDecl(P);
2086
Douglas Gregor218937c2011-02-01 19:23:04 +00002087 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002088 // When we see an optional default argument, put that argument and
2089 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002090 CodeCompletionBuilder Opt(Result.getAllocator());
2091 if (!FirstParameter)
2092 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002093 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregor218937c2011-02-01 19:23:04 +00002094 Result.AddOptionalChunk(Opt.TakeString());
2095 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002096 }
2097
Douglas Gregor218937c2011-02-01 19:23:04 +00002098 if (FirstParameter)
2099 FirstParameter = false;
2100 else
2101 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2102
2103 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002104
2105 // Format the placeholder string.
Douglas Gregor8987b232011-09-27 23:30:47 +00002106 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2107 Param);
Douglas Gregor83482d12010-08-24 16:15:59 +00002108
Douglas Gregore17794f2010-08-31 05:13:43 +00002109 if (Function->isVariadic() && P == N - 1)
2110 PlaceholderStr += ", ...";
2111
Douglas Gregor86d9a522009-09-21 16:56:56 +00002112 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002113 Result.AddPlaceholderChunk(
2114 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002115 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002116
2117 if (const FunctionProtoType *Proto
2118 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002119 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002120 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002121 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002122
Douglas Gregor218937c2011-02-01 19:23:04 +00002123 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002124 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002125}
2126
2127/// \brief Add template parameter chunks to the given code completion string.
2128static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002129 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002130 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002131 CodeCompletionBuilder &Result,
2132 unsigned MaxParameters = 0,
2133 unsigned Start = 0,
2134 bool InDefaultArg = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002135 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002136 bool FirstParameter = true;
2137
2138 TemplateParameterList *Params = Template->getTemplateParameters();
2139 TemplateParameterList::iterator PEnd = Params->end();
2140 if (MaxParameters)
2141 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002142 for (TemplateParameterList::iterator P = Params->begin() + Start;
2143 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002144 bool HasDefaultArg = false;
2145 std::string PlaceholderStr;
2146 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2147 if (TTP->wasDeclaredWithTypename())
2148 PlaceholderStr = "typename";
2149 else
2150 PlaceholderStr = "class";
2151
2152 if (TTP->getIdentifier()) {
2153 PlaceholderStr += ' ';
2154 PlaceholderStr += TTP->getIdentifier()->getName();
2155 }
2156
2157 HasDefaultArg = TTP->hasDefaultArgument();
2158 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002159 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002160 if (NTTP->getIdentifier())
2161 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002162 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002163 HasDefaultArg = NTTP->hasDefaultArgument();
2164 } else {
2165 assert(isa<TemplateTemplateParmDecl>(*P));
2166 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2167
2168 // Since putting the template argument list into the placeholder would
2169 // be very, very long, we just use an abbreviation.
2170 PlaceholderStr = "template<...> class";
2171 if (TTP->getIdentifier()) {
2172 PlaceholderStr += ' ';
2173 PlaceholderStr += TTP->getIdentifier()->getName();
2174 }
2175
2176 HasDefaultArg = TTP->hasDefaultArgument();
2177 }
2178
Douglas Gregor218937c2011-02-01 19:23:04 +00002179 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002180 // When we see an optional default argument, put that argument and
2181 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002182 CodeCompletionBuilder Opt(Result.getAllocator());
2183 if (!FirstParameter)
2184 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002185 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregor218937c2011-02-01 19:23:04 +00002186 P - Params->begin(), true);
2187 Result.AddOptionalChunk(Opt.TakeString());
2188 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002189 }
2190
Douglas Gregor218937c2011-02-01 19:23:04 +00002191 InDefaultArg = false;
2192
Douglas Gregor86d9a522009-09-21 16:56:56 +00002193 if (FirstParameter)
2194 FirstParameter = false;
2195 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002196 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002197
2198 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002199 Result.AddPlaceholderChunk(
2200 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002201 }
2202}
2203
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002204/// \brief Add a qualifier to the given code-completion string, if the
2205/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002206static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002207AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002208 NestedNameSpecifier *Qualifier,
2209 bool QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002210 ASTContext &Context,
2211 const PrintingPolicy &Policy) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002212 if (!Qualifier)
2213 return;
2214
2215 std::string PrintedNNS;
2216 {
2217 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor8987b232011-09-27 23:30:47 +00002218 Qualifier->print(OS, Policy);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002219 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002220 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002221 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002222 else
Douglas Gregordae68752011-02-01 22:57:45 +00002223 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002224}
2225
Douglas Gregor218937c2011-02-01 19:23:04 +00002226static void
2227AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2228 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002229 const FunctionProtoType *Proto
2230 = Function->getType()->getAs<FunctionProtoType>();
2231 if (!Proto || !Proto->getTypeQuals())
2232 return;
2233
Douglas Gregora63f6de2011-02-01 21:15:40 +00002234 // FIXME: Add ref-qualifier!
2235
2236 // Handle single qualifiers without copying
2237 if (Proto->getTypeQuals() == Qualifiers::Const) {
2238 Result.AddInformativeChunk(" const");
2239 return;
2240 }
2241
2242 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2243 Result.AddInformativeChunk(" volatile");
2244 return;
2245 }
2246
2247 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2248 Result.AddInformativeChunk(" restrict");
2249 return;
2250 }
2251
2252 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002253 std::string QualsStr;
2254 if (Proto->getTypeQuals() & Qualifiers::Const)
2255 QualsStr += " const";
2256 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2257 QualsStr += " volatile";
2258 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2259 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002260 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002261}
2262
Douglas Gregor6f942b22010-09-21 16:06:22 +00002263/// \brief Add the name of the given declaration
Douglas Gregor8987b232011-09-27 23:30:47 +00002264static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2265 NamedDecl *ND, CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002266 typedef CodeCompletionString::Chunk Chunk;
2267
2268 DeclarationName Name = ND->getDeclName();
2269 if (!Name)
2270 return;
2271
2272 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002273 case DeclarationName::CXXOperatorName: {
2274 const char *OperatorName = 0;
2275 switch (Name.getCXXOverloadedOperator()) {
2276 case OO_None:
2277 case OO_Conditional:
2278 case NUM_OVERLOADED_OPERATORS:
2279 OperatorName = "operator";
2280 break;
2281
2282#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2283 case OO_##Name: OperatorName = "operator" Spelling; break;
2284#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2285#include "clang/Basic/OperatorKinds.def"
2286
2287 case OO_New: OperatorName = "operator new"; break;
2288 case OO_Delete: OperatorName = "operator delete"; break;
2289 case OO_Array_New: OperatorName = "operator new[]"; break;
2290 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2291 case OO_Call: OperatorName = "operator()"; break;
2292 case OO_Subscript: OperatorName = "operator[]"; break;
2293 }
2294 Result.AddTypedTextChunk(OperatorName);
2295 break;
2296 }
2297
Douglas Gregor6f942b22010-09-21 16:06:22 +00002298 case DeclarationName::Identifier:
2299 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002300 case DeclarationName::CXXDestructorName:
2301 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002302 Result.AddTypedTextChunk(
2303 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002304 break;
2305
2306 case DeclarationName::CXXUsingDirective:
2307 case DeclarationName::ObjCZeroArgSelector:
2308 case DeclarationName::ObjCOneArgSelector:
2309 case DeclarationName::ObjCMultiArgSelector:
2310 break;
2311
2312 case DeclarationName::CXXConstructorName: {
2313 CXXRecordDecl *Record = 0;
2314 QualType Ty = Name.getCXXNameType();
2315 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2316 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2317 else if (const InjectedClassNameType *InjectedTy
2318 = Ty->getAs<InjectedClassNameType>())
2319 Record = InjectedTy->getDecl();
2320 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002321 Result.AddTypedTextChunk(
2322 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002323 break;
2324 }
2325
Douglas Gregordae68752011-02-01 22:57:45 +00002326 Result.AddTypedTextChunk(
2327 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002328 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002329 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002330 AddTemplateParameterChunks(Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002331 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002332 }
2333 break;
2334 }
2335 }
2336}
2337
Douglas Gregor86d9a522009-09-21 16:56:56 +00002338/// \brief If possible, create a new code completion string for the given
2339/// result.
2340///
2341/// \returns Either a new, heap-allocated code completion string describing
2342/// how to use this result, or NULL to indicate that the string or name of the
2343/// result is all that is needed.
2344CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002345CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002346 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002347 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002348 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002349
Douglas Gregor8987b232011-09-27 23:30:47 +00002350 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregor218937c2011-02-01 19:23:04 +00002351 if (Kind == RK_Pattern) {
2352 Pattern->Priority = Priority;
2353 Pattern->Availability = Availability;
2354 return Pattern;
2355 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002356
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002357 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002358 Result.AddTypedTextChunk(Keyword);
2359 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002360 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002361
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002362 if (Kind == RK_Macro) {
2363 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002364 assert(MI && "Not a macro?");
2365
Douglas Gregordae68752011-02-01 22:57:45 +00002366 Result.AddTypedTextChunk(
2367 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002368
2369 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002370 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002371
2372 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002373 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregore4244702011-07-30 08:17:44 +00002374 bool CombineVariadicArgument = false;
2375 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2376 if (MI->isVariadic() && AEnd - A > 1) {
2377 AEnd -= 2;
2378 CombineVariadicArgument = true;
2379 }
2380 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002381 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002382 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002383
Douglas Gregore4244702011-07-30 08:17:44 +00002384 if (!MI->isVariadic() || A + 1 != AEnd) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002385 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002386 Result.AddPlaceholderChunk(
2387 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002388 continue;
2389 }
2390
Douglas Gregore4244702011-07-30 08:17:44 +00002391 // Variadic argument; cope with the difference between GNU and C99
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002392 // variadic macros, providing a single placeholder for the rest of the
2393 // arguments.
2394 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002395 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002396 else {
2397 std::string Arg = (*A)->getName();
2398 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002399 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002400 }
2401 }
Douglas Gregore4244702011-07-30 08:17:44 +00002402
2403 if (CombineVariadicArgument) {
2404 // Handle the next-to-last argument, combining it with the variadic
2405 // argument.
2406 std::string LastArg = (*A)->getName();
2407 ++A;
2408 if ((*A)->isStr("__VA_ARGS__"))
2409 LastArg += ", ...";
2410 else
2411 LastArg += ", " + (*A)->getName().str() + "...";
2412 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(LastArg));
2413 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002414 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2415 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002416 }
2417
Douglas Gregord8e8a582010-05-25 21:41:55 +00002418 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002419 NamedDecl *ND = Declaration;
2420
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002421 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002422 Result.AddTypedTextChunk(
2423 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002424 Result.AddTextChunk("::");
2425 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002426 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00002427
2428 for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2429 if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2430 Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2431 }
2432 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002433
Douglas Gregor8987b232011-09-27 23:30:47 +00002434 AddResultTypeChunk(S.Context, Policy, ND, Result);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002435
Douglas Gregor86d9a522009-09-21 16:56:56 +00002436 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002437 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002438 S.Context, Policy);
2439 AddTypedNameChunk(S.Context, Policy, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002440 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002441 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002442 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002443 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002444 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002445 }
2446
2447 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002448 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002449 S.Context, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002450 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor8987b232011-09-27 23:30:47 +00002451 AddTypedNameChunk(S.Context, Policy, Function, Result);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002452
Douglas Gregor86d9a522009-09-21 16:56:56 +00002453 // Figure out which template parameters are deduced (or have default
2454 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002455 SmallVector<bool, 16> Deduced;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002456 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2457 unsigned LastDeducibleArgument;
2458 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2459 --LastDeducibleArgument) {
2460 if (!Deduced[LastDeducibleArgument - 1]) {
2461 // C++0x: Figure out if the template argument has a default. If so,
2462 // the user doesn't need to type this argument.
2463 // FIXME: We need to abstract template parameters better!
2464 bool HasDefaultArg = false;
2465 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002466 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002467 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2468 HasDefaultArg = TTP->hasDefaultArgument();
2469 else if (NonTypeTemplateParmDecl *NTTP
2470 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2471 HasDefaultArg = NTTP->hasDefaultArgument();
2472 else {
2473 assert(isa<TemplateTemplateParmDecl>(Param));
2474 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002475 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002476 }
2477
2478 if (!HasDefaultArg)
2479 break;
2480 }
2481 }
2482
2483 if (LastDeducibleArgument) {
2484 // Some of the function template arguments cannot be deduced from a
2485 // function call, so we introduce an explicit template argument list
2486 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002487 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002488 AddTemplateParameterChunks(S.Context, Policy, FunTmpl, Result,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002489 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002490 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002491 }
2492
2493 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002494 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002495 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002496 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002497 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002498 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002499 }
2500
2501 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002502 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002503 S.Context, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002504 Result.AddTypedTextChunk(
2505 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002506 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002507 AddTemplateParameterChunks(S.Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002508 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2509 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002510 }
2511
Douglas Gregor9630eb62009-11-17 16:44:22 +00002512 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002513 Selector Sel = Method->getSelector();
2514 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002515 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002516 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002517 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002518 }
2519
Douglas Gregor813d8342011-02-18 22:29:55 +00002520 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002521 SelName += ':';
2522 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002523 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002524 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002525 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002526
2527 // If there is only one parameter, and we're past it, add an empty
2528 // typed-text chunk since there is nothing to type.
2529 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002530 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002531 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002532 unsigned Idx = 0;
2533 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2534 PEnd = Method->param_end();
2535 P != PEnd; (void)++P, ++Idx) {
2536 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002537 std::string Keyword;
2538 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002539 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002540 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002541 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002542 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002543 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002544 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002545 else
Douglas Gregordae68752011-02-01 22:57:45 +00002546 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002547 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002548
2549 // If we're before the starting parameter, skip the placeholder.
2550 if (Idx < StartParameter)
2551 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002552
2553 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002554
2555 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregor8987b232011-09-27 23:30:47 +00002556 Arg = FormatFunctionParameter(S.Context, Policy, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002557 else {
John McCallf85e1932011-06-15 23:02:42 +00002558 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002559 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2560 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002561 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002562 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002563 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002564 }
2565
Douglas Gregore17794f2010-08-31 05:13:43 +00002566 if (Method->isVariadic() && (P + 1) == PEnd)
2567 Arg += ", ...";
2568
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002569 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002570 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002571 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002572 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002573 else
Douglas Gregordae68752011-02-01 22:57:45 +00002574 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002575 }
2576
Douglas Gregor2a17af02009-12-23 00:21:46 +00002577 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002578 if (Method->param_size() == 0) {
2579 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002580 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002581 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002582 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002583 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002584 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002585 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002586
2587 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002588 }
2589
Douglas Gregor218937c2011-02-01 19:23:04 +00002590 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002591 }
2592
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002593 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002594 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002595 S.Context, Policy);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002596
Douglas Gregordae68752011-02-01 22:57:45 +00002597 Result.AddTypedTextChunk(
2598 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002599 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002600}
2601
Douglas Gregor86d802e2009-09-23 00:34:09 +00002602CodeCompletionString *
2603CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2604 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002605 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002606 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002607 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor8987b232011-09-27 23:30:47 +00002608 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCallf85e1932011-06-15 23:02:42 +00002609
Douglas Gregor218937c2011-02-01 19:23:04 +00002610 // FIXME: Set priority, availability appropriately.
2611 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002612 FunctionDecl *FDecl = getFunction();
Douglas Gregor8987b232011-09-27 23:30:47 +00002613 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002614 const FunctionProtoType *Proto
2615 = dyn_cast<FunctionProtoType>(getFunctionType());
2616 if (!FDecl && !Proto) {
2617 // Function without a prototype. Just give the return type and a
2618 // highlighted ellipsis.
2619 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002620 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
Douglas Gregor8987b232011-09-27 23:30:47 +00002621 S.Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002622 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002623 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2624 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2625 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2626 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002627 }
2628
2629 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002630 Result.AddTextChunk(
2631 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002632 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002633 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002634 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002635 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002636
Douglas Gregor218937c2011-02-01 19:23:04 +00002637 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002638 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2639 for (unsigned I = 0; I != NumParams; ++I) {
2640 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002641 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002642
2643 std::string ArgString;
2644 QualType ArgType;
2645
2646 if (FDecl) {
2647 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2648 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2649 } else {
2650 ArgType = Proto->getArgType(I);
2651 }
2652
John McCallf85e1932011-06-15 23:02:42 +00002653 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002654
2655 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002656 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002657 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002658 else
Douglas Gregordae68752011-02-01 22:57:45 +00002659 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002660 }
2661
2662 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002663 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002664 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002665 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002666 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002667 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002668 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002669 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002670
Douglas Gregor218937c2011-02-01 19:23:04 +00002671 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002672}
2673
Chris Lattner5f9e2722011-07-23 10:55:15 +00002674unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002675 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002676 bool PreferredTypeIsPointer) {
2677 unsigned Priority = CCP_Macro;
2678
Douglas Gregorb05496d2010-09-20 21:11:48 +00002679 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2680 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2681 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002682 Priority = CCP_Constant;
2683 if (PreferredTypeIsPointer)
2684 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002685 }
2686 // Treat "YES", "NO", "true", and "false" as constants.
2687 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2688 MacroName.equals("true") || MacroName.equals("false"))
2689 Priority = CCP_Constant;
2690 // Treat "bool" as a type.
2691 else if (MacroName.equals("bool"))
2692 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2693
Douglas Gregor1827e102010-08-16 16:18:59 +00002694
2695 return Priority;
2696}
2697
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002698CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2699 if (!D)
2700 return CXCursor_UnexposedDecl;
2701
2702 switch (D->getKind()) {
2703 case Decl::Enum: return CXCursor_EnumDecl;
2704 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2705 case Decl::Field: return CXCursor_FieldDecl;
2706 case Decl::Function:
2707 return CXCursor_FunctionDecl;
2708 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2709 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2710 case Decl::ObjCClass:
2711 // FIXME
2712 return CXCursor_UnexposedDecl;
2713 case Decl::ObjCForwardProtocol:
2714 // FIXME
2715 return CXCursor_UnexposedDecl;
2716 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2717 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2718 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2719 case Decl::ObjCMethod:
2720 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2721 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2722 case Decl::CXXMethod: return CXCursor_CXXMethod;
2723 case Decl::CXXConstructor: return CXCursor_Constructor;
2724 case Decl::CXXDestructor: return CXCursor_Destructor;
2725 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2726 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2727 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2728 case Decl::ParmVar: return CXCursor_ParmDecl;
2729 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002730 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002731 case Decl::Var: return CXCursor_VarDecl;
2732 case Decl::Namespace: return CXCursor_Namespace;
2733 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2734 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2735 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2736 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2737 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2738 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00002739 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002740 case Decl::ClassTemplatePartialSpecialization:
2741 return CXCursor_ClassTemplatePartialSpecialization;
2742 case Decl::UsingDirective: return CXCursor_UsingDirective;
2743
2744 case Decl::Using:
2745 case Decl::UnresolvedUsingValue:
2746 case Decl::UnresolvedUsingTypename:
2747 return CXCursor_UsingDeclaration;
2748
Douglas Gregor352697a2011-06-03 23:08:58 +00002749 case Decl::ObjCPropertyImpl:
2750 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2751 case ObjCPropertyImplDecl::Dynamic:
2752 return CXCursor_ObjCDynamicDecl;
2753
2754 case ObjCPropertyImplDecl::Synthesize:
2755 return CXCursor_ObjCSynthesizeDecl;
2756 }
2757 break;
2758
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002759 default:
2760 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2761 switch (TD->getTagKind()) {
2762 case TTK_Struct: return CXCursor_StructDecl;
2763 case TTK_Class: return CXCursor_ClassDecl;
2764 case TTK_Union: return CXCursor_UnionDecl;
2765 case TTK_Enum: return CXCursor_EnumDecl;
2766 }
2767 }
2768 }
2769
2770 return CXCursor_UnexposedDecl;
2771}
2772
Douglas Gregor590c7d52010-07-08 20:55:51 +00002773static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2774 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002775 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002776
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002777 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002778
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002779 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2780 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002781 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002782 Results.AddResult(Result(M->first,
2783 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002784 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002785 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002786 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002787
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002788 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002789
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002790}
2791
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002792static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2793 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002794 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002795
2796 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002797
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002798 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2799 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2800 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2801 Results.AddResult(Result("__func__", CCP_Constant));
2802 Results.ExitScope();
2803}
2804
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002805static void HandleCodeCompleteResults(Sema *S,
2806 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002807 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002808 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002809 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002810 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002811 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002812}
2813
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002814static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2815 Sema::ParserCompletionContext PCC) {
2816 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002817 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002818 return CodeCompletionContext::CCC_TopLevel;
2819
John McCallf312b1e2010-08-26 23:41:50 +00002820 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002821 return CodeCompletionContext::CCC_ClassStructUnion;
2822
John McCallf312b1e2010-08-26 23:41:50 +00002823 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002824 return CodeCompletionContext::CCC_ObjCInterface;
2825
John McCallf312b1e2010-08-26 23:41:50 +00002826 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002827 return CodeCompletionContext::CCC_ObjCImplementation;
2828
John McCallf312b1e2010-08-26 23:41:50 +00002829 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002830 return CodeCompletionContext::CCC_ObjCIvarList;
2831
John McCallf312b1e2010-08-26 23:41:50 +00002832 case Sema::PCC_Template:
2833 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002834 if (S.CurContext->isFileContext())
2835 return CodeCompletionContext::CCC_TopLevel;
2836 else if (S.CurContext->isRecord())
2837 return CodeCompletionContext::CCC_ClassStructUnion;
2838 else
2839 return CodeCompletionContext::CCC_Other;
2840
John McCallf312b1e2010-08-26 23:41:50 +00002841 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002842 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002843
John McCallf312b1e2010-08-26 23:41:50 +00002844 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002845 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2846 S.getLangOptions().ObjC1)
2847 return CodeCompletionContext::CCC_ParenthesizedExpression;
2848 else
2849 return CodeCompletionContext::CCC_Expression;
2850
2851 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002852 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002853 return CodeCompletionContext::CCC_Expression;
2854
John McCallf312b1e2010-08-26 23:41:50 +00002855 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002856 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002857
John McCallf312b1e2010-08-26 23:41:50 +00002858 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002859 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002860
2861 case Sema::PCC_ParenthesizedExpression:
2862 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002863
2864 case Sema::PCC_LocalDeclarationSpecifiers:
2865 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002866 }
2867
2868 return CodeCompletionContext::CCC_Other;
2869}
2870
Douglas Gregorf6961522010-08-27 21:18:54 +00002871/// \brief If we're in a C++ virtual member function, add completion results
2872/// that invoke the functions we override, since it's common to invoke the
2873/// overridden function as well as adding new functionality.
2874///
2875/// \param S The semantic analysis object for which we are generating results.
2876///
2877/// \param InContext This context in which the nested-name-specifier preceding
2878/// the code-completion point
2879static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2880 ResultBuilder &Results) {
2881 // Look through blocks.
2882 DeclContext *CurContext = S.CurContext;
2883 while (isa<BlockDecl>(CurContext))
2884 CurContext = CurContext->getParent();
2885
2886
2887 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2888 if (!Method || !Method->isVirtual())
2889 return;
2890
2891 // We need to have names for all of the parameters, if we're going to
2892 // generate a forwarding call.
2893 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2894 PEnd = Method->param_end();
2895 P != PEnd;
2896 ++P) {
2897 if (!(*P)->getDeclName())
2898 return;
2899 }
2900
Douglas Gregor8987b232011-09-27 23:30:47 +00002901 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorf6961522010-08-27 21:18:54 +00002902 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2903 MEnd = Method->end_overridden_methods();
2904 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002905 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002906 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2907 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2908 continue;
2909
2910 // If we need a nested-name-specifier, add one now.
2911 if (!InContext) {
2912 NestedNameSpecifier *NNS
2913 = getRequiredQualification(S.Context, CurContext,
2914 Overridden->getDeclContext());
2915 if (NNS) {
2916 std::string Str;
2917 llvm::raw_string_ostream OS(Str);
Douglas Gregor8987b232011-09-27 23:30:47 +00002918 NNS->print(OS, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002919 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002920 }
2921 } else if (!InContext->Equals(Overridden->getDeclContext()))
2922 continue;
2923
Douglas Gregordae68752011-02-01 22:57:45 +00002924 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002925 Overridden->getNameAsString()));
2926 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00002927 bool FirstParam = true;
2928 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2929 PEnd = Method->param_end();
2930 P != PEnd; ++P) {
2931 if (FirstParam)
2932 FirstParam = false;
2933 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002934 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00002935
Douglas Gregordae68752011-02-01 22:57:45 +00002936 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002937 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002938 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002939 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2940 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00002941 CCP_SuperCompletion,
2942 CXCursor_CXXMethod));
2943 Results.Ignore(Overridden);
2944 }
2945}
2946
Douglas Gregor01dfea02010-01-10 23:08:15 +00002947void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002948 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002949 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002950 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002951 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002952 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002953
Douglas Gregor01dfea02010-01-10 23:08:15 +00002954 // Determine how to filter results, e.g., so that the names of
2955 // values (functions, enumerators, function templates, etc.) are
2956 // only allowed where we can have an expression.
2957 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002958 case PCC_Namespace:
2959 case PCC_Class:
2960 case PCC_ObjCInterface:
2961 case PCC_ObjCImplementation:
2962 case PCC_ObjCInstanceVariableList:
2963 case PCC_Template:
2964 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002965 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002966 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002967 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2968 break;
2969
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002970 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002971 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002972 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002973 case PCC_ForInit:
2974 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002975 if (WantTypesInContext(CompletionContext, getLangOptions()))
2976 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2977 else
2978 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002979
2980 if (getLangOptions().CPlusPlus)
2981 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002982 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002983
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002984 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002985 // Unfiltered
2986 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002987 }
2988
Douglas Gregor3cdee122010-08-26 16:36:48 +00002989 // If we are in a C++ non-static member function, check the qualifiers on
2990 // the member function to filter/prioritize the results list.
2991 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2992 if (CurMethod->isInstance())
2993 Results.setObjectTypeQualifiers(
2994 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2995
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002996 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002997 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2998 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002999
Douglas Gregorbca403c2010-01-13 23:51:12 +00003000 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003001 Results.ExitScope();
3002
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003003 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00003004 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00003005 case PCC_Expression:
3006 case PCC_Statement:
3007 case PCC_RecoveryInFunction:
3008 if (S->getFnParent())
3009 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3010 break;
3011
3012 case PCC_Namespace:
3013 case PCC_Class:
3014 case PCC_ObjCInterface:
3015 case PCC_ObjCImplementation:
3016 case PCC_ObjCInstanceVariableList:
3017 case PCC_Template:
3018 case PCC_MemberTemplate:
3019 case PCC_ForInit:
3020 case PCC_Condition:
3021 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003022 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003023 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003024 }
3025
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003026 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003027 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003028
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003029 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003030 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003031}
3032
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003033static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3034 ParsedType Receiver,
3035 IdentifierInfo **SelIdents,
3036 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003037 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003038 bool IsSuper,
3039 ResultBuilder &Results);
3040
3041void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3042 bool AllowNonIdentifiers,
3043 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003044 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003045 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003046 AllowNestedNameSpecifiers
3047 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3048 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003049 Results.EnterNewScope();
3050
3051 // Type qualifiers can come after names.
3052 Results.AddResult(Result("const"));
3053 Results.AddResult(Result("volatile"));
3054 if (getLangOptions().C99)
3055 Results.AddResult(Result("restrict"));
3056
3057 if (getLangOptions().CPlusPlus) {
3058 if (AllowNonIdentifiers) {
3059 Results.AddResult(Result("operator"));
3060 }
3061
3062 // Add nested-name-specifiers.
3063 if (AllowNestedNameSpecifiers) {
3064 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003065 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003066 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3067 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3068 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003069 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003070 }
3071 }
3072 Results.ExitScope();
3073
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003074 // If we're in a context where we might have an expression (rather than a
3075 // declaration), and what we've seen so far is an Objective-C type that could
3076 // be a receiver of a class message, this may be a class message send with
3077 // the initial opening bracket '[' missing. Add appropriate completions.
3078 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3079 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3080 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3081 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3082 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3083 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3084 DS.getTypeQualifiers() == 0 &&
3085 S &&
3086 (S->getFlags() & Scope::DeclScope) != 0 &&
3087 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3088 Scope::FunctionPrototypeScope |
3089 Scope::AtCatchScope)) == 0) {
3090 ParsedType T = DS.getRepAsType();
3091 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003092 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003093 }
3094
Douglas Gregor4497dd42010-08-24 04:59:56 +00003095 // Note that we intentionally suppress macro results here, since we do not
3096 // encourage using macros to produce the names of entities.
3097
Douglas Gregor52779fb2010-09-23 23:01:17 +00003098 HandleCodeCompleteResults(this, CodeCompleter,
3099 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003100 Results.data(), Results.size());
3101}
3102
Douglas Gregorfb629412010-08-23 21:17:50 +00003103struct Sema::CodeCompleteExpressionData {
3104 CodeCompleteExpressionData(QualType PreferredType = QualType())
3105 : PreferredType(PreferredType), IntegralConstantExpression(false),
3106 ObjCCollection(false) { }
3107
3108 QualType PreferredType;
3109 bool IntegralConstantExpression;
3110 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003111 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003112};
3113
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003114/// \brief Perform code-completion in an expression context when we know what
3115/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003116///
3117/// \param IntegralConstantExpression Only permit integral constant
3118/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003119void Sema::CodeCompleteExpression(Scope *S,
3120 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003121 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003122 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3123 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003124 if (Data.ObjCCollection)
3125 Results.setFilter(&ResultBuilder::IsObjCCollection);
3126 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003127 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003128 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003129 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3130 else
3131 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003132
3133 if (!Data.PreferredType.isNull())
3134 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3135
3136 // Ignore any declarations that we were told that we don't care about.
3137 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3138 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003139
3140 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003141 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3142 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003143
3144 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003145 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003146 Results.ExitScope();
3147
Douglas Gregor590c7d52010-07-08 20:55:51 +00003148 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003149 if (!Data.PreferredType.isNull())
3150 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3151 || Data.PreferredType->isMemberPointerType()
3152 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003153
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003154 if (S->getFnParent() &&
3155 !Data.ObjCCollection &&
3156 !Data.IntegralConstantExpression)
3157 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3158
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003159 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003160 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003161 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003162 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3163 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003164 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003165}
3166
Douglas Gregorac5fd842010-09-18 01:28:11 +00003167void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3168 if (E.isInvalid())
3169 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3170 else if (getLangOptions().ObjC1)
3171 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003172}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003173
Douglas Gregor73449212010-12-09 23:01:55 +00003174/// \brief The set of properties that have already been added, referenced by
3175/// property name.
3176typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3177
Douglas Gregor95ac6552009-11-18 01:29:26 +00003178static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003179 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003180 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003181 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003182 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003183 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003184 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003185
3186 // Add properties in this container.
3187 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3188 PEnd = Container->prop_end();
3189 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003190 ++P) {
3191 if (AddedProperties.insert(P->getIdentifier()))
3192 Results.MaybeAddResult(Result(*P, 0), CurContext);
3193 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003194
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003195 // Add nullary methods
3196 if (AllowNullaryMethods) {
3197 ASTContext &Context = Container->getASTContext();
Douglas Gregor8987b232011-09-27 23:30:47 +00003198 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003199 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3200 MEnd = Container->meth_end();
3201 M != MEnd; ++M) {
3202 if (M->getSelector().isUnarySelector())
3203 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3204 if (AddedProperties.insert(Name)) {
3205 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor8987b232011-09-27 23:30:47 +00003206 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003207 Builder.AddTypedTextChunk(
3208 Results.getAllocator().CopyString(Name->getName()));
3209
3210 CXAvailabilityKind Availability = CXAvailability_Available;
3211 switch (M->getAvailability()) {
3212 case AR_Available:
3213 case AR_NotYetIntroduced:
3214 Availability = CXAvailability_Available;
3215 break;
3216
3217 case AR_Deprecated:
3218 Availability = CXAvailability_Deprecated;
3219 break;
3220
3221 case AR_Unavailable:
3222 Availability = CXAvailability_NotAvailable;
3223 break;
3224 }
3225
3226 Results.MaybeAddResult(Result(Builder.TakeString(),
3227 CCP_MemberDeclaration + CCD_MethodAsProperty,
3228 M->isInstanceMethod()
3229 ? CXCursor_ObjCInstanceMethodDecl
3230 : CXCursor_ObjCClassMethodDecl,
3231 Availability),
3232 CurContext);
3233 }
3234 }
3235 }
3236
3237
Douglas Gregor95ac6552009-11-18 01:29:26 +00003238 // Add properties in referenced protocols.
3239 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3240 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3241 PEnd = Protocol->protocol_end();
3242 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003243 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3244 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003245 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003246 if (AllowCategories) {
3247 // Look through categories.
3248 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3249 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003250 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3251 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003252 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003253
3254 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003255 for (ObjCInterfaceDecl::all_protocol_iterator
3256 I = IFace->all_referenced_protocol_begin(),
3257 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003258 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3259 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003260
3261 // Look in the superclass.
3262 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003263 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3264 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003265 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003266 } else if (const ObjCCategoryDecl *Category
3267 = dyn_cast<ObjCCategoryDecl>(Container)) {
3268 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003269 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3270 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003271 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003272 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3273 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003274 }
3275}
3276
Richard Trieuf81e5a92011-09-09 02:00:50 +00003277void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *BaseE,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003278 SourceLocation OpLoc,
3279 bool IsArrow) {
3280 if (!BaseE || !CodeCompleter)
3281 return;
3282
John McCall0a2c5e22010-08-25 06:19:51 +00003283 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003284
Douglas Gregor81b747b2009-09-17 21:32:03 +00003285 Expr *Base = static_cast<Expr *>(BaseE);
3286 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003287
3288 if (IsArrow) {
3289 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3290 BaseType = Ptr->getPointeeType();
3291 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003292 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003293 else
3294 return;
3295 }
3296
Douglas Gregor3da626b2011-07-07 16:03:39 +00003297 enum CodeCompletionContext::Kind contextKind;
3298
3299 if (IsArrow) {
3300 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3301 }
3302 else {
3303 if (BaseType->isObjCObjectPointerType() ||
3304 BaseType->isObjCObjectOrInterfaceType()) {
3305 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3306 }
3307 else {
3308 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3309 }
3310 }
3311
Douglas Gregor218937c2011-02-01 19:23:04 +00003312 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003313 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003314 BaseType),
3315 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003316 Results.EnterNewScope();
3317 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003318 // Indicate that we are performing a member access, and the cv-qualifiers
3319 // for the base object type.
3320 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3321
Douglas Gregor95ac6552009-11-18 01:29:26 +00003322 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003323 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003324 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003325 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3326 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003327
Douglas Gregor95ac6552009-11-18 01:29:26 +00003328 if (getLangOptions().CPlusPlus) {
3329 if (!Results.empty()) {
3330 // The "template" keyword can follow "->" or "." in the grammar.
3331 // However, we only want to suggest the template keyword if something
3332 // is dependent.
3333 bool IsDependent = BaseType->isDependentType();
3334 if (!IsDependent) {
3335 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3336 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3337 IsDependent = Ctx->isDependentContext();
3338 break;
3339 }
3340 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003341
Douglas Gregor95ac6552009-11-18 01:29:26 +00003342 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003343 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003344 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003345 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003346 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3347 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003348 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003349
3350 // Add property results based on our interface.
3351 const ObjCObjectPointerType *ObjCPtr
3352 = BaseType->getAsObjCInterfacePointerType();
3353 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003354 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3355 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003356 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003357
3358 // Add properties from the protocols in a qualified interface.
3359 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3360 E = ObjCPtr->qual_end();
3361 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003362 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3363 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003364 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003365 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003366 // Objective-C instance variable access.
3367 ObjCInterfaceDecl *Class = 0;
3368 if (const ObjCObjectPointerType *ObjCPtr
3369 = BaseType->getAs<ObjCObjectPointerType>())
3370 Class = ObjCPtr->getInterfaceDecl();
3371 else
John McCallc12c5bb2010-05-15 11:32:37 +00003372 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003373
3374 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003375 if (Class) {
3376 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3377 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003378 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3379 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003380 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003381 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003382
3383 // FIXME: How do we cope with isa?
3384
3385 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003386
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003387 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003388 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003389 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003390 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003391}
3392
Douglas Gregor374929f2009-09-18 15:37:17 +00003393void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3394 if (!CodeCompleter)
3395 return;
3396
John McCall0a2c5e22010-08-25 06:19:51 +00003397 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003398 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003399 enum CodeCompletionContext::Kind ContextKind
3400 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003401 switch ((DeclSpec::TST)TagSpec) {
3402 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003403 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003404 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003405 break;
3406
3407 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003408 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003409 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003410 break;
3411
3412 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003413 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003414 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003415 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003416 break;
3417
3418 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003419 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003420 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003421
Douglas Gregor218937c2011-02-01 19:23:04 +00003422 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003423 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003424
3425 // First pass: look for tags.
3426 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003427 LookupVisibleDecls(S, LookupTagName, Consumer,
3428 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003429
Douglas Gregor8071e422010-08-15 06:18:01 +00003430 if (CodeCompleter->includeGlobals()) {
3431 // Second pass: look for nested name specifiers.
3432 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3433 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3434 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003435
Douglas Gregor52779fb2010-09-23 23:01:17 +00003436 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003437 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003438}
3439
Douglas Gregor1a480c42010-08-27 17:35:51 +00003440void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003441 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3442 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003443 Results.EnterNewScope();
3444 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3445 Results.AddResult("const");
3446 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3447 Results.AddResult("volatile");
3448 if (getLangOptions().C99 &&
3449 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3450 Results.AddResult("restrict");
3451 Results.ExitScope();
3452 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003453 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003454 Results.data(), Results.size());
3455}
3456
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003457void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003458 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003459 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003460
John McCall781472f2010-08-25 08:40:02 +00003461 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003462 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3463 if (!type->isEnumeralType()) {
3464 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003465 Data.IntegralConstantExpression = true;
3466 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003467 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003468 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003469
3470 // Code-complete the cases of a switch statement over an enumeration type
3471 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003472 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003473
3474 // Determine which enumerators we have already seen in the switch statement.
3475 // FIXME: Ideally, we would also be able to look *past* the code-completion
3476 // token, in case we are code-completing in the middle of the switch and not
3477 // at the end. However, we aren't able to do so at the moment.
3478 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003479 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003480 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3481 SC = SC->getNextSwitchCase()) {
3482 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3483 if (!Case)
3484 continue;
3485
3486 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3487 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3488 if (EnumConstantDecl *Enumerator
3489 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3490 // We look into the AST of the case statement to determine which
3491 // enumerator was named. Alternatively, we could compute the value of
3492 // the integral constant expression, then compare it against the
3493 // values of each enumerator. However, value-based approach would not
3494 // work as well with C++ templates where enumerators declared within a
3495 // template are type- and value-dependent.
3496 EnumeratorsSeen.insert(Enumerator);
3497
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003498 // If this is a qualified-id, keep track of the nested-name-specifier
3499 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003500 //
3501 // switch (TagD.getKind()) {
3502 // case TagDecl::TK_enum:
3503 // break;
3504 // case XXX
3505 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003506 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003507 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3508 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003509 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003510 }
3511 }
3512
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003513 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3514 // If there are no prior enumerators in C++, check whether we have to
3515 // qualify the names of the enumerators that we suggest, because they
3516 // may not be visible in this scope.
3517 Qualifier = getRequiredQualification(Context, CurContext,
3518 Enum->getDeclContext());
3519
3520 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3521 }
3522
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003523 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003524 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3525 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003526 Results.EnterNewScope();
3527 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3528 EEnd = Enum->enumerator_end();
3529 E != EEnd; ++E) {
3530 if (EnumeratorsSeen.count(*E))
3531 continue;
3532
Douglas Gregor5c722c702011-02-18 23:30:37 +00003533 CodeCompletionResult R(*E, Qualifier);
3534 R.Priority = CCP_EnumInCase;
3535 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003536 }
3537 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003538
Douglas Gregor3da626b2011-07-07 16:03:39 +00003539 //We need to make sure we're setting the right context,
3540 //so only say we include macros if the code completer says we do
3541 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3542 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003543 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003544 kind = CodeCompletionContext::CCC_OtherWithMacros;
3545 }
3546
3547
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003548 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003549 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003550 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003551}
3552
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003553namespace {
3554 struct IsBetterOverloadCandidate {
3555 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003556 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003557
3558 public:
John McCall5769d612010-02-08 23:07:23 +00003559 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3560 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003561
3562 bool
3563 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003564 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003565 }
3566 };
3567}
3568
Douglas Gregord28dcd72010-05-30 06:10:08 +00003569static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3570 if (NumArgs && !Args)
3571 return true;
3572
3573 for (unsigned I = 0; I != NumArgs; ++I)
3574 if (!Args[I])
3575 return true;
3576
3577 return false;
3578}
3579
Richard Trieuf81e5a92011-09-09 02:00:50 +00003580void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3581 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003582 if (!CodeCompleter)
3583 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003584
3585 // When we're code-completing for a call, we fall back to ordinary
3586 // name code-completion whenever we can't produce specific
3587 // results. We may want to revisit this strategy in the future,
3588 // e.g., by merging the two kinds of results.
3589
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003590 Expr *Fn = (Expr *)FnIn;
3591 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003592
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003593 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003594 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003595 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003596 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003597 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003598 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003599
John McCall3b4294e2009-12-16 12:17:52 +00003600 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003601 SourceLocation Loc = Fn->getExprLoc();
3602 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003603
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003604 // FIXME: What if we're calling something that isn't a function declaration?
3605 // FIXME: What if we're calling a pseudo-destructor?
3606 // FIXME: What if we're calling a member function?
3607
Douglas Gregorc0265402010-01-21 15:46:19 +00003608 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003609 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003610
John McCall3b4294e2009-12-16 12:17:52 +00003611 Expr *NakedFn = Fn->IgnoreParenCasts();
3612 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3613 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3614 /*PartialOverloading=*/ true);
3615 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3616 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003617 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003618 if (!getLangOptions().CPlusPlus ||
3619 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003620 Results.push_back(ResultCandidate(FDecl));
3621 else
John McCall86820f52010-01-26 01:37:31 +00003622 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003623 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3624 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003625 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003626 }
John McCall3b4294e2009-12-16 12:17:52 +00003627 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003628
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003629 QualType ParamType;
3630
Douglas Gregorc0265402010-01-21 15:46:19 +00003631 if (!CandidateSet.empty()) {
3632 // Sort the overload candidate set by placing the best overloads first.
3633 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003634 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003635
Douglas Gregorc0265402010-01-21 15:46:19 +00003636 // Add the remaining viable overload candidates as code-completion reslults.
3637 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3638 CandEnd = CandidateSet.end();
3639 Cand != CandEnd; ++Cand) {
3640 if (Cand->Viable)
3641 Results.push_back(ResultCandidate(Cand->Function));
3642 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003643
3644 // From the viable candidates, try to determine the type of this parameter.
3645 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3646 if (const FunctionType *FType = Results[I].getFunctionType())
3647 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3648 if (NumArgs < Proto->getNumArgs()) {
3649 if (ParamType.isNull())
3650 ParamType = Proto->getArgType(NumArgs);
3651 else if (!Context.hasSameUnqualifiedType(
3652 ParamType.getNonReferenceType(),
3653 Proto->getArgType(NumArgs).getNonReferenceType())) {
3654 ParamType = QualType();
3655 break;
3656 }
3657 }
3658 }
3659 } else {
3660 // Try to determine the parameter type from the type of the expression
3661 // being called.
3662 QualType FunctionType = Fn->getType();
3663 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3664 FunctionType = Ptr->getPointeeType();
3665 else if (const BlockPointerType *BlockPtr
3666 = FunctionType->getAs<BlockPointerType>())
3667 FunctionType = BlockPtr->getPointeeType();
3668 else if (const MemberPointerType *MemPtr
3669 = FunctionType->getAs<MemberPointerType>())
3670 FunctionType = MemPtr->getPointeeType();
3671
3672 if (const FunctionProtoType *Proto
3673 = FunctionType->getAs<FunctionProtoType>()) {
3674 if (NumArgs < Proto->getNumArgs())
3675 ParamType = Proto->getArgType(NumArgs);
3676 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003677 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003678
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003679 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003680 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003681 else
3682 CodeCompleteExpression(S, ParamType);
3683
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003684 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003685 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3686 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003687}
3688
John McCalld226f652010-08-21 09:40:31 +00003689void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3690 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003691 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003692 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003693 return;
3694 }
3695
3696 CodeCompleteExpression(S, VD->getType());
3697}
3698
3699void Sema::CodeCompleteReturn(Scope *S) {
3700 QualType ResultType;
3701 if (isa<BlockDecl>(CurContext)) {
3702 if (BlockScopeInfo *BSI = getCurBlock())
3703 ResultType = BSI->ReturnType;
3704 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3705 ResultType = Function->getResultType();
3706 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3707 ResultType = Method->getResultType();
3708
3709 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003710 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003711 else
3712 CodeCompleteExpression(S, ResultType);
3713}
3714
Douglas Gregord2d8be62011-07-30 08:36:53 +00003715void Sema::CodeCompleteAfterIf(Scope *S) {
3716 typedef CodeCompletionResult Result;
3717 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3718 mapCodeCompletionContext(*this, PCC_Statement));
3719 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3720 Results.EnterNewScope();
3721
3722 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3723 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3724 CodeCompleter->includeGlobals());
3725
3726 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3727
3728 // "else" block
3729 CodeCompletionBuilder Builder(Results.getAllocator());
3730 Builder.AddTypedTextChunk("else");
3731 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3732 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3733 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3734 Builder.AddPlaceholderChunk("statements");
3735 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3736 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3737 Results.AddResult(Builder.TakeString());
3738
3739 // "else if" block
3740 Builder.AddTypedTextChunk("else");
3741 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3742 Builder.AddTextChunk("if");
3743 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3744 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3745 if (getLangOptions().CPlusPlus)
3746 Builder.AddPlaceholderChunk("condition");
3747 else
3748 Builder.AddPlaceholderChunk("expression");
3749 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3750 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3751 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3752 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3753 Builder.AddPlaceholderChunk("statements");
3754 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3755 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3756 Results.AddResult(Builder.TakeString());
3757
3758 Results.ExitScope();
3759
3760 if (S->getFnParent())
3761 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3762
3763 if (CodeCompleter->includeMacros())
3764 AddMacroResults(PP, Results);
3765
3766 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3767 Results.data(),Results.size());
3768}
3769
Richard Trieuf81e5a92011-09-09 02:00:50 +00003770void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003771 if (LHS)
3772 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3773 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003774 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003775}
3776
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003777void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003778 bool EnteringContext) {
3779 if (!SS.getScopeRep() || !CodeCompleter)
3780 return;
3781
Douglas Gregor86d9a522009-09-21 16:56:56 +00003782 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3783 if (!Ctx)
3784 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003785
3786 // Try to instantiate any non-dependent declaration contexts before
3787 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003788 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003789 return;
3790
Douglas Gregor218937c2011-02-01 19:23:04 +00003791 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3792 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003793 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003794
Douglas Gregor86d9a522009-09-21 16:56:56 +00003795 // The "template" keyword can follow "::" in the grammar, but only
3796 // put it into the grammar if the nested-name-specifier is dependent.
3797 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3798 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003799 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003800
3801 // Add calls to overridden virtual functions, if there are any.
3802 //
3803 // FIXME: This isn't wonderful, because we don't know whether we're actually
3804 // in a context that permits expressions. This is a general issue with
3805 // qualified-id completions.
3806 if (!EnteringContext)
3807 MaybeAddOverrideCalls(*this, Ctx, Results);
3808 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003809
Douglas Gregorf6961522010-08-27 21:18:54 +00003810 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3811 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3812
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003813 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003814 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003815 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003816}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003817
3818void Sema::CodeCompleteUsing(Scope *S) {
3819 if (!CodeCompleter)
3820 return;
3821
Douglas Gregor218937c2011-02-01 19:23:04 +00003822 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003823 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3824 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003825 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003826
3827 // If we aren't in class scope, we could see the "namespace" keyword.
3828 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003829 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003830
3831 // After "using", we can see anything that would start a
3832 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003833 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003834 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3835 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003836 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003837
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003838 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003839 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003840 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003841}
3842
3843void Sema::CodeCompleteUsingDirective(Scope *S) {
3844 if (!CodeCompleter)
3845 return;
3846
Douglas Gregor86d9a522009-09-21 16:56:56 +00003847 // After "using namespace", we expect to see a namespace name or namespace
3848 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003849 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3850 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003851 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003852 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003853 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003854 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3855 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003856 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003857 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003858 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003859 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003860}
3861
3862void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3863 if (!CodeCompleter)
3864 return;
3865
Douglas Gregor86d9a522009-09-21 16:56:56 +00003866 DeclContext *Ctx = (DeclContext *)S->getEntity();
3867 if (!S->getParent())
3868 Ctx = Context.getTranslationUnitDecl();
3869
Douglas Gregor52779fb2010-09-23 23:01:17 +00003870 bool SuppressedGlobalResults
3871 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3872
Douglas Gregor218937c2011-02-01 19:23:04 +00003873 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003874 SuppressedGlobalResults
3875 ? CodeCompletionContext::CCC_Namespace
3876 : CodeCompletionContext::CCC_Other,
3877 &ResultBuilder::IsNamespace);
3878
3879 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003880 // We only want to see those namespaces that have already been defined
3881 // within this scope, because its likely that the user is creating an
3882 // extended namespace declaration. Keep track of the most recent
3883 // definition of each namespace.
3884 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3885 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3886 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3887 NS != NSEnd; ++NS)
3888 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3889
3890 // Add the most recent definition (or extended definition) of each
3891 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003892 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003893 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3894 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3895 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003896 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003897 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003898 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003899 }
3900
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003901 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003902 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003903 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003904}
3905
3906void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3907 if (!CodeCompleter)
3908 return;
3909
Douglas Gregor86d9a522009-09-21 16:56:56 +00003910 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003911 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3912 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003913 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003914 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003915 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3916 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003917 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003918 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003919 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003920}
3921
Douglas Gregored8d3222009-09-18 20:05:18 +00003922void Sema::CodeCompleteOperatorName(Scope *S) {
3923 if (!CodeCompleter)
3924 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003925
John McCall0a2c5e22010-08-25 06:19:51 +00003926 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003927 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3928 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003929 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003930 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003931
Douglas Gregor86d9a522009-09-21 16:56:56 +00003932 // Add the names of overloadable operators.
3933#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3934 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003935 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003936#include "clang/Basic/OperatorKinds.def"
3937
3938 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003939 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003940 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003941 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3942 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003943
3944 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003945 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003946 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003947
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003948 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003949 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003950 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003951}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003952
Douglas Gregor0133f522010-08-28 00:00:50 +00003953void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00003954 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00003955 unsigned NumInitializers) {
Douglas Gregor8987b232011-09-27 23:30:47 +00003956 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor0133f522010-08-28 00:00:50 +00003957 CXXConstructorDecl *Constructor
3958 = static_cast<CXXConstructorDecl *>(ConstructorD);
3959 if (!Constructor)
3960 return;
3961
Douglas Gregor218937c2011-02-01 19:23:04 +00003962 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003963 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003964 Results.EnterNewScope();
3965
3966 // Fill in any already-initialized fields or base classes.
3967 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3968 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3969 for (unsigned I = 0; I != NumInitializers; ++I) {
3970 if (Initializers[I]->isBaseInitializer())
3971 InitializedBases.insert(
3972 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3973 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003974 InitializedFields.insert(cast<FieldDecl>(
3975 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00003976 }
3977
3978 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00003979 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00003980 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003981 CXXRecordDecl *ClassDecl = Constructor->getParent();
3982 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3983 BaseEnd = ClassDecl->bases_end();
3984 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003985 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3986 SawLastInitializer
3987 = NumInitializers > 0 &&
3988 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3989 Context.hasSameUnqualifiedType(Base->getType(),
3990 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003991 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003992 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003993
Douglas Gregor218937c2011-02-01 19:23:04 +00003994 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003995 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00003996 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00003997 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3998 Builder.AddPlaceholderChunk("args");
3999 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4000 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004001 SawLastInitializer? CCP_NextInitializer
4002 : CCP_MemberDeclaration));
4003 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004004 }
4005
4006 // Add completions for virtual base classes.
4007 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4008 BaseEnd = ClassDecl->vbases_end();
4009 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004010 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4011 SawLastInitializer
4012 = NumInitializers > 0 &&
4013 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4014 Context.hasSameUnqualifiedType(Base->getType(),
4015 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004016 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004017 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004018
Douglas Gregor218937c2011-02-01 19:23:04 +00004019 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004020 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004021 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004022 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4023 Builder.AddPlaceholderChunk("args");
4024 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4025 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004026 SawLastInitializer? CCP_NextInitializer
4027 : CCP_MemberDeclaration));
4028 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004029 }
4030
4031 // Add completions for members.
4032 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4033 FieldEnd = ClassDecl->field_end();
4034 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004035 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4036 SawLastInitializer
4037 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004038 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4039 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004040 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004041 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004042
4043 if (!Field->getDeclName())
4044 continue;
4045
Douglas Gregordae68752011-02-01 22:57:45 +00004046 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004047 Field->getIdentifier()->getName()));
4048 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4049 Builder.AddPlaceholderChunk("args");
4050 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4051 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004052 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004053 : CCP_MemberDeclaration,
4054 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004055 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004056 }
4057 Results.ExitScope();
4058
Douglas Gregor52779fb2010-09-23 23:01:17 +00004059 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004060 Results.data(), Results.size());
4061}
4062
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004063// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4064// true or false.
4065#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004066static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004067 ResultBuilder &Results,
4068 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004069 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004070 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004071 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004072
Douglas Gregor218937c2011-02-01 19:23:04 +00004073 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004074 if (LangOpts.ObjC2) {
4075 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004076 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4077 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4078 Builder.AddPlaceholderChunk("property");
4079 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004080
4081 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004082 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4083 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4084 Builder.AddPlaceholderChunk("property");
4085 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004086 }
4087}
4088
Douglas Gregorbca403c2010-01-13 23:51:12 +00004089static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004090 ResultBuilder &Results,
4091 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004092 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004093
4094 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004095 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004096
4097 if (LangOpts.ObjC2) {
4098 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004099 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004100
4101 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004102 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004103
4104 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004105 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004106 }
4107}
4108
Douglas Gregorbca403c2010-01-13 23:51:12 +00004109static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004110 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004111 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004112
4113 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004114 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4115 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4116 Builder.AddPlaceholderChunk("name");
4117 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004118
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004119 if (Results.includeCodePatterns()) {
4120 // @interface name
4121 // FIXME: Could introduce the whole pattern, including superclasses and
4122 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004123 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4124 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4125 Builder.AddPlaceholderChunk("class");
4126 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004127
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004128 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004129 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4130 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4131 Builder.AddPlaceholderChunk("protocol");
4132 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004133
4134 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004135 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4136 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4137 Builder.AddPlaceholderChunk("class");
4138 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004139 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004140
4141 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004142 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4143 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4144 Builder.AddPlaceholderChunk("alias");
4145 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4146 Builder.AddPlaceholderChunk("class");
4147 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004148}
4149
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004150void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004151 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004152 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4153 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004154 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004155 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorbca403c2010-01-13 23:51:12 +00004156 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004157 else if (CurContext->isObjCContainer())
Douglas Gregorbca403c2010-01-13 23:51:12 +00004158 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004159 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004160 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004161 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004162 HandleCodeCompleteResults(this, CodeCompleter,
4163 CodeCompletionContext::CCC_Other,
4164 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004165}
4166
Douglas Gregorbca403c2010-01-13 23:51:12 +00004167static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004168 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004169 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004170
4171 // @encode ( type-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004172 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4173 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4174 Builder.AddPlaceholderChunk("type-name");
4175 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4176 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004177
4178 // @protocol ( protocol-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004179 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4180 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4181 Builder.AddPlaceholderChunk("protocol-name");
4182 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4183 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004184
4185 // @selector ( selector )
Douglas Gregor218937c2011-02-01 19:23:04 +00004186 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4187 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4188 Builder.AddPlaceholderChunk("selector");
4189 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4190 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004191}
4192
Douglas Gregorbca403c2010-01-13 23:51:12 +00004193static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004194 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004195 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004196
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004197 if (Results.includeCodePatterns()) {
4198 // @try { statements } @catch ( declaration ) { statements } @finally
4199 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004200 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4201 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4202 Builder.AddPlaceholderChunk("statements");
4203 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4204 Builder.AddTextChunk("@catch");
4205 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4206 Builder.AddPlaceholderChunk("parameter");
4207 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4208 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4209 Builder.AddPlaceholderChunk("statements");
4210 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4211 Builder.AddTextChunk("@finally");
4212 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4213 Builder.AddPlaceholderChunk("statements");
4214 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4215 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004216 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004217
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004218 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004219 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4220 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4221 Builder.AddPlaceholderChunk("expression");
4222 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004223
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004224 if (Results.includeCodePatterns()) {
4225 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004226 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4227 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4228 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4229 Builder.AddPlaceholderChunk("expression");
4230 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4231 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4232 Builder.AddPlaceholderChunk("statements");
4233 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4234 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004235 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004236}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004237
Douglas Gregorbca403c2010-01-13 23:51:12 +00004238static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004239 ResultBuilder &Results,
4240 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004241 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004242 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4243 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4244 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004245 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004246 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004247}
4248
4249void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004250 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4251 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004252 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004253 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004254 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004255 HandleCodeCompleteResults(this, CodeCompleter,
4256 CodeCompletionContext::CCC_Other,
4257 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004258}
4259
4260void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004261 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4262 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004263 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004264 AddObjCStatementResults(Results, false);
4265 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004266 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004267 HandleCodeCompleteResults(this, CodeCompleter,
4268 CodeCompletionContext::CCC_Other,
4269 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004270}
4271
4272void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004273 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4274 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004275 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004276 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004277 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004278 HandleCodeCompleteResults(this, CodeCompleter,
4279 CodeCompletionContext::CCC_Other,
4280 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004281}
4282
Douglas Gregor988358f2009-11-19 00:14:45 +00004283/// \brief Determine whether the addition of the given flag to an Objective-C
4284/// property's attributes will cause a conflict.
4285static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4286 // Check if we've already added this flag.
4287 if (Attributes & NewFlag)
4288 return true;
4289
4290 Attributes |= NewFlag;
4291
4292 // Check for collisions with "readonly".
4293 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4294 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4295 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004296 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004297 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004298 ObjCDeclSpec::DQ_PR_retain |
4299 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004300 return true;
4301
John McCallf85e1932011-06-15 23:02:42 +00004302 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004303 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004304 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004305 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004306 ObjCDeclSpec::DQ_PR_retain|
4307 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004308 if (AssignCopyRetMask &&
4309 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004310 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004311 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004312 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4313 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004314 return true;
4315
4316 return false;
4317}
4318
Douglas Gregora93b1082009-11-18 23:08:07 +00004319void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004320 if (!CodeCompleter)
4321 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004322
Steve Naroffece8e712009-10-08 21:55:05 +00004323 unsigned Attributes = ODS.getPropertyAttributes();
4324
John McCall0a2c5e22010-08-25 06:19:51 +00004325 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004326 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4327 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004328 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004329 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004330 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004331 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004332 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004333 if (!ObjCPropertyFlagConflicts(Attributes,
4334 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4335 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004336 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004337 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004338 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004339 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004340 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4341 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004342 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004343 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004344 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004345 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004346 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4347 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004348 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004349 CodeCompletionBuilder Setter(Results.getAllocator());
4350 Setter.AddTypedTextChunk("setter");
4351 Setter.AddTextChunk(" = ");
4352 Setter.AddPlaceholderChunk("method");
4353 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004354 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004355 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004356 CodeCompletionBuilder Getter(Results.getAllocator());
4357 Getter.AddTypedTextChunk("getter");
4358 Getter.AddTextChunk(" = ");
4359 Getter.AddPlaceholderChunk("method");
4360 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004361 }
Steve Naroffece8e712009-10-08 21:55:05 +00004362 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004363 HandleCodeCompleteResults(this, CodeCompleter,
4364 CodeCompletionContext::CCC_Other,
4365 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004366}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004367
Douglas Gregor4ad96852009-11-19 07:41:15 +00004368/// \brief Descripts the kind of Objective-C method that we want to find
4369/// via code completion.
4370enum ObjCMethodKind {
4371 MK_Any, //< Any kind of method, provided it means other specified criteria.
4372 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4373 MK_OneArgSelector //< One-argument selector.
4374};
4375
Douglas Gregor458433d2010-08-26 15:07:07 +00004376static bool isAcceptableObjCSelector(Selector Sel,
4377 ObjCMethodKind WantKind,
4378 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004379 unsigned NumSelIdents,
4380 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004381 if (NumSelIdents > Sel.getNumArgs())
4382 return false;
4383
4384 switch (WantKind) {
4385 case MK_Any: break;
4386 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4387 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4388 }
4389
Douglas Gregorcf544262010-11-17 21:36:08 +00004390 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4391 return false;
4392
Douglas Gregor458433d2010-08-26 15:07:07 +00004393 for (unsigned I = 0; I != NumSelIdents; ++I)
4394 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4395 return false;
4396
4397 return true;
4398}
4399
Douglas Gregor4ad96852009-11-19 07:41:15 +00004400static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4401 ObjCMethodKind WantKind,
4402 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004403 unsigned NumSelIdents,
4404 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004405 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004406 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004407}
Douglas Gregord36adf52010-09-16 16:06:31 +00004408
4409namespace {
4410 /// \brief A set of selectors, which is used to avoid introducing multiple
4411 /// completions with the same selector into the result set.
4412 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4413}
4414
Douglas Gregor36ecb042009-11-17 23:22:23 +00004415/// \brief Add all of the Objective-C methods in the given Objective-C
4416/// container to the set of results.
4417///
4418/// The container will be a class, protocol, category, or implementation of
4419/// any of the above. This mether will recurse to include methods from
4420/// the superclasses of classes along with their categories, protocols, and
4421/// implementations.
4422///
4423/// \param Container the container in which we'll look to find methods.
4424///
4425/// \param WantInstance whether to add instance methods (only); if false, this
4426/// routine will add factory methods (only).
4427///
4428/// \param CurContext the context in which we're performing the lookup that
4429/// finds methods.
4430///
Douglas Gregorcf544262010-11-17 21:36:08 +00004431/// \param AllowSameLength Whether we allow a method to be added to the list
4432/// when it has the same number of parameters as we have selector identifiers.
4433///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004434/// \param Results the structure into which we'll add results.
4435static void AddObjCMethods(ObjCContainerDecl *Container,
4436 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004437 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004438 IdentifierInfo **SelIdents,
4439 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004440 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004441 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004442 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004443 ResultBuilder &Results,
4444 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004445 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004446 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4447 MEnd = Container->meth_end();
4448 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004449 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4450 // Check whether the selector identifiers we've been given are a
4451 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004452 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4453 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004454 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004455
Douglas Gregord36adf52010-09-16 16:06:31 +00004456 if (!Selectors.insert((*M)->getSelector()))
4457 continue;
4458
Douglas Gregord3c68542009-11-19 01:08:35 +00004459 Result R = Result(*M, 0);
4460 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004461 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004462 if (!InOriginalClass)
4463 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004464 Results.MaybeAddResult(R, CurContext);
4465 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004466 }
4467
Douglas Gregore396c7b2010-09-16 15:34:59 +00004468 // Visit the protocols of protocols.
4469 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4470 const ObjCList<ObjCProtocolDecl> &Protocols
4471 = Protocol->getReferencedProtocols();
4472 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4473 E = Protocols.end();
4474 I != E; ++I)
4475 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004476 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004477 }
4478
Douglas Gregor36ecb042009-11-17 23:22:23 +00004479 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4480 if (!IFace)
4481 return;
4482
4483 // Add methods in protocols.
4484 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4485 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4486 E = Protocols.end();
4487 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004488 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004489 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004490
4491 // Add methods in categories.
4492 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4493 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004494 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004495 NumSelIdents, CurContext, Selectors, AllowSameLength,
4496 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004497
4498 // Add a categories protocol methods.
4499 const ObjCList<ObjCProtocolDecl> &Protocols
4500 = CatDecl->getReferencedProtocols();
4501 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4502 E = Protocols.end();
4503 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004504 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004505 NumSelIdents, CurContext, Selectors, AllowSameLength,
4506 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004507
4508 // Add methods in category implementations.
4509 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004510 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004511 NumSelIdents, CurContext, Selectors, AllowSameLength,
4512 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004513 }
4514
4515 // Add methods in superclass.
4516 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004517 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004518 SelIdents, NumSelIdents, CurContext, Selectors,
4519 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004520
4521 // Add methods in our implementation, if any.
4522 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004523 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004524 NumSelIdents, CurContext, Selectors, AllowSameLength,
4525 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004526}
4527
4528
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004529void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004530 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004531
4532 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004533 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004534 if (!Class) {
4535 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004536 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004537 Class = Category->getClassInterface();
4538
4539 if (!Class)
4540 return;
4541 }
4542
4543 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004544 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4545 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004546 Results.EnterNewScope();
4547
Douglas Gregord36adf52010-09-16 16:06:31 +00004548 VisitedSelectorSet Selectors;
4549 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004550 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004551 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004552 HandleCodeCompleteResults(this, CodeCompleter,
4553 CodeCompletionContext::CCC_Other,
4554 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004555}
4556
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004557void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004558 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004559
4560 // Try to find the interface where setters might live.
4561 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004562 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004563 if (!Class) {
4564 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004565 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004566 Class = Category->getClassInterface();
4567
4568 if (!Class)
4569 return;
4570 }
4571
4572 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004573 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4574 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004575 Results.EnterNewScope();
4576
Douglas Gregord36adf52010-09-16 16:06:31 +00004577 VisitedSelectorSet Selectors;
4578 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004579 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004580
4581 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004582 HandleCodeCompleteResults(this, CodeCompleter,
4583 CodeCompletionContext::CCC_Other,
4584 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004585}
4586
Douglas Gregorafc45782011-02-15 22:19:42 +00004587void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4588 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004589 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004590 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4591 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004592 Results.EnterNewScope();
4593
4594 // Add context-sensitive, Objective-C parameter-passing keywords.
4595 bool AddedInOut = false;
4596 if ((DS.getObjCDeclQualifier() &
4597 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4598 Results.AddResult("in");
4599 Results.AddResult("inout");
4600 AddedInOut = true;
4601 }
4602 if ((DS.getObjCDeclQualifier() &
4603 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4604 Results.AddResult("out");
4605 if (!AddedInOut)
4606 Results.AddResult("inout");
4607 }
4608 if ((DS.getObjCDeclQualifier() &
4609 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4610 ObjCDeclSpec::DQ_Oneway)) == 0) {
4611 Results.AddResult("bycopy");
4612 Results.AddResult("byref");
4613 Results.AddResult("oneway");
4614 }
4615
Douglas Gregorafc45782011-02-15 22:19:42 +00004616 // If we're completing the return type of an Objective-C method and the
4617 // identifier IBAction refers to a macro, provide a completion item for
4618 // an action, e.g.,
4619 // IBAction)<#selector#>:(id)sender
4620 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4621 Context.Idents.get("IBAction").hasMacroDefinition()) {
4622 typedef CodeCompletionString::Chunk Chunk;
4623 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4624 CXAvailability_Available);
4625 Builder.AddTypedTextChunk("IBAction");
4626 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4627 Builder.AddPlaceholderChunk("selector");
4628 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4629 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4630 Builder.AddTextChunk("id");
4631 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4632 Builder.AddTextChunk("sender");
4633 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4634 }
4635
Douglas Gregord32b0222010-08-24 01:06:58 +00004636 // Add various builtin type names and specifiers.
4637 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4638 Results.ExitScope();
4639
4640 // Add the various type names
4641 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4642 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4643 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4644 CodeCompleter->includeGlobals());
4645
4646 if (CodeCompleter->includeMacros())
4647 AddMacroResults(PP, Results);
4648
4649 HandleCodeCompleteResults(this, CodeCompleter,
4650 CodeCompletionContext::CCC_Type,
4651 Results.data(), Results.size());
4652}
4653
Douglas Gregor22f56992010-04-06 19:22:33 +00004654/// \brief When we have an expression with type "id", we may assume
4655/// that it has some more-specific class type based on knowledge of
4656/// common uses of Objective-C. This routine returns that class type,
4657/// or NULL if no better result could be determined.
4658static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004659 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004660 if (!Msg)
4661 return 0;
4662
4663 Selector Sel = Msg->getSelector();
4664 if (Sel.isNull())
4665 return 0;
4666
4667 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4668 if (!Id)
4669 return 0;
4670
4671 ObjCMethodDecl *Method = Msg->getMethodDecl();
4672 if (!Method)
4673 return 0;
4674
4675 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004676 ObjCInterfaceDecl *IFace = 0;
4677 switch (Msg->getReceiverKind()) {
4678 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004679 if (const ObjCObjectType *ObjType
4680 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4681 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004682 break;
4683
4684 case ObjCMessageExpr::Instance: {
4685 QualType T = Msg->getInstanceReceiver()->getType();
4686 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4687 IFace = Ptr->getInterfaceDecl();
4688 break;
4689 }
4690
4691 case ObjCMessageExpr::SuperInstance:
4692 case ObjCMessageExpr::SuperClass:
4693 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004694 }
4695
4696 if (!IFace)
4697 return 0;
4698
4699 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4700 if (Method->isInstanceMethod())
4701 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4702 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004703 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004704 .Case("autorelease", IFace)
4705 .Case("copy", IFace)
4706 .Case("copyWithZone", IFace)
4707 .Case("mutableCopy", IFace)
4708 .Case("mutableCopyWithZone", IFace)
4709 .Case("awakeFromCoder", IFace)
4710 .Case("replacementObjectFromCoder", IFace)
4711 .Case("class", IFace)
4712 .Case("classForCoder", IFace)
4713 .Case("superclass", Super)
4714 .Default(0);
4715
4716 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4717 .Case("new", IFace)
4718 .Case("alloc", IFace)
4719 .Case("allocWithZone", IFace)
4720 .Case("class", IFace)
4721 .Case("superclass", Super)
4722 .Default(0);
4723}
4724
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004725// Add a special completion for a message send to "super", which fills in the
4726// most likely case of forwarding all of our arguments to the superclass
4727// function.
4728///
4729/// \param S The semantic analysis object.
4730///
4731/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4732/// the "super" keyword. Otherwise, we just need to provide the arguments.
4733///
4734/// \param SelIdents The identifiers in the selector that have already been
4735/// provided as arguments for a send to "super".
4736///
4737/// \param NumSelIdents The number of identifiers in \p SelIdents.
4738///
4739/// \param Results The set of results to augment.
4740///
4741/// \returns the Objective-C method declaration that would be invoked by
4742/// this "super" completion. If NULL, no completion was added.
4743static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4744 IdentifierInfo **SelIdents,
4745 unsigned NumSelIdents,
4746 ResultBuilder &Results) {
4747 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4748 if (!CurMethod)
4749 return 0;
4750
4751 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4752 if (!Class)
4753 return 0;
4754
4755 // Try to find a superclass method with the same selector.
4756 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004757 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4758 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004759 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4760 CurMethod->isInstanceMethod());
4761
Douglas Gregor78bcd912011-02-16 00:51:18 +00004762 // Check in categories or class extensions.
4763 if (!SuperMethod) {
4764 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4765 Category = Category->getNextClassCategory())
4766 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4767 CurMethod->isInstanceMethod())))
4768 break;
4769 }
4770 }
4771
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004772 if (!SuperMethod)
4773 return 0;
4774
4775 // Check whether the superclass method has the same signature.
4776 if (CurMethod->param_size() != SuperMethod->param_size() ||
4777 CurMethod->isVariadic() != SuperMethod->isVariadic())
4778 return 0;
4779
4780 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4781 CurPEnd = CurMethod->param_end(),
4782 SuperP = SuperMethod->param_begin();
4783 CurP != CurPEnd; ++CurP, ++SuperP) {
4784 // Make sure the parameter types are compatible.
4785 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4786 (*SuperP)->getType()))
4787 return 0;
4788
4789 // Make sure we have a parameter name to forward!
4790 if (!(*CurP)->getIdentifier())
4791 return 0;
4792 }
4793
4794 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004795 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004796
4797 // Give this completion a return type.
Douglas Gregor8987b232011-09-27 23:30:47 +00004798 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
4799 Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004800
4801 // If we need the "super" keyword, add it (plus some spacing).
4802 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004803 Builder.AddTypedTextChunk("super");
4804 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004805 }
4806
4807 Selector Sel = CurMethod->getSelector();
4808 if (Sel.isUnarySelector()) {
4809 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004810 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004811 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004812 else
Douglas Gregordae68752011-02-01 22:57:45 +00004813 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004814 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004815 } else {
4816 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4817 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4818 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004819 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004820
4821 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004822 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004823 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004824 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004825 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004826 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004827 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004828 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004829 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004830 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004831 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004832 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004833 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004834 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004835 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004836 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004837 }
4838 }
4839 }
4840
Douglas Gregor218937c2011-02-01 19:23:04 +00004841 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004842 SuperMethod->isInstanceMethod()
4843 ? CXCursor_ObjCInstanceMethodDecl
4844 : CXCursor_ObjCClassMethodDecl));
4845 return SuperMethod;
4846}
4847
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004848void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004849 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004850 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4851 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004852 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004853
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004854 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4855 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004856 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4857 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004858
4859 // If we are in an Objective-C method inside a class that has a superclass,
4860 // add "super" as an option.
4861 if (ObjCMethodDecl *Method = getCurMethodDecl())
4862 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004863 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004864 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004865
4866 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4867 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004868
4869 Results.ExitScope();
4870
4871 if (CodeCompleter->includeMacros())
4872 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004873 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004874 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004875
4876}
4877
Douglas Gregor2725ca82010-04-21 19:57:20 +00004878void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4879 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004880 unsigned NumSelIdents,
4881 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004882 ObjCInterfaceDecl *CDecl = 0;
4883 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4884 // Figure out which interface we're in.
4885 CDecl = CurMethod->getClassInterface();
4886 if (!CDecl)
4887 return;
4888
4889 // Find the superclass of this class.
4890 CDecl = CDecl->getSuperClass();
4891 if (!CDecl)
4892 return;
4893
4894 if (CurMethod->isInstanceMethod()) {
4895 // We are inside an instance method, which means that the message
4896 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004897 // current object.
4898 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004899 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004900 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004901 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004902 }
4903
4904 // Fall through to send to the superclass in CDecl.
4905 } else {
4906 // "super" may be the name of a type or variable. Figure out which
4907 // it is.
4908 IdentifierInfo *Super = &Context.Idents.get("super");
4909 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4910 LookupOrdinaryName);
4911 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4912 // "super" names an interface. Use it.
4913 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004914 if (const ObjCObjectType *Iface
4915 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4916 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004917 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4918 // "super" names an unresolved type; we can't be more specific.
4919 } else {
4920 // Assume that "super" names some kind of value and parse that way.
4921 CXXScopeSpec SS;
4922 UnqualifiedId id;
4923 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004924 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004925 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004926 SelIdents, NumSelIdents,
4927 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004928 }
4929
4930 // Fall through
4931 }
4932
John McCallb3d87482010-08-24 05:47:05 +00004933 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004934 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004935 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004936 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004937 NumSelIdents, AtArgumentExpression,
4938 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004939}
4940
Douglas Gregorb9d77572010-09-21 00:03:25 +00004941/// \brief Given a set of code-completion results for the argument of a message
4942/// send, determine the preferred type (if any) for that argument expression.
4943static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4944 unsigned NumSelIdents) {
4945 typedef CodeCompletionResult Result;
4946 ASTContext &Context = Results.getSema().Context;
4947
4948 QualType PreferredType;
4949 unsigned BestPriority = CCP_Unlikely * 2;
4950 Result *ResultsData = Results.data();
4951 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4952 Result &R = ResultsData[I];
4953 if (R.Kind == Result::RK_Declaration &&
4954 isa<ObjCMethodDecl>(R.Declaration)) {
4955 if (R.Priority <= BestPriority) {
4956 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4957 if (NumSelIdents <= Method->param_size()) {
4958 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4959 ->getType();
4960 if (R.Priority < BestPriority || PreferredType.isNull()) {
4961 BestPriority = R.Priority;
4962 PreferredType = MyPreferredType;
4963 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4964 MyPreferredType)) {
4965 PreferredType = QualType();
4966 }
4967 }
4968 }
4969 }
4970 }
4971
4972 return PreferredType;
4973}
4974
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004975static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4976 ParsedType Receiver,
4977 IdentifierInfo **SelIdents,
4978 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004979 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004980 bool IsSuper,
4981 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004982 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004983 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004984
Douglas Gregor24a069f2009-11-17 17:59:40 +00004985 // If the given name refers to an interface type, retrieve the
4986 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004987 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004988 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004989 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004990 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4991 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004992 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004993
Douglas Gregor36ecb042009-11-17 23:22:23 +00004994 // Add all of the factory methods in this Objective-C class, its protocols,
4995 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004996 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004997
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004998 // If this is a send-to-super, try to add the special "super" send
4999 // completion.
5000 if (IsSuper) {
5001 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005002 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5003 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005004 Results.Ignore(SuperMethod);
5005 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005006
Douglas Gregor265f7492010-08-27 15:29:55 +00005007 // If we're inside an Objective-C method definition, prefer its selector to
5008 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005009 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005010 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005011
Douglas Gregord36adf52010-09-16 16:06:31 +00005012 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005013 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005014 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005015 SemaRef.CurContext, Selectors, AtArgumentExpression,
5016 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005017 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005018 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005019
Douglas Gregor719770d2010-04-06 17:30:22 +00005020 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005021 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005022 if (SemaRef.ExternalSource) {
5023 for (uint32_t I = 0,
5024 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005025 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005026 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5027 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005028 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005029
5030 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005031 }
5032 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005033
5034 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5035 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005036 M != MEnd; ++M) {
5037 for (ObjCMethodList *MethList = &M->second.second;
5038 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005039 MethList = MethList->Next) {
5040 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5041 NumSelIdents))
5042 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005043
Douglas Gregor13438f92010-04-06 16:40:00 +00005044 Result R(MethList->Method, 0);
5045 R.StartParameter = NumSelIdents;
5046 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005047 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005048 }
5049 }
5050 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005051
5052 Results.ExitScope();
5053}
Douglas Gregor13438f92010-04-06 16:40:00 +00005054
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005055void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5056 IdentifierInfo **SelIdents,
5057 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005058 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005059 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005060
5061 QualType T = this->GetTypeFromParser(Receiver);
5062
Douglas Gregor218937c2011-02-01 19:23:04 +00005063 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005064 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005065 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005066
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005067 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5068 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005069
5070 // If we're actually at the argument expression (rather than prior to the
5071 // selector), we're actually performing code completion for an expression.
5072 // Determine whether we have a single, best method. If so, we can
5073 // code-complete the expression using the corresponding parameter type as
5074 // our preferred type, improving completion results.
5075 if (AtArgumentExpression) {
5076 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005077 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005078 if (PreferredType.isNull())
5079 CodeCompleteOrdinaryName(S, PCC_Expression);
5080 else
5081 CodeCompleteExpression(S, PreferredType);
5082 return;
5083 }
5084
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005085 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005086 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005087 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005088}
5089
Richard Trieuf81e5a92011-09-09 02:00:50 +00005090void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005091 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005092 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005093 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005094 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005095 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005096
5097 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005098
Douglas Gregor36ecb042009-11-17 23:22:23 +00005099 // If necessary, apply function/array conversion to the receiver.
5100 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005101 if (RecExpr) {
5102 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5103 if (Conv.isInvalid()) // conversion failed. bail.
5104 return;
5105 RecExpr = Conv.take();
5106 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005107 QualType ReceiverType = RecExpr? RecExpr->getType()
5108 : Super? Context.getObjCObjectPointerType(
5109 Context.getObjCInterfaceType(Super))
5110 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005111
Douglas Gregorda892642010-11-08 21:12:30 +00005112 // If we're messaging an expression with type "id" or "Class", check
5113 // whether we know something special about the receiver that allows
5114 // us to assume a more-specific receiver type.
5115 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5116 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5117 if (ReceiverType->isObjCClassType())
5118 return CodeCompleteObjCClassMessage(S,
5119 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5120 SelIdents, NumSelIdents,
5121 AtArgumentExpression, Super);
5122
5123 ReceiverType = Context.getObjCObjectPointerType(
5124 Context.getObjCInterfaceType(IFace));
5125 }
5126
Douglas Gregor36ecb042009-11-17 23:22:23 +00005127 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005128 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005129 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005130 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005131
Douglas Gregor36ecb042009-11-17 23:22:23 +00005132 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005133
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005134 // If this is a send-to-super, try to add the special "super" send
5135 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005136 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005137 if (ObjCMethodDecl *SuperMethod
5138 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5139 Results))
5140 Results.Ignore(SuperMethod);
5141 }
5142
Douglas Gregor265f7492010-08-27 15:29:55 +00005143 // If we're inside an Objective-C method definition, prefer its selector to
5144 // others.
5145 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5146 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005147
Douglas Gregord36adf52010-09-16 16:06:31 +00005148 // Keep track of the selectors we've already added.
5149 VisitedSelectorSet Selectors;
5150
Douglas Gregorf74a4192009-11-18 00:06:18 +00005151 // Handle messages to Class. This really isn't a message to an instance
5152 // method, so we treat it the same way we would treat a message send to a
5153 // class method.
5154 if (ReceiverType->isObjCClassType() ||
5155 ReceiverType->isObjCQualifiedClassType()) {
5156 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5157 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005158 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005159 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005160 }
5161 }
5162 // Handle messages to a qualified ID ("id<foo>").
5163 else if (const ObjCObjectPointerType *QualID
5164 = ReceiverType->getAsObjCQualifiedIdType()) {
5165 // Search protocols for instance methods.
5166 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5167 E = QualID->qual_end();
5168 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005169 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005170 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005171 }
5172 // Handle messages to a pointer to interface type.
5173 else if (const ObjCObjectPointerType *IFacePtr
5174 = ReceiverType->getAsObjCInterfacePointerType()) {
5175 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005176 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005177 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5178 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005179
5180 // Search protocols for instance methods.
5181 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5182 E = IFacePtr->qual_end();
5183 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005184 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005185 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005186 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005187 // Handle messages to "id".
5188 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005189 // We're messaging "id", so provide all instance methods we know
5190 // about as code-completion results.
5191
5192 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005193 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005194 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005195 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5196 I != N; ++I) {
5197 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005198 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005199 continue;
5200
Sebastian Redldb9d2142010-08-02 23:18:59 +00005201 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005202 }
5203 }
5204
Sebastian Redldb9d2142010-08-02 23:18:59 +00005205 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5206 MEnd = MethodPool.end();
5207 M != MEnd; ++M) {
5208 for (ObjCMethodList *MethList = &M->second.first;
5209 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005210 MethList = MethList->Next) {
5211 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5212 NumSelIdents))
5213 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005214
5215 if (!Selectors.insert(MethList->Method->getSelector()))
5216 continue;
5217
Douglas Gregor13438f92010-04-06 16:40:00 +00005218 Result R(MethList->Method, 0);
5219 R.StartParameter = NumSelIdents;
5220 R.AllParametersAreInformative = false;
5221 Results.MaybeAddResult(R, CurContext);
5222 }
5223 }
5224 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005225 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005226
5227
5228 // If we're actually at the argument expression (rather than prior to the
5229 // selector), we're actually performing code completion for an expression.
5230 // Determine whether we have a single, best method. If so, we can
5231 // code-complete the expression using the corresponding parameter type as
5232 // our preferred type, improving completion results.
5233 if (AtArgumentExpression) {
5234 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5235 NumSelIdents);
5236 if (PreferredType.isNull())
5237 CodeCompleteOrdinaryName(S, PCC_Expression);
5238 else
5239 CodeCompleteExpression(S, PreferredType);
5240 return;
5241 }
5242
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005243 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005244 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005245 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005246}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005247
Douglas Gregorfb629412010-08-23 21:17:50 +00005248void Sema::CodeCompleteObjCForCollection(Scope *S,
5249 DeclGroupPtrTy IterationVar) {
5250 CodeCompleteExpressionData Data;
5251 Data.ObjCCollection = true;
5252
5253 if (IterationVar.getAsOpaquePtr()) {
5254 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5255 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5256 if (*I)
5257 Data.IgnoreDecls.push_back(*I);
5258 }
5259 }
5260
5261 CodeCompleteExpression(S, Data);
5262}
5263
Douglas Gregor458433d2010-08-26 15:07:07 +00005264void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5265 unsigned NumSelIdents) {
5266 // If we have an external source, load the entire class method
5267 // pool from the AST file.
5268 if (ExternalSource) {
5269 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5270 I != N; ++I) {
5271 Selector Sel = ExternalSource->GetExternalSelector(I);
5272 if (Sel.isNull() || MethodPool.count(Sel))
5273 continue;
5274
5275 ReadMethodPool(Sel);
5276 }
5277 }
5278
Douglas Gregor218937c2011-02-01 19:23:04 +00005279 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5280 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005281 Results.EnterNewScope();
5282 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5283 MEnd = MethodPool.end();
5284 M != MEnd; ++M) {
5285
5286 Selector Sel = M->first;
5287 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5288 continue;
5289
Douglas Gregor218937c2011-02-01 19:23:04 +00005290 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005291 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005292 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005293 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005294 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005295 continue;
5296 }
5297
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005298 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005299 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005300 if (I == NumSelIdents) {
5301 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005302 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005303 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005304 Accumulator.clear();
5305 }
5306 }
5307
Benjamin Kramera0651c52011-07-26 16:59:25 +00005308 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005309 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005310 }
Douglas Gregordae68752011-02-01 22:57:45 +00005311 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005312 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005313 }
5314 Results.ExitScope();
5315
5316 HandleCodeCompleteResults(this, CodeCompleter,
5317 CodeCompletionContext::CCC_SelectorName,
5318 Results.data(), Results.size());
5319}
5320
Douglas Gregor55385fe2009-11-18 04:19:12 +00005321/// \brief Add all of the protocol declarations that we find in the given
5322/// (translation unit) context.
5323static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005324 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005325 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005326 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005327
5328 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5329 DEnd = Ctx->decls_end();
5330 D != DEnd; ++D) {
5331 // Record any protocols we find.
5332 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005333 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005334 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005335
5336 // Record any forward-declared protocols we find.
5337 if (ObjCForwardProtocolDecl *Forward
5338 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5339 for (ObjCForwardProtocolDecl::protocol_iterator
5340 P = Forward->protocol_begin(),
5341 PEnd = Forward->protocol_end();
5342 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005343 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005344 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005345 }
5346 }
5347}
5348
5349void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5350 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005351 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5352 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005353
Douglas Gregor70c23352010-12-09 21:44:02 +00005354 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5355 Results.EnterNewScope();
5356
5357 // Tell the result set to ignore all of the protocols we have
5358 // already seen.
5359 // FIXME: This doesn't work when caching code-completion results.
5360 for (unsigned I = 0; I != NumProtocols; ++I)
5361 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5362 Protocols[I].second))
5363 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005364
Douglas Gregor70c23352010-12-09 21:44:02 +00005365 // Add all protocols.
5366 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5367 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005368
Douglas Gregor70c23352010-12-09 21:44:02 +00005369 Results.ExitScope();
5370 }
5371
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005372 HandleCodeCompleteResults(this, CodeCompleter,
5373 CodeCompletionContext::CCC_ObjCProtocolName,
5374 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005375}
5376
5377void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005378 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5379 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005380
Douglas Gregor70c23352010-12-09 21:44:02 +00005381 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5382 Results.EnterNewScope();
5383
5384 // Add all protocols.
5385 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5386 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005387
Douglas Gregor70c23352010-12-09 21:44:02 +00005388 Results.ExitScope();
5389 }
5390
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005391 HandleCodeCompleteResults(this, CodeCompleter,
5392 CodeCompletionContext::CCC_ObjCProtocolName,
5393 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005394}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005395
5396/// \brief Add all of the Objective-C interface declarations that we find in
5397/// the given (translation unit) context.
5398static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5399 bool OnlyForwardDeclarations,
5400 bool OnlyUnimplemented,
5401 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005402 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005403
5404 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5405 DEnd = Ctx->decls_end();
5406 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005407 // Record any interfaces we find.
5408 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5409 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5410 (!OnlyUnimplemented || !Class->getImplementation()))
5411 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005412
5413 // Record any forward-declared interfaces we find.
5414 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005415 ObjCInterfaceDecl *IDecl = Forward->getForwardInterfaceDecl();
5416 if ((!OnlyForwardDeclarations || IDecl->isForwardDecl()) &&
5417 (!OnlyUnimplemented || !IDecl->getImplementation()))
5418 Results.AddResult(Result(IDecl, 0), CurContext,
5419 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005420 }
5421 }
5422}
5423
5424void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005425 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5426 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005427 Results.EnterNewScope();
5428
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005429 if (CodeCompleter->includeGlobals()) {
5430 // Add all classes.
5431 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5432 false, Results);
5433 }
5434
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005435 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005436
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005437 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005438 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005439 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005440}
5441
Douglas Gregorc83c6872010-04-15 22:33:43 +00005442void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5443 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005444 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005445 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005446 Results.EnterNewScope();
5447
5448 // Make sure that we ignore the class we're currently defining.
5449 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005450 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005451 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005452 Results.Ignore(CurClass);
5453
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005454 if (CodeCompleter->includeGlobals()) {
5455 // Add all classes.
5456 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5457 false, Results);
5458 }
5459
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005460 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005461
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005462 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005463 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005464 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005465}
5466
5467void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005468 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5469 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005470 Results.EnterNewScope();
5471
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005472 if (CodeCompleter->includeGlobals()) {
5473 // Add all unimplemented classes.
5474 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5475 true, Results);
5476 }
5477
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005478 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005479
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005480 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005481 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005482 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005483}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005484
5485void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005486 IdentifierInfo *ClassName,
5487 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005488 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005489
Douglas Gregor218937c2011-02-01 19:23:04 +00005490 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005491 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005492
5493 // Ignore any categories we find that have already been implemented by this
5494 // interface.
5495 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5496 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005497 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005498 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5499 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5500 Category = Category->getNextClassCategory())
5501 CategoryNames.insert(Category->getIdentifier());
5502
5503 // Add all of the categories we know about.
5504 Results.EnterNewScope();
5505 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5506 for (DeclContext::decl_iterator D = TU->decls_begin(),
5507 DEnd = TU->decls_end();
5508 D != DEnd; ++D)
5509 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5510 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005511 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005512 Results.ExitScope();
5513
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005514 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005515 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005516 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005517}
5518
5519void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005520 IdentifierInfo *ClassName,
5521 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005522 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005523
5524 // Find the corresponding interface. If we couldn't find the interface, the
5525 // program itself is ill-formed. However, we'll try to be helpful still by
5526 // providing the list of all of the categories we know about.
5527 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005528 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005529 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5530 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005531 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005532
Douglas Gregor218937c2011-02-01 19:23:04 +00005533 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005534 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005535
5536 // Add all of the categories that have have corresponding interface
5537 // declarations in this class and any of its superclasses, except for
5538 // already-implemented categories in the class itself.
5539 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5540 Results.EnterNewScope();
5541 bool IgnoreImplemented = true;
5542 while (Class) {
5543 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5544 Category = Category->getNextClassCategory())
5545 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5546 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005547 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005548
5549 Class = Class->getSuperClass();
5550 IgnoreImplemented = false;
5551 }
5552 Results.ExitScope();
5553
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005554 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005555 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005556 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005557}
Douglas Gregor322328b2009-11-18 22:32:06 +00005558
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005559void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005560 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005561 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5562 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005563
5564 // Figure out where this @synthesize lives.
5565 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005566 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005567 if (!Container ||
5568 (!isa<ObjCImplementationDecl>(Container) &&
5569 !isa<ObjCCategoryImplDecl>(Container)))
5570 return;
5571
5572 // Ignore any properties that have already been implemented.
5573 for (DeclContext::decl_iterator D = Container->decls_begin(),
5574 DEnd = Container->decls_end();
5575 D != DEnd; ++D)
5576 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5577 Results.Ignore(PropertyImpl->getPropertyDecl());
5578
5579 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005580 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005581 Results.EnterNewScope();
5582 if (ObjCImplementationDecl *ClassImpl
5583 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005584 AddObjCProperties(ClassImpl->getClassInterface(), false,
5585 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005586 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005587 else
5588 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005589 false, /*AllowNullaryMethods=*/false, CurContext,
5590 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005591 Results.ExitScope();
5592
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005593 HandleCodeCompleteResults(this, CodeCompleter,
5594 CodeCompletionContext::CCC_Other,
5595 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005596}
5597
5598void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005599 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005600 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005601 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5602 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005603
5604 // Figure out where this @synthesize lives.
5605 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005606 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005607 if (!Container ||
5608 (!isa<ObjCImplementationDecl>(Container) &&
5609 !isa<ObjCCategoryImplDecl>(Container)))
5610 return;
5611
5612 // Figure out which interface we're looking into.
5613 ObjCInterfaceDecl *Class = 0;
5614 if (ObjCImplementationDecl *ClassImpl
5615 = dyn_cast<ObjCImplementationDecl>(Container))
5616 Class = ClassImpl->getClassInterface();
5617 else
5618 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5619 ->getClassInterface();
5620
Douglas Gregore8426052011-04-18 14:40:46 +00005621 // Determine the type of the property we're synthesizing.
5622 QualType PropertyType = Context.getObjCIdType();
5623 if (Class) {
5624 if (ObjCPropertyDecl *Property
5625 = Class->FindPropertyDeclaration(PropertyName)) {
5626 PropertyType
5627 = Property->getType().getNonReferenceType().getUnqualifiedType();
5628
5629 // Give preference to ivars
5630 Results.setPreferredType(PropertyType);
5631 }
5632 }
5633
Douglas Gregor322328b2009-11-18 22:32:06 +00005634 // Add all of the instance variables in this class and its superclasses.
5635 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005636 bool SawSimilarlyNamedIvar = false;
5637 std::string NameWithPrefix;
5638 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005639 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005640 std::string NameWithSuffix = PropertyName->getName().str();
5641 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005642 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005643 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5644 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005645 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5646
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005647 // Determine whether we've seen an ivar with a name similar to the
5648 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005649 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005650 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005651 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005652 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005653
5654 // Reduce the priority of this result by one, to give it a slight
5655 // advantage over other results whose names don't match so closely.
5656 if (Results.size() &&
5657 Results.data()[Results.size() - 1].Kind
5658 == CodeCompletionResult::RK_Declaration &&
5659 Results.data()[Results.size() - 1].Declaration == Ivar)
5660 Results.data()[Results.size() - 1].Priority--;
5661 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005662 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005663 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005664
5665 if (!SawSimilarlyNamedIvar) {
5666 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005667 // an ivar of the appropriate type.
5668 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005669 typedef CodeCompletionResult Result;
5670 CodeCompletionAllocator &Allocator = Results.getAllocator();
5671 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5672
Douglas Gregor8987b232011-09-27 23:30:47 +00005673 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8426052011-04-18 14:40:46 +00005674 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005675 Policy, Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005676 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5677 Results.AddResult(Result(Builder.TakeString(), Priority,
5678 CXCursor_ObjCIvarDecl));
5679 }
5680
Douglas Gregor322328b2009-11-18 22:32:06 +00005681 Results.ExitScope();
5682
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005683 HandleCodeCompleteResults(this, CodeCompleter,
5684 CodeCompletionContext::CCC_Other,
5685 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005686}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005687
Douglas Gregor408be5a2010-08-25 01:08:01 +00005688// Mapping from selectors to the methods that implement that selector, along
5689// with the "in original class" flag.
5690typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5691 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005692
5693/// \brief Find all of the methods that reside in the given container
5694/// (and its superclasses, protocols, etc.) that meet the given
5695/// criteria. Insert those methods into the map of known methods,
5696/// indexed by selector so they can be easily found.
5697static void FindImplementableMethods(ASTContext &Context,
5698 ObjCContainerDecl *Container,
5699 bool WantInstanceMethods,
5700 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005701 KnownMethodsMap &KnownMethods,
5702 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005703 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5704 // Recurse into protocols.
5705 const ObjCList<ObjCProtocolDecl> &Protocols
5706 = IFace->getReferencedProtocols();
5707 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005708 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005709 I != E; ++I)
5710 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005711 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005712
Douglas Gregorea766182010-10-18 18:21:28 +00005713 // Add methods from any class extensions and categories.
5714 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5715 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005716 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5717 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005718 KnownMethods, false);
5719
5720 // Visit the superclass.
5721 if (IFace->getSuperClass())
5722 FindImplementableMethods(Context, IFace->getSuperClass(),
5723 WantInstanceMethods, ReturnType,
5724 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005725 }
5726
5727 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5728 // Recurse into protocols.
5729 const ObjCList<ObjCProtocolDecl> &Protocols
5730 = Category->getReferencedProtocols();
5731 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005732 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005733 I != E; ++I)
5734 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005735 KnownMethods, InOriginalClass);
5736
5737 // If this category is the original class, jump to the interface.
5738 if (InOriginalClass && Category->getClassInterface())
5739 FindImplementableMethods(Context, Category->getClassInterface(),
5740 WantInstanceMethods, ReturnType, KnownMethods,
5741 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005742 }
5743
5744 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5745 // Recurse into protocols.
5746 const ObjCList<ObjCProtocolDecl> &Protocols
5747 = Protocol->getReferencedProtocols();
5748 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5749 E = Protocols.end();
5750 I != E; ++I)
5751 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005752 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005753 }
5754
5755 // Add methods in this container. This operation occurs last because
5756 // we want the methods from this container to override any methods
5757 // we've previously seen with the same selector.
5758 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5759 MEnd = Container->meth_end();
5760 M != MEnd; ++M) {
5761 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5762 if (!ReturnType.isNull() &&
5763 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5764 continue;
5765
Douglas Gregor408be5a2010-08-25 01:08:01 +00005766 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005767 }
5768 }
5769}
5770
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005771/// \brief Add the parenthesized return or parameter type chunk to a code
5772/// completion string.
5773static void AddObjCPassingTypeChunk(QualType Type,
5774 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005775 const PrintingPolicy &Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005776 CodeCompletionBuilder &Builder) {
5777 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor8987b232011-09-27 23:30:47 +00005778 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005779 Builder.getAllocator()));
5780 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5781}
5782
5783/// \brief Determine whether the given class is or inherits from a class by
5784/// the given name.
5785static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005786 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005787 if (!Class)
5788 return false;
5789
5790 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5791 return true;
5792
5793 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5794}
5795
5796/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5797/// Key-Value Observing (KVO).
5798static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5799 bool IsInstanceMethod,
5800 QualType ReturnType,
5801 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005802 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005803 ResultBuilder &Results) {
5804 IdentifierInfo *PropName = Property->getIdentifier();
5805 if (!PropName || PropName->getLength() == 0)
5806 return;
5807
Douglas Gregor8987b232011-09-27 23:30:47 +00005808 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5809
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005810 // Builder that will create each code completion.
5811 typedef CodeCompletionResult Result;
5812 CodeCompletionAllocator &Allocator = Results.getAllocator();
5813 CodeCompletionBuilder Builder(Allocator);
5814
5815 // The selector table.
5816 SelectorTable &Selectors = Context.Selectors;
5817
5818 // The property name, copied into the code completion allocation region
5819 // on demand.
5820 struct KeyHolder {
5821 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005822 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005823 const char *CopiedKey;
5824
Chris Lattner5f9e2722011-07-23 10:55:15 +00005825 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005826 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5827
5828 operator const char *() {
5829 if (CopiedKey)
5830 return CopiedKey;
5831
5832 return CopiedKey = Allocator.CopyString(Key);
5833 }
5834 } Key(Allocator, PropName->getName());
5835
5836 // The uppercased name of the property name.
5837 std::string UpperKey = PropName->getName();
5838 if (!UpperKey.empty())
5839 UpperKey[0] = toupper(UpperKey[0]);
5840
5841 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5842 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5843 Property->getType());
5844 bool ReturnTypeMatchesVoid
5845 = ReturnType.isNull() || ReturnType->isVoidType();
5846
5847 // Add the normal accessor -(type)key.
5848 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005849 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005850 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5851 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00005852 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005853
5854 Builder.AddTypedTextChunk(Key);
5855 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5856 CXCursor_ObjCInstanceMethodDecl));
5857 }
5858
5859 // If we have an integral or boolean property (or the user has provided
5860 // an integral or boolean return type), add the accessor -(type)isKey.
5861 if (IsInstanceMethod &&
5862 ((!ReturnType.isNull() &&
5863 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5864 (ReturnType.isNull() &&
5865 (Property->getType()->isIntegerType() ||
5866 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005867 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005868 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005869 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005870 if (ReturnType.isNull()) {
5871 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5872 Builder.AddTextChunk("BOOL");
5873 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5874 }
5875
5876 Builder.AddTypedTextChunk(
5877 Allocator.CopyString(SelectorId->getName()));
5878 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5879 CXCursor_ObjCInstanceMethodDecl));
5880 }
5881 }
5882
5883 // Add the normal mutator.
5884 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5885 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005886 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005887 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005888 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005889 if (ReturnType.isNull()) {
5890 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5891 Builder.AddTextChunk("void");
5892 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5893 }
5894
5895 Builder.AddTypedTextChunk(
5896 Allocator.CopyString(SelectorId->getName()));
5897 Builder.AddTypedTextChunk(":");
Douglas Gregor8987b232011-09-27 23:30:47 +00005898 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005899 Builder.AddTextChunk(Key);
5900 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5901 CXCursor_ObjCInstanceMethodDecl));
5902 }
5903 }
5904
5905 // Indexed and unordered accessors
5906 unsigned IndexedGetterPriority = CCP_CodePattern;
5907 unsigned IndexedSetterPriority = CCP_CodePattern;
5908 unsigned UnorderedGetterPriority = CCP_CodePattern;
5909 unsigned UnorderedSetterPriority = CCP_CodePattern;
5910 if (const ObjCObjectPointerType *ObjCPointer
5911 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5912 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5913 // If this interface type is not provably derived from a known
5914 // collection, penalize the corresponding completions.
5915 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5916 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5917 if (!InheritsFromClassNamed(IFace, "NSArray"))
5918 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5919 }
5920
5921 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5922 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5923 if (!InheritsFromClassNamed(IFace, "NSSet"))
5924 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5925 }
5926 }
5927 } else {
5928 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5929 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5930 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5931 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5932 }
5933
5934 // Add -(NSUInteger)countOf<key>
5935 if (IsInstanceMethod &&
5936 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005937 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005938 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005939 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005940 if (ReturnType.isNull()) {
5941 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5942 Builder.AddTextChunk("NSUInteger");
5943 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5944 }
5945
5946 Builder.AddTypedTextChunk(
5947 Allocator.CopyString(SelectorId->getName()));
5948 Results.AddResult(Result(Builder.TakeString(),
5949 std::min(IndexedGetterPriority,
5950 UnorderedGetterPriority),
5951 CXCursor_ObjCInstanceMethodDecl));
5952 }
5953 }
5954
5955 // Indexed getters
5956 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
5957 if (IsInstanceMethod &&
5958 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005959 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005960 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005961 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005962 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005963 if (ReturnType.isNull()) {
5964 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5965 Builder.AddTextChunk("id");
5966 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5967 }
5968
5969 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5970 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5971 Builder.AddTextChunk("NSUInteger");
5972 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5973 Builder.AddTextChunk("index");
5974 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5975 CXCursor_ObjCInstanceMethodDecl));
5976 }
5977 }
5978
5979 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
5980 if (IsInstanceMethod &&
5981 (ReturnType.isNull() ||
5982 (ReturnType->isObjCObjectPointerType() &&
5983 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
5984 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
5985 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005986 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005987 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005988 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005989 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005990 if (ReturnType.isNull()) {
5991 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5992 Builder.AddTextChunk("NSArray *");
5993 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5994 }
5995
5996 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5997 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5998 Builder.AddTextChunk("NSIndexSet *");
5999 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6000 Builder.AddTextChunk("indexes");
6001 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6002 CXCursor_ObjCInstanceMethodDecl));
6003 }
6004 }
6005
6006 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6007 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006008 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006009 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006010 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006011 &Context.Idents.get("range")
6012 };
6013
Douglas Gregore74c25c2011-05-04 23:50:46 +00006014 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006015 if (ReturnType.isNull()) {
6016 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6017 Builder.AddTextChunk("void");
6018 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6019 }
6020
6021 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6022 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6023 Builder.AddPlaceholderChunk("object-type");
6024 Builder.AddTextChunk(" **");
6025 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6026 Builder.AddTextChunk("buffer");
6027 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6028 Builder.AddTypedTextChunk("range:");
6029 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6030 Builder.AddTextChunk("NSRange");
6031 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6032 Builder.AddTextChunk("inRange");
6033 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6034 CXCursor_ObjCInstanceMethodDecl));
6035 }
6036 }
6037
6038 // Mutable indexed accessors
6039
6040 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6041 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006042 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006043 IdentifierInfo *SelectorIds[2] = {
6044 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006045 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006046 };
6047
Douglas Gregore74c25c2011-05-04 23:50:46 +00006048 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006049 if (ReturnType.isNull()) {
6050 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6051 Builder.AddTextChunk("void");
6052 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6053 }
6054
6055 Builder.AddTypedTextChunk("insertObject:");
6056 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6057 Builder.AddPlaceholderChunk("object-type");
6058 Builder.AddTextChunk(" *");
6059 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6060 Builder.AddTextChunk("object");
6061 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6062 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6063 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6064 Builder.AddPlaceholderChunk("NSUInteger");
6065 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6066 Builder.AddTextChunk("index");
6067 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6068 CXCursor_ObjCInstanceMethodDecl));
6069 }
6070 }
6071
6072 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6073 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006074 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006075 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006076 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006077 &Context.Idents.get("atIndexes")
6078 };
6079
Douglas Gregore74c25c2011-05-04 23:50:46 +00006080 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006081 if (ReturnType.isNull()) {
6082 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6083 Builder.AddTextChunk("void");
6084 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6085 }
6086
6087 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6088 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6089 Builder.AddTextChunk("NSArray *");
6090 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6091 Builder.AddTextChunk("array");
6092 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6093 Builder.AddTypedTextChunk("atIndexes:");
6094 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6095 Builder.AddPlaceholderChunk("NSIndexSet *");
6096 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6097 Builder.AddTextChunk("indexes");
6098 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6099 CXCursor_ObjCInstanceMethodDecl));
6100 }
6101 }
6102
6103 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6104 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006105 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006106 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006107 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006108 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006109 if (ReturnType.isNull()) {
6110 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6111 Builder.AddTextChunk("void");
6112 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6113 }
6114
6115 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6116 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6117 Builder.AddTextChunk("NSUInteger");
6118 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6119 Builder.AddTextChunk("index");
6120 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6121 CXCursor_ObjCInstanceMethodDecl));
6122 }
6123 }
6124
6125 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6126 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006127 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006128 = (Twine("remove") + UpperKey + "AtIndexes").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("NSIndexSet *");
6140 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6141 Builder.AddTextChunk("indexes");
6142 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6143 CXCursor_ObjCInstanceMethodDecl));
6144 }
6145 }
6146
6147 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6148 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006149 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006150 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006151 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006152 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006153 &Context.Idents.get("withObject")
6154 };
6155
Douglas Gregore74c25c2011-05-04 23:50:46 +00006156 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006157 if (ReturnType.isNull()) {
6158 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6159 Builder.AddTextChunk("void");
6160 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6161 }
6162
6163 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6164 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6165 Builder.AddPlaceholderChunk("NSUInteger");
6166 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6167 Builder.AddTextChunk("index");
6168 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6169 Builder.AddTypedTextChunk("withObject:");
6170 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6171 Builder.AddTextChunk("id");
6172 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6173 Builder.AddTextChunk("object");
6174 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6175 CXCursor_ObjCInstanceMethodDecl));
6176 }
6177 }
6178
6179 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6180 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006181 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006182 = (Twine("replace") + UpperKey + "AtIndexes").str();
6183 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006184 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006185 &Context.Idents.get(SelectorName1),
6186 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006187 };
6188
Douglas Gregore74c25c2011-05-04 23:50:46 +00006189 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006190 if (ReturnType.isNull()) {
6191 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6192 Builder.AddTextChunk("void");
6193 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6194 }
6195
6196 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6197 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6198 Builder.AddPlaceholderChunk("NSIndexSet *");
6199 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6200 Builder.AddTextChunk("indexes");
6201 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6202 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6203 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6204 Builder.AddTextChunk("NSArray *");
6205 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6206 Builder.AddTextChunk("array");
6207 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6208 CXCursor_ObjCInstanceMethodDecl));
6209 }
6210 }
6211
6212 // Unordered getters
6213 // - (NSEnumerator *)enumeratorOfKey
6214 if (IsInstanceMethod &&
6215 (ReturnType.isNull() ||
6216 (ReturnType->isObjCObjectPointerType() &&
6217 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6218 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6219 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006220 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006221 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006222 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006223 if (ReturnType.isNull()) {
6224 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6225 Builder.AddTextChunk("NSEnumerator *");
6226 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6227 }
6228
6229 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6230 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6231 CXCursor_ObjCInstanceMethodDecl));
6232 }
6233 }
6234
6235 // - (type *)memberOfKey:(type *)object
6236 if (IsInstanceMethod &&
6237 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006238 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006239 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006240 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006241 if (ReturnType.isNull()) {
6242 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6243 Builder.AddPlaceholderChunk("object-type");
6244 Builder.AddTextChunk(" *");
6245 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6246 }
6247
6248 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6249 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6250 if (ReturnType.isNull()) {
6251 Builder.AddPlaceholderChunk("object-type");
6252 Builder.AddTextChunk(" *");
6253 } else {
6254 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006255 Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006256 Builder.getAllocator()));
6257 }
6258 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6259 Builder.AddTextChunk("object");
6260 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6261 CXCursor_ObjCInstanceMethodDecl));
6262 }
6263 }
6264
6265 // Mutable unordered accessors
6266 // - (void)addKeyObject:(type *)object
6267 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006268 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006269 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006270 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006271 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006272 if (ReturnType.isNull()) {
6273 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6274 Builder.AddTextChunk("void");
6275 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6276 }
6277
6278 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6279 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6280 Builder.AddPlaceholderChunk("object-type");
6281 Builder.AddTextChunk(" *");
6282 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6283 Builder.AddTextChunk("object");
6284 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6285 CXCursor_ObjCInstanceMethodDecl));
6286 }
6287 }
6288
6289 // - (void)addKey:(NSSet *)objects
6290 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006291 std::string SelectorName = (Twine("add") + UpperKey).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.AddTextChunk("NSSet *");
6303 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6304 Builder.AddTextChunk("objects");
6305 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6306 CXCursor_ObjCInstanceMethodDecl));
6307 }
6308 }
6309
6310 // - (void)removeKeyObject:(type *)object
6311 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006312 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006313 = (Twine("remove") + UpperKey + Twine("Object")).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.AddPlaceholderChunk("object-type");
6325 Builder.AddTextChunk(" *");
6326 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6327 Builder.AddTextChunk("object");
6328 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6329 CXCursor_ObjCInstanceMethodDecl));
6330 }
6331 }
6332
6333 // - (void)removeKey:(NSSet *)objects
6334 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006335 std::string SelectorName = (Twine("remove") + UpperKey).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.AddTextChunk("NSSet *");
6347 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6348 Builder.AddTextChunk("objects");
6349 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6350 CXCursor_ObjCInstanceMethodDecl));
6351 }
6352 }
6353
6354 // - (void)intersectKey:(NSSet *)objects
6355 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006356 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006357 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006358 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006359 if (ReturnType.isNull()) {
6360 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6361 Builder.AddTextChunk("void");
6362 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6363 }
6364
6365 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6366 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6367 Builder.AddTextChunk("NSSet *");
6368 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6369 Builder.AddTextChunk("objects");
6370 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6371 CXCursor_ObjCInstanceMethodDecl));
6372 }
6373 }
6374
6375 // Key-Value Observing
6376 // + (NSSet *)keyPathsForValuesAffectingKey
6377 if (!IsInstanceMethod &&
6378 (ReturnType.isNull() ||
6379 (ReturnType->isObjCObjectPointerType() &&
6380 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6381 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6382 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006383 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006384 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006385 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006386 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006387 if (ReturnType.isNull()) {
6388 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6389 Builder.AddTextChunk("NSSet *");
6390 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6391 }
6392
6393 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6394 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006395 CXCursor_ObjCClassMethodDecl));
6396 }
6397 }
6398
6399 // + (BOOL)automaticallyNotifiesObserversForKey
6400 if (!IsInstanceMethod &&
6401 (ReturnType.isNull() ||
6402 ReturnType->isIntegerType() ||
6403 ReturnType->isBooleanType())) {
6404 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006405 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006406 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6407 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6408 if (ReturnType.isNull()) {
6409 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6410 Builder.AddTextChunk("BOOL");
6411 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6412 }
6413
6414 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6415 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6416 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006417 }
6418 }
6419}
6420
Douglas Gregore8f5a172010-04-07 00:21:17 +00006421void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6422 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006423 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006424 // Determine the return type of the method we're declaring, if
6425 // provided.
6426 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006427 Decl *IDecl = 0;
6428 if (CurContext->isObjCContainer()) {
6429 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6430 IDecl = cast<Decl>(OCD);
6431 }
Douglas Gregorea766182010-10-18 18:21:28 +00006432 // Determine where we should start searching for methods.
6433 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006434 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006435 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006436 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6437 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006438 IsInImplementation = true;
6439 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006440 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006441 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006442 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006443 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006444 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006445 }
6446
6447 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006448 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006449 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006450 }
6451
Douglas Gregorea766182010-10-18 18:21:28 +00006452 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006453 HandleCodeCompleteResults(this, CodeCompleter,
6454 CodeCompletionContext::CCC_Other,
6455 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006456 return;
6457 }
6458
6459 // Find all of the methods that we could declare/implement here.
6460 KnownMethodsMap KnownMethods;
6461 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006462 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006463
Douglas Gregore8f5a172010-04-07 00:21:17 +00006464 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006465 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006466 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6467 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006468 Results.EnterNewScope();
Douglas Gregor8987b232011-09-27 23:30:47 +00006469 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006470 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6471 MEnd = KnownMethods.end();
6472 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006473 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006474 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006475
6476 // If the result type was not already provided, add it to the
6477 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006478 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00006479 AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,
6480 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006481
6482 Selector Sel = Method->getSelector();
6483
6484 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006485 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006486 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006487
6488 // Add parameters to the pattern.
6489 unsigned I = 0;
6490 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6491 PEnd = Method->param_end();
6492 P != PEnd; (void)++P, ++I) {
6493 // Add the part of the selector name.
6494 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006495 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006496 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006497 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6498 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006499 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006500 } else
6501 break;
6502
6503 // Add the parameter type.
Douglas Gregor8987b232011-09-27 23:30:47 +00006504 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,
6505 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006506
6507 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006508 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006509 }
6510
6511 if (Method->isVariadic()) {
6512 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006513 Builder.AddChunk(CodeCompletionString::CK_Comma);
6514 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006515 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006516
Douglas Gregor447107d2010-05-28 00:57:46 +00006517 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006518 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006519 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6520 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6521 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006522 if (!Method->getResultType()->isVoidType()) {
6523 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006524 Builder.AddTextChunk("return");
6525 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6526 Builder.AddPlaceholderChunk("expression");
6527 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006528 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006529 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006530
Douglas Gregor218937c2011-02-01 19:23:04 +00006531 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6532 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006533 }
6534
Douglas Gregor408be5a2010-08-25 01:08:01 +00006535 unsigned Priority = CCP_CodePattern;
6536 if (!M->second.second)
6537 Priority += CCD_InBaseClass;
6538
Douglas Gregor218937c2011-02-01 19:23:04 +00006539 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006540 Method->isInstanceMethod()
6541 ? CXCursor_ObjCInstanceMethodDecl
6542 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006543 }
6544
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006545 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6546 // the properties in this class and its categories.
6547 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006548 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006549 Containers.push_back(SearchDecl);
6550
Douglas Gregore74c25c2011-05-04 23:50:46 +00006551 VisitedSelectorSet KnownSelectors;
6552 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6553 MEnd = KnownMethods.end();
6554 M != MEnd; ++M)
6555 KnownSelectors.insert(M->first);
6556
6557
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006558 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6559 if (!IFace)
6560 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6561 IFace = Category->getClassInterface();
6562
6563 if (IFace) {
6564 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6565 Category = Category->getNextClassCategory())
6566 Containers.push_back(Category);
6567 }
6568
6569 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6570 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6571 PEnd = Containers[I]->prop_end();
6572 P != PEnd; ++P) {
6573 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006574 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006575 }
6576 }
6577 }
6578
Douglas Gregore8f5a172010-04-07 00:21:17 +00006579 Results.ExitScope();
6580
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006581 HandleCodeCompleteResults(this, CodeCompleter,
6582 CodeCompletionContext::CCC_Other,
6583 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006584}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006585
6586void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6587 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006588 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006589 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006590 IdentifierInfo **SelIdents,
6591 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006592 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006593 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006594 if (ExternalSource) {
6595 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6596 I != N; ++I) {
6597 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006598 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006599 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006600
6601 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006602 }
6603 }
6604
6605 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006606 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006607 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6608 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006609
6610 if (ReturnTy)
6611 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006612
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006613 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006614 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6615 MEnd = MethodPool.end();
6616 M != MEnd; ++M) {
6617 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6618 &M->second.second;
6619 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006620 MethList = MethList->Next) {
6621 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6622 NumSelIdents))
6623 continue;
6624
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006625 if (AtParameterName) {
6626 // Suggest parameter names we've seen before.
6627 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6628 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6629 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006630 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006631 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006632 Param->getIdentifier()->getName()));
6633 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006634 }
6635 }
6636
6637 continue;
6638 }
6639
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006640 Result R(MethList->Method, 0);
6641 R.StartParameter = NumSelIdents;
6642 R.AllParametersAreInformative = false;
6643 R.DeclaringEntity = true;
6644 Results.MaybeAddResult(R, CurContext);
6645 }
6646 }
6647
6648 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006649 HandleCodeCompleteResults(this, CodeCompleter,
6650 CodeCompletionContext::CCC_Other,
6651 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006652}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006653
Douglas Gregorf29c5232010-08-24 22:20:20 +00006654void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006655 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006656 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006657 Results.EnterNewScope();
6658
6659 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006660 CodeCompletionBuilder Builder(Results.getAllocator());
6661 Builder.AddTypedTextChunk("if");
6662 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6663 Builder.AddPlaceholderChunk("condition");
6664 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006665
6666 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006667 Builder.AddTypedTextChunk("ifdef");
6668 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6669 Builder.AddPlaceholderChunk("macro");
6670 Results.AddResult(Builder.TakeString());
6671
Douglas Gregorf44e8542010-08-24 19:08:16 +00006672 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006673 Builder.AddTypedTextChunk("ifndef");
6674 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6675 Builder.AddPlaceholderChunk("macro");
6676 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006677
6678 if (InConditional) {
6679 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006680 Builder.AddTypedTextChunk("elif");
6681 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6682 Builder.AddPlaceholderChunk("condition");
6683 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006684
6685 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006686 Builder.AddTypedTextChunk("else");
6687 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006688
6689 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006690 Builder.AddTypedTextChunk("endif");
6691 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006692 }
6693
6694 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006695 Builder.AddTypedTextChunk("include");
6696 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6697 Builder.AddTextChunk("\"");
6698 Builder.AddPlaceholderChunk("header");
6699 Builder.AddTextChunk("\"");
6700 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006701
6702 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006703 Builder.AddTypedTextChunk("include");
6704 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6705 Builder.AddTextChunk("<");
6706 Builder.AddPlaceholderChunk("header");
6707 Builder.AddTextChunk(">");
6708 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006709
6710 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006711 Builder.AddTypedTextChunk("define");
6712 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6713 Builder.AddPlaceholderChunk("macro");
6714 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006715
6716 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006717 Builder.AddTypedTextChunk("define");
6718 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6719 Builder.AddPlaceholderChunk("macro");
6720 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6721 Builder.AddPlaceholderChunk("args");
6722 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6723 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006724
6725 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006726 Builder.AddTypedTextChunk("undef");
6727 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6728 Builder.AddPlaceholderChunk("macro");
6729 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006730
6731 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006732 Builder.AddTypedTextChunk("line");
6733 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6734 Builder.AddPlaceholderChunk("number");
6735 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006736
6737 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006738 Builder.AddTypedTextChunk("line");
6739 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6740 Builder.AddPlaceholderChunk("number");
6741 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6742 Builder.AddTextChunk("\"");
6743 Builder.AddPlaceholderChunk("filename");
6744 Builder.AddTextChunk("\"");
6745 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006746
6747 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006748 Builder.AddTypedTextChunk("error");
6749 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6750 Builder.AddPlaceholderChunk("message");
6751 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006752
6753 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006754 Builder.AddTypedTextChunk("pragma");
6755 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6756 Builder.AddPlaceholderChunk("arguments");
6757 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006758
6759 if (getLangOptions().ObjC1) {
6760 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006761 Builder.AddTypedTextChunk("import");
6762 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6763 Builder.AddTextChunk("\"");
6764 Builder.AddPlaceholderChunk("header");
6765 Builder.AddTextChunk("\"");
6766 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006767
6768 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006769 Builder.AddTypedTextChunk("import");
6770 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6771 Builder.AddTextChunk("<");
6772 Builder.AddPlaceholderChunk("header");
6773 Builder.AddTextChunk(">");
6774 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006775 }
6776
6777 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006778 Builder.AddTypedTextChunk("include_next");
6779 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6780 Builder.AddTextChunk("\"");
6781 Builder.AddPlaceholderChunk("header");
6782 Builder.AddTextChunk("\"");
6783 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006784
6785 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006786 Builder.AddTypedTextChunk("include_next");
6787 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6788 Builder.AddTextChunk("<");
6789 Builder.AddPlaceholderChunk("header");
6790 Builder.AddTextChunk(">");
6791 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006792
6793 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006794 Builder.AddTypedTextChunk("warning");
6795 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6796 Builder.AddPlaceholderChunk("message");
6797 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006798
6799 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6800 // completions for them. And __include_macros is a Clang-internal extension
6801 // that we don't want to encourage anyone to use.
6802
6803 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6804 Results.ExitScope();
6805
Douglas Gregorf44e8542010-08-24 19:08:16 +00006806 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006807 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006808 Results.data(), Results.size());
6809}
6810
6811void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006812 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006813 S->getFnParent()? Sema::PCC_RecoveryInFunction
6814 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006815}
6816
Douglas Gregorf29c5232010-08-24 22:20:20 +00006817void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006818 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006819 IsDefinition? CodeCompletionContext::CCC_MacroName
6820 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006821 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6822 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006823 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006824 Results.EnterNewScope();
6825 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6826 MEnd = PP.macro_end();
6827 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006828 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006829 M->first->getName()));
6830 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006831 }
6832 Results.ExitScope();
6833 } else if (IsDefinition) {
6834 // FIXME: Can we detect when the user just wrote an include guard above?
6835 }
6836
Douglas Gregor52779fb2010-09-23 23:01:17 +00006837 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006838 Results.data(), Results.size());
6839}
6840
Douglas Gregorf29c5232010-08-24 22:20:20 +00006841void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006842 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006843 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006844
6845 if (!CodeCompleter || CodeCompleter->includeMacros())
6846 AddMacroResults(PP, Results);
6847
6848 // defined (<macro>)
6849 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006850 CodeCompletionBuilder Builder(Results.getAllocator());
6851 Builder.AddTypedTextChunk("defined");
6852 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6853 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6854 Builder.AddPlaceholderChunk("macro");
6855 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6856 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006857 Results.ExitScope();
6858
6859 HandleCodeCompleteResults(this, CodeCompleter,
6860 CodeCompletionContext::CCC_PreprocessorExpression,
6861 Results.data(), Results.size());
6862}
6863
6864void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6865 IdentifierInfo *Macro,
6866 MacroInfo *MacroInfo,
6867 unsigned Argument) {
6868 // FIXME: In the future, we could provide "overload" results, much like we
6869 // do for function calls.
6870
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00006871 // Now just ignore this. There will be another code-completion callback
6872 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00006873}
6874
Douglas Gregor55817af2010-08-25 17:04:25 +00006875void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006876 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006877 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006878 0, 0);
6879}
6880
Douglas Gregordae68752011-02-01 22:57:45 +00006881void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006882 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006883 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006884 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6885 CodeCompletionDeclConsumer Consumer(Builder,
6886 Context.getTranslationUnitDecl());
6887 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6888 Consumer);
6889 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006890
6891 if (!CodeCompleter || CodeCompleter->includeMacros())
6892 AddMacroResults(PP, Builder);
6893
6894 Results.clear();
6895 Results.insert(Results.end(),
6896 Builder.data(), Builder.data() + Builder.size());
6897}