blob: 56b351c4cfb8b3296a4fa6224966d3a8f644d2a1 [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 }
2427
Douglas Gregor8987b232011-09-27 23:30:47 +00002428 AddResultTypeChunk(S.Context, Policy, ND, Result);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002429
Douglas Gregor86d9a522009-09-21 16:56:56 +00002430 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002431 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002432 S.Context, Policy);
2433 AddTypedNameChunk(S.Context, Policy, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002434 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002435 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002436 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002437 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002438 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002439 }
2440
2441 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002442 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002443 S.Context, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002444 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor8987b232011-09-27 23:30:47 +00002445 AddTypedNameChunk(S.Context, Policy, Function, Result);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002446
Douglas Gregor86d9a522009-09-21 16:56:56 +00002447 // Figure out which template parameters are deduced (or have default
2448 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002449 SmallVector<bool, 16> Deduced;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002450 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2451 unsigned LastDeducibleArgument;
2452 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2453 --LastDeducibleArgument) {
2454 if (!Deduced[LastDeducibleArgument - 1]) {
2455 // C++0x: Figure out if the template argument has a default. If so,
2456 // the user doesn't need to type this argument.
2457 // FIXME: We need to abstract template parameters better!
2458 bool HasDefaultArg = false;
2459 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002460 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002461 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2462 HasDefaultArg = TTP->hasDefaultArgument();
2463 else if (NonTypeTemplateParmDecl *NTTP
2464 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2465 HasDefaultArg = NTTP->hasDefaultArgument();
2466 else {
2467 assert(isa<TemplateTemplateParmDecl>(Param));
2468 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002469 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002470 }
2471
2472 if (!HasDefaultArg)
2473 break;
2474 }
2475 }
2476
2477 if (LastDeducibleArgument) {
2478 // Some of the function template arguments cannot be deduced from a
2479 // function call, so we introduce an explicit template argument list
2480 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002481 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002482 AddTemplateParameterChunks(S.Context, Policy, FunTmpl, Result,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002483 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002484 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002485 }
2486
2487 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002488 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor8987b232011-09-27 23:30:47 +00002489 AddFunctionParameterChunks(S.Context, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002490 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002491 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002492 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002493 }
2494
2495 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002496 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002497 S.Context, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002498 Result.AddTypedTextChunk(
2499 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002500 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002501 AddTemplateParameterChunks(S.Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002502 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2503 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002504 }
2505
Douglas Gregor9630eb62009-11-17 16:44:22 +00002506 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002507 Selector Sel = Method->getSelector();
2508 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002509 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002510 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002511 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002512 }
2513
Douglas Gregor813d8342011-02-18 22:29:55 +00002514 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002515 SelName += ':';
2516 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002517 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002518 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002519 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002520
2521 // If there is only one parameter, and we're past it, add an empty
2522 // typed-text chunk since there is nothing to type.
2523 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002524 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002525 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002526 unsigned Idx = 0;
2527 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2528 PEnd = Method->param_end();
2529 P != PEnd; (void)++P, ++Idx) {
2530 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002531 std::string Keyword;
2532 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002533 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002534 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002535 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002536 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002537 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002538 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002539 else
Douglas Gregordae68752011-02-01 22:57:45 +00002540 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002541 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002542
2543 // If we're before the starting parameter, skip the placeholder.
2544 if (Idx < StartParameter)
2545 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002546
2547 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002548
2549 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregor8987b232011-09-27 23:30:47 +00002550 Arg = FormatFunctionParameter(S.Context, Policy, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002551 else {
John McCallf85e1932011-06-15 23:02:42 +00002552 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002553 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2554 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002555 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002556 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002557 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002558 }
2559
Douglas Gregore17794f2010-08-31 05:13:43 +00002560 if (Method->isVariadic() && (P + 1) == PEnd)
2561 Arg += ", ...";
2562
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002563 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002564 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002565 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002566 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002567 else
Douglas Gregordae68752011-02-01 22:57:45 +00002568 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002569 }
2570
Douglas Gregor2a17af02009-12-23 00:21:46 +00002571 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002572 if (Method->param_size() == 0) {
2573 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002574 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002575 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002576 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002577 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002578 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002579 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002580
2581 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002582 }
2583
Douglas Gregor218937c2011-02-01 19:23:04 +00002584 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002585 }
2586
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002587 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002588 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002589 S.Context, Policy);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002590
Douglas Gregordae68752011-02-01 22:57:45 +00002591 Result.AddTypedTextChunk(
2592 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002593 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002594}
2595
Douglas Gregor86d802e2009-09-23 00:34:09 +00002596CodeCompletionString *
2597CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2598 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002599 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002600 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002601 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor8987b232011-09-27 23:30:47 +00002602 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCallf85e1932011-06-15 23:02:42 +00002603
Douglas Gregor218937c2011-02-01 19:23:04 +00002604 // FIXME: Set priority, availability appropriately.
2605 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002606 FunctionDecl *FDecl = getFunction();
Douglas Gregor8987b232011-09-27 23:30:47 +00002607 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002608 const FunctionProtoType *Proto
2609 = dyn_cast<FunctionProtoType>(getFunctionType());
2610 if (!FDecl && !Proto) {
2611 // Function without a prototype. Just give the return type and a
2612 // highlighted ellipsis.
2613 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002614 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
Douglas Gregor8987b232011-09-27 23:30:47 +00002615 S.Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002616 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002617 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2618 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2619 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2620 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002621 }
2622
2623 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002624 Result.AddTextChunk(
2625 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002626 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002627 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002628 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002629 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002630
Douglas Gregor218937c2011-02-01 19:23:04 +00002631 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002632 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2633 for (unsigned I = 0; I != NumParams; ++I) {
2634 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002635 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002636
2637 std::string ArgString;
2638 QualType ArgType;
2639
2640 if (FDecl) {
2641 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2642 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2643 } else {
2644 ArgType = Proto->getArgType(I);
2645 }
2646
John McCallf85e1932011-06-15 23:02:42 +00002647 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002648
2649 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002650 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002651 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002652 else
Douglas Gregordae68752011-02-01 22:57:45 +00002653 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002654 }
2655
2656 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002657 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002658 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002659 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002660 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002661 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002662 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002663 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002664
Douglas Gregor218937c2011-02-01 19:23:04 +00002665 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002666}
2667
Chris Lattner5f9e2722011-07-23 10:55:15 +00002668unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002669 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002670 bool PreferredTypeIsPointer) {
2671 unsigned Priority = CCP_Macro;
2672
Douglas Gregorb05496d2010-09-20 21:11:48 +00002673 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2674 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2675 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002676 Priority = CCP_Constant;
2677 if (PreferredTypeIsPointer)
2678 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002679 }
2680 // Treat "YES", "NO", "true", and "false" as constants.
2681 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2682 MacroName.equals("true") || MacroName.equals("false"))
2683 Priority = CCP_Constant;
2684 // Treat "bool" as a type.
2685 else if (MacroName.equals("bool"))
2686 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2687
Douglas Gregor1827e102010-08-16 16:18:59 +00002688
2689 return Priority;
2690}
2691
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002692CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2693 if (!D)
2694 return CXCursor_UnexposedDecl;
2695
2696 switch (D->getKind()) {
2697 case Decl::Enum: return CXCursor_EnumDecl;
2698 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2699 case Decl::Field: return CXCursor_FieldDecl;
2700 case Decl::Function:
2701 return CXCursor_FunctionDecl;
2702 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2703 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2704 case Decl::ObjCClass:
2705 // FIXME
2706 return CXCursor_UnexposedDecl;
2707 case Decl::ObjCForwardProtocol:
2708 // FIXME
2709 return CXCursor_UnexposedDecl;
2710 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2711 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2712 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2713 case Decl::ObjCMethod:
2714 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2715 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2716 case Decl::CXXMethod: return CXCursor_CXXMethod;
2717 case Decl::CXXConstructor: return CXCursor_Constructor;
2718 case Decl::CXXDestructor: return CXCursor_Destructor;
2719 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2720 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2721 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2722 case Decl::ParmVar: return CXCursor_ParmDecl;
2723 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002724 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002725 case Decl::Var: return CXCursor_VarDecl;
2726 case Decl::Namespace: return CXCursor_Namespace;
2727 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2728 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2729 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2730 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2731 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2732 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00002733 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002734 case Decl::ClassTemplatePartialSpecialization:
2735 return CXCursor_ClassTemplatePartialSpecialization;
2736 case Decl::UsingDirective: return CXCursor_UsingDirective;
2737
2738 case Decl::Using:
2739 case Decl::UnresolvedUsingValue:
2740 case Decl::UnresolvedUsingTypename:
2741 return CXCursor_UsingDeclaration;
2742
Douglas Gregor352697a2011-06-03 23:08:58 +00002743 case Decl::ObjCPropertyImpl:
2744 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2745 case ObjCPropertyImplDecl::Dynamic:
2746 return CXCursor_ObjCDynamicDecl;
2747
2748 case ObjCPropertyImplDecl::Synthesize:
2749 return CXCursor_ObjCSynthesizeDecl;
2750 }
2751 break;
2752
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002753 default:
2754 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2755 switch (TD->getTagKind()) {
2756 case TTK_Struct: return CXCursor_StructDecl;
2757 case TTK_Class: return CXCursor_ClassDecl;
2758 case TTK_Union: return CXCursor_UnionDecl;
2759 case TTK_Enum: return CXCursor_EnumDecl;
2760 }
2761 }
2762 }
2763
2764 return CXCursor_UnexposedDecl;
2765}
2766
Douglas Gregor590c7d52010-07-08 20:55:51 +00002767static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2768 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002769 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002770
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002771 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002772
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002773 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2774 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002775 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002776 Results.AddResult(Result(M->first,
2777 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002778 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002779 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002780 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002781
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002782 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002783
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002784}
2785
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002786static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2787 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002788 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002789
2790 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002791
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002792 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2793 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2794 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2795 Results.AddResult(Result("__func__", CCP_Constant));
2796 Results.ExitScope();
2797}
2798
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002799static void HandleCodeCompleteResults(Sema *S,
2800 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002801 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002802 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002803 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002804 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002805 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002806}
2807
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002808static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2809 Sema::ParserCompletionContext PCC) {
2810 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002811 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002812 return CodeCompletionContext::CCC_TopLevel;
2813
John McCallf312b1e2010-08-26 23:41:50 +00002814 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002815 return CodeCompletionContext::CCC_ClassStructUnion;
2816
John McCallf312b1e2010-08-26 23:41:50 +00002817 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002818 return CodeCompletionContext::CCC_ObjCInterface;
2819
John McCallf312b1e2010-08-26 23:41:50 +00002820 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002821 return CodeCompletionContext::CCC_ObjCImplementation;
2822
John McCallf312b1e2010-08-26 23:41:50 +00002823 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002824 return CodeCompletionContext::CCC_ObjCIvarList;
2825
John McCallf312b1e2010-08-26 23:41:50 +00002826 case Sema::PCC_Template:
2827 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002828 if (S.CurContext->isFileContext())
2829 return CodeCompletionContext::CCC_TopLevel;
2830 else if (S.CurContext->isRecord())
2831 return CodeCompletionContext::CCC_ClassStructUnion;
2832 else
2833 return CodeCompletionContext::CCC_Other;
2834
John McCallf312b1e2010-08-26 23:41:50 +00002835 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002836 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002837
John McCallf312b1e2010-08-26 23:41:50 +00002838 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002839 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2840 S.getLangOptions().ObjC1)
2841 return CodeCompletionContext::CCC_ParenthesizedExpression;
2842 else
2843 return CodeCompletionContext::CCC_Expression;
2844
2845 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002846 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002847 return CodeCompletionContext::CCC_Expression;
2848
John McCallf312b1e2010-08-26 23:41:50 +00002849 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002850 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002851
John McCallf312b1e2010-08-26 23:41:50 +00002852 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002853 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002854
2855 case Sema::PCC_ParenthesizedExpression:
2856 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002857
2858 case Sema::PCC_LocalDeclarationSpecifiers:
2859 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002860 }
2861
2862 return CodeCompletionContext::CCC_Other;
2863}
2864
Douglas Gregorf6961522010-08-27 21:18:54 +00002865/// \brief If we're in a C++ virtual member function, add completion results
2866/// that invoke the functions we override, since it's common to invoke the
2867/// overridden function as well as adding new functionality.
2868///
2869/// \param S The semantic analysis object for which we are generating results.
2870///
2871/// \param InContext This context in which the nested-name-specifier preceding
2872/// the code-completion point
2873static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2874 ResultBuilder &Results) {
2875 // Look through blocks.
2876 DeclContext *CurContext = S.CurContext;
2877 while (isa<BlockDecl>(CurContext))
2878 CurContext = CurContext->getParent();
2879
2880
2881 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2882 if (!Method || !Method->isVirtual())
2883 return;
2884
2885 // We need to have names for all of the parameters, if we're going to
2886 // generate a forwarding call.
2887 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2888 PEnd = Method->param_end();
2889 P != PEnd;
2890 ++P) {
2891 if (!(*P)->getDeclName())
2892 return;
2893 }
2894
Douglas Gregor8987b232011-09-27 23:30:47 +00002895 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorf6961522010-08-27 21:18:54 +00002896 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2897 MEnd = Method->end_overridden_methods();
2898 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002899 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002900 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2901 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2902 continue;
2903
2904 // If we need a nested-name-specifier, add one now.
2905 if (!InContext) {
2906 NestedNameSpecifier *NNS
2907 = getRequiredQualification(S.Context, CurContext,
2908 Overridden->getDeclContext());
2909 if (NNS) {
2910 std::string Str;
2911 llvm::raw_string_ostream OS(Str);
Douglas Gregor8987b232011-09-27 23:30:47 +00002912 NNS->print(OS, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002913 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002914 }
2915 } else if (!InContext->Equals(Overridden->getDeclContext()))
2916 continue;
2917
Douglas Gregordae68752011-02-01 22:57:45 +00002918 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002919 Overridden->getNameAsString()));
2920 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00002921 bool FirstParam = true;
2922 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2923 PEnd = Method->param_end();
2924 P != PEnd; ++P) {
2925 if (FirstParam)
2926 FirstParam = false;
2927 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002928 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00002929
Douglas Gregordae68752011-02-01 22:57:45 +00002930 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002931 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002932 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002933 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2934 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00002935 CCP_SuperCompletion,
2936 CXCursor_CXXMethod));
2937 Results.Ignore(Overridden);
2938 }
2939}
2940
Douglas Gregor01dfea02010-01-10 23:08:15 +00002941void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002942 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002943 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002944 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002945 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002946 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002947
Douglas Gregor01dfea02010-01-10 23:08:15 +00002948 // Determine how to filter results, e.g., so that the names of
2949 // values (functions, enumerators, function templates, etc.) are
2950 // only allowed where we can have an expression.
2951 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002952 case PCC_Namespace:
2953 case PCC_Class:
2954 case PCC_ObjCInterface:
2955 case PCC_ObjCImplementation:
2956 case PCC_ObjCInstanceVariableList:
2957 case PCC_Template:
2958 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002959 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002960 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002961 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2962 break;
2963
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002964 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002965 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002966 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002967 case PCC_ForInit:
2968 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002969 if (WantTypesInContext(CompletionContext, getLangOptions()))
2970 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2971 else
2972 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002973
2974 if (getLangOptions().CPlusPlus)
2975 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002976 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002977
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002978 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002979 // Unfiltered
2980 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002981 }
2982
Douglas Gregor3cdee122010-08-26 16:36:48 +00002983 // If we are in a C++ non-static member function, check the qualifiers on
2984 // the member function to filter/prioritize the results list.
2985 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2986 if (CurMethod->isInstance())
2987 Results.setObjectTypeQualifiers(
2988 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2989
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002990 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002991 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2992 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002993
Douglas Gregorbca403c2010-01-13 23:51:12 +00002994 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002995 Results.ExitScope();
2996
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002997 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00002998 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00002999 case PCC_Expression:
3000 case PCC_Statement:
3001 case PCC_RecoveryInFunction:
3002 if (S->getFnParent())
3003 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3004 break;
3005
3006 case PCC_Namespace:
3007 case PCC_Class:
3008 case PCC_ObjCInterface:
3009 case PCC_ObjCImplementation:
3010 case PCC_ObjCInstanceVariableList:
3011 case PCC_Template:
3012 case PCC_MemberTemplate:
3013 case PCC_ForInit:
3014 case PCC_Condition:
3015 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003016 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003017 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003018 }
3019
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003020 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003021 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003022
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003023 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003024 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003025}
3026
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003027static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3028 ParsedType Receiver,
3029 IdentifierInfo **SelIdents,
3030 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003031 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003032 bool IsSuper,
3033 ResultBuilder &Results);
3034
3035void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3036 bool AllowNonIdentifiers,
3037 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003038 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003039 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003040 AllowNestedNameSpecifiers
3041 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3042 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003043 Results.EnterNewScope();
3044
3045 // Type qualifiers can come after names.
3046 Results.AddResult(Result("const"));
3047 Results.AddResult(Result("volatile"));
3048 if (getLangOptions().C99)
3049 Results.AddResult(Result("restrict"));
3050
3051 if (getLangOptions().CPlusPlus) {
3052 if (AllowNonIdentifiers) {
3053 Results.AddResult(Result("operator"));
3054 }
3055
3056 // Add nested-name-specifiers.
3057 if (AllowNestedNameSpecifiers) {
3058 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003059 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003060 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3061 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3062 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003063 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003064 }
3065 }
3066 Results.ExitScope();
3067
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003068 // If we're in a context where we might have an expression (rather than a
3069 // declaration), and what we've seen so far is an Objective-C type that could
3070 // be a receiver of a class message, this may be a class message send with
3071 // the initial opening bracket '[' missing. Add appropriate completions.
3072 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3073 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3074 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3075 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3076 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3077 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3078 DS.getTypeQualifiers() == 0 &&
3079 S &&
3080 (S->getFlags() & Scope::DeclScope) != 0 &&
3081 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3082 Scope::FunctionPrototypeScope |
3083 Scope::AtCatchScope)) == 0) {
3084 ParsedType T = DS.getRepAsType();
3085 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003086 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003087 }
3088
Douglas Gregor4497dd42010-08-24 04:59:56 +00003089 // Note that we intentionally suppress macro results here, since we do not
3090 // encourage using macros to produce the names of entities.
3091
Douglas Gregor52779fb2010-09-23 23:01:17 +00003092 HandleCodeCompleteResults(this, CodeCompleter,
3093 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003094 Results.data(), Results.size());
3095}
3096
Douglas Gregorfb629412010-08-23 21:17:50 +00003097struct Sema::CodeCompleteExpressionData {
3098 CodeCompleteExpressionData(QualType PreferredType = QualType())
3099 : PreferredType(PreferredType), IntegralConstantExpression(false),
3100 ObjCCollection(false) { }
3101
3102 QualType PreferredType;
3103 bool IntegralConstantExpression;
3104 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003105 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003106};
3107
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003108/// \brief Perform code-completion in an expression context when we know what
3109/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003110///
3111/// \param IntegralConstantExpression Only permit integral constant
3112/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003113void Sema::CodeCompleteExpression(Scope *S,
3114 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003115 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003116 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3117 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003118 if (Data.ObjCCollection)
3119 Results.setFilter(&ResultBuilder::IsObjCCollection);
3120 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003121 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003122 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003123 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3124 else
3125 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003126
3127 if (!Data.PreferredType.isNull())
3128 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3129
3130 // Ignore any declarations that we were told that we don't care about.
3131 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3132 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003133
3134 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003135 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3136 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003137
3138 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003139 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003140 Results.ExitScope();
3141
Douglas Gregor590c7d52010-07-08 20:55:51 +00003142 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003143 if (!Data.PreferredType.isNull())
3144 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3145 || Data.PreferredType->isMemberPointerType()
3146 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003147
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003148 if (S->getFnParent() &&
3149 !Data.ObjCCollection &&
3150 !Data.IntegralConstantExpression)
3151 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3152
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003153 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003154 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003155 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003156 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3157 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003158 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003159}
3160
Douglas Gregorac5fd842010-09-18 01:28:11 +00003161void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3162 if (E.isInvalid())
3163 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3164 else if (getLangOptions().ObjC1)
3165 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003166}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003167
Douglas Gregor73449212010-12-09 23:01:55 +00003168/// \brief The set of properties that have already been added, referenced by
3169/// property name.
3170typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3171
Douglas Gregor95ac6552009-11-18 01:29:26 +00003172static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003173 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003174 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003175 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003176 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003177 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003178 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003179
3180 // Add properties in this container.
3181 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3182 PEnd = Container->prop_end();
3183 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003184 ++P) {
3185 if (AddedProperties.insert(P->getIdentifier()))
3186 Results.MaybeAddResult(Result(*P, 0), CurContext);
3187 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003188
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003189 // Add nullary methods
3190 if (AllowNullaryMethods) {
3191 ASTContext &Context = Container->getASTContext();
Douglas Gregor8987b232011-09-27 23:30:47 +00003192 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003193 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3194 MEnd = Container->meth_end();
3195 M != MEnd; ++M) {
3196 if (M->getSelector().isUnarySelector())
3197 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3198 if (AddedProperties.insert(Name)) {
3199 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor8987b232011-09-27 23:30:47 +00003200 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003201 Builder.AddTypedTextChunk(
3202 Results.getAllocator().CopyString(Name->getName()));
3203
3204 CXAvailabilityKind Availability = CXAvailability_Available;
3205 switch (M->getAvailability()) {
3206 case AR_Available:
3207 case AR_NotYetIntroduced:
3208 Availability = CXAvailability_Available;
3209 break;
3210
3211 case AR_Deprecated:
3212 Availability = CXAvailability_Deprecated;
3213 break;
3214
3215 case AR_Unavailable:
3216 Availability = CXAvailability_NotAvailable;
3217 break;
3218 }
3219
3220 Results.MaybeAddResult(Result(Builder.TakeString(),
3221 CCP_MemberDeclaration + CCD_MethodAsProperty,
3222 M->isInstanceMethod()
3223 ? CXCursor_ObjCInstanceMethodDecl
3224 : CXCursor_ObjCClassMethodDecl,
3225 Availability),
3226 CurContext);
3227 }
3228 }
3229 }
3230
3231
Douglas Gregor95ac6552009-11-18 01:29:26 +00003232 // Add properties in referenced protocols.
3233 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3234 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3235 PEnd = Protocol->protocol_end();
3236 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003237 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3238 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003239 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003240 if (AllowCategories) {
3241 // Look through categories.
3242 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3243 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003244 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3245 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003246 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003247
3248 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003249 for (ObjCInterfaceDecl::all_protocol_iterator
3250 I = IFace->all_referenced_protocol_begin(),
3251 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003252 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3253 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003254
3255 // Look in the superclass.
3256 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003257 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3258 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003259 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003260 } else if (const ObjCCategoryDecl *Category
3261 = dyn_cast<ObjCCategoryDecl>(Container)) {
3262 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003263 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3264 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003265 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003266 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3267 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003268 }
3269}
3270
Richard Trieuf81e5a92011-09-09 02:00:50 +00003271void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *BaseE,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003272 SourceLocation OpLoc,
3273 bool IsArrow) {
3274 if (!BaseE || !CodeCompleter)
3275 return;
3276
John McCall0a2c5e22010-08-25 06:19:51 +00003277 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003278
Douglas Gregor81b747b2009-09-17 21:32:03 +00003279 Expr *Base = static_cast<Expr *>(BaseE);
3280 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003281
3282 if (IsArrow) {
3283 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3284 BaseType = Ptr->getPointeeType();
3285 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003286 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003287 else
3288 return;
3289 }
3290
Douglas Gregor3da626b2011-07-07 16:03:39 +00003291 enum CodeCompletionContext::Kind contextKind;
3292
3293 if (IsArrow) {
3294 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3295 }
3296 else {
3297 if (BaseType->isObjCObjectPointerType() ||
3298 BaseType->isObjCObjectOrInterfaceType()) {
3299 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3300 }
3301 else {
3302 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3303 }
3304 }
3305
Douglas Gregor218937c2011-02-01 19:23:04 +00003306 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003307 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003308 BaseType),
3309 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003310 Results.EnterNewScope();
3311 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003312 // Indicate that we are performing a member access, and the cv-qualifiers
3313 // for the base object type.
3314 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3315
Douglas Gregor95ac6552009-11-18 01:29:26 +00003316 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003317 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003318 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003319 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3320 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003321
Douglas Gregor95ac6552009-11-18 01:29:26 +00003322 if (getLangOptions().CPlusPlus) {
3323 if (!Results.empty()) {
3324 // The "template" keyword can follow "->" or "." in the grammar.
3325 // However, we only want to suggest the template keyword if something
3326 // is dependent.
3327 bool IsDependent = BaseType->isDependentType();
3328 if (!IsDependent) {
3329 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3330 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3331 IsDependent = Ctx->isDependentContext();
3332 break;
3333 }
3334 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003335
Douglas Gregor95ac6552009-11-18 01:29:26 +00003336 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003337 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003338 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003339 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003340 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3341 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003342 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003343
3344 // Add property results based on our interface.
3345 const ObjCObjectPointerType *ObjCPtr
3346 = BaseType->getAsObjCInterfacePointerType();
3347 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003348 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3349 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003350 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003351
3352 // Add properties from the protocols in a qualified interface.
3353 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3354 E = ObjCPtr->qual_end();
3355 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003356 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3357 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003358 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003359 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003360 // Objective-C instance variable access.
3361 ObjCInterfaceDecl *Class = 0;
3362 if (const ObjCObjectPointerType *ObjCPtr
3363 = BaseType->getAs<ObjCObjectPointerType>())
3364 Class = ObjCPtr->getInterfaceDecl();
3365 else
John McCallc12c5bb2010-05-15 11:32:37 +00003366 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003367
3368 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003369 if (Class) {
3370 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3371 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003372 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3373 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003374 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003375 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003376
3377 // FIXME: How do we cope with isa?
3378
3379 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003380
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003381 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003382 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003383 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003384 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003385}
3386
Douglas Gregor374929f2009-09-18 15:37:17 +00003387void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3388 if (!CodeCompleter)
3389 return;
3390
John McCall0a2c5e22010-08-25 06:19:51 +00003391 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003392 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003393 enum CodeCompletionContext::Kind ContextKind
3394 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003395 switch ((DeclSpec::TST)TagSpec) {
3396 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003397 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003398 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003399 break;
3400
3401 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003402 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003403 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003404 break;
3405
3406 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003407 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003408 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003409 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003410 break;
3411
3412 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003413 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003414 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003415
Douglas Gregor218937c2011-02-01 19:23:04 +00003416 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003417 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003418
3419 // First pass: look for tags.
3420 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003421 LookupVisibleDecls(S, LookupTagName, Consumer,
3422 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003423
Douglas Gregor8071e422010-08-15 06:18:01 +00003424 if (CodeCompleter->includeGlobals()) {
3425 // Second pass: look for nested name specifiers.
3426 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3427 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3428 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003429
Douglas Gregor52779fb2010-09-23 23:01:17 +00003430 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003431 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003432}
3433
Douglas Gregor1a480c42010-08-27 17:35:51 +00003434void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003435 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3436 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003437 Results.EnterNewScope();
3438 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3439 Results.AddResult("const");
3440 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3441 Results.AddResult("volatile");
3442 if (getLangOptions().C99 &&
3443 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3444 Results.AddResult("restrict");
3445 Results.ExitScope();
3446 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003447 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003448 Results.data(), Results.size());
3449}
3450
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003451void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003452 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003453 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003454
John McCall781472f2010-08-25 08:40:02 +00003455 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003456 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3457 if (!type->isEnumeralType()) {
3458 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003459 Data.IntegralConstantExpression = true;
3460 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003461 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003462 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003463
3464 // Code-complete the cases of a switch statement over an enumeration type
3465 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003466 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003467
3468 // Determine which enumerators we have already seen in the switch statement.
3469 // FIXME: Ideally, we would also be able to look *past* the code-completion
3470 // token, in case we are code-completing in the middle of the switch and not
3471 // at the end. However, we aren't able to do so at the moment.
3472 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003473 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003474 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3475 SC = SC->getNextSwitchCase()) {
3476 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3477 if (!Case)
3478 continue;
3479
3480 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3481 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3482 if (EnumConstantDecl *Enumerator
3483 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3484 // We look into the AST of the case statement to determine which
3485 // enumerator was named. Alternatively, we could compute the value of
3486 // the integral constant expression, then compare it against the
3487 // values of each enumerator. However, value-based approach would not
3488 // work as well with C++ templates where enumerators declared within a
3489 // template are type- and value-dependent.
3490 EnumeratorsSeen.insert(Enumerator);
3491
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003492 // If this is a qualified-id, keep track of the nested-name-specifier
3493 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003494 //
3495 // switch (TagD.getKind()) {
3496 // case TagDecl::TK_enum:
3497 // break;
3498 // case XXX
3499 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003500 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003501 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3502 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003503 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003504 }
3505 }
3506
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003507 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3508 // If there are no prior enumerators in C++, check whether we have to
3509 // qualify the names of the enumerators that we suggest, because they
3510 // may not be visible in this scope.
3511 Qualifier = getRequiredQualification(Context, CurContext,
3512 Enum->getDeclContext());
3513
3514 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3515 }
3516
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003517 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003518 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3519 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003520 Results.EnterNewScope();
3521 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3522 EEnd = Enum->enumerator_end();
3523 E != EEnd; ++E) {
3524 if (EnumeratorsSeen.count(*E))
3525 continue;
3526
Douglas Gregor5c722c702011-02-18 23:30:37 +00003527 CodeCompletionResult R(*E, Qualifier);
3528 R.Priority = CCP_EnumInCase;
3529 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003530 }
3531 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003532
Douglas Gregor3da626b2011-07-07 16:03:39 +00003533 //We need to make sure we're setting the right context,
3534 //so only say we include macros if the code completer says we do
3535 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3536 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003537 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003538 kind = CodeCompletionContext::CCC_OtherWithMacros;
3539 }
3540
3541
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003542 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003543 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003544 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003545}
3546
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003547namespace {
3548 struct IsBetterOverloadCandidate {
3549 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003550 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003551
3552 public:
John McCall5769d612010-02-08 23:07:23 +00003553 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3554 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003555
3556 bool
3557 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003558 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003559 }
3560 };
3561}
3562
Douglas Gregord28dcd72010-05-30 06:10:08 +00003563static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3564 if (NumArgs && !Args)
3565 return true;
3566
3567 for (unsigned I = 0; I != NumArgs; ++I)
3568 if (!Args[I])
3569 return true;
3570
3571 return false;
3572}
3573
Richard Trieuf81e5a92011-09-09 02:00:50 +00003574void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3575 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003576 if (!CodeCompleter)
3577 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003578
3579 // When we're code-completing for a call, we fall back to ordinary
3580 // name code-completion whenever we can't produce specific
3581 // results. We may want to revisit this strategy in the future,
3582 // e.g., by merging the two kinds of results.
3583
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003584 Expr *Fn = (Expr *)FnIn;
3585 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003586
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003587 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003588 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003589 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003590 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003591 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003592 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003593
John McCall3b4294e2009-12-16 12:17:52 +00003594 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003595 SourceLocation Loc = Fn->getExprLoc();
3596 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003597
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003598 // FIXME: What if we're calling something that isn't a function declaration?
3599 // FIXME: What if we're calling a pseudo-destructor?
3600 // FIXME: What if we're calling a member function?
3601
Douglas Gregorc0265402010-01-21 15:46:19 +00003602 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003603 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003604
John McCall3b4294e2009-12-16 12:17:52 +00003605 Expr *NakedFn = Fn->IgnoreParenCasts();
3606 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3607 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3608 /*PartialOverloading=*/ true);
3609 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3610 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003611 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003612 if (!getLangOptions().CPlusPlus ||
3613 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003614 Results.push_back(ResultCandidate(FDecl));
3615 else
John McCall86820f52010-01-26 01:37:31 +00003616 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003617 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3618 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003619 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003620 }
John McCall3b4294e2009-12-16 12:17:52 +00003621 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003622
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003623 QualType ParamType;
3624
Douglas Gregorc0265402010-01-21 15:46:19 +00003625 if (!CandidateSet.empty()) {
3626 // Sort the overload candidate set by placing the best overloads first.
3627 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003628 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003629
Douglas Gregorc0265402010-01-21 15:46:19 +00003630 // Add the remaining viable overload candidates as code-completion reslults.
3631 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3632 CandEnd = CandidateSet.end();
3633 Cand != CandEnd; ++Cand) {
3634 if (Cand->Viable)
3635 Results.push_back(ResultCandidate(Cand->Function));
3636 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003637
3638 // From the viable candidates, try to determine the type of this parameter.
3639 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3640 if (const FunctionType *FType = Results[I].getFunctionType())
3641 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3642 if (NumArgs < Proto->getNumArgs()) {
3643 if (ParamType.isNull())
3644 ParamType = Proto->getArgType(NumArgs);
3645 else if (!Context.hasSameUnqualifiedType(
3646 ParamType.getNonReferenceType(),
3647 Proto->getArgType(NumArgs).getNonReferenceType())) {
3648 ParamType = QualType();
3649 break;
3650 }
3651 }
3652 }
3653 } else {
3654 // Try to determine the parameter type from the type of the expression
3655 // being called.
3656 QualType FunctionType = Fn->getType();
3657 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3658 FunctionType = Ptr->getPointeeType();
3659 else if (const BlockPointerType *BlockPtr
3660 = FunctionType->getAs<BlockPointerType>())
3661 FunctionType = BlockPtr->getPointeeType();
3662 else if (const MemberPointerType *MemPtr
3663 = FunctionType->getAs<MemberPointerType>())
3664 FunctionType = MemPtr->getPointeeType();
3665
3666 if (const FunctionProtoType *Proto
3667 = FunctionType->getAs<FunctionProtoType>()) {
3668 if (NumArgs < Proto->getNumArgs())
3669 ParamType = Proto->getArgType(NumArgs);
3670 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003671 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003672
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003673 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003674 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003675 else
3676 CodeCompleteExpression(S, ParamType);
3677
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003678 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003679 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3680 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003681}
3682
John McCalld226f652010-08-21 09:40:31 +00003683void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3684 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003685 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003686 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003687 return;
3688 }
3689
3690 CodeCompleteExpression(S, VD->getType());
3691}
3692
3693void Sema::CodeCompleteReturn(Scope *S) {
3694 QualType ResultType;
3695 if (isa<BlockDecl>(CurContext)) {
3696 if (BlockScopeInfo *BSI = getCurBlock())
3697 ResultType = BSI->ReturnType;
3698 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3699 ResultType = Function->getResultType();
3700 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3701 ResultType = Method->getResultType();
3702
3703 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003704 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003705 else
3706 CodeCompleteExpression(S, ResultType);
3707}
3708
Douglas Gregord2d8be62011-07-30 08:36:53 +00003709void Sema::CodeCompleteAfterIf(Scope *S) {
3710 typedef CodeCompletionResult Result;
3711 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3712 mapCodeCompletionContext(*this, PCC_Statement));
3713 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3714 Results.EnterNewScope();
3715
3716 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3717 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3718 CodeCompleter->includeGlobals());
3719
3720 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3721
3722 // "else" block
3723 CodeCompletionBuilder Builder(Results.getAllocator());
3724 Builder.AddTypedTextChunk("else");
3725 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3726 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3727 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3728 Builder.AddPlaceholderChunk("statements");
3729 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3730 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3731 Results.AddResult(Builder.TakeString());
3732
3733 // "else if" block
3734 Builder.AddTypedTextChunk("else");
3735 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3736 Builder.AddTextChunk("if");
3737 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3738 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3739 if (getLangOptions().CPlusPlus)
3740 Builder.AddPlaceholderChunk("condition");
3741 else
3742 Builder.AddPlaceholderChunk("expression");
3743 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3744 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3745 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3746 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3747 Builder.AddPlaceholderChunk("statements");
3748 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3749 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3750 Results.AddResult(Builder.TakeString());
3751
3752 Results.ExitScope();
3753
3754 if (S->getFnParent())
3755 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3756
3757 if (CodeCompleter->includeMacros())
3758 AddMacroResults(PP, Results);
3759
3760 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3761 Results.data(),Results.size());
3762}
3763
Richard Trieuf81e5a92011-09-09 02:00:50 +00003764void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003765 if (LHS)
3766 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3767 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003768 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003769}
3770
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003771void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003772 bool EnteringContext) {
3773 if (!SS.getScopeRep() || !CodeCompleter)
3774 return;
3775
Douglas Gregor86d9a522009-09-21 16:56:56 +00003776 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3777 if (!Ctx)
3778 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003779
3780 // Try to instantiate any non-dependent declaration contexts before
3781 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003782 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003783 return;
3784
Douglas Gregor218937c2011-02-01 19:23:04 +00003785 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3786 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003787 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003788
Douglas Gregor86d9a522009-09-21 16:56:56 +00003789 // The "template" keyword can follow "::" in the grammar, but only
3790 // put it into the grammar if the nested-name-specifier is dependent.
3791 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3792 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003793 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003794
3795 // Add calls to overridden virtual functions, if there are any.
3796 //
3797 // FIXME: This isn't wonderful, because we don't know whether we're actually
3798 // in a context that permits expressions. This is a general issue with
3799 // qualified-id completions.
3800 if (!EnteringContext)
3801 MaybeAddOverrideCalls(*this, Ctx, Results);
3802 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003803
Douglas Gregorf6961522010-08-27 21:18:54 +00003804 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3805 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3806
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003807 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003808 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003809 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003810}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003811
3812void Sema::CodeCompleteUsing(Scope *S) {
3813 if (!CodeCompleter)
3814 return;
3815
Douglas Gregor218937c2011-02-01 19:23:04 +00003816 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003817 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3818 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003819 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003820
3821 // If we aren't in class scope, we could see the "namespace" keyword.
3822 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003823 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003824
3825 // After "using", we can see anything that would start a
3826 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003827 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003828 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3829 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003830 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003831
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003832 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003833 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003834 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003835}
3836
3837void Sema::CodeCompleteUsingDirective(Scope *S) {
3838 if (!CodeCompleter)
3839 return;
3840
Douglas Gregor86d9a522009-09-21 16:56:56 +00003841 // After "using namespace", we expect to see a namespace name or namespace
3842 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003843 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3844 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003845 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003846 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003847 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003848 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3849 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003850 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003851 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003852 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003853 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003854}
3855
3856void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3857 if (!CodeCompleter)
3858 return;
3859
Douglas Gregor86d9a522009-09-21 16:56:56 +00003860 DeclContext *Ctx = (DeclContext *)S->getEntity();
3861 if (!S->getParent())
3862 Ctx = Context.getTranslationUnitDecl();
3863
Douglas Gregor52779fb2010-09-23 23:01:17 +00003864 bool SuppressedGlobalResults
3865 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3866
Douglas Gregor218937c2011-02-01 19:23:04 +00003867 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003868 SuppressedGlobalResults
3869 ? CodeCompletionContext::CCC_Namespace
3870 : CodeCompletionContext::CCC_Other,
3871 &ResultBuilder::IsNamespace);
3872
3873 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003874 // We only want to see those namespaces that have already been defined
3875 // within this scope, because its likely that the user is creating an
3876 // extended namespace declaration. Keep track of the most recent
3877 // definition of each namespace.
3878 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3879 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3880 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3881 NS != NSEnd; ++NS)
3882 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3883
3884 // Add the most recent definition (or extended definition) of each
3885 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003886 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003887 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3888 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3889 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003890 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003891 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003892 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003893 }
3894
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003895 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003896 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003897 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003898}
3899
3900void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3901 if (!CodeCompleter)
3902 return;
3903
Douglas Gregor86d9a522009-09-21 16:56:56 +00003904 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003905 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3906 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003907 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003908 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003909 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3910 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003911 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003912 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003913 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003914}
3915
Douglas Gregored8d3222009-09-18 20:05:18 +00003916void Sema::CodeCompleteOperatorName(Scope *S) {
3917 if (!CodeCompleter)
3918 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003919
John McCall0a2c5e22010-08-25 06:19:51 +00003920 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003921 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3922 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003923 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003924 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003925
Douglas Gregor86d9a522009-09-21 16:56:56 +00003926 // Add the names of overloadable operators.
3927#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3928 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003929 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003930#include "clang/Basic/OperatorKinds.def"
3931
3932 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003933 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003934 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003935 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3936 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003937
3938 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003939 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003940 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003941
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003942 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003943 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003944 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003945}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003946
Douglas Gregor0133f522010-08-28 00:00:50 +00003947void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00003948 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00003949 unsigned NumInitializers) {
Douglas Gregor8987b232011-09-27 23:30:47 +00003950 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor0133f522010-08-28 00:00:50 +00003951 CXXConstructorDecl *Constructor
3952 = static_cast<CXXConstructorDecl *>(ConstructorD);
3953 if (!Constructor)
3954 return;
3955
Douglas Gregor218937c2011-02-01 19:23:04 +00003956 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003957 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003958 Results.EnterNewScope();
3959
3960 // Fill in any already-initialized fields or base classes.
3961 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3962 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3963 for (unsigned I = 0; I != NumInitializers; ++I) {
3964 if (Initializers[I]->isBaseInitializer())
3965 InitializedBases.insert(
3966 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3967 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003968 InitializedFields.insert(cast<FieldDecl>(
3969 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00003970 }
3971
3972 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00003973 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00003974 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003975 CXXRecordDecl *ClassDecl = Constructor->getParent();
3976 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3977 BaseEnd = ClassDecl->bases_end();
3978 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003979 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3980 SawLastInitializer
3981 = NumInitializers > 0 &&
3982 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3983 Context.hasSameUnqualifiedType(Base->getType(),
3984 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003985 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003986 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003987
Douglas Gregor218937c2011-02-01 19:23:04 +00003988 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003989 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00003990 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00003991 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3992 Builder.AddPlaceholderChunk("args");
3993 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3994 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003995 SawLastInitializer? CCP_NextInitializer
3996 : CCP_MemberDeclaration));
3997 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003998 }
3999
4000 // Add completions for virtual base classes.
4001 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4002 BaseEnd = ClassDecl->vbases_end();
4003 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004004 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4005 SawLastInitializer
4006 = NumInitializers > 0 &&
4007 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4008 Context.hasSameUnqualifiedType(Base->getType(),
4009 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004010 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004011 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004012
Douglas Gregor218937c2011-02-01 19:23:04 +00004013 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004014 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004015 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004016 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4017 Builder.AddPlaceholderChunk("args");
4018 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4019 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004020 SawLastInitializer? CCP_NextInitializer
4021 : CCP_MemberDeclaration));
4022 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004023 }
4024
4025 // Add completions for members.
4026 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4027 FieldEnd = ClassDecl->field_end();
4028 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004029 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4030 SawLastInitializer
4031 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004032 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4033 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004034 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004035 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004036
4037 if (!Field->getDeclName())
4038 continue;
4039
Douglas Gregordae68752011-02-01 22:57:45 +00004040 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004041 Field->getIdentifier()->getName()));
4042 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4043 Builder.AddPlaceholderChunk("args");
4044 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4045 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004046 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004047 : CCP_MemberDeclaration,
4048 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004049 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004050 }
4051 Results.ExitScope();
4052
Douglas Gregor52779fb2010-09-23 23:01:17 +00004053 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004054 Results.data(), Results.size());
4055}
4056
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004057// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4058// true or false.
4059#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004060static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004061 ResultBuilder &Results,
4062 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004063 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004064 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004065 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004066
Douglas Gregor218937c2011-02-01 19:23:04 +00004067 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004068 if (LangOpts.ObjC2) {
4069 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004070 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4071 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4072 Builder.AddPlaceholderChunk("property");
4073 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004074
4075 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004076 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
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}
4082
Douglas Gregorbca403c2010-01-13 23:51:12 +00004083static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004084 ResultBuilder &Results,
4085 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004086 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004087
4088 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004089 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004090
4091 if (LangOpts.ObjC2) {
4092 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004093 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004094
4095 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004096 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004097
4098 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004099 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004100 }
4101}
4102
Douglas Gregorbca403c2010-01-13 23:51:12 +00004103static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004104 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004105 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004106
4107 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004108 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4109 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4110 Builder.AddPlaceholderChunk("name");
4111 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004112
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004113 if (Results.includeCodePatterns()) {
4114 // @interface name
4115 // FIXME: Could introduce the whole pattern, including superclasses and
4116 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004117 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4118 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4119 Builder.AddPlaceholderChunk("class");
4120 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004121
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004122 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004123 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4124 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4125 Builder.AddPlaceholderChunk("protocol");
4126 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004127
4128 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004129 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4130 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4131 Builder.AddPlaceholderChunk("class");
4132 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004133 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004134
4135 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004136 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4137 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4138 Builder.AddPlaceholderChunk("alias");
4139 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4140 Builder.AddPlaceholderChunk("class");
4141 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004142}
4143
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004144void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004145 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004146 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4147 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004148 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004149 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorbca403c2010-01-13 23:51:12 +00004150 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004151 else if (CurContext->isObjCContainer())
Douglas Gregorbca403c2010-01-13 23:51:12 +00004152 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004153 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004154 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004155 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004156 HandleCodeCompleteResults(this, CodeCompleter,
4157 CodeCompletionContext::CCC_Other,
4158 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004159}
4160
Douglas Gregorbca403c2010-01-13 23:51:12 +00004161static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004162 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004163 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004164
4165 // @encode ( type-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004166 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4167 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4168 Builder.AddPlaceholderChunk("type-name");
4169 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4170 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004171
4172 // @protocol ( protocol-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004173 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4174 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4175 Builder.AddPlaceholderChunk("protocol-name");
4176 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4177 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004178
4179 // @selector ( selector )
Douglas Gregor218937c2011-02-01 19:23:04 +00004180 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4181 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4182 Builder.AddPlaceholderChunk("selector");
4183 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4184 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004185}
4186
Douglas Gregorbca403c2010-01-13 23:51:12 +00004187static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004188 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004189 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004190
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004191 if (Results.includeCodePatterns()) {
4192 // @try { statements } @catch ( declaration ) { statements } @finally
4193 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004194 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4195 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4196 Builder.AddPlaceholderChunk("statements");
4197 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4198 Builder.AddTextChunk("@catch");
4199 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4200 Builder.AddPlaceholderChunk("parameter");
4201 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4202 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4203 Builder.AddPlaceholderChunk("statements");
4204 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4205 Builder.AddTextChunk("@finally");
4206 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4207 Builder.AddPlaceholderChunk("statements");
4208 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4209 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004210 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004211
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004212 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004213 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4214 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4215 Builder.AddPlaceholderChunk("expression");
4216 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004217
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004218 if (Results.includeCodePatterns()) {
4219 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004220 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4221 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4222 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4223 Builder.AddPlaceholderChunk("expression");
4224 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4225 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4226 Builder.AddPlaceholderChunk("statements");
4227 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4228 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004229 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004230}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004231
Douglas Gregorbca403c2010-01-13 23:51:12 +00004232static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004233 ResultBuilder &Results,
4234 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004235 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004236 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4237 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4238 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004239 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004240 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004241}
4242
4243void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004244 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4245 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004246 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004247 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004248 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004249 HandleCodeCompleteResults(this, CodeCompleter,
4250 CodeCompletionContext::CCC_Other,
4251 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004252}
4253
4254void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004255 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4256 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004257 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004258 AddObjCStatementResults(Results, false);
4259 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004260 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004261 HandleCodeCompleteResults(this, CodeCompleter,
4262 CodeCompletionContext::CCC_Other,
4263 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004264}
4265
4266void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004267 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4268 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004269 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004270 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004271 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004272 HandleCodeCompleteResults(this, CodeCompleter,
4273 CodeCompletionContext::CCC_Other,
4274 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004275}
4276
Douglas Gregor988358f2009-11-19 00:14:45 +00004277/// \brief Determine whether the addition of the given flag to an Objective-C
4278/// property's attributes will cause a conflict.
4279static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4280 // Check if we've already added this flag.
4281 if (Attributes & NewFlag)
4282 return true;
4283
4284 Attributes |= NewFlag;
4285
4286 // Check for collisions with "readonly".
4287 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4288 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4289 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004290 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004291 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004292 ObjCDeclSpec::DQ_PR_retain |
4293 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004294 return true;
4295
John McCallf85e1932011-06-15 23:02:42 +00004296 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004297 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004298 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004299 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004300 ObjCDeclSpec::DQ_PR_retain|
4301 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004302 if (AssignCopyRetMask &&
4303 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004304 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004305 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004306 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4307 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004308 return true;
4309
4310 return false;
4311}
4312
Douglas Gregora93b1082009-11-18 23:08:07 +00004313void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004314 if (!CodeCompleter)
4315 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004316
Steve Naroffece8e712009-10-08 21:55:05 +00004317 unsigned Attributes = ODS.getPropertyAttributes();
4318
John McCall0a2c5e22010-08-25 06:19:51 +00004319 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004320 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4321 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004322 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004323 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004324 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004325 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004326 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004327 if (!ObjCPropertyFlagConflicts(Attributes,
4328 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4329 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004330 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004331 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004332 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004333 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004334 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4335 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004336 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004337 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004338 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004339 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004340 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4341 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004342 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004343 CodeCompletionBuilder Setter(Results.getAllocator());
4344 Setter.AddTypedTextChunk("setter");
4345 Setter.AddTextChunk(" = ");
4346 Setter.AddPlaceholderChunk("method");
4347 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004348 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004349 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004350 CodeCompletionBuilder Getter(Results.getAllocator());
4351 Getter.AddTypedTextChunk("getter");
4352 Getter.AddTextChunk(" = ");
4353 Getter.AddPlaceholderChunk("method");
4354 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004355 }
Steve Naroffece8e712009-10-08 21:55:05 +00004356 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004357 HandleCodeCompleteResults(this, CodeCompleter,
4358 CodeCompletionContext::CCC_Other,
4359 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004360}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004361
Douglas Gregor4ad96852009-11-19 07:41:15 +00004362/// \brief Descripts the kind of Objective-C method that we want to find
4363/// via code completion.
4364enum ObjCMethodKind {
4365 MK_Any, //< Any kind of method, provided it means other specified criteria.
4366 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4367 MK_OneArgSelector //< One-argument selector.
4368};
4369
Douglas Gregor458433d2010-08-26 15:07:07 +00004370static bool isAcceptableObjCSelector(Selector Sel,
4371 ObjCMethodKind WantKind,
4372 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004373 unsigned NumSelIdents,
4374 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004375 if (NumSelIdents > Sel.getNumArgs())
4376 return false;
4377
4378 switch (WantKind) {
4379 case MK_Any: break;
4380 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4381 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4382 }
4383
Douglas Gregorcf544262010-11-17 21:36:08 +00004384 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4385 return false;
4386
Douglas Gregor458433d2010-08-26 15:07:07 +00004387 for (unsigned I = 0; I != NumSelIdents; ++I)
4388 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4389 return false;
4390
4391 return true;
4392}
4393
Douglas Gregor4ad96852009-11-19 07:41:15 +00004394static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4395 ObjCMethodKind WantKind,
4396 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004397 unsigned NumSelIdents,
4398 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004399 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004400 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004401}
Douglas Gregord36adf52010-09-16 16:06:31 +00004402
4403namespace {
4404 /// \brief A set of selectors, which is used to avoid introducing multiple
4405 /// completions with the same selector into the result set.
4406 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4407}
4408
Douglas Gregor36ecb042009-11-17 23:22:23 +00004409/// \brief Add all of the Objective-C methods in the given Objective-C
4410/// container to the set of results.
4411///
4412/// The container will be a class, protocol, category, or implementation of
4413/// any of the above. This mether will recurse to include methods from
4414/// the superclasses of classes along with their categories, protocols, and
4415/// implementations.
4416///
4417/// \param Container the container in which we'll look to find methods.
4418///
4419/// \param WantInstance whether to add instance methods (only); if false, this
4420/// routine will add factory methods (only).
4421///
4422/// \param CurContext the context in which we're performing the lookup that
4423/// finds methods.
4424///
Douglas Gregorcf544262010-11-17 21:36:08 +00004425/// \param AllowSameLength Whether we allow a method to be added to the list
4426/// when it has the same number of parameters as we have selector identifiers.
4427///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004428/// \param Results the structure into which we'll add results.
4429static void AddObjCMethods(ObjCContainerDecl *Container,
4430 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004431 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004432 IdentifierInfo **SelIdents,
4433 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004434 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004435 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004436 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004437 ResultBuilder &Results,
4438 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004439 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004440 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4441 MEnd = Container->meth_end();
4442 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004443 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4444 // Check whether the selector identifiers we've been given are a
4445 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004446 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4447 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004448 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004449
Douglas Gregord36adf52010-09-16 16:06:31 +00004450 if (!Selectors.insert((*M)->getSelector()))
4451 continue;
4452
Douglas Gregord3c68542009-11-19 01:08:35 +00004453 Result R = Result(*M, 0);
4454 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004455 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004456 if (!InOriginalClass)
4457 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004458 Results.MaybeAddResult(R, CurContext);
4459 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004460 }
4461
Douglas Gregore396c7b2010-09-16 15:34:59 +00004462 // Visit the protocols of protocols.
4463 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4464 const ObjCList<ObjCProtocolDecl> &Protocols
4465 = Protocol->getReferencedProtocols();
4466 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4467 E = Protocols.end();
4468 I != E; ++I)
4469 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004470 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004471 }
4472
Douglas Gregor36ecb042009-11-17 23:22:23 +00004473 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4474 if (!IFace)
4475 return;
4476
4477 // Add methods in protocols.
4478 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4479 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4480 E = Protocols.end();
4481 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004482 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004483 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004484
4485 // Add methods in categories.
4486 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4487 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004488 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004489 NumSelIdents, CurContext, Selectors, AllowSameLength,
4490 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004491
4492 // Add a categories protocol methods.
4493 const ObjCList<ObjCProtocolDecl> &Protocols
4494 = CatDecl->getReferencedProtocols();
4495 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4496 E = Protocols.end();
4497 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004498 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004499 NumSelIdents, CurContext, Selectors, AllowSameLength,
4500 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004501
4502 // Add methods in category implementations.
4503 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004504 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004505 NumSelIdents, CurContext, Selectors, AllowSameLength,
4506 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004507 }
4508
4509 // Add methods in superclass.
4510 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004511 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004512 SelIdents, NumSelIdents, CurContext, Selectors,
4513 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004514
4515 // Add methods in our implementation, if any.
4516 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004517 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004518 NumSelIdents, CurContext, Selectors, AllowSameLength,
4519 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004520}
4521
4522
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004523void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004524 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004525
4526 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004527 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004528 if (!Class) {
4529 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004530 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004531 Class = Category->getClassInterface();
4532
4533 if (!Class)
4534 return;
4535 }
4536
4537 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004538 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4539 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004540 Results.EnterNewScope();
4541
Douglas Gregord36adf52010-09-16 16:06:31 +00004542 VisitedSelectorSet Selectors;
4543 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004544 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004545 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004546 HandleCodeCompleteResults(this, CodeCompleter,
4547 CodeCompletionContext::CCC_Other,
4548 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004549}
4550
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004551void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004552 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004553
4554 // Try to find the interface where setters might live.
4555 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004556 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004557 if (!Class) {
4558 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004559 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004560 Class = Category->getClassInterface();
4561
4562 if (!Class)
4563 return;
4564 }
4565
4566 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004567 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4568 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004569 Results.EnterNewScope();
4570
Douglas Gregord36adf52010-09-16 16:06:31 +00004571 VisitedSelectorSet Selectors;
4572 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004573 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004574
4575 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004576 HandleCodeCompleteResults(this, CodeCompleter,
4577 CodeCompletionContext::CCC_Other,
4578 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004579}
4580
Douglas Gregorafc45782011-02-15 22:19:42 +00004581void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4582 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004583 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004584 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4585 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004586 Results.EnterNewScope();
4587
4588 // Add context-sensitive, Objective-C parameter-passing keywords.
4589 bool AddedInOut = false;
4590 if ((DS.getObjCDeclQualifier() &
4591 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4592 Results.AddResult("in");
4593 Results.AddResult("inout");
4594 AddedInOut = true;
4595 }
4596 if ((DS.getObjCDeclQualifier() &
4597 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4598 Results.AddResult("out");
4599 if (!AddedInOut)
4600 Results.AddResult("inout");
4601 }
4602 if ((DS.getObjCDeclQualifier() &
4603 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4604 ObjCDeclSpec::DQ_Oneway)) == 0) {
4605 Results.AddResult("bycopy");
4606 Results.AddResult("byref");
4607 Results.AddResult("oneway");
4608 }
4609
Douglas Gregorafc45782011-02-15 22:19:42 +00004610 // If we're completing the return type of an Objective-C method and the
4611 // identifier IBAction refers to a macro, provide a completion item for
4612 // an action, e.g.,
4613 // IBAction)<#selector#>:(id)sender
4614 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4615 Context.Idents.get("IBAction").hasMacroDefinition()) {
4616 typedef CodeCompletionString::Chunk Chunk;
4617 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4618 CXAvailability_Available);
4619 Builder.AddTypedTextChunk("IBAction");
4620 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4621 Builder.AddPlaceholderChunk("selector");
4622 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4623 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4624 Builder.AddTextChunk("id");
4625 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4626 Builder.AddTextChunk("sender");
4627 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4628 }
4629
Douglas Gregord32b0222010-08-24 01:06:58 +00004630 // Add various builtin type names and specifiers.
4631 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4632 Results.ExitScope();
4633
4634 // Add the various type names
4635 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4636 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4637 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4638 CodeCompleter->includeGlobals());
4639
4640 if (CodeCompleter->includeMacros())
4641 AddMacroResults(PP, Results);
4642
4643 HandleCodeCompleteResults(this, CodeCompleter,
4644 CodeCompletionContext::CCC_Type,
4645 Results.data(), Results.size());
4646}
4647
Douglas Gregor22f56992010-04-06 19:22:33 +00004648/// \brief When we have an expression with type "id", we may assume
4649/// that it has some more-specific class type based on knowledge of
4650/// common uses of Objective-C. This routine returns that class type,
4651/// or NULL if no better result could be determined.
4652static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004653 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004654 if (!Msg)
4655 return 0;
4656
4657 Selector Sel = Msg->getSelector();
4658 if (Sel.isNull())
4659 return 0;
4660
4661 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4662 if (!Id)
4663 return 0;
4664
4665 ObjCMethodDecl *Method = Msg->getMethodDecl();
4666 if (!Method)
4667 return 0;
4668
4669 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004670 ObjCInterfaceDecl *IFace = 0;
4671 switch (Msg->getReceiverKind()) {
4672 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004673 if (const ObjCObjectType *ObjType
4674 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4675 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004676 break;
4677
4678 case ObjCMessageExpr::Instance: {
4679 QualType T = Msg->getInstanceReceiver()->getType();
4680 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4681 IFace = Ptr->getInterfaceDecl();
4682 break;
4683 }
4684
4685 case ObjCMessageExpr::SuperInstance:
4686 case ObjCMessageExpr::SuperClass:
4687 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004688 }
4689
4690 if (!IFace)
4691 return 0;
4692
4693 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4694 if (Method->isInstanceMethod())
4695 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4696 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004697 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004698 .Case("autorelease", IFace)
4699 .Case("copy", IFace)
4700 .Case("copyWithZone", IFace)
4701 .Case("mutableCopy", IFace)
4702 .Case("mutableCopyWithZone", IFace)
4703 .Case("awakeFromCoder", IFace)
4704 .Case("replacementObjectFromCoder", IFace)
4705 .Case("class", IFace)
4706 .Case("classForCoder", IFace)
4707 .Case("superclass", Super)
4708 .Default(0);
4709
4710 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4711 .Case("new", IFace)
4712 .Case("alloc", IFace)
4713 .Case("allocWithZone", IFace)
4714 .Case("class", IFace)
4715 .Case("superclass", Super)
4716 .Default(0);
4717}
4718
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004719// Add a special completion for a message send to "super", which fills in the
4720// most likely case of forwarding all of our arguments to the superclass
4721// function.
4722///
4723/// \param S The semantic analysis object.
4724///
4725/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4726/// the "super" keyword. Otherwise, we just need to provide the arguments.
4727///
4728/// \param SelIdents The identifiers in the selector that have already been
4729/// provided as arguments for a send to "super".
4730///
4731/// \param NumSelIdents The number of identifiers in \p SelIdents.
4732///
4733/// \param Results The set of results to augment.
4734///
4735/// \returns the Objective-C method declaration that would be invoked by
4736/// this "super" completion. If NULL, no completion was added.
4737static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4738 IdentifierInfo **SelIdents,
4739 unsigned NumSelIdents,
4740 ResultBuilder &Results) {
4741 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4742 if (!CurMethod)
4743 return 0;
4744
4745 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4746 if (!Class)
4747 return 0;
4748
4749 // Try to find a superclass method with the same selector.
4750 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004751 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4752 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004753 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4754 CurMethod->isInstanceMethod());
4755
Douglas Gregor78bcd912011-02-16 00:51:18 +00004756 // Check in categories or class extensions.
4757 if (!SuperMethod) {
4758 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4759 Category = Category->getNextClassCategory())
4760 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4761 CurMethod->isInstanceMethod())))
4762 break;
4763 }
4764 }
4765
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004766 if (!SuperMethod)
4767 return 0;
4768
4769 // Check whether the superclass method has the same signature.
4770 if (CurMethod->param_size() != SuperMethod->param_size() ||
4771 CurMethod->isVariadic() != SuperMethod->isVariadic())
4772 return 0;
4773
4774 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4775 CurPEnd = CurMethod->param_end(),
4776 SuperP = SuperMethod->param_begin();
4777 CurP != CurPEnd; ++CurP, ++SuperP) {
4778 // Make sure the parameter types are compatible.
4779 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4780 (*SuperP)->getType()))
4781 return 0;
4782
4783 // Make sure we have a parameter name to forward!
4784 if (!(*CurP)->getIdentifier())
4785 return 0;
4786 }
4787
4788 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004789 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004790
4791 // Give this completion a return type.
Douglas Gregor8987b232011-09-27 23:30:47 +00004792 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
4793 Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004794
4795 // If we need the "super" keyword, add it (plus some spacing).
4796 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004797 Builder.AddTypedTextChunk("super");
4798 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004799 }
4800
4801 Selector Sel = CurMethod->getSelector();
4802 if (Sel.isUnarySelector()) {
4803 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004804 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004805 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004806 else
Douglas Gregordae68752011-02-01 22:57:45 +00004807 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004808 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004809 } else {
4810 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4811 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4812 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004813 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004814
4815 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004816 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004817 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004818 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004819 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004820 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004821 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004822 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004823 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004824 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004825 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004826 Builder.AddTypedTextChunk(
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 }
4832 }
4833 }
4834
Douglas Gregor218937c2011-02-01 19:23:04 +00004835 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004836 SuperMethod->isInstanceMethod()
4837 ? CXCursor_ObjCInstanceMethodDecl
4838 : CXCursor_ObjCClassMethodDecl));
4839 return SuperMethod;
4840}
4841
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004842void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004843 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004844 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4845 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004846 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004847
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004848 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4849 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004850 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4851 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004852
4853 // If we are in an Objective-C method inside a class that has a superclass,
4854 // add "super" as an option.
4855 if (ObjCMethodDecl *Method = getCurMethodDecl())
4856 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004857 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004858 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004859
4860 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4861 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004862
4863 Results.ExitScope();
4864
4865 if (CodeCompleter->includeMacros())
4866 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004867 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004868 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004869
4870}
4871
Douglas Gregor2725ca82010-04-21 19:57:20 +00004872void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4873 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004874 unsigned NumSelIdents,
4875 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004876 ObjCInterfaceDecl *CDecl = 0;
4877 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4878 // Figure out which interface we're in.
4879 CDecl = CurMethod->getClassInterface();
4880 if (!CDecl)
4881 return;
4882
4883 // Find the superclass of this class.
4884 CDecl = CDecl->getSuperClass();
4885 if (!CDecl)
4886 return;
4887
4888 if (CurMethod->isInstanceMethod()) {
4889 // We are inside an instance method, which means that the message
4890 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004891 // current object.
4892 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004893 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004894 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004895 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004896 }
4897
4898 // Fall through to send to the superclass in CDecl.
4899 } else {
4900 // "super" may be the name of a type or variable. Figure out which
4901 // it is.
4902 IdentifierInfo *Super = &Context.Idents.get("super");
4903 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4904 LookupOrdinaryName);
4905 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4906 // "super" names an interface. Use it.
4907 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004908 if (const ObjCObjectType *Iface
4909 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4910 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004911 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4912 // "super" names an unresolved type; we can't be more specific.
4913 } else {
4914 // Assume that "super" names some kind of value and parse that way.
4915 CXXScopeSpec SS;
4916 UnqualifiedId id;
4917 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004918 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004919 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004920 SelIdents, NumSelIdents,
4921 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004922 }
4923
4924 // Fall through
4925 }
4926
John McCallb3d87482010-08-24 05:47:05 +00004927 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004928 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004929 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004930 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004931 NumSelIdents, AtArgumentExpression,
4932 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004933}
4934
Douglas Gregorb9d77572010-09-21 00:03:25 +00004935/// \brief Given a set of code-completion results for the argument of a message
4936/// send, determine the preferred type (if any) for that argument expression.
4937static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4938 unsigned NumSelIdents) {
4939 typedef CodeCompletionResult Result;
4940 ASTContext &Context = Results.getSema().Context;
4941
4942 QualType PreferredType;
4943 unsigned BestPriority = CCP_Unlikely * 2;
4944 Result *ResultsData = Results.data();
4945 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4946 Result &R = ResultsData[I];
4947 if (R.Kind == Result::RK_Declaration &&
4948 isa<ObjCMethodDecl>(R.Declaration)) {
4949 if (R.Priority <= BestPriority) {
4950 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4951 if (NumSelIdents <= Method->param_size()) {
4952 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4953 ->getType();
4954 if (R.Priority < BestPriority || PreferredType.isNull()) {
4955 BestPriority = R.Priority;
4956 PreferredType = MyPreferredType;
4957 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4958 MyPreferredType)) {
4959 PreferredType = QualType();
4960 }
4961 }
4962 }
4963 }
4964 }
4965
4966 return PreferredType;
4967}
4968
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004969static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4970 ParsedType Receiver,
4971 IdentifierInfo **SelIdents,
4972 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004973 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004974 bool IsSuper,
4975 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004976 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004977 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004978
Douglas Gregor24a069f2009-11-17 17:59:40 +00004979 // If the given name refers to an interface type, retrieve the
4980 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004981 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004982 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004983 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004984 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4985 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004986 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004987
Douglas Gregor36ecb042009-11-17 23:22:23 +00004988 // Add all of the factory methods in this Objective-C class, its protocols,
4989 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004990 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004991
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004992 // If this is a send-to-super, try to add the special "super" send
4993 // completion.
4994 if (IsSuper) {
4995 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004996 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4997 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004998 Results.Ignore(SuperMethod);
4999 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005000
Douglas Gregor265f7492010-08-27 15:29:55 +00005001 // If we're inside an Objective-C method definition, prefer its selector to
5002 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005003 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005004 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005005
Douglas Gregord36adf52010-09-16 16:06:31 +00005006 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005007 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005008 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005009 SemaRef.CurContext, Selectors, AtArgumentExpression,
5010 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005011 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005012 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005013
Douglas Gregor719770d2010-04-06 17:30:22 +00005014 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005015 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005016 if (SemaRef.ExternalSource) {
5017 for (uint32_t I = 0,
5018 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005019 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005020 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5021 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005022 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005023
5024 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005025 }
5026 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005027
5028 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5029 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005030 M != MEnd; ++M) {
5031 for (ObjCMethodList *MethList = &M->second.second;
5032 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005033 MethList = MethList->Next) {
5034 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5035 NumSelIdents))
5036 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005037
Douglas Gregor13438f92010-04-06 16:40:00 +00005038 Result R(MethList->Method, 0);
5039 R.StartParameter = NumSelIdents;
5040 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005041 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005042 }
5043 }
5044 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005045
5046 Results.ExitScope();
5047}
Douglas Gregor13438f92010-04-06 16:40:00 +00005048
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005049void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5050 IdentifierInfo **SelIdents,
5051 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005052 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005053 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005054
5055 QualType T = this->GetTypeFromParser(Receiver);
5056
Douglas Gregor218937c2011-02-01 19:23:04 +00005057 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005058 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005059 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005060
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005061 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5062 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005063
5064 // If we're actually at the argument expression (rather than prior to the
5065 // selector), we're actually performing code completion for an expression.
5066 // Determine whether we have a single, best method. If so, we can
5067 // code-complete the expression using the corresponding parameter type as
5068 // our preferred type, improving completion results.
5069 if (AtArgumentExpression) {
5070 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005071 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005072 if (PreferredType.isNull())
5073 CodeCompleteOrdinaryName(S, PCC_Expression);
5074 else
5075 CodeCompleteExpression(S, PreferredType);
5076 return;
5077 }
5078
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005079 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005080 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005081 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005082}
5083
Richard Trieuf81e5a92011-09-09 02:00:50 +00005084void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005085 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005086 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005087 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005088 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005089 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005090
5091 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005092
Douglas Gregor36ecb042009-11-17 23:22:23 +00005093 // If necessary, apply function/array conversion to the receiver.
5094 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005095 if (RecExpr) {
5096 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5097 if (Conv.isInvalid()) // conversion failed. bail.
5098 return;
5099 RecExpr = Conv.take();
5100 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005101 QualType ReceiverType = RecExpr? RecExpr->getType()
5102 : Super? Context.getObjCObjectPointerType(
5103 Context.getObjCInterfaceType(Super))
5104 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005105
Douglas Gregorda892642010-11-08 21:12:30 +00005106 // If we're messaging an expression with type "id" or "Class", check
5107 // whether we know something special about the receiver that allows
5108 // us to assume a more-specific receiver type.
5109 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5110 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5111 if (ReceiverType->isObjCClassType())
5112 return CodeCompleteObjCClassMessage(S,
5113 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5114 SelIdents, NumSelIdents,
5115 AtArgumentExpression, Super);
5116
5117 ReceiverType = Context.getObjCObjectPointerType(
5118 Context.getObjCInterfaceType(IFace));
5119 }
5120
Douglas Gregor36ecb042009-11-17 23:22:23 +00005121 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005122 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005123 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005124 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005125
Douglas Gregor36ecb042009-11-17 23:22:23 +00005126 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005127
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005128 // If this is a send-to-super, try to add the special "super" send
5129 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005130 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005131 if (ObjCMethodDecl *SuperMethod
5132 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5133 Results))
5134 Results.Ignore(SuperMethod);
5135 }
5136
Douglas Gregor265f7492010-08-27 15:29:55 +00005137 // If we're inside an Objective-C method definition, prefer its selector to
5138 // others.
5139 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5140 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005141
Douglas Gregord36adf52010-09-16 16:06:31 +00005142 // Keep track of the selectors we've already added.
5143 VisitedSelectorSet Selectors;
5144
Douglas Gregorf74a4192009-11-18 00:06:18 +00005145 // Handle messages to Class. This really isn't a message to an instance
5146 // method, so we treat it the same way we would treat a message send to a
5147 // class method.
5148 if (ReceiverType->isObjCClassType() ||
5149 ReceiverType->isObjCQualifiedClassType()) {
5150 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5151 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005152 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005153 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005154 }
5155 }
5156 // Handle messages to a qualified ID ("id<foo>").
5157 else if (const ObjCObjectPointerType *QualID
5158 = ReceiverType->getAsObjCQualifiedIdType()) {
5159 // Search protocols for instance methods.
5160 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5161 E = QualID->qual_end();
5162 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005163 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005164 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005165 }
5166 // Handle messages to a pointer to interface type.
5167 else if (const ObjCObjectPointerType *IFacePtr
5168 = ReceiverType->getAsObjCInterfacePointerType()) {
5169 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005170 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005171 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5172 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005173
5174 // Search protocols for instance methods.
5175 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5176 E = IFacePtr->qual_end();
5177 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005178 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005179 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005180 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005181 // Handle messages to "id".
5182 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005183 // We're messaging "id", so provide all instance methods we know
5184 // about as code-completion results.
5185
5186 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005187 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005188 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005189 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5190 I != N; ++I) {
5191 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005192 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005193 continue;
5194
Sebastian Redldb9d2142010-08-02 23:18:59 +00005195 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005196 }
5197 }
5198
Sebastian Redldb9d2142010-08-02 23:18:59 +00005199 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5200 MEnd = MethodPool.end();
5201 M != MEnd; ++M) {
5202 for (ObjCMethodList *MethList = &M->second.first;
5203 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005204 MethList = MethList->Next) {
5205 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5206 NumSelIdents))
5207 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005208
5209 if (!Selectors.insert(MethList->Method->getSelector()))
5210 continue;
5211
Douglas Gregor13438f92010-04-06 16:40:00 +00005212 Result R(MethList->Method, 0);
5213 R.StartParameter = NumSelIdents;
5214 R.AllParametersAreInformative = false;
5215 Results.MaybeAddResult(R, CurContext);
5216 }
5217 }
5218 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005219 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005220
5221
5222 // If we're actually at the argument expression (rather than prior to the
5223 // selector), we're actually performing code completion for an expression.
5224 // Determine whether we have a single, best method. If so, we can
5225 // code-complete the expression using the corresponding parameter type as
5226 // our preferred type, improving completion results.
5227 if (AtArgumentExpression) {
5228 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5229 NumSelIdents);
5230 if (PreferredType.isNull())
5231 CodeCompleteOrdinaryName(S, PCC_Expression);
5232 else
5233 CodeCompleteExpression(S, PreferredType);
5234 return;
5235 }
5236
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005237 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005238 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005239 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005240}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005241
Douglas Gregorfb629412010-08-23 21:17:50 +00005242void Sema::CodeCompleteObjCForCollection(Scope *S,
5243 DeclGroupPtrTy IterationVar) {
5244 CodeCompleteExpressionData Data;
5245 Data.ObjCCollection = true;
5246
5247 if (IterationVar.getAsOpaquePtr()) {
5248 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5249 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5250 if (*I)
5251 Data.IgnoreDecls.push_back(*I);
5252 }
5253 }
5254
5255 CodeCompleteExpression(S, Data);
5256}
5257
Douglas Gregor458433d2010-08-26 15:07:07 +00005258void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5259 unsigned NumSelIdents) {
5260 // If we have an external source, load the entire class method
5261 // pool from the AST file.
5262 if (ExternalSource) {
5263 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5264 I != N; ++I) {
5265 Selector Sel = ExternalSource->GetExternalSelector(I);
5266 if (Sel.isNull() || MethodPool.count(Sel))
5267 continue;
5268
5269 ReadMethodPool(Sel);
5270 }
5271 }
5272
Douglas Gregor218937c2011-02-01 19:23:04 +00005273 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5274 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005275 Results.EnterNewScope();
5276 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5277 MEnd = MethodPool.end();
5278 M != MEnd; ++M) {
5279
5280 Selector Sel = M->first;
5281 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5282 continue;
5283
Douglas Gregor218937c2011-02-01 19:23:04 +00005284 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005285 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005286 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005287 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005288 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005289 continue;
5290 }
5291
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005292 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005293 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005294 if (I == NumSelIdents) {
5295 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005296 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005297 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005298 Accumulator.clear();
5299 }
5300 }
5301
Benjamin Kramera0651c52011-07-26 16:59:25 +00005302 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005303 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005304 }
Douglas Gregordae68752011-02-01 22:57:45 +00005305 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005306 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005307 }
5308 Results.ExitScope();
5309
5310 HandleCodeCompleteResults(this, CodeCompleter,
5311 CodeCompletionContext::CCC_SelectorName,
5312 Results.data(), Results.size());
5313}
5314
Douglas Gregor55385fe2009-11-18 04:19:12 +00005315/// \brief Add all of the protocol declarations that we find in the given
5316/// (translation unit) context.
5317static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005318 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005319 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005320 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005321
5322 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5323 DEnd = Ctx->decls_end();
5324 D != DEnd; ++D) {
5325 // Record any protocols we find.
5326 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005327 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005328 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005329
5330 // Record any forward-declared protocols we find.
5331 if (ObjCForwardProtocolDecl *Forward
5332 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5333 for (ObjCForwardProtocolDecl::protocol_iterator
5334 P = Forward->protocol_begin(),
5335 PEnd = Forward->protocol_end();
5336 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005337 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005338 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005339 }
5340 }
5341}
5342
5343void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5344 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005345 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5346 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005347
Douglas Gregor70c23352010-12-09 21:44:02 +00005348 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5349 Results.EnterNewScope();
5350
5351 // Tell the result set to ignore all of the protocols we have
5352 // already seen.
5353 // FIXME: This doesn't work when caching code-completion results.
5354 for (unsigned I = 0; I != NumProtocols; ++I)
5355 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5356 Protocols[I].second))
5357 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005358
Douglas Gregor70c23352010-12-09 21:44:02 +00005359 // Add all protocols.
5360 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5361 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005362
Douglas Gregor70c23352010-12-09 21:44:02 +00005363 Results.ExitScope();
5364 }
5365
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005366 HandleCodeCompleteResults(this, CodeCompleter,
5367 CodeCompletionContext::CCC_ObjCProtocolName,
5368 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005369}
5370
5371void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005372 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5373 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005374
Douglas Gregor70c23352010-12-09 21:44:02 +00005375 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5376 Results.EnterNewScope();
5377
5378 // Add all protocols.
5379 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5380 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005381
Douglas Gregor70c23352010-12-09 21:44:02 +00005382 Results.ExitScope();
5383 }
5384
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005385 HandleCodeCompleteResults(this, CodeCompleter,
5386 CodeCompletionContext::CCC_ObjCProtocolName,
5387 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005388}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005389
5390/// \brief Add all of the Objective-C interface declarations that we find in
5391/// the given (translation unit) context.
5392static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5393 bool OnlyForwardDeclarations,
5394 bool OnlyUnimplemented,
5395 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005396 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005397
5398 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5399 DEnd = Ctx->decls_end();
5400 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005401 // Record any interfaces we find.
5402 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5403 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5404 (!OnlyUnimplemented || !Class->getImplementation()))
5405 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005406
5407 // Record any forward-declared interfaces we find.
5408 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005409 ObjCInterfaceDecl *IDecl = Forward->getForwardInterfaceDecl();
5410 if ((!OnlyForwardDeclarations || IDecl->isForwardDecl()) &&
5411 (!OnlyUnimplemented || !IDecl->getImplementation()))
5412 Results.AddResult(Result(IDecl, 0), CurContext,
5413 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005414 }
5415 }
5416}
5417
5418void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005419 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5420 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005421 Results.EnterNewScope();
5422
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005423 if (CodeCompleter->includeGlobals()) {
5424 // Add all classes.
5425 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5426 false, Results);
5427 }
5428
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005429 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005430
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005431 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005432 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005433 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005434}
5435
Douglas Gregorc83c6872010-04-15 22:33:43 +00005436void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5437 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005438 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005439 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005440 Results.EnterNewScope();
5441
5442 // Make sure that we ignore the class we're currently defining.
5443 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005444 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005445 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005446 Results.Ignore(CurClass);
5447
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005448 if (CodeCompleter->includeGlobals()) {
5449 // Add all classes.
5450 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5451 false, Results);
5452 }
5453
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005454 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005455
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005456 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005457 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005458 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005459}
5460
5461void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005462 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5463 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005464 Results.EnterNewScope();
5465
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005466 if (CodeCompleter->includeGlobals()) {
5467 // Add all unimplemented classes.
5468 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5469 true, Results);
5470 }
5471
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005472 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005473
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005474 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005475 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005476 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005477}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005478
5479void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005480 IdentifierInfo *ClassName,
5481 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005482 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005483
Douglas Gregor218937c2011-02-01 19:23:04 +00005484 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005485 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005486
5487 // Ignore any categories we find that have already been implemented by this
5488 // interface.
5489 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5490 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005491 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005492 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5493 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5494 Category = Category->getNextClassCategory())
5495 CategoryNames.insert(Category->getIdentifier());
5496
5497 // Add all of the categories we know about.
5498 Results.EnterNewScope();
5499 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5500 for (DeclContext::decl_iterator D = TU->decls_begin(),
5501 DEnd = TU->decls_end();
5502 D != DEnd; ++D)
5503 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5504 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005505 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005506 Results.ExitScope();
5507
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005508 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005509 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005510 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005511}
5512
5513void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005514 IdentifierInfo *ClassName,
5515 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005516 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005517
5518 // Find the corresponding interface. If we couldn't find the interface, the
5519 // program itself is ill-formed. However, we'll try to be helpful still by
5520 // providing the list of all of the categories we know about.
5521 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005522 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005523 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5524 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005525 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005526
Douglas Gregor218937c2011-02-01 19:23:04 +00005527 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005528 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005529
5530 // Add all of the categories that have have corresponding interface
5531 // declarations in this class and any of its superclasses, except for
5532 // already-implemented categories in the class itself.
5533 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5534 Results.EnterNewScope();
5535 bool IgnoreImplemented = true;
5536 while (Class) {
5537 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5538 Category = Category->getNextClassCategory())
5539 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5540 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005541 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005542
5543 Class = Class->getSuperClass();
5544 IgnoreImplemented = false;
5545 }
5546 Results.ExitScope();
5547
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005548 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005549 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005550 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005551}
Douglas Gregor322328b2009-11-18 22:32:06 +00005552
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005553void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005554 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005555 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5556 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005557
5558 // Figure out where this @synthesize lives.
5559 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005560 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005561 if (!Container ||
5562 (!isa<ObjCImplementationDecl>(Container) &&
5563 !isa<ObjCCategoryImplDecl>(Container)))
5564 return;
5565
5566 // Ignore any properties that have already been implemented.
5567 for (DeclContext::decl_iterator D = Container->decls_begin(),
5568 DEnd = Container->decls_end();
5569 D != DEnd; ++D)
5570 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5571 Results.Ignore(PropertyImpl->getPropertyDecl());
5572
5573 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005574 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005575 Results.EnterNewScope();
5576 if (ObjCImplementationDecl *ClassImpl
5577 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005578 AddObjCProperties(ClassImpl->getClassInterface(), false,
5579 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005580 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005581 else
5582 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005583 false, /*AllowNullaryMethods=*/false, CurContext,
5584 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005585 Results.ExitScope();
5586
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005587 HandleCodeCompleteResults(this, CodeCompleter,
5588 CodeCompletionContext::CCC_Other,
5589 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005590}
5591
5592void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005593 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005594 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005595 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5596 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005597
5598 // Figure out where this @synthesize lives.
5599 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005600 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005601 if (!Container ||
5602 (!isa<ObjCImplementationDecl>(Container) &&
5603 !isa<ObjCCategoryImplDecl>(Container)))
5604 return;
5605
5606 // Figure out which interface we're looking into.
5607 ObjCInterfaceDecl *Class = 0;
5608 if (ObjCImplementationDecl *ClassImpl
5609 = dyn_cast<ObjCImplementationDecl>(Container))
5610 Class = ClassImpl->getClassInterface();
5611 else
5612 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5613 ->getClassInterface();
5614
Douglas Gregore8426052011-04-18 14:40:46 +00005615 // Determine the type of the property we're synthesizing.
5616 QualType PropertyType = Context.getObjCIdType();
5617 if (Class) {
5618 if (ObjCPropertyDecl *Property
5619 = Class->FindPropertyDeclaration(PropertyName)) {
5620 PropertyType
5621 = Property->getType().getNonReferenceType().getUnqualifiedType();
5622
5623 // Give preference to ivars
5624 Results.setPreferredType(PropertyType);
5625 }
5626 }
5627
Douglas Gregor322328b2009-11-18 22:32:06 +00005628 // Add all of the instance variables in this class and its superclasses.
5629 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005630 bool SawSimilarlyNamedIvar = false;
5631 std::string NameWithPrefix;
5632 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005633 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005634 std::string NameWithSuffix = PropertyName->getName().str();
5635 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005636 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005637 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5638 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005639 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5640
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005641 // Determine whether we've seen an ivar with a name similar to the
5642 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005643 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005644 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005645 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005646 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005647
5648 // Reduce the priority of this result by one, to give it a slight
5649 // advantage over other results whose names don't match so closely.
5650 if (Results.size() &&
5651 Results.data()[Results.size() - 1].Kind
5652 == CodeCompletionResult::RK_Declaration &&
5653 Results.data()[Results.size() - 1].Declaration == Ivar)
5654 Results.data()[Results.size() - 1].Priority--;
5655 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005656 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005657 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005658
5659 if (!SawSimilarlyNamedIvar) {
5660 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005661 // an ivar of the appropriate type.
5662 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005663 typedef CodeCompletionResult Result;
5664 CodeCompletionAllocator &Allocator = Results.getAllocator();
5665 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5666
Douglas Gregor8987b232011-09-27 23:30:47 +00005667 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8426052011-04-18 14:40:46 +00005668 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005669 Policy, Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005670 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5671 Results.AddResult(Result(Builder.TakeString(), Priority,
5672 CXCursor_ObjCIvarDecl));
5673 }
5674
Douglas Gregor322328b2009-11-18 22:32:06 +00005675 Results.ExitScope();
5676
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005677 HandleCodeCompleteResults(this, CodeCompleter,
5678 CodeCompletionContext::CCC_Other,
5679 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005680}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005681
Douglas Gregor408be5a2010-08-25 01:08:01 +00005682// Mapping from selectors to the methods that implement that selector, along
5683// with the "in original class" flag.
5684typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5685 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005686
5687/// \brief Find all of the methods that reside in the given container
5688/// (and its superclasses, protocols, etc.) that meet the given
5689/// criteria. Insert those methods into the map of known methods,
5690/// indexed by selector so they can be easily found.
5691static void FindImplementableMethods(ASTContext &Context,
5692 ObjCContainerDecl *Container,
5693 bool WantInstanceMethods,
5694 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005695 KnownMethodsMap &KnownMethods,
5696 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005697 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5698 // Recurse into protocols.
5699 const ObjCList<ObjCProtocolDecl> &Protocols
5700 = IFace->getReferencedProtocols();
5701 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005702 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005703 I != E; ++I)
5704 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005705 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005706
Douglas Gregorea766182010-10-18 18:21:28 +00005707 // Add methods from any class extensions and categories.
5708 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5709 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005710 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5711 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005712 KnownMethods, false);
5713
5714 // Visit the superclass.
5715 if (IFace->getSuperClass())
5716 FindImplementableMethods(Context, IFace->getSuperClass(),
5717 WantInstanceMethods, ReturnType,
5718 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005719 }
5720
5721 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5722 // Recurse into protocols.
5723 const ObjCList<ObjCProtocolDecl> &Protocols
5724 = Category->getReferencedProtocols();
5725 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005726 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005727 I != E; ++I)
5728 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005729 KnownMethods, InOriginalClass);
5730
5731 // If this category is the original class, jump to the interface.
5732 if (InOriginalClass && Category->getClassInterface())
5733 FindImplementableMethods(Context, Category->getClassInterface(),
5734 WantInstanceMethods, ReturnType, KnownMethods,
5735 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005736 }
5737
5738 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5739 // Recurse into protocols.
5740 const ObjCList<ObjCProtocolDecl> &Protocols
5741 = Protocol->getReferencedProtocols();
5742 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5743 E = Protocols.end();
5744 I != E; ++I)
5745 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005746 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005747 }
5748
5749 // Add methods in this container. This operation occurs last because
5750 // we want the methods from this container to override any methods
5751 // we've previously seen with the same selector.
5752 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5753 MEnd = Container->meth_end();
5754 M != MEnd; ++M) {
5755 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5756 if (!ReturnType.isNull() &&
5757 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5758 continue;
5759
Douglas Gregor408be5a2010-08-25 01:08:01 +00005760 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005761 }
5762 }
5763}
5764
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005765/// \brief Add the parenthesized return or parameter type chunk to a code
5766/// completion string.
5767static void AddObjCPassingTypeChunk(QualType Type,
5768 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005769 const PrintingPolicy &Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005770 CodeCompletionBuilder &Builder) {
5771 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor8987b232011-09-27 23:30:47 +00005772 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005773 Builder.getAllocator()));
5774 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5775}
5776
5777/// \brief Determine whether the given class is or inherits from a class by
5778/// the given name.
5779static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005780 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005781 if (!Class)
5782 return false;
5783
5784 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5785 return true;
5786
5787 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5788}
5789
5790/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5791/// Key-Value Observing (KVO).
5792static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5793 bool IsInstanceMethod,
5794 QualType ReturnType,
5795 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005796 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005797 ResultBuilder &Results) {
5798 IdentifierInfo *PropName = Property->getIdentifier();
5799 if (!PropName || PropName->getLength() == 0)
5800 return;
5801
Douglas Gregor8987b232011-09-27 23:30:47 +00005802 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5803
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005804 // Builder that will create each code completion.
5805 typedef CodeCompletionResult Result;
5806 CodeCompletionAllocator &Allocator = Results.getAllocator();
5807 CodeCompletionBuilder Builder(Allocator);
5808
5809 // The selector table.
5810 SelectorTable &Selectors = Context.Selectors;
5811
5812 // The property name, copied into the code completion allocation region
5813 // on demand.
5814 struct KeyHolder {
5815 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005816 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005817 const char *CopiedKey;
5818
Chris Lattner5f9e2722011-07-23 10:55:15 +00005819 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005820 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5821
5822 operator const char *() {
5823 if (CopiedKey)
5824 return CopiedKey;
5825
5826 return CopiedKey = Allocator.CopyString(Key);
5827 }
5828 } Key(Allocator, PropName->getName());
5829
5830 // The uppercased name of the property name.
5831 std::string UpperKey = PropName->getName();
5832 if (!UpperKey.empty())
5833 UpperKey[0] = toupper(UpperKey[0]);
5834
5835 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5836 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5837 Property->getType());
5838 bool ReturnTypeMatchesVoid
5839 = ReturnType.isNull() || ReturnType->isVoidType();
5840
5841 // Add the normal accessor -(type)key.
5842 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005843 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005844 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5845 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00005846 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005847
5848 Builder.AddTypedTextChunk(Key);
5849 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5850 CXCursor_ObjCInstanceMethodDecl));
5851 }
5852
5853 // If we have an integral or boolean property (or the user has provided
5854 // an integral or boolean return type), add the accessor -(type)isKey.
5855 if (IsInstanceMethod &&
5856 ((!ReturnType.isNull() &&
5857 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5858 (ReturnType.isNull() &&
5859 (Property->getType()->isIntegerType() ||
5860 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005861 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005862 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005863 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005864 if (ReturnType.isNull()) {
5865 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5866 Builder.AddTextChunk("BOOL");
5867 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5868 }
5869
5870 Builder.AddTypedTextChunk(
5871 Allocator.CopyString(SelectorId->getName()));
5872 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5873 CXCursor_ObjCInstanceMethodDecl));
5874 }
5875 }
5876
5877 // Add the normal mutator.
5878 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5879 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005880 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005881 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005882 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005883 if (ReturnType.isNull()) {
5884 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5885 Builder.AddTextChunk("void");
5886 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5887 }
5888
5889 Builder.AddTypedTextChunk(
5890 Allocator.CopyString(SelectorId->getName()));
5891 Builder.AddTypedTextChunk(":");
Douglas Gregor8987b232011-09-27 23:30:47 +00005892 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005893 Builder.AddTextChunk(Key);
5894 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5895 CXCursor_ObjCInstanceMethodDecl));
5896 }
5897 }
5898
5899 // Indexed and unordered accessors
5900 unsigned IndexedGetterPriority = CCP_CodePattern;
5901 unsigned IndexedSetterPriority = CCP_CodePattern;
5902 unsigned UnorderedGetterPriority = CCP_CodePattern;
5903 unsigned UnorderedSetterPriority = CCP_CodePattern;
5904 if (const ObjCObjectPointerType *ObjCPointer
5905 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5906 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5907 // If this interface type is not provably derived from a known
5908 // collection, penalize the corresponding completions.
5909 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5910 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5911 if (!InheritsFromClassNamed(IFace, "NSArray"))
5912 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5913 }
5914
5915 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5916 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5917 if (!InheritsFromClassNamed(IFace, "NSSet"))
5918 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5919 }
5920 }
5921 } else {
5922 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5923 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5924 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5925 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5926 }
5927
5928 // Add -(NSUInteger)countOf<key>
5929 if (IsInstanceMethod &&
5930 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005931 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005932 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005933 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005934 if (ReturnType.isNull()) {
5935 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5936 Builder.AddTextChunk("NSUInteger");
5937 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5938 }
5939
5940 Builder.AddTypedTextChunk(
5941 Allocator.CopyString(SelectorId->getName()));
5942 Results.AddResult(Result(Builder.TakeString(),
5943 std::min(IndexedGetterPriority,
5944 UnorderedGetterPriority),
5945 CXCursor_ObjCInstanceMethodDecl));
5946 }
5947 }
5948
5949 // Indexed getters
5950 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
5951 if (IsInstanceMethod &&
5952 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005953 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005954 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005955 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005956 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005957 if (ReturnType.isNull()) {
5958 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5959 Builder.AddTextChunk("id");
5960 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5961 }
5962
5963 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5964 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5965 Builder.AddTextChunk("NSUInteger");
5966 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5967 Builder.AddTextChunk("index");
5968 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5969 CXCursor_ObjCInstanceMethodDecl));
5970 }
5971 }
5972
5973 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
5974 if (IsInstanceMethod &&
5975 (ReturnType.isNull() ||
5976 (ReturnType->isObjCObjectPointerType() &&
5977 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
5978 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
5979 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005980 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005981 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005982 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005983 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005984 if (ReturnType.isNull()) {
5985 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5986 Builder.AddTextChunk("NSArray *");
5987 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5988 }
5989
5990 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5991 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5992 Builder.AddTextChunk("NSIndexSet *");
5993 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5994 Builder.AddTextChunk("indexes");
5995 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5996 CXCursor_ObjCInstanceMethodDecl));
5997 }
5998 }
5999
6000 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6001 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006002 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006003 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006004 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006005 &Context.Idents.get("range")
6006 };
6007
Douglas Gregore74c25c2011-05-04 23:50:46 +00006008 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006009 if (ReturnType.isNull()) {
6010 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6011 Builder.AddTextChunk("void");
6012 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6013 }
6014
6015 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6016 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6017 Builder.AddPlaceholderChunk("object-type");
6018 Builder.AddTextChunk(" **");
6019 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6020 Builder.AddTextChunk("buffer");
6021 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6022 Builder.AddTypedTextChunk("range:");
6023 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6024 Builder.AddTextChunk("NSRange");
6025 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6026 Builder.AddTextChunk("inRange");
6027 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6028 CXCursor_ObjCInstanceMethodDecl));
6029 }
6030 }
6031
6032 // Mutable indexed accessors
6033
6034 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6035 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006036 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006037 IdentifierInfo *SelectorIds[2] = {
6038 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006039 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006040 };
6041
Douglas Gregore74c25c2011-05-04 23:50:46 +00006042 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006043 if (ReturnType.isNull()) {
6044 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6045 Builder.AddTextChunk("void");
6046 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6047 }
6048
6049 Builder.AddTypedTextChunk("insertObject:");
6050 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6051 Builder.AddPlaceholderChunk("object-type");
6052 Builder.AddTextChunk(" *");
6053 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6054 Builder.AddTextChunk("object");
6055 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6056 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6057 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6058 Builder.AddPlaceholderChunk("NSUInteger");
6059 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6060 Builder.AddTextChunk("index");
6061 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6062 CXCursor_ObjCInstanceMethodDecl));
6063 }
6064 }
6065
6066 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6067 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006068 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006069 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006070 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006071 &Context.Idents.get("atIndexes")
6072 };
6073
Douglas Gregore74c25c2011-05-04 23:50:46 +00006074 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006075 if (ReturnType.isNull()) {
6076 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6077 Builder.AddTextChunk("void");
6078 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6079 }
6080
6081 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6082 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6083 Builder.AddTextChunk("NSArray *");
6084 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6085 Builder.AddTextChunk("array");
6086 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6087 Builder.AddTypedTextChunk("atIndexes:");
6088 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6089 Builder.AddPlaceholderChunk("NSIndexSet *");
6090 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6091 Builder.AddTextChunk("indexes");
6092 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6093 CXCursor_ObjCInstanceMethodDecl));
6094 }
6095 }
6096
6097 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6098 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006099 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006100 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006101 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006102 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006103 if (ReturnType.isNull()) {
6104 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6105 Builder.AddTextChunk("void");
6106 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6107 }
6108
6109 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6110 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6111 Builder.AddTextChunk("NSUInteger");
6112 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6113 Builder.AddTextChunk("index");
6114 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6115 CXCursor_ObjCInstanceMethodDecl));
6116 }
6117 }
6118
6119 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6120 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006121 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006122 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006123 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006124 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006125 if (ReturnType.isNull()) {
6126 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6127 Builder.AddTextChunk("void");
6128 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6129 }
6130
6131 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6132 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6133 Builder.AddTextChunk("NSIndexSet *");
6134 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6135 Builder.AddTextChunk("indexes");
6136 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6137 CXCursor_ObjCInstanceMethodDecl));
6138 }
6139 }
6140
6141 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6142 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006143 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006144 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006145 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006146 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006147 &Context.Idents.get("withObject")
6148 };
6149
Douglas Gregore74c25c2011-05-04 23:50:46 +00006150 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006151 if (ReturnType.isNull()) {
6152 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6153 Builder.AddTextChunk("void");
6154 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6155 }
6156
6157 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6158 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6159 Builder.AddPlaceholderChunk("NSUInteger");
6160 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6161 Builder.AddTextChunk("index");
6162 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6163 Builder.AddTypedTextChunk("withObject:");
6164 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6165 Builder.AddTextChunk("id");
6166 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6167 Builder.AddTextChunk("object");
6168 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6169 CXCursor_ObjCInstanceMethodDecl));
6170 }
6171 }
6172
6173 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6174 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006175 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006176 = (Twine("replace") + UpperKey + "AtIndexes").str();
6177 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006178 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006179 &Context.Idents.get(SelectorName1),
6180 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006181 };
6182
Douglas Gregore74c25c2011-05-04 23:50:46 +00006183 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006184 if (ReturnType.isNull()) {
6185 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6186 Builder.AddTextChunk("void");
6187 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6188 }
6189
6190 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6191 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6192 Builder.AddPlaceholderChunk("NSIndexSet *");
6193 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6194 Builder.AddTextChunk("indexes");
6195 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6196 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6197 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6198 Builder.AddTextChunk("NSArray *");
6199 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6200 Builder.AddTextChunk("array");
6201 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6202 CXCursor_ObjCInstanceMethodDecl));
6203 }
6204 }
6205
6206 // Unordered getters
6207 // - (NSEnumerator *)enumeratorOfKey
6208 if (IsInstanceMethod &&
6209 (ReturnType.isNull() ||
6210 (ReturnType->isObjCObjectPointerType() &&
6211 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6212 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6213 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006214 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006215 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006216 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006217 if (ReturnType.isNull()) {
6218 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6219 Builder.AddTextChunk("NSEnumerator *");
6220 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6221 }
6222
6223 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6224 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6225 CXCursor_ObjCInstanceMethodDecl));
6226 }
6227 }
6228
6229 // - (type *)memberOfKey:(type *)object
6230 if (IsInstanceMethod &&
6231 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006232 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006233 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006234 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006235 if (ReturnType.isNull()) {
6236 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6237 Builder.AddPlaceholderChunk("object-type");
6238 Builder.AddTextChunk(" *");
6239 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6240 }
6241
6242 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6243 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6244 if (ReturnType.isNull()) {
6245 Builder.AddPlaceholderChunk("object-type");
6246 Builder.AddTextChunk(" *");
6247 } else {
6248 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006249 Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006250 Builder.getAllocator()));
6251 }
6252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6253 Builder.AddTextChunk("object");
6254 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6255 CXCursor_ObjCInstanceMethodDecl));
6256 }
6257 }
6258
6259 // Mutable unordered accessors
6260 // - (void)addKeyObject:(type *)object
6261 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006262 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006263 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006264 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006265 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006266 if (ReturnType.isNull()) {
6267 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6268 Builder.AddTextChunk("void");
6269 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6270 }
6271
6272 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6273 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6274 Builder.AddPlaceholderChunk("object-type");
6275 Builder.AddTextChunk(" *");
6276 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6277 Builder.AddTextChunk("object");
6278 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6279 CXCursor_ObjCInstanceMethodDecl));
6280 }
6281 }
6282
6283 // - (void)addKey:(NSSet *)objects
6284 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006285 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006286 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006287 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006288 if (ReturnType.isNull()) {
6289 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6290 Builder.AddTextChunk("void");
6291 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6292 }
6293
6294 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6295 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6296 Builder.AddTextChunk("NSSet *");
6297 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6298 Builder.AddTextChunk("objects");
6299 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6300 CXCursor_ObjCInstanceMethodDecl));
6301 }
6302 }
6303
6304 // - (void)removeKeyObject:(type *)object
6305 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006306 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006307 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006308 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006309 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006310 if (ReturnType.isNull()) {
6311 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6312 Builder.AddTextChunk("void");
6313 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6314 }
6315
6316 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6317 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6318 Builder.AddPlaceholderChunk("object-type");
6319 Builder.AddTextChunk(" *");
6320 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6321 Builder.AddTextChunk("object");
6322 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6323 CXCursor_ObjCInstanceMethodDecl));
6324 }
6325 }
6326
6327 // - (void)removeKey:(NSSet *)objects
6328 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006329 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006330 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006331 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006332 if (ReturnType.isNull()) {
6333 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6334 Builder.AddTextChunk("void");
6335 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6336 }
6337
6338 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6339 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6340 Builder.AddTextChunk("NSSet *");
6341 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6342 Builder.AddTextChunk("objects");
6343 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6344 CXCursor_ObjCInstanceMethodDecl));
6345 }
6346 }
6347
6348 // - (void)intersectKey:(NSSet *)objects
6349 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006350 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006351 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006352 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006353 if (ReturnType.isNull()) {
6354 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6355 Builder.AddTextChunk("void");
6356 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6357 }
6358
6359 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6360 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6361 Builder.AddTextChunk("NSSet *");
6362 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6363 Builder.AddTextChunk("objects");
6364 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6365 CXCursor_ObjCInstanceMethodDecl));
6366 }
6367 }
6368
6369 // Key-Value Observing
6370 // + (NSSet *)keyPathsForValuesAffectingKey
6371 if (!IsInstanceMethod &&
6372 (ReturnType.isNull() ||
6373 (ReturnType->isObjCObjectPointerType() &&
6374 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6375 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6376 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006377 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006378 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006379 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006380 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006381 if (ReturnType.isNull()) {
6382 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6383 Builder.AddTextChunk("NSSet *");
6384 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6385 }
6386
6387 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6388 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006389 CXCursor_ObjCClassMethodDecl));
6390 }
6391 }
6392
6393 // + (BOOL)automaticallyNotifiesObserversForKey
6394 if (!IsInstanceMethod &&
6395 (ReturnType.isNull() ||
6396 ReturnType->isIntegerType() ||
6397 ReturnType->isBooleanType())) {
6398 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006399 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006400 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6401 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6402 if (ReturnType.isNull()) {
6403 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6404 Builder.AddTextChunk("BOOL");
6405 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6406 }
6407
6408 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6409 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6410 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006411 }
6412 }
6413}
6414
Douglas Gregore8f5a172010-04-07 00:21:17 +00006415void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6416 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006417 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006418 // Determine the return type of the method we're declaring, if
6419 // provided.
6420 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006421 Decl *IDecl = 0;
6422 if (CurContext->isObjCContainer()) {
6423 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6424 IDecl = cast<Decl>(OCD);
6425 }
Douglas Gregorea766182010-10-18 18:21:28 +00006426 // Determine where we should start searching for methods.
6427 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006428 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006429 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006430 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6431 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006432 IsInImplementation = true;
6433 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006434 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006435 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006436 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006437 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006438 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006439 }
6440
6441 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006442 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006443 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006444 }
6445
Douglas Gregorea766182010-10-18 18:21:28 +00006446 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006447 HandleCodeCompleteResults(this, CodeCompleter,
6448 CodeCompletionContext::CCC_Other,
6449 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006450 return;
6451 }
6452
6453 // Find all of the methods that we could declare/implement here.
6454 KnownMethodsMap KnownMethods;
6455 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006456 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006457
Douglas Gregore8f5a172010-04-07 00:21:17 +00006458 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006459 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006460 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6461 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006462 Results.EnterNewScope();
Douglas Gregor8987b232011-09-27 23:30:47 +00006463 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006464 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6465 MEnd = KnownMethods.end();
6466 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006467 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006468 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006469
6470 // If the result type was not already provided, add it to the
6471 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006472 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00006473 AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,
6474 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006475
6476 Selector Sel = Method->getSelector();
6477
6478 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006479 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006480 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006481
6482 // Add parameters to the pattern.
6483 unsigned I = 0;
6484 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6485 PEnd = Method->param_end();
6486 P != PEnd; (void)++P, ++I) {
6487 // Add the part of the selector name.
6488 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006489 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006490 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006491 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6492 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006493 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006494 } else
6495 break;
6496
6497 // Add the parameter type.
Douglas Gregor8987b232011-09-27 23:30:47 +00006498 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,
6499 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006500
6501 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006502 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006503 }
6504
6505 if (Method->isVariadic()) {
6506 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006507 Builder.AddChunk(CodeCompletionString::CK_Comma);
6508 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006509 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006510
Douglas Gregor447107d2010-05-28 00:57:46 +00006511 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006512 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006513 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6514 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6515 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006516 if (!Method->getResultType()->isVoidType()) {
6517 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006518 Builder.AddTextChunk("return");
6519 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6520 Builder.AddPlaceholderChunk("expression");
6521 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006522 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006523 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006524
Douglas Gregor218937c2011-02-01 19:23:04 +00006525 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6526 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006527 }
6528
Douglas Gregor408be5a2010-08-25 01:08:01 +00006529 unsigned Priority = CCP_CodePattern;
6530 if (!M->second.second)
6531 Priority += CCD_InBaseClass;
6532
Douglas Gregor218937c2011-02-01 19:23:04 +00006533 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006534 Method->isInstanceMethod()
6535 ? CXCursor_ObjCInstanceMethodDecl
6536 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006537 }
6538
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006539 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6540 // the properties in this class and its categories.
6541 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006542 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006543 Containers.push_back(SearchDecl);
6544
Douglas Gregore74c25c2011-05-04 23:50:46 +00006545 VisitedSelectorSet KnownSelectors;
6546 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6547 MEnd = KnownMethods.end();
6548 M != MEnd; ++M)
6549 KnownSelectors.insert(M->first);
6550
6551
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006552 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6553 if (!IFace)
6554 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6555 IFace = Category->getClassInterface();
6556
6557 if (IFace) {
6558 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6559 Category = Category->getNextClassCategory())
6560 Containers.push_back(Category);
6561 }
6562
6563 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6564 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6565 PEnd = Containers[I]->prop_end();
6566 P != PEnd; ++P) {
6567 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006568 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006569 }
6570 }
6571 }
6572
Douglas Gregore8f5a172010-04-07 00:21:17 +00006573 Results.ExitScope();
6574
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006575 HandleCodeCompleteResults(this, CodeCompleter,
6576 CodeCompletionContext::CCC_Other,
6577 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006578}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006579
6580void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6581 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006582 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006583 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006584 IdentifierInfo **SelIdents,
6585 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006586 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006587 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006588 if (ExternalSource) {
6589 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6590 I != N; ++I) {
6591 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006592 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006593 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006594
6595 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006596 }
6597 }
6598
6599 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006600 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006601 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6602 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006603
6604 if (ReturnTy)
6605 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006606
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006607 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006608 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6609 MEnd = MethodPool.end();
6610 M != MEnd; ++M) {
6611 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6612 &M->second.second;
6613 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006614 MethList = MethList->Next) {
6615 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6616 NumSelIdents))
6617 continue;
6618
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006619 if (AtParameterName) {
6620 // Suggest parameter names we've seen before.
6621 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6622 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6623 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006624 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006625 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006626 Param->getIdentifier()->getName()));
6627 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006628 }
6629 }
6630
6631 continue;
6632 }
6633
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006634 Result R(MethList->Method, 0);
6635 R.StartParameter = NumSelIdents;
6636 R.AllParametersAreInformative = false;
6637 R.DeclaringEntity = true;
6638 Results.MaybeAddResult(R, CurContext);
6639 }
6640 }
6641
6642 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006643 HandleCodeCompleteResults(this, CodeCompleter,
6644 CodeCompletionContext::CCC_Other,
6645 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006646}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006647
Douglas Gregorf29c5232010-08-24 22:20:20 +00006648void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006649 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006650 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006651 Results.EnterNewScope();
6652
6653 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006654 CodeCompletionBuilder Builder(Results.getAllocator());
6655 Builder.AddTypedTextChunk("if");
6656 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6657 Builder.AddPlaceholderChunk("condition");
6658 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006659
6660 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006661 Builder.AddTypedTextChunk("ifdef");
6662 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6663 Builder.AddPlaceholderChunk("macro");
6664 Results.AddResult(Builder.TakeString());
6665
Douglas Gregorf44e8542010-08-24 19:08:16 +00006666 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006667 Builder.AddTypedTextChunk("ifndef");
6668 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6669 Builder.AddPlaceholderChunk("macro");
6670 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006671
6672 if (InConditional) {
6673 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006674 Builder.AddTypedTextChunk("elif");
6675 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6676 Builder.AddPlaceholderChunk("condition");
6677 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006678
6679 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006680 Builder.AddTypedTextChunk("else");
6681 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006682
6683 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006684 Builder.AddTypedTextChunk("endif");
6685 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006686 }
6687
6688 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006689 Builder.AddTypedTextChunk("include");
6690 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6691 Builder.AddTextChunk("\"");
6692 Builder.AddPlaceholderChunk("header");
6693 Builder.AddTextChunk("\"");
6694 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006695
6696 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006697 Builder.AddTypedTextChunk("include");
6698 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6699 Builder.AddTextChunk("<");
6700 Builder.AddPlaceholderChunk("header");
6701 Builder.AddTextChunk(">");
6702 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006703
6704 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006705 Builder.AddTypedTextChunk("define");
6706 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6707 Builder.AddPlaceholderChunk("macro");
6708 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006709
6710 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006711 Builder.AddTypedTextChunk("define");
6712 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6713 Builder.AddPlaceholderChunk("macro");
6714 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6715 Builder.AddPlaceholderChunk("args");
6716 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6717 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006718
6719 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006720 Builder.AddTypedTextChunk("undef");
6721 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6722 Builder.AddPlaceholderChunk("macro");
6723 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006724
6725 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006726 Builder.AddTypedTextChunk("line");
6727 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6728 Builder.AddPlaceholderChunk("number");
6729 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006730
6731 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006732 Builder.AddTypedTextChunk("line");
6733 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6734 Builder.AddPlaceholderChunk("number");
6735 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6736 Builder.AddTextChunk("\"");
6737 Builder.AddPlaceholderChunk("filename");
6738 Builder.AddTextChunk("\"");
6739 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006740
6741 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006742 Builder.AddTypedTextChunk("error");
6743 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6744 Builder.AddPlaceholderChunk("message");
6745 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006746
6747 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006748 Builder.AddTypedTextChunk("pragma");
6749 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6750 Builder.AddPlaceholderChunk("arguments");
6751 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006752
6753 if (getLangOptions().ObjC1) {
6754 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006755 Builder.AddTypedTextChunk("import");
6756 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6757 Builder.AddTextChunk("\"");
6758 Builder.AddPlaceholderChunk("header");
6759 Builder.AddTextChunk("\"");
6760 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006761
6762 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006763 Builder.AddTypedTextChunk("import");
6764 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6765 Builder.AddTextChunk("<");
6766 Builder.AddPlaceholderChunk("header");
6767 Builder.AddTextChunk(">");
6768 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006769 }
6770
6771 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006772 Builder.AddTypedTextChunk("include_next");
6773 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6774 Builder.AddTextChunk("\"");
6775 Builder.AddPlaceholderChunk("header");
6776 Builder.AddTextChunk("\"");
6777 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006778
6779 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006780 Builder.AddTypedTextChunk("include_next");
6781 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6782 Builder.AddTextChunk("<");
6783 Builder.AddPlaceholderChunk("header");
6784 Builder.AddTextChunk(">");
6785 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006786
6787 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006788 Builder.AddTypedTextChunk("warning");
6789 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6790 Builder.AddPlaceholderChunk("message");
6791 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006792
6793 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6794 // completions for them. And __include_macros is a Clang-internal extension
6795 // that we don't want to encourage anyone to use.
6796
6797 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6798 Results.ExitScope();
6799
Douglas Gregorf44e8542010-08-24 19:08:16 +00006800 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006801 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006802 Results.data(), Results.size());
6803}
6804
6805void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006806 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006807 S->getFnParent()? Sema::PCC_RecoveryInFunction
6808 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006809}
6810
Douglas Gregorf29c5232010-08-24 22:20:20 +00006811void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006812 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006813 IsDefinition? CodeCompletionContext::CCC_MacroName
6814 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006815 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6816 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006817 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006818 Results.EnterNewScope();
6819 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6820 MEnd = PP.macro_end();
6821 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006822 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006823 M->first->getName()));
6824 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006825 }
6826 Results.ExitScope();
6827 } else if (IsDefinition) {
6828 // FIXME: Can we detect when the user just wrote an include guard above?
6829 }
6830
Douglas Gregor52779fb2010-09-23 23:01:17 +00006831 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006832 Results.data(), Results.size());
6833}
6834
Douglas Gregorf29c5232010-08-24 22:20:20 +00006835void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006836 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006837 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006838
6839 if (!CodeCompleter || CodeCompleter->includeMacros())
6840 AddMacroResults(PP, Results);
6841
6842 // defined (<macro>)
6843 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006844 CodeCompletionBuilder Builder(Results.getAllocator());
6845 Builder.AddTypedTextChunk("defined");
6846 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6847 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6848 Builder.AddPlaceholderChunk("macro");
6849 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6850 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006851 Results.ExitScope();
6852
6853 HandleCodeCompleteResults(this, CodeCompleter,
6854 CodeCompletionContext::CCC_PreprocessorExpression,
6855 Results.data(), Results.size());
6856}
6857
6858void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6859 IdentifierInfo *Macro,
6860 MacroInfo *MacroInfo,
6861 unsigned Argument) {
6862 // FIXME: In the future, we could provide "overload" results, much like we
6863 // do for function calls.
6864
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00006865 // Now just ignore this. There will be another code-completion callback
6866 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00006867}
6868
Douglas Gregor55817af2010-08-25 17:04:25 +00006869void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006870 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006871 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006872 0, 0);
6873}
6874
Douglas Gregordae68752011-02-01 22:57:45 +00006875void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006876 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006877 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006878 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6879 CodeCompletionDeclConsumer Consumer(Builder,
6880 Context.getTranslationUnitDecl());
6881 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6882 Consumer);
6883 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006884
6885 if (!CodeCompleter || CodeCompleter->includeMacros())
6886 AddMacroResults(PP, Builder);
6887
6888 Results.clear();
6889 Results.insert(Results.end(),
6890 Builder.data(), Builder.data() + Builder.size());
6891}