blob: 15a54f8d0aabe2414aa271873a8cd7bf8a35e98e [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;
993 if (isa<ObjCPropertyDecl>(ND) &&
994 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
995 return true;
996 }
997
Douglas Gregor791215b2009-09-21 20:51:25 +0000998 return ND->getIdentifierNamespace() & IDNS;
999}
1000
Douglas Gregor01dfea02010-01-10 23:08:15 +00001001/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001002/// ordinary name lookup but is not a type name.
1003bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
1004 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1005 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1006 return false;
1007
1008 unsigned IDNS = Decl::IDNS_Ordinary;
1009 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +00001010 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +00001011 else if (SemaRef.getLangOptions().ObjC1) {
1012 if (isa<ObjCIvarDecl>(ND))
1013 return true;
1014 if (isa<ObjCPropertyDecl>(ND) &&
1015 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
1016 return true;
1017 }
1018
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001019 return ND->getIdentifierNamespace() & IDNS;
1020}
1021
Douglas Gregorf9578432010-07-28 21:50:18 +00001022bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
1023 if (!IsOrdinaryNonTypeName(ND))
1024 return 0;
1025
1026 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1027 if (VD->getType()->isIntegralOrEnumerationType())
1028 return true;
1029
1030 return false;
1031}
1032
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001033/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +00001034/// ordinary name lookup.
1035bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001036 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1037
Douglas Gregor01dfea02010-01-10 23:08:15 +00001038 unsigned IDNS = Decl::IDNS_Ordinary;
1039 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +00001040 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001041
1042 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001043 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1044 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001045}
1046
Douglas Gregor86d9a522009-09-21 16:56:56 +00001047/// \brief Determines whether the given declaration is suitable as the
1048/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1049bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1050 // Allow us to find class templates, too.
1051 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1052 ND = ClassTemplate->getTemplatedDecl();
1053
1054 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1055}
1056
1057/// \brief Determines whether the given declaration is an enumeration.
1058bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1059 return isa<EnumDecl>(ND);
1060}
1061
1062/// \brief Determines whether the given declaration is a class or struct.
1063bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1064 // Allow us to find class templates, too.
1065 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1066 ND = ClassTemplate->getTemplatedDecl();
1067
1068 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001069 return RD->getTagKind() == TTK_Class ||
1070 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001071
1072 return false;
1073}
1074
1075/// \brief Determines whether the given declaration is a union.
1076bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1077 // Allow us to find class templates, too.
1078 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1079 ND = ClassTemplate->getTemplatedDecl();
1080
1081 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001082 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001083
1084 return false;
1085}
1086
1087/// \brief Determines whether the given declaration is a namespace.
1088bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1089 return isa<NamespaceDecl>(ND);
1090}
1091
1092/// \brief Determines whether the given declaration is a namespace or
1093/// namespace alias.
1094bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1095 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1096}
1097
Douglas Gregor76282942009-12-11 17:31:05 +00001098/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001099bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001100 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1101 ND = Using->getTargetDecl();
1102
1103 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001104}
1105
Douglas Gregor76282942009-12-11 17:31:05 +00001106/// \brief Determines which members of a class should be visible via
1107/// "." or "->". Only value declarations, nested name specifiers, and
1108/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001109bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001110 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1111 ND = Using->getTargetDecl();
1112
Douglas Gregorce821962009-12-11 18:14:22 +00001113 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1114 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001115}
1116
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001117static bool isObjCReceiverType(ASTContext &C, QualType T) {
1118 T = C.getCanonicalType(T);
1119 switch (T->getTypeClass()) {
1120 case Type::ObjCObject:
1121 case Type::ObjCInterface:
1122 case Type::ObjCObjectPointer:
1123 return true;
1124
1125 case Type::Builtin:
1126 switch (cast<BuiltinType>(T)->getKind()) {
1127 case BuiltinType::ObjCId:
1128 case BuiltinType::ObjCClass:
1129 case BuiltinType::ObjCSel:
1130 return true;
1131
1132 default:
1133 break;
1134 }
1135 return false;
1136
1137 default:
1138 break;
1139 }
1140
1141 if (!C.getLangOptions().CPlusPlus)
1142 return false;
1143
1144 // FIXME: We could perform more analysis here to determine whether a
1145 // particular class type has any conversions to Objective-C types. For now,
1146 // just accept all class types.
1147 return T->isDependentType() || T->isRecordType();
1148}
1149
1150bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1151 QualType T = getDeclUsageType(SemaRef.Context, ND);
1152 if (T.isNull())
1153 return false;
1154
1155 T = SemaRef.Context.getBaseElementType(T);
1156 return isObjCReceiverType(SemaRef.Context, T);
1157}
1158
Douglas Gregorfb629412010-08-23 21:17:50 +00001159bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1160 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1161 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1162 return false;
1163
1164 QualType T = getDeclUsageType(SemaRef.Context, ND);
1165 if (T.isNull())
1166 return false;
1167
1168 T = SemaRef.Context.getBaseElementType(T);
1169 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1170 T->isObjCIdType() ||
1171 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1172}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001173
Douglas Gregor52779fb2010-09-23 23:01:17 +00001174bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1175 return false;
1176}
1177
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001178/// \rief Determines whether the given declaration is an Objective-C
1179/// instance variable.
1180bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1181 return isa<ObjCIvarDecl>(ND);
1182}
1183
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001184namespace {
1185 /// \brief Visible declaration consumer that adds a code-completion result
1186 /// for each visible declaration.
1187 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1188 ResultBuilder &Results;
1189 DeclContext *CurContext;
1190
1191 public:
1192 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1193 : Results(Results), CurContext(CurContext) { }
1194
Douglas Gregor0cc84042010-01-14 15:47:35 +00001195 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1196 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001197 }
1198 };
1199}
1200
Douglas Gregor86d9a522009-09-21 16:56:56 +00001201/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001202static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001203 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001204 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001205 Results.AddResult(Result("short", CCP_Type));
1206 Results.AddResult(Result("long", CCP_Type));
1207 Results.AddResult(Result("signed", CCP_Type));
1208 Results.AddResult(Result("unsigned", CCP_Type));
1209 Results.AddResult(Result("void", CCP_Type));
1210 Results.AddResult(Result("char", CCP_Type));
1211 Results.AddResult(Result("int", CCP_Type));
1212 Results.AddResult(Result("float", CCP_Type));
1213 Results.AddResult(Result("double", CCP_Type));
1214 Results.AddResult(Result("enum", CCP_Type));
1215 Results.AddResult(Result("struct", CCP_Type));
1216 Results.AddResult(Result("union", CCP_Type));
1217 Results.AddResult(Result("const", CCP_Type));
1218 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001219
Douglas Gregor86d9a522009-09-21 16:56:56 +00001220 if (LangOpts.C99) {
1221 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001222 Results.AddResult(Result("_Complex", CCP_Type));
1223 Results.AddResult(Result("_Imaginary", CCP_Type));
1224 Results.AddResult(Result("_Bool", CCP_Type));
1225 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001226 }
1227
Douglas Gregor218937c2011-02-01 19:23:04 +00001228 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001229 if (LangOpts.CPlusPlus) {
1230 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001231 Results.AddResult(Result("bool", CCP_Type +
1232 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001233 Results.AddResult(Result("class", CCP_Type));
1234 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001235
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001236 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001237 Builder.AddTypedTextChunk("typename");
1238 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1239 Builder.AddPlaceholderChunk("qualifier");
1240 Builder.AddTextChunk("::");
1241 Builder.AddPlaceholderChunk("name");
1242 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001243
Douglas Gregor86d9a522009-09-21 16:56:56 +00001244 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001245 Results.AddResult(Result("auto", CCP_Type));
1246 Results.AddResult(Result("char16_t", CCP_Type));
1247 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001248
Douglas Gregor218937c2011-02-01 19:23:04 +00001249 Builder.AddTypedTextChunk("decltype");
1250 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1251 Builder.AddPlaceholderChunk("expression");
1252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1253 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001254 }
1255 }
1256
1257 // GNU extensions
1258 if (LangOpts.GNUMode) {
1259 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001260 // Results.AddResult(Result("_Decimal32"));
1261 // Results.AddResult(Result("_Decimal64"));
1262 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001263
Douglas Gregor218937c2011-02-01 19:23:04 +00001264 Builder.AddTypedTextChunk("typeof");
1265 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1266 Builder.AddPlaceholderChunk("expression");
1267 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001268
Douglas Gregor218937c2011-02-01 19:23:04 +00001269 Builder.AddTypedTextChunk("typeof");
1270 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1271 Builder.AddPlaceholderChunk("type");
1272 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1273 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001274 }
1275}
1276
John McCallf312b1e2010-08-26 23:41:50 +00001277static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001278 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001279 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001280 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001281 // Note: we don't suggest either "auto" or "register", because both
1282 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1283 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001284 Results.AddResult(Result("extern"));
1285 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001286}
1287
John McCallf312b1e2010-08-26 23:41:50 +00001288static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001289 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001290 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001291 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001292 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001293 case Sema::PCC_Class:
1294 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001295 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001296 Results.AddResult(Result("explicit"));
1297 Results.AddResult(Result("friend"));
1298 Results.AddResult(Result("mutable"));
1299 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001300 }
1301 // Fall through
1302
John McCallf312b1e2010-08-26 23:41:50 +00001303 case Sema::PCC_ObjCInterface:
1304 case Sema::PCC_ObjCImplementation:
1305 case Sema::PCC_Namespace:
1306 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001307 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001308 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001309 break;
1310
John McCallf312b1e2010-08-26 23:41:50 +00001311 case Sema::PCC_ObjCInstanceVariableList:
1312 case Sema::PCC_Expression:
1313 case Sema::PCC_Statement:
1314 case Sema::PCC_ForInit:
1315 case Sema::PCC_Condition:
1316 case Sema::PCC_RecoveryInFunction:
1317 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001318 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001319 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001320 break;
1321 }
1322}
1323
Douglas Gregorbca403c2010-01-13 23:51:12 +00001324static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1325static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1326static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001327 ResultBuilder &Results,
1328 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001329static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001330 ResultBuilder &Results,
1331 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001332static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001333 ResultBuilder &Results,
1334 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001335static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001336
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001337static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001338 CodeCompletionBuilder Builder(Results.getAllocator());
1339 Builder.AddTypedTextChunk("typedef");
1340 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1341 Builder.AddPlaceholderChunk("type");
1342 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1343 Builder.AddPlaceholderChunk("name");
1344 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001345}
1346
John McCallf312b1e2010-08-26 23:41:50 +00001347static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001348 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001349 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001350 case Sema::PCC_Namespace:
1351 case Sema::PCC_Class:
1352 case Sema::PCC_ObjCInstanceVariableList:
1353 case Sema::PCC_Template:
1354 case Sema::PCC_MemberTemplate:
1355 case Sema::PCC_Statement:
1356 case Sema::PCC_RecoveryInFunction:
1357 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001358 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001359 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001360 return true;
1361
John McCallf312b1e2010-08-26 23:41:50 +00001362 case Sema::PCC_Expression:
1363 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001364 return LangOpts.CPlusPlus;
1365
1366 case Sema::PCC_ObjCInterface:
1367 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001368 return false;
1369
John McCallf312b1e2010-08-26 23:41:50 +00001370 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001371 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001372 }
1373
1374 return false;
1375}
1376
Douglas Gregor01dfea02010-01-10 23:08:15 +00001377/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001378static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001379 Scope *S,
1380 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001381 ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001382 CodeCompletionBuilder Builder(Results.getAllocator());
1383
John McCall0a2c5e22010-08-25 06:19:51 +00001384 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001385 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001386 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001387 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001388 if (Results.includeCodePatterns()) {
1389 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001390 Builder.AddTypedTextChunk("namespace");
1391 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1392 Builder.AddPlaceholderChunk("identifier");
1393 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1394 Builder.AddPlaceholderChunk("declarations");
1395 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1396 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1397 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001398 }
1399
Douglas Gregor01dfea02010-01-10 23:08:15 +00001400 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001401 Builder.AddTypedTextChunk("namespace");
1402 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1403 Builder.AddPlaceholderChunk("name");
1404 Builder.AddChunk(CodeCompletionString::CK_Equal);
1405 Builder.AddPlaceholderChunk("namespace");
1406 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001407
1408 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001409 Builder.AddTypedTextChunk("using");
1410 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1411 Builder.AddTextChunk("namespace");
1412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1413 Builder.AddPlaceholderChunk("identifier");
1414 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001415
1416 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001417 Builder.AddTypedTextChunk("asm");
1418 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1419 Builder.AddPlaceholderChunk("string-literal");
1420 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1421 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001422
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001423 if (Results.includeCodePatterns()) {
1424 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001425 Builder.AddTypedTextChunk("template");
1426 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1427 Builder.AddPlaceholderChunk("declaration");
1428 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001429 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001430 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001431
1432 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001433 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001434
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001435 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001436 // Fall through
1437
John McCallf312b1e2010-08-26 23:41:50 +00001438 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001439 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001440 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001441 Builder.AddTypedTextChunk("using");
1442 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1443 Builder.AddPlaceholderChunk("qualifier");
1444 Builder.AddTextChunk("::");
1445 Builder.AddPlaceholderChunk("name");
1446 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001447
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001448 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001449 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001450 Builder.AddTypedTextChunk("using");
1451 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1452 Builder.AddTextChunk("typename");
1453 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1454 Builder.AddPlaceholderChunk("qualifier");
1455 Builder.AddTextChunk("::");
1456 Builder.AddPlaceholderChunk("name");
1457 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001458 }
1459
John McCallf312b1e2010-08-26 23:41:50 +00001460 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001461 AddTypedefResult(Results);
1462
Douglas Gregor01dfea02010-01-10 23:08:15 +00001463 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001464 Builder.AddTypedTextChunk("public");
1465 Builder.AddChunk(CodeCompletionString::CK_Colon);
1466 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001467
1468 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001469 Builder.AddTypedTextChunk("protected");
1470 Builder.AddChunk(CodeCompletionString::CK_Colon);
1471 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001472
1473 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001474 Builder.AddTypedTextChunk("private");
1475 Builder.AddChunk(CodeCompletionString::CK_Colon);
1476 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001477 }
1478 }
1479 // Fall through
1480
John McCallf312b1e2010-08-26 23:41:50 +00001481 case Sema::PCC_Template:
1482 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001483 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001484 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001485 Builder.AddTypedTextChunk("template");
1486 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1487 Builder.AddPlaceholderChunk("parameters");
1488 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1489 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001490 }
1491
Douglas Gregorbca403c2010-01-13 23:51:12 +00001492 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1493 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001494 break;
1495
John McCallf312b1e2010-08-26 23:41:50 +00001496 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001497 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1498 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1499 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001500 break;
1501
John McCallf312b1e2010-08-26 23:41:50 +00001502 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001503 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1504 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1505 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001506 break;
1507
John McCallf312b1e2010-08-26 23:41:50 +00001508 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001509 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001510 break;
1511
John McCallf312b1e2010-08-26 23:41:50 +00001512 case Sema::PCC_RecoveryInFunction:
1513 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001514 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001515
Douglas Gregorec3310a2011-04-12 02:47:21 +00001516 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1517 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001518 Builder.AddTypedTextChunk("try");
1519 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1520 Builder.AddPlaceholderChunk("statements");
1521 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1522 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1523 Builder.AddTextChunk("catch");
1524 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1525 Builder.AddPlaceholderChunk("declaration");
1526 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1527 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1528 Builder.AddPlaceholderChunk("statements");
1529 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1530 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1531 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001532 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001533 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001534 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001535
Douglas Gregord8e8a582010-05-25 21:41:55 +00001536 if (Results.includeCodePatterns()) {
1537 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001538 Builder.AddTypedTextChunk("if");
1539 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001540 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001541 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001542 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001543 Builder.AddPlaceholderChunk("expression");
1544 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1545 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1546 Builder.AddPlaceholderChunk("statements");
1547 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1548 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1549 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001550
Douglas Gregord8e8a582010-05-25 21:41:55 +00001551 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001552 Builder.AddTypedTextChunk("switch");
1553 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001554 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001555 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001556 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001557 Builder.AddPlaceholderChunk("expression");
1558 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1559 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1560 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1561 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1562 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001563 }
1564
Douglas Gregor01dfea02010-01-10 23:08:15 +00001565 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001566 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001567 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001568 Builder.AddTypedTextChunk("case");
1569 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1570 Builder.AddPlaceholderChunk("expression");
1571 Builder.AddChunk(CodeCompletionString::CK_Colon);
1572 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001573
1574 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001575 Builder.AddTypedTextChunk("default");
1576 Builder.AddChunk(CodeCompletionString::CK_Colon);
1577 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001578 }
1579
Douglas Gregord8e8a582010-05-25 21:41:55 +00001580 if (Results.includeCodePatterns()) {
1581 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001582 Builder.AddTypedTextChunk("while");
1583 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001584 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001585 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001586 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001587 Builder.AddPlaceholderChunk("expression");
1588 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1589 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1590 Builder.AddPlaceholderChunk("statements");
1591 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1592 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1593 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001594
1595 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001596 Builder.AddTypedTextChunk("do");
1597 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1598 Builder.AddPlaceholderChunk("statements");
1599 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1600 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1601 Builder.AddTextChunk("while");
1602 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1603 Builder.AddPlaceholderChunk("expression");
1604 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1605 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001606
Douglas Gregord8e8a582010-05-25 21:41:55 +00001607 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001608 Builder.AddTypedTextChunk("for");
1609 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001610 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001611 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001612 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001613 Builder.AddPlaceholderChunk("init-expression");
1614 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1615 Builder.AddPlaceholderChunk("condition");
1616 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1617 Builder.AddPlaceholderChunk("inc-expression");
1618 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1619 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1620 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1621 Builder.AddPlaceholderChunk("statements");
1622 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1623 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1624 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001625 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001626
1627 if (S->getContinueParent()) {
1628 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001629 Builder.AddTypedTextChunk("continue");
1630 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001631 }
1632
1633 if (S->getBreakParent()) {
1634 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001635 Builder.AddTypedTextChunk("break");
1636 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001637 }
1638
1639 // "return expression ;" or "return ;", depending on whether we
1640 // know the function is void or not.
1641 bool isVoid = false;
1642 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1643 isVoid = Function->getResultType()->isVoidType();
1644 else if (ObjCMethodDecl *Method
1645 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1646 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001647 else if (SemaRef.getCurBlock() &&
1648 !SemaRef.getCurBlock()->ReturnType.isNull())
1649 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001650 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001651 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001652 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1653 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001654 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001655 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001656
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001657 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001658 Builder.AddTypedTextChunk("goto");
1659 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1660 Builder.AddPlaceholderChunk("label");
1661 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001662
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001663 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001664 Builder.AddTypedTextChunk("using");
1665 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1666 Builder.AddTextChunk("namespace");
1667 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1668 Builder.AddPlaceholderChunk("identifier");
1669 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001670 }
1671
1672 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001673 case Sema::PCC_ForInit:
1674 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001675 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001676 // Fall through: conditions and statements can have expressions.
1677
Douglas Gregor02688102010-09-14 23:59:36 +00001678 case Sema::PCC_ParenthesizedExpression:
John McCallf85e1932011-06-15 23:02:42 +00001679 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1680 CCC == Sema::PCC_ParenthesizedExpression) {
1681 // (__bridge <type>)<expression>
1682 Builder.AddTypedTextChunk("__bridge");
1683 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1684 Builder.AddPlaceholderChunk("type");
1685 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1686 Builder.AddPlaceholderChunk("expression");
1687 Results.AddResult(Result(Builder.TakeString()));
1688
1689 // (__bridge_transfer <Objective-C type>)<expression>
1690 Builder.AddTypedTextChunk("__bridge_transfer");
1691 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1692 Builder.AddPlaceholderChunk("Objective-C type");
1693 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1694 Builder.AddPlaceholderChunk("expression");
1695 Results.AddResult(Result(Builder.TakeString()));
1696
1697 // (__bridge_retained <CF type>)<expression>
1698 Builder.AddTypedTextChunk("__bridge_retained");
1699 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1700 Builder.AddPlaceholderChunk("CF type");
1701 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1702 Builder.AddPlaceholderChunk("expression");
1703 Results.AddResult(Result(Builder.TakeString()));
1704 }
1705 // Fall through
1706
John McCallf312b1e2010-08-26 23:41:50 +00001707 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001708 if (SemaRef.getLangOptions().CPlusPlus) {
1709 // 'this', if we're in a non-static member function.
1710 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1711 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001712 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001713
1714 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001715 Results.AddResult(Result("true"));
1716 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001717
Douglas Gregorec3310a2011-04-12 02:47:21 +00001718 if (SemaRef.getLangOptions().RTTI) {
1719 // dynamic_cast < type-id > ( expression )
1720 Builder.AddTypedTextChunk("dynamic_cast");
1721 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1722 Builder.AddPlaceholderChunk("type");
1723 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1724 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1725 Builder.AddPlaceholderChunk("expression");
1726 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1727 Results.AddResult(Result(Builder.TakeString()));
1728 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001729
1730 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001731 Builder.AddTypedTextChunk("static_cast");
1732 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1733 Builder.AddPlaceholderChunk("type");
1734 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1735 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1736 Builder.AddPlaceholderChunk("expression");
1737 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1738 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001739
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001740 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001741 Builder.AddTypedTextChunk("reinterpret_cast");
1742 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1743 Builder.AddPlaceholderChunk("type");
1744 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1745 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1746 Builder.AddPlaceholderChunk("expression");
1747 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1748 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001749
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001750 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001751 Builder.AddTypedTextChunk("const_cast");
1752 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1753 Builder.AddPlaceholderChunk("type");
1754 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1755 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1756 Builder.AddPlaceholderChunk("expression");
1757 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1758 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001759
Douglas Gregorec3310a2011-04-12 02:47:21 +00001760 if (SemaRef.getLangOptions().RTTI) {
1761 // typeid ( expression-or-type )
1762 Builder.AddTypedTextChunk("typeid");
1763 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1764 Builder.AddPlaceholderChunk("expression-or-type");
1765 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1766 Results.AddResult(Result(Builder.TakeString()));
1767 }
1768
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001769 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001770 Builder.AddTypedTextChunk("new");
1771 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1772 Builder.AddPlaceholderChunk("type");
1773 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1774 Builder.AddPlaceholderChunk("expressions");
1775 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1776 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001777
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001778 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001779 Builder.AddTypedTextChunk("new");
1780 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1781 Builder.AddPlaceholderChunk("type");
1782 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1783 Builder.AddPlaceholderChunk("size");
1784 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1785 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1786 Builder.AddPlaceholderChunk("expressions");
1787 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1788 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001789
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001790 // delete expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001791 Builder.AddTypedTextChunk("delete");
1792 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1793 Builder.AddPlaceholderChunk("expression");
1794 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001795
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001796 // delete [] expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001797 Builder.AddTypedTextChunk("delete");
1798 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1799 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1800 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1801 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1802 Builder.AddPlaceholderChunk("expression");
1803 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001804
Douglas Gregorec3310a2011-04-12 02:47:21 +00001805 if (SemaRef.getLangOptions().CXXExceptions) {
1806 // throw expression
1807 Builder.AddTypedTextChunk("throw");
1808 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1809 Builder.AddPlaceholderChunk("expression");
1810 Results.AddResult(Result(Builder.TakeString()));
1811 }
Douglas Gregor12e13132010-05-26 22:00:08 +00001812
1813 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001814 }
1815
1816 if (SemaRef.getLangOptions().ObjC1) {
1817 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001818 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1819 // The interface can be NULL.
1820 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1821 if (ID->getSuperClass())
1822 Results.AddResult(Result("super"));
1823 }
1824
Douglas Gregorbca403c2010-01-13 23:51:12 +00001825 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001826 }
1827
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001828 // sizeof expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001829 Builder.AddTypedTextChunk("sizeof");
1830 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1831 Builder.AddPlaceholderChunk("expression-or-type");
1832 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1833 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001834 break;
1835 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001836
John McCallf312b1e2010-08-26 23:41:50 +00001837 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001838 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001839 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001840 }
1841
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001842 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1843 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001844
John McCallf312b1e2010-08-26 23:41:50 +00001845 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001846 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001847}
1848
Douglas Gregora63f6de2011-02-01 21:15:40 +00001849/// \brief Retrieve the string representation of the given type as a string
1850/// that has the appropriate lifetime for code completion.
1851///
1852/// This routine provides a fast path where we provide constant strings for
1853/// common type names.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001854static const char *GetCompletionTypeString(QualType T,
1855 ASTContext &Context,
1856 CodeCompletionAllocator &Allocator) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001857 PrintingPolicy Policy(Context.PrintingPolicy);
1858 Policy.AnonymousTagLocations = false;
John McCallf85e1932011-06-15 23:02:42 +00001859 Policy.SuppressStrongLifetime = true;
1860
Douglas Gregora63f6de2011-02-01 21:15:40 +00001861 if (!T.getLocalQualifiers()) {
1862 // Built-in type names are constant strings.
1863 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1864 return BT->getName(Context.getLangOptions());
1865
1866 // Anonymous tag types are constant strings.
1867 if (const TagType *TagT = dyn_cast<TagType>(T))
1868 if (TagDecl *Tag = TagT->getDecl())
Richard Smith162e1c12011-04-15 14:24:37 +00001869 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001870 switch (Tag->getTagKind()) {
1871 case TTK_Struct: return "struct <anonymous>";
1872 case TTK_Class: return "class <anonymous>";
1873 case TTK_Union: return "union <anonymous>";
1874 case TTK_Enum: return "enum <anonymous>";
1875 }
1876 }
1877 }
1878
1879 // Slow path: format the type as a string.
1880 std::string Result;
1881 T.getAsStringInternal(Result, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00001882 return Allocator.CopyString(Result);
Douglas Gregora63f6de2011-02-01 21:15:40 +00001883}
1884
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001885/// \brief If the given declaration has an associated type, add it as a result
1886/// type chunk.
1887static void AddResultTypeChunk(ASTContext &Context,
1888 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001889 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001890 if (!ND)
1891 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001892
1893 // Skip constructors and conversion functions, which have their return types
1894 // built into their names.
1895 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1896 return;
1897
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001898 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001899 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001900 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1901 T = Function->getResultType();
1902 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1903 T = Method->getResultType();
1904 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1905 T = FunTmpl->getTemplatedDecl()->getResultType();
1906 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1907 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1908 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1909 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00001910 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001911 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001912 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001913 T = Property->getType();
1914
1915 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1916 return;
1917
Douglas Gregora63f6de2011-02-01 21:15:40 +00001918 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context,
1919 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001920}
1921
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001922static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001923 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001924 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1925 if (Sentinel->getSentinel() == 0) {
1926 if (Context.getLangOptions().ObjC1 &&
1927 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001928 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001929 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001930 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001931 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001932 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001933 }
1934}
1935
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00001936static void appendWithSpace(std::string &Result, StringRef Text) {
1937 if (!Result.empty())
1938 Result += ' ';
1939 Result += Text.str();
1940}
1941static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
1942 std::string Result;
1943 if (ObjCQuals & Decl::OBJC_TQ_In)
1944 appendWithSpace(Result, "in");
1945 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
1946 appendWithSpace(Result, "inout");
1947 else if (ObjCQuals & Decl::OBJC_TQ_Out)
1948 appendWithSpace(Result, "out");
1949 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
1950 appendWithSpace(Result, "bycopy");
1951 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
1952 appendWithSpace(Result, "byref");
1953 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
1954 appendWithSpace(Result, "oneway");
1955 return Result;
1956}
1957
Douglas Gregor83482d12010-08-24 16:15:59 +00001958static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregoraba48082010-08-29 19:47:46 +00001959 ParmVarDecl *Param,
1960 bool SuppressName = false) {
John McCallf85e1932011-06-15 23:02:42 +00001961 PrintingPolicy Policy(Context.PrintingPolicy);
1962 Policy.AnonymousTagLocations = false;
1963 Policy.SuppressStrongLifetime = true;
1964
Douglas Gregor83482d12010-08-24 16:15:59 +00001965 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1966 if (Param->getType()->isDependentType() ||
1967 !Param->getType()->isBlockPointerType()) {
1968 // The argument for a dependent or non-block parameter is a placeholder
1969 // containing that parameter's type.
1970 std::string Result;
1971
Douglas Gregoraba48082010-08-29 19:47:46 +00001972 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001973 Result = Param->getIdentifier()->getName();
1974
John McCallf85e1932011-06-15 23:02:42 +00001975 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00001976
1977 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00001978 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
1979 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001980 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001981 Result += Param->getIdentifier()->getName();
1982 }
1983 return Result;
1984 }
1985
1986 // The argument for a block pointer parameter is a block literal with
1987 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00001988 FunctionTypeLoc *Block = 0;
1989 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00001990 TypeLoc TL;
1991 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1992 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1993 while (true) {
1994 // Look through typedefs.
1995 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1996 if (TypeSourceInfo *InnerTSInfo
Richard Smith162e1c12011-04-15 14:24:37 +00001997 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001998 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1999 continue;
2000 }
2001 }
2002
2003 // Look through qualified types
2004 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2005 TL = QualifiedTL->getUnqualifiedLoc();
2006 continue;
2007 }
2008
2009 // Try to get the function prototype behind the block pointer type,
2010 // then we're done.
2011 if (BlockPointerTypeLoc *BlockPtr
2012 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002013 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002014 Block = dyn_cast<FunctionTypeLoc>(&TL);
2015 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002016 }
2017 break;
2018 }
2019 }
2020
2021 if (!Block) {
2022 // We were unable to find a FunctionProtoTypeLoc with parameter names
2023 // for the block; just use the parameter type as a placeholder.
2024 std::string Result;
John McCallf85e1932011-06-15 23:02:42 +00002025 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002026
2027 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002028 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2029 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002030 if (Param->getIdentifier())
2031 Result += Param->getIdentifier()->getName();
2032 }
2033
2034 return Result;
2035 }
2036
2037 // We have the function prototype behind the block pointer type, as it was
2038 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002039 std::string Result;
2040 QualType ResultType = Block->getTypePtr()->getResultType();
2041 if (!ResultType->isVoidType())
John McCallf85e1932011-06-15 23:02:42 +00002042 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregor38276252010-09-08 22:47:51 +00002043
2044 Result = '^' + Result;
Douglas Gregor830072c2011-02-15 22:37:09 +00002045 if (!BlockProto || Block->getNumArgs() == 0) {
2046 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002047 Result += "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002048 else
2049 Result += "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002050 } else {
2051 Result += "(";
2052 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2053 if (I)
2054 Result += ", ";
2055 Result += FormatFunctionParameter(Context, Block->getArg(I));
2056
Douglas Gregor830072c2011-02-15 22:37:09 +00002057 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002058 Result += ", ...";
2059 }
2060 Result += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002061 }
Douglas Gregor38276252010-09-08 22:47:51 +00002062
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002063 if (Param->getIdentifier())
2064 Result += Param->getIdentifier()->getName();
2065
Douglas Gregor83482d12010-08-24 16:15:59 +00002066 return Result;
2067}
2068
Douglas Gregor86d9a522009-09-21 16:56:56 +00002069/// \brief Add function parameter chunks to the given code completion string.
2070static void AddFunctionParameterChunks(ASTContext &Context,
2071 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002072 CodeCompletionBuilder &Result,
2073 unsigned Start = 0,
2074 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002075 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002076 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002077
Douglas Gregor218937c2011-02-01 19:23:04 +00002078 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002079 ParmVarDecl *Param = Function->getParamDecl(P);
2080
Douglas Gregor218937c2011-02-01 19:23:04 +00002081 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002082 // When we see an optional default argument, put that argument and
2083 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002084 CodeCompletionBuilder Opt(Result.getAllocator());
2085 if (!FirstParameter)
2086 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2087 AddFunctionParameterChunks(Context, Function, Opt, P, true);
2088 Result.AddOptionalChunk(Opt.TakeString());
2089 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002090 }
2091
Douglas Gregor218937c2011-02-01 19:23:04 +00002092 if (FirstParameter)
2093 FirstParameter = false;
2094 else
2095 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2096
2097 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002098
2099 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00002100 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
2101
Douglas Gregore17794f2010-08-31 05:13:43 +00002102 if (Function->isVariadic() && P == N - 1)
2103 PlaceholderStr += ", ...";
2104
Douglas Gregor86d9a522009-09-21 16:56:56 +00002105 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002106 Result.AddPlaceholderChunk(
2107 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002108 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002109
2110 if (const FunctionProtoType *Proto
2111 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002112 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002113 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002114 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002115
Douglas Gregor218937c2011-02-01 19:23:04 +00002116 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002117 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002118}
2119
2120/// \brief Add template parameter chunks to the given code completion string.
2121static void AddTemplateParameterChunks(ASTContext &Context,
2122 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002123 CodeCompletionBuilder &Result,
2124 unsigned MaxParameters = 0,
2125 unsigned Start = 0,
2126 bool InDefaultArg = false) {
John McCallf85e1932011-06-15 23:02:42 +00002127 PrintingPolicy Policy(Context.PrintingPolicy);
2128 Policy.AnonymousTagLocations = false;
2129
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002130 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002131 bool FirstParameter = true;
2132
2133 TemplateParameterList *Params = Template->getTemplateParameters();
2134 TemplateParameterList::iterator PEnd = Params->end();
2135 if (MaxParameters)
2136 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002137 for (TemplateParameterList::iterator P = Params->begin() + Start;
2138 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002139 bool HasDefaultArg = false;
2140 std::string PlaceholderStr;
2141 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2142 if (TTP->wasDeclaredWithTypename())
2143 PlaceholderStr = "typename";
2144 else
2145 PlaceholderStr = "class";
2146
2147 if (TTP->getIdentifier()) {
2148 PlaceholderStr += ' ';
2149 PlaceholderStr += TTP->getIdentifier()->getName();
2150 }
2151
2152 HasDefaultArg = TTP->hasDefaultArgument();
2153 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002154 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002155 if (NTTP->getIdentifier())
2156 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002157 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002158 HasDefaultArg = NTTP->hasDefaultArgument();
2159 } else {
2160 assert(isa<TemplateTemplateParmDecl>(*P));
2161 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2162
2163 // Since putting the template argument list into the placeholder would
2164 // be very, very long, we just use an abbreviation.
2165 PlaceholderStr = "template<...> class";
2166 if (TTP->getIdentifier()) {
2167 PlaceholderStr += ' ';
2168 PlaceholderStr += TTP->getIdentifier()->getName();
2169 }
2170
2171 HasDefaultArg = TTP->hasDefaultArgument();
2172 }
2173
Douglas Gregor218937c2011-02-01 19:23:04 +00002174 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002175 // When we see an optional default argument, put that argument and
2176 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002177 CodeCompletionBuilder Opt(Result.getAllocator());
2178 if (!FirstParameter)
2179 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2180 AddTemplateParameterChunks(Context, Template, Opt, MaxParameters,
2181 P - Params->begin(), true);
2182 Result.AddOptionalChunk(Opt.TakeString());
2183 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002184 }
2185
Douglas Gregor218937c2011-02-01 19:23:04 +00002186 InDefaultArg = false;
2187
Douglas Gregor86d9a522009-09-21 16:56:56 +00002188 if (FirstParameter)
2189 FirstParameter = false;
2190 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002191 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002192
2193 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002194 Result.AddPlaceholderChunk(
2195 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002196 }
2197}
2198
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002199/// \brief Add a qualifier to the given code-completion string, if the
2200/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002201static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002202AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002203 NestedNameSpecifier *Qualifier,
2204 bool QualifierIsInformative,
2205 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002206 if (!Qualifier)
2207 return;
2208
2209 std::string PrintedNNS;
2210 {
2211 llvm::raw_string_ostream OS(PrintedNNS);
2212 Qualifier->print(OS, Context.PrintingPolicy);
2213 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002214 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002215 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002216 else
Douglas Gregordae68752011-02-01 22:57:45 +00002217 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002218}
2219
Douglas Gregor218937c2011-02-01 19:23:04 +00002220static void
2221AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2222 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002223 const FunctionProtoType *Proto
2224 = Function->getType()->getAs<FunctionProtoType>();
2225 if (!Proto || !Proto->getTypeQuals())
2226 return;
2227
Douglas Gregora63f6de2011-02-01 21:15:40 +00002228 // FIXME: Add ref-qualifier!
2229
2230 // Handle single qualifiers without copying
2231 if (Proto->getTypeQuals() == Qualifiers::Const) {
2232 Result.AddInformativeChunk(" const");
2233 return;
2234 }
2235
2236 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2237 Result.AddInformativeChunk(" volatile");
2238 return;
2239 }
2240
2241 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2242 Result.AddInformativeChunk(" restrict");
2243 return;
2244 }
2245
2246 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002247 std::string QualsStr;
2248 if (Proto->getTypeQuals() & Qualifiers::Const)
2249 QualsStr += " const";
2250 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2251 QualsStr += " volatile";
2252 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2253 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002254 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002255}
2256
Douglas Gregor6f942b22010-09-21 16:06:22 +00002257/// \brief Add the name of the given declaration
2258static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00002259 CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002260 typedef CodeCompletionString::Chunk Chunk;
2261
2262 DeclarationName Name = ND->getDeclName();
2263 if (!Name)
2264 return;
2265
2266 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002267 case DeclarationName::CXXOperatorName: {
2268 const char *OperatorName = 0;
2269 switch (Name.getCXXOverloadedOperator()) {
2270 case OO_None:
2271 case OO_Conditional:
2272 case NUM_OVERLOADED_OPERATORS:
2273 OperatorName = "operator";
2274 break;
2275
2276#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2277 case OO_##Name: OperatorName = "operator" Spelling; break;
2278#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2279#include "clang/Basic/OperatorKinds.def"
2280
2281 case OO_New: OperatorName = "operator new"; break;
2282 case OO_Delete: OperatorName = "operator delete"; break;
2283 case OO_Array_New: OperatorName = "operator new[]"; break;
2284 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2285 case OO_Call: OperatorName = "operator()"; break;
2286 case OO_Subscript: OperatorName = "operator[]"; break;
2287 }
2288 Result.AddTypedTextChunk(OperatorName);
2289 break;
2290 }
2291
Douglas Gregor6f942b22010-09-21 16:06:22 +00002292 case DeclarationName::Identifier:
2293 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002294 case DeclarationName::CXXDestructorName:
2295 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002296 Result.AddTypedTextChunk(
2297 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002298 break;
2299
2300 case DeclarationName::CXXUsingDirective:
2301 case DeclarationName::ObjCZeroArgSelector:
2302 case DeclarationName::ObjCOneArgSelector:
2303 case DeclarationName::ObjCMultiArgSelector:
2304 break;
2305
2306 case DeclarationName::CXXConstructorName: {
2307 CXXRecordDecl *Record = 0;
2308 QualType Ty = Name.getCXXNameType();
2309 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2310 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2311 else if (const InjectedClassNameType *InjectedTy
2312 = Ty->getAs<InjectedClassNameType>())
2313 Record = InjectedTy->getDecl();
2314 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002315 Result.AddTypedTextChunk(
2316 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002317 break;
2318 }
2319
Douglas Gregordae68752011-02-01 22:57:45 +00002320 Result.AddTypedTextChunk(
2321 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002322 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002323 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002324 AddTemplateParameterChunks(Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002325 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002326 }
2327 break;
2328 }
2329 }
2330}
2331
Douglas Gregor86d9a522009-09-21 16:56:56 +00002332/// \brief If possible, create a new code completion string for the given
2333/// result.
2334///
2335/// \returns Either a new, heap-allocated code completion string describing
2336/// how to use this result, or NULL to indicate that the string or name of the
2337/// result is all that is needed.
2338CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002339CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002340 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002341 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002342 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002343
John McCallf85e1932011-06-15 23:02:42 +00002344 PrintingPolicy Policy(S.Context.PrintingPolicy);
2345 Policy.AnonymousTagLocations = false;
2346 Policy.SuppressStrongLifetime = true;
2347
Douglas Gregor218937c2011-02-01 19:23:04 +00002348 if (Kind == RK_Pattern) {
2349 Pattern->Priority = Priority;
2350 Pattern->Availability = Availability;
2351 return Pattern;
2352 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002353
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002354 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002355 Result.AddTypedTextChunk(Keyword);
2356 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002357 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002358
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002359 if (Kind == RK_Macro) {
2360 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002361 assert(MI && "Not a macro?");
2362
Douglas Gregordae68752011-02-01 22:57:45 +00002363 Result.AddTypedTextChunk(
2364 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002365
2366 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002367 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002368
2369 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002370 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002371 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2372 A != AEnd; ++A) {
2373 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002374 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002375
2376 if (!MI->isVariadic() || A != AEnd - 1) {
2377 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002378 Result.AddPlaceholderChunk(
2379 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002380 continue;
2381 }
2382
2383 // Variadic argument; cope with the different between GNU and C99
2384 // variadic macros, providing a single placeholder for the rest of the
2385 // arguments.
2386 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002387 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002388 else {
2389 std::string Arg = (*A)->getName();
2390 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002391 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002392 }
2393 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002394 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2395 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002396 }
2397
Douglas Gregord8e8a582010-05-25 21:41:55 +00002398 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002399 NamedDecl *ND = Declaration;
2400
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002401 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002402 Result.AddTypedTextChunk(
2403 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002404 Result.AddTextChunk("::");
2405 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002406 }
2407
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002408 AddResultTypeChunk(S.Context, ND, Result);
2409
Douglas Gregor86d9a522009-09-21 16:56:56 +00002410 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002411 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2412 S.Context);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002413 AddTypedNameChunk(S.Context, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002414 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002415 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002416 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002417 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002418 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002419 }
2420
2421 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002422 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2423 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002424 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor6f942b22010-09-21 16:06:22 +00002425 AddTypedNameChunk(S.Context, Function, Result);
2426
Douglas Gregor86d9a522009-09-21 16:56:56 +00002427 // Figure out which template parameters are deduced (or have default
2428 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002429 SmallVector<bool, 16> Deduced;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002430 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2431 unsigned LastDeducibleArgument;
2432 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2433 --LastDeducibleArgument) {
2434 if (!Deduced[LastDeducibleArgument - 1]) {
2435 // C++0x: Figure out if the template argument has a default. If so,
2436 // the user doesn't need to type this argument.
2437 // FIXME: We need to abstract template parameters better!
2438 bool HasDefaultArg = false;
2439 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002440 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002441 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2442 HasDefaultArg = TTP->hasDefaultArgument();
2443 else if (NonTypeTemplateParmDecl *NTTP
2444 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2445 HasDefaultArg = NTTP->hasDefaultArgument();
2446 else {
2447 assert(isa<TemplateTemplateParmDecl>(Param));
2448 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002449 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002450 }
2451
2452 if (!HasDefaultArg)
2453 break;
2454 }
2455 }
2456
2457 if (LastDeducibleArgument) {
2458 // Some of the function template arguments cannot be deduced from a
2459 // function call, so we introduce an explicit template argument list
2460 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002461 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002462 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2463 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002464 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002465 }
2466
2467 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002468 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002469 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002470 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002471 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002472 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002473 }
2474
2475 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002476 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2477 S.Context);
Douglas Gregordae68752011-02-01 22:57:45 +00002478 Result.AddTypedTextChunk(
2479 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002480 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002481 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002482 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2483 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002484 }
2485
Douglas Gregor9630eb62009-11-17 16:44:22 +00002486 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002487 Selector Sel = Method->getSelector();
2488 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002489 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002490 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002491 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002492 }
2493
Douglas Gregor813d8342011-02-18 22:29:55 +00002494 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002495 SelName += ':';
2496 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002497 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002498 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002499 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002500
2501 // If there is only one parameter, and we're past it, add an empty
2502 // typed-text chunk since there is nothing to type.
2503 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002504 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002505 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002506 unsigned Idx = 0;
2507 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2508 PEnd = Method->param_end();
2509 P != PEnd; (void)++P, ++Idx) {
2510 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002511 std::string Keyword;
2512 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002513 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002514 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002515 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002516 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002517 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002518 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002519 else
Douglas Gregordae68752011-02-01 22:57:45 +00002520 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002521 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002522
2523 // If we're before the starting parameter, skip the placeholder.
2524 if (Idx < StartParameter)
2525 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002526
2527 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002528
2529 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregoraba48082010-08-29 19:47:46 +00002530 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002531 else {
John McCallf85e1932011-06-15 23:02:42 +00002532 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002533 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2534 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002535 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002536 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002537 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002538 }
2539
Douglas Gregore17794f2010-08-31 05:13:43 +00002540 if (Method->isVariadic() && (P + 1) == PEnd)
2541 Arg += ", ...";
2542
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002543 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002544 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002545 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002546 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002547 else
Douglas Gregordae68752011-02-01 22:57:45 +00002548 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002549 }
2550
Douglas Gregor2a17af02009-12-23 00:21:46 +00002551 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002552 if (Method->param_size() == 0) {
2553 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002554 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002555 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002556 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002557 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002558 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002559 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002560
2561 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002562 }
2563
Douglas Gregor218937c2011-02-01 19:23:04 +00002564 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002565 }
2566
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002567 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002568 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2569 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002570
Douglas Gregordae68752011-02-01 22:57:45 +00002571 Result.AddTypedTextChunk(
2572 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002573 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002574}
2575
Douglas Gregor86d802e2009-09-23 00:34:09 +00002576CodeCompletionString *
2577CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2578 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002579 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002580 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002581 typedef CodeCompletionString::Chunk Chunk;
John McCallf85e1932011-06-15 23:02:42 +00002582 PrintingPolicy Policy(S.Context.PrintingPolicy);
2583 Policy.AnonymousTagLocations = false;
2584 Policy.SuppressStrongLifetime = true;
2585
Douglas Gregor218937c2011-02-01 19:23:04 +00002586 // FIXME: Set priority, availability appropriately.
2587 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002588 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002589 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002590 const FunctionProtoType *Proto
2591 = dyn_cast<FunctionProtoType>(getFunctionType());
2592 if (!FDecl && !Proto) {
2593 // Function without a prototype. Just give the return type and a
2594 // highlighted ellipsis.
2595 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002596 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
2597 S.Context,
2598 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002599 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2600 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2601 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2602 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002603 }
2604
2605 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002606 Result.AddTextChunk(
2607 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002608 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002609 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002610 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002611 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002612
Douglas Gregor218937c2011-02-01 19:23:04 +00002613 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002614 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2615 for (unsigned I = 0; I != NumParams; ++I) {
2616 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002617 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002618
2619 std::string ArgString;
2620 QualType ArgType;
2621
2622 if (FDecl) {
2623 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2624 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2625 } else {
2626 ArgType = Proto->getArgType(I);
2627 }
2628
John McCallf85e1932011-06-15 23:02:42 +00002629 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002630
2631 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002632 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002633 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002634 else
Douglas Gregordae68752011-02-01 22:57:45 +00002635 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002636 }
2637
2638 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002639 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002640 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002641 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002642 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002643 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002644 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002645 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002646
Douglas Gregor218937c2011-02-01 19:23:04 +00002647 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002648}
2649
Chris Lattner5f9e2722011-07-23 10:55:15 +00002650unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002651 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002652 bool PreferredTypeIsPointer) {
2653 unsigned Priority = CCP_Macro;
2654
Douglas Gregorb05496d2010-09-20 21:11:48 +00002655 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2656 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2657 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002658 Priority = CCP_Constant;
2659 if (PreferredTypeIsPointer)
2660 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002661 }
2662 // Treat "YES", "NO", "true", and "false" as constants.
2663 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2664 MacroName.equals("true") || MacroName.equals("false"))
2665 Priority = CCP_Constant;
2666 // Treat "bool" as a type.
2667 else if (MacroName.equals("bool"))
2668 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2669
Douglas Gregor1827e102010-08-16 16:18:59 +00002670
2671 return Priority;
2672}
2673
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002674CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2675 if (!D)
2676 return CXCursor_UnexposedDecl;
2677
2678 switch (D->getKind()) {
2679 case Decl::Enum: return CXCursor_EnumDecl;
2680 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2681 case Decl::Field: return CXCursor_FieldDecl;
2682 case Decl::Function:
2683 return CXCursor_FunctionDecl;
2684 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2685 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2686 case Decl::ObjCClass:
2687 // FIXME
2688 return CXCursor_UnexposedDecl;
2689 case Decl::ObjCForwardProtocol:
2690 // FIXME
2691 return CXCursor_UnexposedDecl;
2692 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2693 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2694 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2695 case Decl::ObjCMethod:
2696 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2697 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2698 case Decl::CXXMethod: return CXCursor_CXXMethod;
2699 case Decl::CXXConstructor: return CXCursor_Constructor;
2700 case Decl::CXXDestructor: return CXCursor_Destructor;
2701 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2702 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2703 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2704 case Decl::ParmVar: return CXCursor_ParmDecl;
2705 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002706 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002707 case Decl::Var: return CXCursor_VarDecl;
2708 case Decl::Namespace: return CXCursor_Namespace;
2709 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2710 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2711 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2712 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2713 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2714 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2715 case Decl::ClassTemplatePartialSpecialization:
2716 return CXCursor_ClassTemplatePartialSpecialization;
2717 case Decl::UsingDirective: return CXCursor_UsingDirective;
2718
2719 case Decl::Using:
2720 case Decl::UnresolvedUsingValue:
2721 case Decl::UnresolvedUsingTypename:
2722 return CXCursor_UsingDeclaration;
2723
Douglas Gregor352697a2011-06-03 23:08:58 +00002724 case Decl::ObjCPropertyImpl:
2725 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2726 case ObjCPropertyImplDecl::Dynamic:
2727 return CXCursor_ObjCDynamicDecl;
2728
2729 case ObjCPropertyImplDecl::Synthesize:
2730 return CXCursor_ObjCSynthesizeDecl;
2731 }
2732 break;
2733
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002734 default:
2735 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2736 switch (TD->getTagKind()) {
2737 case TTK_Struct: return CXCursor_StructDecl;
2738 case TTK_Class: return CXCursor_ClassDecl;
2739 case TTK_Union: return CXCursor_UnionDecl;
2740 case TTK_Enum: return CXCursor_EnumDecl;
2741 }
2742 }
2743 }
2744
2745 return CXCursor_UnexposedDecl;
2746}
2747
Douglas Gregor590c7d52010-07-08 20:55:51 +00002748static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2749 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002750 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002751
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002752 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002753
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002754 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2755 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002756 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002757 Results.AddResult(Result(M->first,
2758 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002759 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002760 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002761 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002762
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002763 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002764
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002765}
2766
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002767static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2768 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002769 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002770
2771 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002772
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002773 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2774 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2775 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2776 Results.AddResult(Result("__func__", CCP_Constant));
2777 Results.ExitScope();
2778}
2779
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002780static void HandleCodeCompleteResults(Sema *S,
2781 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002782 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002783 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002784 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002785 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002786 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002787}
2788
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002789static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2790 Sema::ParserCompletionContext PCC) {
2791 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002792 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002793 return CodeCompletionContext::CCC_TopLevel;
2794
John McCallf312b1e2010-08-26 23:41:50 +00002795 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002796 return CodeCompletionContext::CCC_ClassStructUnion;
2797
John McCallf312b1e2010-08-26 23:41:50 +00002798 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002799 return CodeCompletionContext::CCC_ObjCInterface;
2800
John McCallf312b1e2010-08-26 23:41:50 +00002801 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002802 return CodeCompletionContext::CCC_ObjCImplementation;
2803
John McCallf312b1e2010-08-26 23:41:50 +00002804 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002805 return CodeCompletionContext::CCC_ObjCIvarList;
2806
John McCallf312b1e2010-08-26 23:41:50 +00002807 case Sema::PCC_Template:
2808 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002809 if (S.CurContext->isFileContext())
2810 return CodeCompletionContext::CCC_TopLevel;
2811 else if (S.CurContext->isRecord())
2812 return CodeCompletionContext::CCC_ClassStructUnion;
2813 else
2814 return CodeCompletionContext::CCC_Other;
2815
John McCallf312b1e2010-08-26 23:41:50 +00002816 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002817 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002818
John McCallf312b1e2010-08-26 23:41:50 +00002819 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002820 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2821 S.getLangOptions().ObjC1)
2822 return CodeCompletionContext::CCC_ParenthesizedExpression;
2823 else
2824 return CodeCompletionContext::CCC_Expression;
2825
2826 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002827 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002828 return CodeCompletionContext::CCC_Expression;
2829
John McCallf312b1e2010-08-26 23:41:50 +00002830 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002831 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002832
John McCallf312b1e2010-08-26 23:41:50 +00002833 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002834 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002835
2836 case Sema::PCC_ParenthesizedExpression:
2837 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002838
2839 case Sema::PCC_LocalDeclarationSpecifiers:
2840 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002841 }
2842
2843 return CodeCompletionContext::CCC_Other;
2844}
2845
Douglas Gregorf6961522010-08-27 21:18:54 +00002846/// \brief If we're in a C++ virtual member function, add completion results
2847/// that invoke the functions we override, since it's common to invoke the
2848/// overridden function as well as adding new functionality.
2849///
2850/// \param S The semantic analysis object for which we are generating results.
2851///
2852/// \param InContext This context in which the nested-name-specifier preceding
2853/// the code-completion point
2854static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2855 ResultBuilder &Results) {
2856 // Look through blocks.
2857 DeclContext *CurContext = S.CurContext;
2858 while (isa<BlockDecl>(CurContext))
2859 CurContext = CurContext->getParent();
2860
2861
2862 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2863 if (!Method || !Method->isVirtual())
2864 return;
2865
2866 // We need to have names for all of the parameters, if we're going to
2867 // generate a forwarding call.
2868 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2869 PEnd = Method->param_end();
2870 P != PEnd;
2871 ++P) {
2872 if (!(*P)->getDeclName())
2873 return;
2874 }
2875
2876 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2877 MEnd = Method->end_overridden_methods();
2878 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002879 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002880 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2881 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2882 continue;
2883
2884 // If we need a nested-name-specifier, add one now.
2885 if (!InContext) {
2886 NestedNameSpecifier *NNS
2887 = getRequiredQualification(S.Context, CurContext,
2888 Overridden->getDeclContext());
2889 if (NNS) {
2890 std::string Str;
2891 llvm::raw_string_ostream OS(Str);
2892 NNS->print(OS, S.Context.PrintingPolicy);
Douglas Gregordae68752011-02-01 22:57:45 +00002893 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002894 }
2895 } else if (!InContext->Equals(Overridden->getDeclContext()))
2896 continue;
2897
Douglas Gregordae68752011-02-01 22:57:45 +00002898 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002899 Overridden->getNameAsString()));
2900 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00002901 bool FirstParam = true;
2902 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2903 PEnd = Method->param_end();
2904 P != PEnd; ++P) {
2905 if (FirstParam)
2906 FirstParam = false;
2907 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002908 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00002909
Douglas Gregordae68752011-02-01 22:57:45 +00002910 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002911 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002912 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002913 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2914 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00002915 CCP_SuperCompletion,
2916 CXCursor_CXXMethod));
2917 Results.Ignore(Overridden);
2918 }
2919}
2920
Douglas Gregor01dfea02010-01-10 23:08:15 +00002921void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002922 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002923 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002924 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002925 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002926 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002927
Douglas Gregor01dfea02010-01-10 23:08:15 +00002928 // Determine how to filter results, e.g., so that the names of
2929 // values (functions, enumerators, function templates, etc.) are
2930 // only allowed where we can have an expression.
2931 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002932 case PCC_Namespace:
2933 case PCC_Class:
2934 case PCC_ObjCInterface:
2935 case PCC_ObjCImplementation:
2936 case PCC_ObjCInstanceVariableList:
2937 case PCC_Template:
2938 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002939 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002940 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002941 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2942 break;
2943
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002944 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002945 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002946 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002947 case PCC_ForInit:
2948 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002949 if (WantTypesInContext(CompletionContext, getLangOptions()))
2950 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2951 else
2952 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002953
2954 if (getLangOptions().CPlusPlus)
2955 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002956 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002957
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002958 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002959 // Unfiltered
2960 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002961 }
2962
Douglas Gregor3cdee122010-08-26 16:36:48 +00002963 // If we are in a C++ non-static member function, check the qualifiers on
2964 // the member function to filter/prioritize the results list.
2965 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2966 if (CurMethod->isInstance())
2967 Results.setObjectTypeQualifiers(
2968 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2969
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002970 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002971 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2972 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002973
Douglas Gregorbca403c2010-01-13 23:51:12 +00002974 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002975 Results.ExitScope();
2976
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002977 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00002978 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00002979 case PCC_Expression:
2980 case PCC_Statement:
2981 case PCC_RecoveryInFunction:
2982 if (S->getFnParent())
2983 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2984 break;
2985
2986 case PCC_Namespace:
2987 case PCC_Class:
2988 case PCC_ObjCInterface:
2989 case PCC_ObjCImplementation:
2990 case PCC_ObjCInstanceVariableList:
2991 case PCC_Template:
2992 case PCC_MemberTemplate:
2993 case PCC_ForInit:
2994 case PCC_Condition:
2995 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002996 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00002997 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002998 }
2999
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003000 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003001 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003002
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003003 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003004 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003005}
3006
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003007static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3008 ParsedType Receiver,
3009 IdentifierInfo **SelIdents,
3010 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003011 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003012 bool IsSuper,
3013 ResultBuilder &Results);
3014
3015void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3016 bool AllowNonIdentifiers,
3017 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003018 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003019 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003020 AllowNestedNameSpecifiers
3021 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3022 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003023 Results.EnterNewScope();
3024
3025 // Type qualifiers can come after names.
3026 Results.AddResult(Result("const"));
3027 Results.AddResult(Result("volatile"));
3028 if (getLangOptions().C99)
3029 Results.AddResult(Result("restrict"));
3030
3031 if (getLangOptions().CPlusPlus) {
3032 if (AllowNonIdentifiers) {
3033 Results.AddResult(Result("operator"));
3034 }
3035
3036 // Add nested-name-specifiers.
3037 if (AllowNestedNameSpecifiers) {
3038 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003039 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003040 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3041 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3042 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003043 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003044 }
3045 }
3046 Results.ExitScope();
3047
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003048 // If we're in a context where we might have an expression (rather than a
3049 // declaration), and what we've seen so far is an Objective-C type that could
3050 // be a receiver of a class message, this may be a class message send with
3051 // the initial opening bracket '[' missing. Add appropriate completions.
3052 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3053 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3054 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3055 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3056 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3057 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3058 DS.getTypeQualifiers() == 0 &&
3059 S &&
3060 (S->getFlags() & Scope::DeclScope) != 0 &&
3061 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3062 Scope::FunctionPrototypeScope |
3063 Scope::AtCatchScope)) == 0) {
3064 ParsedType T = DS.getRepAsType();
3065 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003066 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003067 }
3068
Douglas Gregor4497dd42010-08-24 04:59:56 +00003069 // Note that we intentionally suppress macro results here, since we do not
3070 // encourage using macros to produce the names of entities.
3071
Douglas Gregor52779fb2010-09-23 23:01:17 +00003072 HandleCodeCompleteResults(this, CodeCompleter,
3073 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003074 Results.data(), Results.size());
3075}
3076
Douglas Gregorfb629412010-08-23 21:17:50 +00003077struct Sema::CodeCompleteExpressionData {
3078 CodeCompleteExpressionData(QualType PreferredType = QualType())
3079 : PreferredType(PreferredType), IntegralConstantExpression(false),
3080 ObjCCollection(false) { }
3081
3082 QualType PreferredType;
3083 bool IntegralConstantExpression;
3084 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003085 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003086};
3087
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003088/// \brief Perform code-completion in an expression context when we know what
3089/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003090///
3091/// \param IntegralConstantExpression Only permit integral constant
3092/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003093void Sema::CodeCompleteExpression(Scope *S,
3094 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003095 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003096 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3097 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003098 if (Data.ObjCCollection)
3099 Results.setFilter(&ResultBuilder::IsObjCCollection);
3100 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003101 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003102 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003103 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3104 else
3105 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003106
3107 if (!Data.PreferredType.isNull())
3108 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3109
3110 // Ignore any declarations that we were told that we don't care about.
3111 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3112 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003113
3114 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003115 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3116 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003117
3118 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003119 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003120 Results.ExitScope();
3121
Douglas Gregor590c7d52010-07-08 20:55:51 +00003122 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003123 if (!Data.PreferredType.isNull())
3124 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3125 || Data.PreferredType->isMemberPointerType()
3126 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003127
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003128 if (S->getFnParent() &&
3129 !Data.ObjCCollection &&
3130 !Data.IntegralConstantExpression)
3131 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3132
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003133 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003134 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003135 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003136 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3137 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003138 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003139}
3140
Douglas Gregorac5fd842010-09-18 01:28:11 +00003141void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3142 if (E.isInvalid())
3143 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3144 else if (getLangOptions().ObjC1)
3145 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003146}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003147
Douglas Gregor73449212010-12-09 23:01:55 +00003148/// \brief The set of properties that have already been added, referenced by
3149/// property name.
3150typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3151
Douglas Gregor95ac6552009-11-18 01:29:26 +00003152static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003153 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003154 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003155 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003156 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003157 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003158 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003159
3160 // Add properties in this container.
3161 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3162 PEnd = Container->prop_end();
3163 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003164 ++P) {
3165 if (AddedProperties.insert(P->getIdentifier()))
3166 Results.MaybeAddResult(Result(*P, 0), CurContext);
3167 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003168
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003169 // Add nullary methods
3170 if (AllowNullaryMethods) {
3171 ASTContext &Context = Container->getASTContext();
3172 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3173 MEnd = Container->meth_end();
3174 M != MEnd; ++M) {
3175 if (M->getSelector().isUnarySelector())
3176 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3177 if (AddedProperties.insert(Name)) {
3178 CodeCompletionBuilder Builder(Results.getAllocator());
3179 AddResultTypeChunk(Context, *M, Builder);
3180 Builder.AddTypedTextChunk(
3181 Results.getAllocator().CopyString(Name->getName()));
3182
3183 CXAvailabilityKind Availability = CXAvailability_Available;
3184 switch (M->getAvailability()) {
3185 case AR_Available:
3186 case AR_NotYetIntroduced:
3187 Availability = CXAvailability_Available;
3188 break;
3189
3190 case AR_Deprecated:
3191 Availability = CXAvailability_Deprecated;
3192 break;
3193
3194 case AR_Unavailable:
3195 Availability = CXAvailability_NotAvailable;
3196 break;
3197 }
3198
3199 Results.MaybeAddResult(Result(Builder.TakeString(),
3200 CCP_MemberDeclaration + CCD_MethodAsProperty,
3201 M->isInstanceMethod()
3202 ? CXCursor_ObjCInstanceMethodDecl
3203 : CXCursor_ObjCClassMethodDecl,
3204 Availability),
3205 CurContext);
3206 }
3207 }
3208 }
3209
3210
Douglas Gregor95ac6552009-11-18 01:29:26 +00003211 // Add properties in referenced protocols.
3212 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3213 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3214 PEnd = Protocol->protocol_end();
3215 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003216 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3217 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003218 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003219 if (AllowCategories) {
3220 // Look through categories.
3221 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3222 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003223 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3224 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003225 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003226
3227 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003228 for (ObjCInterfaceDecl::all_protocol_iterator
3229 I = IFace->all_referenced_protocol_begin(),
3230 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003231 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3232 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003233
3234 // Look in the superclass.
3235 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003236 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3237 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003238 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003239 } else if (const ObjCCategoryDecl *Category
3240 = dyn_cast<ObjCCategoryDecl>(Container)) {
3241 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003242 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3243 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003244 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003245 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3246 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003247 }
3248}
3249
Douglas Gregor81b747b2009-09-17 21:32:03 +00003250void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
3251 SourceLocation OpLoc,
3252 bool IsArrow) {
3253 if (!BaseE || !CodeCompleter)
3254 return;
3255
John McCall0a2c5e22010-08-25 06:19:51 +00003256 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003257
Douglas Gregor81b747b2009-09-17 21:32:03 +00003258 Expr *Base = static_cast<Expr *>(BaseE);
3259 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003260
3261 if (IsArrow) {
3262 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3263 BaseType = Ptr->getPointeeType();
3264 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003265 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003266 else
3267 return;
3268 }
3269
Douglas Gregor3da626b2011-07-07 16:03:39 +00003270 enum CodeCompletionContext::Kind contextKind;
3271
3272 if (IsArrow) {
3273 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3274 }
3275 else {
3276 if (BaseType->isObjCObjectPointerType() ||
3277 BaseType->isObjCObjectOrInterfaceType()) {
3278 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3279 }
3280 else {
3281 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3282 }
3283 }
3284
Douglas Gregor218937c2011-02-01 19:23:04 +00003285 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003286 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003287 BaseType),
3288 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003289 Results.EnterNewScope();
3290 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003291 // Indicate that we are performing a member access, and the cv-qualifiers
3292 // for the base object type.
3293 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3294
Douglas Gregor95ac6552009-11-18 01:29:26 +00003295 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003296 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003297 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003298 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3299 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003300
Douglas Gregor95ac6552009-11-18 01:29:26 +00003301 if (getLangOptions().CPlusPlus) {
3302 if (!Results.empty()) {
3303 // The "template" keyword can follow "->" or "." in the grammar.
3304 // However, we only want to suggest the template keyword if something
3305 // is dependent.
3306 bool IsDependent = BaseType->isDependentType();
3307 if (!IsDependent) {
3308 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3309 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3310 IsDependent = Ctx->isDependentContext();
3311 break;
3312 }
3313 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003314
Douglas Gregor95ac6552009-11-18 01:29:26 +00003315 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003316 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003317 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003318 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003319 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3320 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003321 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003322
3323 // Add property results based on our interface.
3324 const ObjCObjectPointerType *ObjCPtr
3325 = BaseType->getAsObjCInterfacePointerType();
3326 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003327 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3328 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003329 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003330
3331 // Add properties from the protocols in a qualified interface.
3332 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3333 E = ObjCPtr->qual_end();
3334 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003335 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3336 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003337 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003338 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003339 // Objective-C instance variable access.
3340 ObjCInterfaceDecl *Class = 0;
3341 if (const ObjCObjectPointerType *ObjCPtr
3342 = BaseType->getAs<ObjCObjectPointerType>())
3343 Class = ObjCPtr->getInterfaceDecl();
3344 else
John McCallc12c5bb2010-05-15 11:32:37 +00003345 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003346
3347 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003348 if (Class) {
3349 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3350 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003351 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3352 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003353 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003354 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003355
3356 // FIXME: How do we cope with isa?
3357
3358 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003359
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003360 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003361 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003362 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003363 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003364}
3365
Douglas Gregor374929f2009-09-18 15:37:17 +00003366void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3367 if (!CodeCompleter)
3368 return;
3369
John McCall0a2c5e22010-08-25 06:19:51 +00003370 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003371 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003372 enum CodeCompletionContext::Kind ContextKind
3373 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003374 switch ((DeclSpec::TST)TagSpec) {
3375 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003376 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003377 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003378 break;
3379
3380 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003381 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003382 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003383 break;
3384
3385 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003386 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003387 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003388 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003389 break;
3390
3391 default:
3392 assert(false && "Unknown type specifier kind in CodeCompleteTag");
3393 return;
3394 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003395
Douglas Gregor218937c2011-02-01 19:23:04 +00003396 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003397 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003398
3399 // First pass: look for tags.
3400 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003401 LookupVisibleDecls(S, LookupTagName, Consumer,
3402 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003403
Douglas Gregor8071e422010-08-15 06:18:01 +00003404 if (CodeCompleter->includeGlobals()) {
3405 // Second pass: look for nested name specifiers.
3406 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3407 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3408 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003409
Douglas Gregor52779fb2010-09-23 23:01:17 +00003410 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003411 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003412}
3413
Douglas Gregor1a480c42010-08-27 17:35:51 +00003414void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003415 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3416 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003417 Results.EnterNewScope();
3418 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3419 Results.AddResult("const");
3420 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3421 Results.AddResult("volatile");
3422 if (getLangOptions().C99 &&
3423 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3424 Results.AddResult("restrict");
3425 Results.ExitScope();
3426 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003427 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003428 Results.data(), Results.size());
3429}
3430
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003431void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003432 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003433 return;
3434
John McCall781472f2010-08-25 08:40:02 +00003435 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregorf9578432010-07-28 21:50:18 +00003436 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregorfb629412010-08-23 21:17:50 +00003437 CodeCompleteExpressionData Data(Switch->getCond()->getType());
3438 Data.IntegralConstantExpression = true;
3439 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003440 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003441 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003442
3443 // Code-complete the cases of a switch statement over an enumeration type
3444 // by providing the list of
3445 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
3446
3447 // Determine which enumerators we have already seen in the switch statement.
3448 // FIXME: Ideally, we would also be able to look *past* the code-completion
3449 // token, in case we are code-completing in the middle of the switch and not
3450 // at the end. However, we aren't able to do so at the moment.
3451 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003452 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003453 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3454 SC = SC->getNextSwitchCase()) {
3455 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3456 if (!Case)
3457 continue;
3458
3459 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3460 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3461 if (EnumConstantDecl *Enumerator
3462 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3463 // We look into the AST of the case statement to determine which
3464 // enumerator was named. Alternatively, we could compute the value of
3465 // the integral constant expression, then compare it against the
3466 // values of each enumerator. However, value-based approach would not
3467 // work as well with C++ templates where enumerators declared within a
3468 // template are type- and value-dependent.
3469 EnumeratorsSeen.insert(Enumerator);
3470
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003471 // If this is a qualified-id, keep track of the nested-name-specifier
3472 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003473 //
3474 // switch (TagD.getKind()) {
3475 // case TagDecl::TK_enum:
3476 // break;
3477 // case XXX
3478 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003479 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003480 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3481 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003482 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003483 }
3484 }
3485
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003486 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3487 // If there are no prior enumerators in C++, check whether we have to
3488 // qualify the names of the enumerators that we suggest, because they
3489 // may not be visible in this scope.
3490 Qualifier = getRequiredQualification(Context, CurContext,
3491 Enum->getDeclContext());
3492
3493 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3494 }
3495
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003496 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003497 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3498 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003499 Results.EnterNewScope();
3500 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3501 EEnd = Enum->enumerator_end();
3502 E != EEnd; ++E) {
3503 if (EnumeratorsSeen.count(*E))
3504 continue;
3505
Douglas Gregor5c722c702011-02-18 23:30:37 +00003506 CodeCompletionResult R(*E, Qualifier);
3507 R.Priority = CCP_EnumInCase;
3508 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003509 }
3510 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003511
Douglas Gregor3da626b2011-07-07 16:03:39 +00003512 //We need to make sure we're setting the right context,
3513 //so only say we include macros if the code completer says we do
3514 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3515 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003516 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003517 kind = CodeCompletionContext::CCC_OtherWithMacros;
3518 }
3519
3520
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003521 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003522 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003523 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003524}
3525
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003526namespace {
3527 struct IsBetterOverloadCandidate {
3528 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003529 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003530
3531 public:
John McCall5769d612010-02-08 23:07:23 +00003532 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3533 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003534
3535 bool
3536 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003537 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003538 }
3539 };
3540}
3541
Douglas Gregord28dcd72010-05-30 06:10:08 +00003542static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3543 if (NumArgs && !Args)
3544 return true;
3545
3546 for (unsigned I = 0; I != NumArgs; ++I)
3547 if (!Args[I])
3548 return true;
3549
3550 return false;
3551}
3552
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003553void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
3554 ExprTy **ArgsIn, unsigned NumArgs) {
3555 if (!CodeCompleter)
3556 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003557
3558 // When we're code-completing for a call, we fall back to ordinary
3559 // name code-completion whenever we can't produce specific
3560 // results. We may want to revisit this strategy in the future,
3561 // e.g., by merging the two kinds of results.
3562
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003563 Expr *Fn = (Expr *)FnIn;
3564 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003565
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003566 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003567 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003568 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003569 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003570 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003571 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003572
John McCall3b4294e2009-12-16 12:17:52 +00003573 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003574 SourceLocation Loc = Fn->getExprLoc();
3575 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003576
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003577 // FIXME: What if we're calling something that isn't a function declaration?
3578 // FIXME: What if we're calling a pseudo-destructor?
3579 // FIXME: What if we're calling a member function?
3580
Douglas Gregorc0265402010-01-21 15:46:19 +00003581 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003582 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003583
John McCall3b4294e2009-12-16 12:17:52 +00003584 Expr *NakedFn = Fn->IgnoreParenCasts();
3585 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3586 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3587 /*PartialOverloading=*/ true);
3588 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3589 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003590 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003591 if (!getLangOptions().CPlusPlus ||
3592 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003593 Results.push_back(ResultCandidate(FDecl));
3594 else
John McCall86820f52010-01-26 01:37:31 +00003595 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003596 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3597 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003598 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003599 }
John McCall3b4294e2009-12-16 12:17:52 +00003600 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003601
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003602 QualType ParamType;
3603
Douglas Gregorc0265402010-01-21 15:46:19 +00003604 if (!CandidateSet.empty()) {
3605 // Sort the overload candidate set by placing the best overloads first.
3606 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003607 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003608
Douglas Gregorc0265402010-01-21 15:46:19 +00003609 // Add the remaining viable overload candidates as code-completion reslults.
3610 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3611 CandEnd = CandidateSet.end();
3612 Cand != CandEnd; ++Cand) {
3613 if (Cand->Viable)
3614 Results.push_back(ResultCandidate(Cand->Function));
3615 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003616
3617 // From the viable candidates, try to determine the type of this parameter.
3618 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3619 if (const FunctionType *FType = Results[I].getFunctionType())
3620 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3621 if (NumArgs < Proto->getNumArgs()) {
3622 if (ParamType.isNull())
3623 ParamType = Proto->getArgType(NumArgs);
3624 else if (!Context.hasSameUnqualifiedType(
3625 ParamType.getNonReferenceType(),
3626 Proto->getArgType(NumArgs).getNonReferenceType())) {
3627 ParamType = QualType();
3628 break;
3629 }
3630 }
3631 }
3632 } else {
3633 // Try to determine the parameter type from the type of the expression
3634 // being called.
3635 QualType FunctionType = Fn->getType();
3636 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3637 FunctionType = Ptr->getPointeeType();
3638 else if (const BlockPointerType *BlockPtr
3639 = FunctionType->getAs<BlockPointerType>())
3640 FunctionType = BlockPtr->getPointeeType();
3641 else if (const MemberPointerType *MemPtr
3642 = FunctionType->getAs<MemberPointerType>())
3643 FunctionType = MemPtr->getPointeeType();
3644
3645 if (const FunctionProtoType *Proto
3646 = FunctionType->getAs<FunctionProtoType>()) {
3647 if (NumArgs < Proto->getNumArgs())
3648 ParamType = Proto->getArgType(NumArgs);
3649 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003650 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003651
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003652 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003653 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003654 else
3655 CodeCompleteExpression(S, ParamType);
3656
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003657 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003658 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3659 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003660}
3661
John McCalld226f652010-08-21 09:40:31 +00003662void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3663 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003664 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003665 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003666 return;
3667 }
3668
3669 CodeCompleteExpression(S, VD->getType());
3670}
3671
3672void Sema::CodeCompleteReturn(Scope *S) {
3673 QualType ResultType;
3674 if (isa<BlockDecl>(CurContext)) {
3675 if (BlockScopeInfo *BSI = getCurBlock())
3676 ResultType = BSI->ReturnType;
3677 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3678 ResultType = Function->getResultType();
3679 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3680 ResultType = Method->getResultType();
3681
3682 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003683 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003684 else
3685 CodeCompleteExpression(S, ResultType);
3686}
3687
3688void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3689 if (LHS)
3690 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3691 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003692 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003693}
3694
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003695void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003696 bool EnteringContext) {
3697 if (!SS.getScopeRep() || !CodeCompleter)
3698 return;
3699
Douglas Gregor86d9a522009-09-21 16:56:56 +00003700 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3701 if (!Ctx)
3702 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003703
3704 // Try to instantiate any non-dependent declaration contexts before
3705 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003706 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003707 return;
3708
Douglas Gregor218937c2011-02-01 19:23:04 +00003709 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3710 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003711 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003712
Douglas Gregor86d9a522009-09-21 16:56:56 +00003713 // The "template" keyword can follow "::" in the grammar, but only
3714 // put it into the grammar if the nested-name-specifier is dependent.
3715 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3716 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003717 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003718
3719 // Add calls to overridden virtual functions, if there are any.
3720 //
3721 // FIXME: This isn't wonderful, because we don't know whether we're actually
3722 // in a context that permits expressions. This is a general issue with
3723 // qualified-id completions.
3724 if (!EnteringContext)
3725 MaybeAddOverrideCalls(*this, Ctx, Results);
3726 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003727
Douglas Gregorf6961522010-08-27 21:18:54 +00003728 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3729 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3730
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003731 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003732 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003733 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003734}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003735
3736void Sema::CodeCompleteUsing(Scope *S) {
3737 if (!CodeCompleter)
3738 return;
3739
Douglas Gregor218937c2011-02-01 19:23:04 +00003740 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003741 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3742 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003743 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003744
3745 // If we aren't in class scope, we could see the "namespace" keyword.
3746 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003747 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003748
3749 // After "using", we can see anything that would start a
3750 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003751 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003752 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3753 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003754 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003755
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003756 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003757 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003758 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003759}
3760
3761void Sema::CodeCompleteUsingDirective(Scope *S) {
3762 if (!CodeCompleter)
3763 return;
3764
Douglas Gregor86d9a522009-09-21 16:56:56 +00003765 // After "using namespace", we expect to see a namespace name or namespace
3766 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003767 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3768 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003769 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003770 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003771 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003772 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3773 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003774 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003775 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003776 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003777 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003778}
3779
3780void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3781 if (!CodeCompleter)
3782 return;
3783
Douglas Gregor86d9a522009-09-21 16:56:56 +00003784 DeclContext *Ctx = (DeclContext *)S->getEntity();
3785 if (!S->getParent())
3786 Ctx = Context.getTranslationUnitDecl();
3787
Douglas Gregor52779fb2010-09-23 23:01:17 +00003788 bool SuppressedGlobalResults
3789 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3790
Douglas Gregor218937c2011-02-01 19:23:04 +00003791 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003792 SuppressedGlobalResults
3793 ? CodeCompletionContext::CCC_Namespace
3794 : CodeCompletionContext::CCC_Other,
3795 &ResultBuilder::IsNamespace);
3796
3797 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003798 // We only want to see those namespaces that have already been defined
3799 // within this scope, because its likely that the user is creating an
3800 // extended namespace declaration. Keep track of the most recent
3801 // definition of each namespace.
3802 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3803 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3804 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3805 NS != NSEnd; ++NS)
3806 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3807
3808 // Add the most recent definition (or extended definition) of each
3809 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003810 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003811 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3812 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3813 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003814 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003815 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003816 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003817 }
3818
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003819 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003820 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003821 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003822}
3823
3824void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3825 if (!CodeCompleter)
3826 return;
3827
Douglas Gregor86d9a522009-09-21 16:56:56 +00003828 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003829 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3830 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003831 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003832 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003833 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3834 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003835 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003836 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003837 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003838}
3839
Douglas Gregored8d3222009-09-18 20:05:18 +00003840void Sema::CodeCompleteOperatorName(Scope *S) {
3841 if (!CodeCompleter)
3842 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003843
John McCall0a2c5e22010-08-25 06:19:51 +00003844 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003845 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3846 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003847 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003848 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003849
Douglas Gregor86d9a522009-09-21 16:56:56 +00003850 // Add the names of overloadable operators.
3851#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3852 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003853 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003854#include "clang/Basic/OperatorKinds.def"
3855
3856 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003857 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003858 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003859 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3860 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003861
3862 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003863 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003864 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003865
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003866 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003867 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003868 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003869}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003870
Douglas Gregor0133f522010-08-28 00:00:50 +00003871void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00003872 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00003873 unsigned NumInitializers) {
John McCallf85e1932011-06-15 23:02:42 +00003874 PrintingPolicy Policy(Context.PrintingPolicy);
3875 Policy.AnonymousTagLocations = false;
3876 Policy.SuppressStrongLifetime = true;
3877
Douglas Gregor0133f522010-08-28 00:00:50 +00003878 CXXConstructorDecl *Constructor
3879 = static_cast<CXXConstructorDecl *>(ConstructorD);
3880 if (!Constructor)
3881 return;
3882
Douglas Gregor218937c2011-02-01 19:23:04 +00003883 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003884 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003885 Results.EnterNewScope();
3886
3887 // Fill in any already-initialized fields or base classes.
3888 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3889 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3890 for (unsigned I = 0; I != NumInitializers; ++I) {
3891 if (Initializers[I]->isBaseInitializer())
3892 InitializedBases.insert(
3893 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3894 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003895 InitializedFields.insert(cast<FieldDecl>(
3896 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00003897 }
3898
3899 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00003900 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00003901 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003902 CXXRecordDecl *ClassDecl = Constructor->getParent();
3903 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3904 BaseEnd = ClassDecl->bases_end();
3905 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003906 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3907 SawLastInitializer
3908 = NumInitializers > 0 &&
3909 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3910 Context.hasSameUnqualifiedType(Base->getType(),
3911 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003912 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003913 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003914
Douglas Gregor218937c2011-02-01 19:23:04 +00003915 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003916 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00003917 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00003918 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3919 Builder.AddPlaceholderChunk("args");
3920 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3921 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003922 SawLastInitializer? CCP_NextInitializer
3923 : CCP_MemberDeclaration));
3924 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003925 }
3926
3927 // Add completions for virtual base classes.
3928 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3929 BaseEnd = ClassDecl->vbases_end();
3930 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003931 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3932 SawLastInitializer
3933 = NumInitializers > 0 &&
3934 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3935 Context.hasSameUnqualifiedType(Base->getType(),
3936 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003937 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003938 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003939
Douglas Gregor218937c2011-02-01 19:23:04 +00003940 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003941 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00003942 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00003943 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3944 Builder.AddPlaceholderChunk("args");
3945 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3946 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003947 SawLastInitializer? CCP_NextInitializer
3948 : CCP_MemberDeclaration));
3949 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003950 }
3951
3952 // Add completions for members.
3953 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3954 FieldEnd = ClassDecl->field_end();
3955 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003956 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
3957 SawLastInitializer
3958 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00003959 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
3960 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00003961 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003962 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003963
3964 if (!Field->getDeclName())
3965 continue;
3966
Douglas Gregordae68752011-02-01 22:57:45 +00003967 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003968 Field->getIdentifier()->getName()));
3969 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3970 Builder.AddPlaceholderChunk("args");
3971 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3972 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003973 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00003974 : CCP_MemberDeclaration,
3975 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00003976 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003977 }
3978 Results.ExitScope();
3979
Douglas Gregor52779fb2010-09-23 23:01:17 +00003980 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00003981 Results.data(), Results.size());
3982}
3983
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003984// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3985// true or false.
3986#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00003987static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003988 ResultBuilder &Results,
3989 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003990 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003991 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003992 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003993
Douglas Gregor218937c2011-02-01 19:23:04 +00003994 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003995 if (LangOpts.ObjC2) {
3996 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00003997 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3998 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3999 Builder.AddPlaceholderChunk("property");
4000 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004001
4002 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004003 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4004 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4005 Builder.AddPlaceholderChunk("property");
4006 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004007 }
4008}
4009
Douglas Gregorbca403c2010-01-13 23:51:12 +00004010static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004011 ResultBuilder &Results,
4012 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004013 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004014
4015 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004016 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004017
4018 if (LangOpts.ObjC2) {
4019 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004020 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004021
4022 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004023 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004024
4025 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004026 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004027 }
4028}
4029
Douglas Gregorbca403c2010-01-13 23:51:12 +00004030static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004031 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004032 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004033
4034 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004035 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4036 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4037 Builder.AddPlaceholderChunk("name");
4038 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004039
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004040 if (Results.includeCodePatterns()) {
4041 // @interface name
4042 // FIXME: Could introduce the whole pattern, including superclasses and
4043 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004044 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4045 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4046 Builder.AddPlaceholderChunk("class");
4047 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004048
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004049 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004050 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4051 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4052 Builder.AddPlaceholderChunk("protocol");
4053 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004054
4055 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004056 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4057 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4058 Builder.AddPlaceholderChunk("class");
4059 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004060 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004061
4062 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004063 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4064 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4065 Builder.AddPlaceholderChunk("alias");
4066 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4067 Builder.AddPlaceholderChunk("class");
4068 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004069}
4070
John McCalld226f652010-08-21 09:40:31 +00004071void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorc464ae82009-12-07 09:27:33 +00004072 bool InInterface) {
John McCall0a2c5e22010-08-25 06:19:51 +00004073 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004074 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4075 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004076 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004077 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00004078 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004079 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00004080 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004081 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004082 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004083 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004084 HandleCodeCompleteResults(this, CodeCompleter,
4085 CodeCompletionContext::CCC_Other,
4086 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004087}
4088
Douglas Gregorbca403c2010-01-13 23:51:12 +00004089static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004090 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004091 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004092
4093 // @encode ( type-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004094 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4095 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4096 Builder.AddPlaceholderChunk("type-name");
4097 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4098 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004099
4100 // @protocol ( protocol-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004101 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4102 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4103 Builder.AddPlaceholderChunk("protocol-name");
4104 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4105 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004106
4107 // @selector ( selector )
Douglas Gregor218937c2011-02-01 19:23:04 +00004108 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4109 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4110 Builder.AddPlaceholderChunk("selector");
4111 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4112 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004113}
4114
Douglas Gregorbca403c2010-01-13 23:51:12 +00004115static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004116 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004117 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004118
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004119 if (Results.includeCodePatterns()) {
4120 // @try { statements } @catch ( declaration ) { statements } @finally
4121 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004122 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4123 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4124 Builder.AddPlaceholderChunk("statements");
4125 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4126 Builder.AddTextChunk("@catch");
4127 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4128 Builder.AddPlaceholderChunk("parameter");
4129 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4130 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4131 Builder.AddPlaceholderChunk("statements");
4132 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4133 Builder.AddTextChunk("@finally");
4134 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4135 Builder.AddPlaceholderChunk("statements");
4136 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4137 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004138 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004139
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004140 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004141 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4142 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4143 Builder.AddPlaceholderChunk("expression");
4144 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004145
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004146 if (Results.includeCodePatterns()) {
4147 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004148 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4149 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4150 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4151 Builder.AddPlaceholderChunk("expression");
4152 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4153 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4154 Builder.AddPlaceholderChunk("statements");
4155 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4156 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004157 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004158}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004159
Douglas Gregorbca403c2010-01-13 23:51:12 +00004160static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004161 ResultBuilder &Results,
4162 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004163 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004164 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4165 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4166 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004167 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004168 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004169}
4170
4171void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004172 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4173 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004174 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004175 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004176 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004177 HandleCodeCompleteResults(this, CodeCompleter,
4178 CodeCompletionContext::CCC_Other,
4179 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004180}
4181
4182void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004183 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4184 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004185 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004186 AddObjCStatementResults(Results, false);
4187 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004188 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004189 HandleCodeCompleteResults(this, CodeCompleter,
4190 CodeCompletionContext::CCC_Other,
4191 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004192}
4193
4194void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004195 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4196 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004197 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004198 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004199 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004200 HandleCodeCompleteResults(this, CodeCompleter,
4201 CodeCompletionContext::CCC_Other,
4202 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004203}
4204
Douglas Gregor988358f2009-11-19 00:14:45 +00004205/// \brief Determine whether the addition of the given flag to an Objective-C
4206/// property's attributes will cause a conflict.
4207static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4208 // Check if we've already added this flag.
4209 if (Attributes & NewFlag)
4210 return true;
4211
4212 Attributes |= NewFlag;
4213
4214 // Check for collisions with "readonly".
4215 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4216 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4217 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004218 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004219 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004220 ObjCDeclSpec::DQ_PR_retain |
4221 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004222 return true;
4223
John McCallf85e1932011-06-15 23:02:42 +00004224 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004225 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004226 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004227 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004228 ObjCDeclSpec::DQ_PR_retain|
4229 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004230 if (AssignCopyRetMask &&
4231 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004232 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004233 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004234 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4235 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004236 return true;
4237
4238 return false;
4239}
4240
Douglas Gregora93b1082009-11-18 23:08:07 +00004241void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004242 if (!CodeCompleter)
4243 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004244
Steve Naroffece8e712009-10-08 21:55:05 +00004245 unsigned Attributes = ODS.getPropertyAttributes();
4246
John McCall0a2c5e22010-08-25 06:19:51 +00004247 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004248 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4249 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004250 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004251 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004252 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004253 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004254 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004255 if (!ObjCPropertyFlagConflicts(Attributes,
4256 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4257 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004258 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004259 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004260 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004261 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004262 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4263 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004264 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004265 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004266 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004267 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004268 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4269 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004270 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004271 CodeCompletionBuilder Setter(Results.getAllocator());
4272 Setter.AddTypedTextChunk("setter");
4273 Setter.AddTextChunk(" = ");
4274 Setter.AddPlaceholderChunk("method");
4275 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004276 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004277 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004278 CodeCompletionBuilder Getter(Results.getAllocator());
4279 Getter.AddTypedTextChunk("getter");
4280 Getter.AddTextChunk(" = ");
4281 Getter.AddPlaceholderChunk("method");
4282 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004283 }
Steve Naroffece8e712009-10-08 21:55:05 +00004284 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004285 HandleCodeCompleteResults(this, CodeCompleter,
4286 CodeCompletionContext::CCC_Other,
4287 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004288}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004289
Douglas Gregor4ad96852009-11-19 07:41:15 +00004290/// \brief Descripts the kind of Objective-C method that we want to find
4291/// via code completion.
4292enum ObjCMethodKind {
4293 MK_Any, //< Any kind of method, provided it means other specified criteria.
4294 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4295 MK_OneArgSelector //< One-argument selector.
4296};
4297
Douglas Gregor458433d2010-08-26 15:07:07 +00004298static bool isAcceptableObjCSelector(Selector Sel,
4299 ObjCMethodKind WantKind,
4300 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004301 unsigned NumSelIdents,
4302 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004303 if (NumSelIdents > Sel.getNumArgs())
4304 return false;
4305
4306 switch (WantKind) {
4307 case MK_Any: break;
4308 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4309 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4310 }
4311
Douglas Gregorcf544262010-11-17 21:36:08 +00004312 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4313 return false;
4314
Douglas Gregor458433d2010-08-26 15:07:07 +00004315 for (unsigned I = 0; I != NumSelIdents; ++I)
4316 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4317 return false;
4318
4319 return true;
4320}
4321
Douglas Gregor4ad96852009-11-19 07:41:15 +00004322static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4323 ObjCMethodKind WantKind,
4324 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004325 unsigned NumSelIdents,
4326 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004327 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004328 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004329}
Douglas Gregord36adf52010-09-16 16:06:31 +00004330
4331namespace {
4332 /// \brief A set of selectors, which is used to avoid introducing multiple
4333 /// completions with the same selector into the result set.
4334 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4335}
4336
Douglas Gregor36ecb042009-11-17 23:22:23 +00004337/// \brief Add all of the Objective-C methods in the given Objective-C
4338/// container to the set of results.
4339///
4340/// The container will be a class, protocol, category, or implementation of
4341/// any of the above. This mether will recurse to include methods from
4342/// the superclasses of classes along with their categories, protocols, and
4343/// implementations.
4344///
4345/// \param Container the container in which we'll look to find methods.
4346///
4347/// \param WantInstance whether to add instance methods (only); if false, this
4348/// routine will add factory methods (only).
4349///
4350/// \param CurContext the context in which we're performing the lookup that
4351/// finds methods.
4352///
Douglas Gregorcf544262010-11-17 21:36:08 +00004353/// \param AllowSameLength Whether we allow a method to be added to the list
4354/// when it has the same number of parameters as we have selector identifiers.
4355///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004356/// \param Results the structure into which we'll add results.
4357static void AddObjCMethods(ObjCContainerDecl *Container,
4358 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004359 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004360 IdentifierInfo **SelIdents,
4361 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004362 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004363 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004364 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004365 ResultBuilder &Results,
4366 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004367 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004368 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4369 MEnd = Container->meth_end();
4370 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004371 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4372 // Check whether the selector identifiers we've been given are a
4373 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004374 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4375 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004376 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004377
Douglas Gregord36adf52010-09-16 16:06:31 +00004378 if (!Selectors.insert((*M)->getSelector()))
4379 continue;
4380
Douglas Gregord3c68542009-11-19 01:08:35 +00004381 Result R = Result(*M, 0);
4382 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004383 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004384 if (!InOriginalClass)
4385 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004386 Results.MaybeAddResult(R, CurContext);
4387 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004388 }
4389
Douglas Gregore396c7b2010-09-16 15:34:59 +00004390 // Visit the protocols of protocols.
4391 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4392 const ObjCList<ObjCProtocolDecl> &Protocols
4393 = Protocol->getReferencedProtocols();
4394 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4395 E = Protocols.end();
4396 I != E; ++I)
4397 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004398 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004399 }
4400
Douglas Gregor36ecb042009-11-17 23:22:23 +00004401 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4402 if (!IFace)
4403 return;
4404
4405 // Add methods in protocols.
4406 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4407 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4408 E = Protocols.end();
4409 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004410 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004411 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004412
4413 // Add methods in categories.
4414 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4415 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004416 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004417 NumSelIdents, CurContext, Selectors, AllowSameLength,
4418 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004419
4420 // Add a categories protocol methods.
4421 const ObjCList<ObjCProtocolDecl> &Protocols
4422 = CatDecl->getReferencedProtocols();
4423 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4424 E = Protocols.end();
4425 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004426 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004427 NumSelIdents, CurContext, Selectors, AllowSameLength,
4428 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004429
4430 // Add methods in category implementations.
4431 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004432 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004433 NumSelIdents, CurContext, Selectors, AllowSameLength,
4434 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004435 }
4436
4437 // Add methods in superclass.
4438 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004439 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004440 SelIdents, NumSelIdents, CurContext, Selectors,
4441 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004442
4443 // Add methods in our implementation, if any.
4444 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004445 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004446 NumSelIdents, CurContext, Selectors, AllowSameLength,
4447 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004448}
4449
4450
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004451void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004452 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004453
4454 // Try to find the interface where getters might live.
John McCalld226f652010-08-21 09:40:31 +00004455 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004456 if (!Class) {
4457 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004458 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004459 Class = Category->getClassInterface();
4460
4461 if (!Class)
4462 return;
4463 }
4464
4465 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004466 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4467 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004468 Results.EnterNewScope();
4469
Douglas Gregord36adf52010-09-16 16:06:31 +00004470 VisitedSelectorSet Selectors;
4471 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004472 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004473 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004474 HandleCodeCompleteResults(this, CodeCompleter,
4475 CodeCompletionContext::CCC_Other,
4476 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004477}
4478
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004479void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004480 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004481
4482 // Try to find the interface where setters might live.
4483 ObjCInterfaceDecl *Class
John McCalld226f652010-08-21 09:40:31 +00004484 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004485 if (!Class) {
4486 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004487 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004488 Class = Category->getClassInterface();
4489
4490 if (!Class)
4491 return;
4492 }
4493
4494 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004495 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4496 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004497 Results.EnterNewScope();
4498
Douglas Gregord36adf52010-09-16 16:06:31 +00004499 VisitedSelectorSet Selectors;
4500 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004501 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004502
4503 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004504 HandleCodeCompleteResults(this, CodeCompleter,
4505 CodeCompletionContext::CCC_Other,
4506 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004507}
4508
Douglas Gregorafc45782011-02-15 22:19:42 +00004509void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4510 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004511 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004512 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4513 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004514 Results.EnterNewScope();
4515
4516 // Add context-sensitive, Objective-C parameter-passing keywords.
4517 bool AddedInOut = false;
4518 if ((DS.getObjCDeclQualifier() &
4519 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4520 Results.AddResult("in");
4521 Results.AddResult("inout");
4522 AddedInOut = true;
4523 }
4524 if ((DS.getObjCDeclQualifier() &
4525 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4526 Results.AddResult("out");
4527 if (!AddedInOut)
4528 Results.AddResult("inout");
4529 }
4530 if ((DS.getObjCDeclQualifier() &
4531 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4532 ObjCDeclSpec::DQ_Oneway)) == 0) {
4533 Results.AddResult("bycopy");
4534 Results.AddResult("byref");
4535 Results.AddResult("oneway");
4536 }
4537
Douglas Gregorafc45782011-02-15 22:19:42 +00004538 // If we're completing the return type of an Objective-C method and the
4539 // identifier IBAction refers to a macro, provide a completion item for
4540 // an action, e.g.,
4541 // IBAction)<#selector#>:(id)sender
4542 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4543 Context.Idents.get("IBAction").hasMacroDefinition()) {
4544 typedef CodeCompletionString::Chunk Chunk;
4545 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4546 CXAvailability_Available);
4547 Builder.AddTypedTextChunk("IBAction");
4548 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4549 Builder.AddPlaceholderChunk("selector");
4550 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4551 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4552 Builder.AddTextChunk("id");
4553 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4554 Builder.AddTextChunk("sender");
4555 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4556 }
4557
Douglas Gregord32b0222010-08-24 01:06:58 +00004558 // Add various builtin type names and specifiers.
4559 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4560 Results.ExitScope();
4561
4562 // Add the various type names
4563 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4564 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4565 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4566 CodeCompleter->includeGlobals());
4567
4568 if (CodeCompleter->includeMacros())
4569 AddMacroResults(PP, Results);
4570
4571 HandleCodeCompleteResults(this, CodeCompleter,
4572 CodeCompletionContext::CCC_Type,
4573 Results.data(), Results.size());
4574}
4575
Douglas Gregor22f56992010-04-06 19:22:33 +00004576/// \brief When we have an expression with type "id", we may assume
4577/// that it has some more-specific class type based on knowledge of
4578/// common uses of Objective-C. This routine returns that class type,
4579/// or NULL if no better result could be determined.
4580static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004581 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004582 if (!Msg)
4583 return 0;
4584
4585 Selector Sel = Msg->getSelector();
4586 if (Sel.isNull())
4587 return 0;
4588
4589 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4590 if (!Id)
4591 return 0;
4592
4593 ObjCMethodDecl *Method = Msg->getMethodDecl();
4594 if (!Method)
4595 return 0;
4596
4597 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004598 ObjCInterfaceDecl *IFace = 0;
4599 switch (Msg->getReceiverKind()) {
4600 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004601 if (const ObjCObjectType *ObjType
4602 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4603 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004604 break;
4605
4606 case ObjCMessageExpr::Instance: {
4607 QualType T = Msg->getInstanceReceiver()->getType();
4608 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4609 IFace = Ptr->getInterfaceDecl();
4610 break;
4611 }
4612
4613 case ObjCMessageExpr::SuperInstance:
4614 case ObjCMessageExpr::SuperClass:
4615 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004616 }
4617
4618 if (!IFace)
4619 return 0;
4620
4621 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4622 if (Method->isInstanceMethod())
4623 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4624 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004625 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004626 .Case("autorelease", IFace)
4627 .Case("copy", IFace)
4628 .Case("copyWithZone", IFace)
4629 .Case("mutableCopy", IFace)
4630 .Case("mutableCopyWithZone", IFace)
4631 .Case("awakeFromCoder", IFace)
4632 .Case("replacementObjectFromCoder", IFace)
4633 .Case("class", IFace)
4634 .Case("classForCoder", IFace)
4635 .Case("superclass", Super)
4636 .Default(0);
4637
4638 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4639 .Case("new", IFace)
4640 .Case("alloc", IFace)
4641 .Case("allocWithZone", IFace)
4642 .Case("class", IFace)
4643 .Case("superclass", Super)
4644 .Default(0);
4645}
4646
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004647// Add a special completion for a message send to "super", which fills in the
4648// most likely case of forwarding all of our arguments to the superclass
4649// function.
4650///
4651/// \param S The semantic analysis object.
4652///
4653/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4654/// the "super" keyword. Otherwise, we just need to provide the arguments.
4655///
4656/// \param SelIdents The identifiers in the selector that have already been
4657/// provided as arguments for a send to "super".
4658///
4659/// \param NumSelIdents The number of identifiers in \p SelIdents.
4660///
4661/// \param Results The set of results to augment.
4662///
4663/// \returns the Objective-C method declaration that would be invoked by
4664/// this "super" completion. If NULL, no completion was added.
4665static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4666 IdentifierInfo **SelIdents,
4667 unsigned NumSelIdents,
4668 ResultBuilder &Results) {
4669 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4670 if (!CurMethod)
4671 return 0;
4672
4673 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4674 if (!Class)
4675 return 0;
4676
4677 // Try to find a superclass method with the same selector.
4678 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004679 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4680 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004681 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4682 CurMethod->isInstanceMethod());
4683
Douglas Gregor78bcd912011-02-16 00:51:18 +00004684 // Check in categories or class extensions.
4685 if (!SuperMethod) {
4686 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4687 Category = Category->getNextClassCategory())
4688 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4689 CurMethod->isInstanceMethod())))
4690 break;
4691 }
4692 }
4693
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004694 if (!SuperMethod)
4695 return 0;
4696
4697 // Check whether the superclass method has the same signature.
4698 if (CurMethod->param_size() != SuperMethod->param_size() ||
4699 CurMethod->isVariadic() != SuperMethod->isVariadic())
4700 return 0;
4701
4702 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4703 CurPEnd = CurMethod->param_end(),
4704 SuperP = SuperMethod->param_begin();
4705 CurP != CurPEnd; ++CurP, ++SuperP) {
4706 // Make sure the parameter types are compatible.
4707 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4708 (*SuperP)->getType()))
4709 return 0;
4710
4711 // Make sure we have a parameter name to forward!
4712 if (!(*CurP)->getIdentifier())
4713 return 0;
4714 }
4715
4716 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004717 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004718
4719 // Give this completion a return type.
Douglas Gregor218937c2011-02-01 19:23:04 +00004720 AddResultTypeChunk(S.Context, SuperMethod, Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004721
4722 // If we need the "super" keyword, add it (plus some spacing).
4723 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004724 Builder.AddTypedTextChunk("super");
4725 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004726 }
4727
4728 Selector Sel = CurMethod->getSelector();
4729 if (Sel.isUnarySelector()) {
4730 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004731 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004732 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004733 else
Douglas Gregordae68752011-02-01 22:57:45 +00004734 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004735 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004736 } else {
4737 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4738 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4739 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004740 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004741
4742 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004743 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004744 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004745 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004746 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004747 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004748 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004749 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004750 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004751 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004752 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004753 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004754 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004755 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004756 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004757 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004758 }
4759 }
4760 }
4761
Douglas Gregor218937c2011-02-01 19:23:04 +00004762 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004763 SuperMethod->isInstanceMethod()
4764 ? CXCursor_ObjCInstanceMethodDecl
4765 : CXCursor_ObjCClassMethodDecl));
4766 return SuperMethod;
4767}
4768
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004769void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004770 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004771 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4772 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004773 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004774
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004775 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4776 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004777 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4778 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004779
4780 // If we are in an Objective-C method inside a class that has a superclass,
4781 // add "super" as an option.
4782 if (ObjCMethodDecl *Method = getCurMethodDecl())
4783 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004784 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004785 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004786
4787 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4788 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004789
4790 Results.ExitScope();
4791
4792 if (CodeCompleter->includeMacros())
4793 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004794 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004795 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004796
4797}
4798
Douglas Gregor2725ca82010-04-21 19:57:20 +00004799void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4800 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004801 unsigned NumSelIdents,
4802 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004803 ObjCInterfaceDecl *CDecl = 0;
4804 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4805 // Figure out which interface we're in.
4806 CDecl = CurMethod->getClassInterface();
4807 if (!CDecl)
4808 return;
4809
4810 // Find the superclass of this class.
4811 CDecl = CDecl->getSuperClass();
4812 if (!CDecl)
4813 return;
4814
4815 if (CurMethod->isInstanceMethod()) {
4816 // We are inside an instance method, which means that the message
4817 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004818 // current object.
4819 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004820 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004821 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004822 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004823 }
4824
4825 // Fall through to send to the superclass in CDecl.
4826 } else {
4827 // "super" may be the name of a type or variable. Figure out which
4828 // it is.
4829 IdentifierInfo *Super = &Context.Idents.get("super");
4830 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4831 LookupOrdinaryName);
4832 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4833 // "super" names an interface. Use it.
4834 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004835 if (const ObjCObjectType *Iface
4836 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4837 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004838 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4839 // "super" names an unresolved type; we can't be more specific.
4840 } else {
4841 // Assume that "super" names some kind of value and parse that way.
4842 CXXScopeSpec SS;
4843 UnqualifiedId id;
4844 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004845 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004846 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004847 SelIdents, NumSelIdents,
4848 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004849 }
4850
4851 // Fall through
4852 }
4853
John McCallb3d87482010-08-24 05:47:05 +00004854 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004855 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004856 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004857 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004858 NumSelIdents, AtArgumentExpression,
4859 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004860}
4861
Douglas Gregorb9d77572010-09-21 00:03:25 +00004862/// \brief Given a set of code-completion results for the argument of a message
4863/// send, determine the preferred type (if any) for that argument expression.
4864static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4865 unsigned NumSelIdents) {
4866 typedef CodeCompletionResult Result;
4867 ASTContext &Context = Results.getSema().Context;
4868
4869 QualType PreferredType;
4870 unsigned BestPriority = CCP_Unlikely * 2;
4871 Result *ResultsData = Results.data();
4872 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4873 Result &R = ResultsData[I];
4874 if (R.Kind == Result::RK_Declaration &&
4875 isa<ObjCMethodDecl>(R.Declaration)) {
4876 if (R.Priority <= BestPriority) {
4877 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4878 if (NumSelIdents <= Method->param_size()) {
4879 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4880 ->getType();
4881 if (R.Priority < BestPriority || PreferredType.isNull()) {
4882 BestPriority = R.Priority;
4883 PreferredType = MyPreferredType;
4884 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4885 MyPreferredType)) {
4886 PreferredType = QualType();
4887 }
4888 }
4889 }
4890 }
4891 }
4892
4893 return PreferredType;
4894}
4895
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004896static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4897 ParsedType Receiver,
4898 IdentifierInfo **SelIdents,
4899 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004900 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004901 bool IsSuper,
4902 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004903 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004904 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004905
Douglas Gregor24a069f2009-11-17 17:59:40 +00004906 // If the given name refers to an interface type, retrieve the
4907 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004908 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004909 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004910 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004911 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4912 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004913 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004914
Douglas Gregor36ecb042009-11-17 23:22:23 +00004915 // Add all of the factory methods in this Objective-C class, its protocols,
4916 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004917 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004918
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004919 // If this is a send-to-super, try to add the special "super" send
4920 // completion.
4921 if (IsSuper) {
4922 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004923 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4924 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004925 Results.Ignore(SuperMethod);
4926 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004927
Douglas Gregor265f7492010-08-27 15:29:55 +00004928 // If we're inside an Objective-C method definition, prefer its selector to
4929 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004930 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00004931 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004932
Douglas Gregord36adf52010-09-16 16:06:31 +00004933 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00004934 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004935 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004936 SemaRef.CurContext, Selectors, AtArgumentExpression,
4937 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004938 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00004939 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004940
Douglas Gregor719770d2010-04-06 17:30:22 +00004941 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004942 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004943 if (SemaRef.ExternalSource) {
4944 for (uint32_t I = 0,
4945 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00004946 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004947 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
4948 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004949 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004950
4951 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004952 }
4953 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004954
4955 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
4956 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00004957 M != MEnd; ++M) {
4958 for (ObjCMethodList *MethList = &M->second.second;
4959 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004960 MethList = MethList->Next) {
4961 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4962 NumSelIdents))
4963 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004964
Douglas Gregor13438f92010-04-06 16:40:00 +00004965 Result R(MethList->Method, 0);
4966 R.StartParameter = NumSelIdents;
4967 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004968 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00004969 }
4970 }
4971 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004972
4973 Results.ExitScope();
4974}
Douglas Gregor13438f92010-04-06 16:40:00 +00004975
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004976void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4977 IdentifierInfo **SelIdents,
4978 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004979 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004980 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00004981
4982 QualType T = this->GetTypeFromParser(Receiver);
4983
Douglas Gregor218937c2011-02-01 19:23:04 +00004984 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00004985 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00004986 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00004987
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004988 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
4989 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00004990
4991 // If we're actually at the argument expression (rather than prior to the
4992 // selector), we're actually performing code completion for an expression.
4993 // Determine whether we have a single, best method. If so, we can
4994 // code-complete the expression using the corresponding parameter type as
4995 // our preferred type, improving completion results.
4996 if (AtArgumentExpression) {
4997 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00004998 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00004999 if (PreferredType.isNull())
5000 CodeCompleteOrdinaryName(S, PCC_Expression);
5001 else
5002 CodeCompleteExpression(S, PreferredType);
5003 return;
5004 }
5005
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005006 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005007 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005008 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005009}
5010
Douglas Gregord3c68542009-11-19 01:08:35 +00005011void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
5012 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005013 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005014 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005015 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005016 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005017
5018 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005019
Douglas Gregor36ecb042009-11-17 23:22:23 +00005020 // If necessary, apply function/array conversion to the receiver.
5021 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005022 if (RecExpr) {
5023 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5024 if (Conv.isInvalid()) // conversion failed. bail.
5025 return;
5026 RecExpr = Conv.take();
5027 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005028 QualType ReceiverType = RecExpr? RecExpr->getType()
5029 : Super? Context.getObjCObjectPointerType(
5030 Context.getObjCInterfaceType(Super))
5031 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005032
Douglas Gregorda892642010-11-08 21:12:30 +00005033 // If we're messaging an expression with type "id" or "Class", check
5034 // whether we know something special about the receiver that allows
5035 // us to assume a more-specific receiver type.
5036 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5037 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5038 if (ReceiverType->isObjCClassType())
5039 return CodeCompleteObjCClassMessage(S,
5040 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5041 SelIdents, NumSelIdents,
5042 AtArgumentExpression, Super);
5043
5044 ReceiverType = Context.getObjCObjectPointerType(
5045 Context.getObjCInterfaceType(IFace));
5046 }
5047
Douglas Gregor36ecb042009-11-17 23:22:23 +00005048 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005049 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005050 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005051 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005052
Douglas Gregor36ecb042009-11-17 23:22:23 +00005053 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005054
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005055 // If this is a send-to-super, try to add the special "super" send
5056 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005057 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005058 if (ObjCMethodDecl *SuperMethod
5059 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5060 Results))
5061 Results.Ignore(SuperMethod);
5062 }
5063
Douglas Gregor265f7492010-08-27 15:29:55 +00005064 // If we're inside an Objective-C method definition, prefer its selector to
5065 // others.
5066 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5067 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005068
Douglas Gregord36adf52010-09-16 16:06:31 +00005069 // Keep track of the selectors we've already added.
5070 VisitedSelectorSet Selectors;
5071
Douglas Gregorf74a4192009-11-18 00:06:18 +00005072 // Handle messages to Class. This really isn't a message to an instance
5073 // method, so we treat it the same way we would treat a message send to a
5074 // class method.
5075 if (ReceiverType->isObjCClassType() ||
5076 ReceiverType->isObjCQualifiedClassType()) {
5077 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5078 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005079 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005080 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005081 }
5082 }
5083 // Handle messages to a qualified ID ("id<foo>").
5084 else if (const ObjCObjectPointerType *QualID
5085 = ReceiverType->getAsObjCQualifiedIdType()) {
5086 // Search protocols for instance methods.
5087 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5088 E = QualID->qual_end();
5089 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005090 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005091 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005092 }
5093 // Handle messages to a pointer to interface type.
5094 else if (const ObjCObjectPointerType *IFacePtr
5095 = ReceiverType->getAsObjCInterfacePointerType()) {
5096 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005097 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005098 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5099 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005100
5101 // Search protocols for instance methods.
5102 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5103 E = IFacePtr->qual_end();
5104 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005105 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005106 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005107 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005108 // Handle messages to "id".
5109 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005110 // We're messaging "id", so provide all instance methods we know
5111 // about as code-completion results.
5112
5113 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005114 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005115 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005116 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5117 I != N; ++I) {
5118 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005119 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005120 continue;
5121
Sebastian Redldb9d2142010-08-02 23:18:59 +00005122 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005123 }
5124 }
5125
Sebastian Redldb9d2142010-08-02 23:18:59 +00005126 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5127 MEnd = MethodPool.end();
5128 M != MEnd; ++M) {
5129 for (ObjCMethodList *MethList = &M->second.first;
5130 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005131 MethList = MethList->Next) {
5132 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5133 NumSelIdents))
5134 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005135
5136 if (!Selectors.insert(MethList->Method->getSelector()))
5137 continue;
5138
Douglas Gregor13438f92010-04-06 16:40:00 +00005139 Result R(MethList->Method, 0);
5140 R.StartParameter = NumSelIdents;
5141 R.AllParametersAreInformative = false;
5142 Results.MaybeAddResult(R, CurContext);
5143 }
5144 }
5145 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005146 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005147
5148
5149 // If we're actually at the argument expression (rather than prior to the
5150 // selector), we're actually performing code completion for an expression.
5151 // Determine whether we have a single, best method. If so, we can
5152 // code-complete the expression using the corresponding parameter type as
5153 // our preferred type, improving completion results.
5154 if (AtArgumentExpression) {
5155 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5156 NumSelIdents);
5157 if (PreferredType.isNull())
5158 CodeCompleteOrdinaryName(S, PCC_Expression);
5159 else
5160 CodeCompleteExpression(S, PreferredType);
5161 return;
5162 }
5163
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005164 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005165 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005166 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005167}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005168
Douglas Gregorfb629412010-08-23 21:17:50 +00005169void Sema::CodeCompleteObjCForCollection(Scope *S,
5170 DeclGroupPtrTy IterationVar) {
5171 CodeCompleteExpressionData Data;
5172 Data.ObjCCollection = true;
5173
5174 if (IterationVar.getAsOpaquePtr()) {
5175 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5176 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5177 if (*I)
5178 Data.IgnoreDecls.push_back(*I);
5179 }
5180 }
5181
5182 CodeCompleteExpression(S, Data);
5183}
5184
Douglas Gregor458433d2010-08-26 15:07:07 +00005185void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5186 unsigned NumSelIdents) {
5187 // If we have an external source, load the entire class method
5188 // pool from the AST file.
5189 if (ExternalSource) {
5190 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5191 I != N; ++I) {
5192 Selector Sel = ExternalSource->GetExternalSelector(I);
5193 if (Sel.isNull() || MethodPool.count(Sel))
5194 continue;
5195
5196 ReadMethodPool(Sel);
5197 }
5198 }
5199
Douglas Gregor218937c2011-02-01 19:23:04 +00005200 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5201 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005202 Results.EnterNewScope();
5203 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5204 MEnd = MethodPool.end();
5205 M != MEnd; ++M) {
5206
5207 Selector Sel = M->first;
5208 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5209 continue;
5210
Douglas Gregor218937c2011-02-01 19:23:04 +00005211 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005212 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005213 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005214 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005215 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005216 continue;
5217 }
5218
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005219 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005220 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005221 if (I == NumSelIdents) {
5222 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005223 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005224 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005225 Accumulator.clear();
5226 }
5227 }
5228
Benjamin Kramera0651c52011-07-26 16:59:25 +00005229 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005230 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005231 }
Douglas Gregordae68752011-02-01 22:57:45 +00005232 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005233 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005234 }
5235 Results.ExitScope();
5236
5237 HandleCodeCompleteResults(this, CodeCompleter,
5238 CodeCompletionContext::CCC_SelectorName,
5239 Results.data(), Results.size());
5240}
5241
Douglas Gregor55385fe2009-11-18 04:19:12 +00005242/// \brief Add all of the protocol declarations that we find in the given
5243/// (translation unit) context.
5244static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005245 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005246 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005247 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005248
5249 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5250 DEnd = Ctx->decls_end();
5251 D != DEnd; ++D) {
5252 // Record any protocols we find.
5253 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005254 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005255 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005256
5257 // Record any forward-declared protocols we find.
5258 if (ObjCForwardProtocolDecl *Forward
5259 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5260 for (ObjCForwardProtocolDecl::protocol_iterator
5261 P = Forward->protocol_begin(),
5262 PEnd = Forward->protocol_end();
5263 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005264 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005265 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005266 }
5267 }
5268}
5269
5270void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5271 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005272 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5273 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005274
Douglas Gregor70c23352010-12-09 21:44:02 +00005275 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5276 Results.EnterNewScope();
5277
5278 // Tell the result set to ignore all of the protocols we have
5279 // already seen.
5280 // FIXME: This doesn't work when caching code-completion results.
5281 for (unsigned I = 0; I != NumProtocols; ++I)
5282 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5283 Protocols[I].second))
5284 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005285
Douglas Gregor70c23352010-12-09 21:44:02 +00005286 // Add all protocols.
5287 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5288 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005289
Douglas Gregor70c23352010-12-09 21:44:02 +00005290 Results.ExitScope();
5291 }
5292
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005293 HandleCodeCompleteResults(this, CodeCompleter,
5294 CodeCompletionContext::CCC_ObjCProtocolName,
5295 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005296}
5297
5298void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005299 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5300 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005301
Douglas Gregor70c23352010-12-09 21:44:02 +00005302 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5303 Results.EnterNewScope();
5304
5305 // Add all protocols.
5306 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5307 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005308
Douglas Gregor70c23352010-12-09 21:44:02 +00005309 Results.ExitScope();
5310 }
5311
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005312 HandleCodeCompleteResults(this, CodeCompleter,
5313 CodeCompletionContext::CCC_ObjCProtocolName,
5314 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005315}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005316
5317/// \brief Add all of the Objective-C interface declarations that we find in
5318/// the given (translation unit) context.
5319static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5320 bool OnlyForwardDeclarations,
5321 bool OnlyUnimplemented,
5322 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005323 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005324
5325 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5326 DEnd = Ctx->decls_end();
5327 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005328 // Record any interfaces we find.
5329 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5330 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5331 (!OnlyUnimplemented || !Class->getImplementation()))
5332 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005333
5334 // Record any forward-declared interfaces we find.
5335 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
5336 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005337 C != CEnd; ++C)
5338 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
5339 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
5340 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00005341 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005342 }
5343 }
5344}
5345
5346void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005347 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5348 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005349 Results.EnterNewScope();
5350
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005351 if (CodeCompleter->includeGlobals()) {
5352 // Add all classes.
5353 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5354 false, Results);
5355 }
5356
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005357 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005358
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005359 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005360 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005361 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005362}
5363
Douglas Gregorc83c6872010-04-15 22:33:43 +00005364void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5365 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005366 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005367 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005368 Results.EnterNewScope();
5369
5370 // Make sure that we ignore the class we're currently defining.
5371 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005372 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005373 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005374 Results.Ignore(CurClass);
5375
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005376 if (CodeCompleter->includeGlobals()) {
5377 // Add all classes.
5378 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5379 false, Results);
5380 }
5381
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005382 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005383
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005384 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005385 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005386 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005387}
5388
5389void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005390 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5391 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005392 Results.EnterNewScope();
5393
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005394 if (CodeCompleter->includeGlobals()) {
5395 // Add all unimplemented classes.
5396 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5397 true, Results);
5398 }
5399
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005400 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005401
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005402 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005403 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005404 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005405}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005406
5407void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005408 IdentifierInfo *ClassName,
5409 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005410 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005411
Douglas Gregor218937c2011-02-01 19:23:04 +00005412 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005413 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005414
5415 // Ignore any categories we find that have already been implemented by this
5416 // interface.
5417 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5418 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005419 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005420 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5421 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5422 Category = Category->getNextClassCategory())
5423 CategoryNames.insert(Category->getIdentifier());
5424
5425 // Add all of the categories we know about.
5426 Results.EnterNewScope();
5427 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5428 for (DeclContext::decl_iterator D = TU->decls_begin(),
5429 DEnd = TU->decls_end();
5430 D != DEnd; ++D)
5431 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5432 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005433 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005434 Results.ExitScope();
5435
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005436 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005437 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005438 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005439}
5440
5441void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005442 IdentifierInfo *ClassName,
5443 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005444 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005445
5446 // Find the corresponding interface. If we couldn't find the interface, the
5447 // program itself is ill-formed. However, we'll try to be helpful still by
5448 // providing the list of all of the categories we know about.
5449 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005450 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005451 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5452 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005453 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005454
Douglas Gregor218937c2011-02-01 19:23:04 +00005455 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005456 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005457
5458 // Add all of the categories that have have corresponding interface
5459 // declarations in this class and any of its superclasses, except for
5460 // already-implemented categories in the class itself.
5461 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5462 Results.EnterNewScope();
5463 bool IgnoreImplemented = true;
5464 while (Class) {
5465 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5466 Category = Category->getNextClassCategory())
5467 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5468 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005469 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005470
5471 Class = Class->getSuperClass();
5472 IgnoreImplemented = false;
5473 }
5474 Results.ExitScope();
5475
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005476 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005477 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005478 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005479}
Douglas Gregor322328b2009-11-18 22:32:06 +00005480
John McCalld226f652010-08-21 09:40:31 +00005481void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005482 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005483 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5484 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005485
5486 // Figure out where this @synthesize lives.
5487 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005488 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005489 if (!Container ||
5490 (!isa<ObjCImplementationDecl>(Container) &&
5491 !isa<ObjCCategoryImplDecl>(Container)))
5492 return;
5493
5494 // Ignore any properties that have already been implemented.
5495 for (DeclContext::decl_iterator D = Container->decls_begin(),
5496 DEnd = Container->decls_end();
5497 D != DEnd; ++D)
5498 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5499 Results.Ignore(PropertyImpl->getPropertyDecl());
5500
5501 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005502 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005503 Results.EnterNewScope();
5504 if (ObjCImplementationDecl *ClassImpl
5505 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005506 AddObjCProperties(ClassImpl->getClassInterface(), false,
5507 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005508 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005509 else
5510 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005511 false, /*AllowNullaryMethods=*/false, CurContext,
5512 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005513 Results.ExitScope();
5514
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005515 HandleCodeCompleteResults(this, CodeCompleter,
5516 CodeCompletionContext::CCC_Other,
5517 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005518}
5519
5520void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5521 IdentifierInfo *PropertyName,
John McCalld226f652010-08-21 09:40:31 +00005522 Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005523 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005524 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5525 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005526
5527 // Figure out where this @synthesize lives.
5528 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005529 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005530 if (!Container ||
5531 (!isa<ObjCImplementationDecl>(Container) &&
5532 !isa<ObjCCategoryImplDecl>(Container)))
5533 return;
5534
5535 // Figure out which interface we're looking into.
5536 ObjCInterfaceDecl *Class = 0;
5537 if (ObjCImplementationDecl *ClassImpl
5538 = dyn_cast<ObjCImplementationDecl>(Container))
5539 Class = ClassImpl->getClassInterface();
5540 else
5541 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5542 ->getClassInterface();
5543
Douglas Gregore8426052011-04-18 14:40:46 +00005544 // Determine the type of the property we're synthesizing.
5545 QualType PropertyType = Context.getObjCIdType();
5546 if (Class) {
5547 if (ObjCPropertyDecl *Property
5548 = Class->FindPropertyDeclaration(PropertyName)) {
5549 PropertyType
5550 = Property->getType().getNonReferenceType().getUnqualifiedType();
5551
5552 // Give preference to ivars
5553 Results.setPreferredType(PropertyType);
5554 }
5555 }
5556
Douglas Gregor322328b2009-11-18 22:32:06 +00005557 // Add all of the instance variables in this class and its superclasses.
5558 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005559 bool SawSimilarlyNamedIvar = false;
5560 std::string NameWithPrefix;
5561 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005562 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005563 std::string NameWithSuffix = PropertyName->getName().str();
5564 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005565 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005566 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5567 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005568 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5569
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005570 // Determine whether we've seen an ivar with a name similar to the
5571 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005572 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005573 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005574 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005575 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005576
5577 // Reduce the priority of this result by one, to give it a slight
5578 // advantage over other results whose names don't match so closely.
5579 if (Results.size() &&
5580 Results.data()[Results.size() - 1].Kind
5581 == CodeCompletionResult::RK_Declaration &&
5582 Results.data()[Results.size() - 1].Declaration == Ivar)
5583 Results.data()[Results.size() - 1].Priority--;
5584 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005585 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005586 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005587
5588 if (!SawSimilarlyNamedIvar) {
5589 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005590 // an ivar of the appropriate type.
5591 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005592 typedef CodeCompletionResult Result;
5593 CodeCompletionAllocator &Allocator = Results.getAllocator();
5594 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5595
Douglas Gregore8426052011-04-18 14:40:46 +00005596 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
5597 Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005598 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5599 Results.AddResult(Result(Builder.TakeString(), Priority,
5600 CXCursor_ObjCIvarDecl));
5601 }
5602
Douglas Gregor322328b2009-11-18 22:32:06 +00005603 Results.ExitScope();
5604
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005605 HandleCodeCompleteResults(this, CodeCompleter,
5606 CodeCompletionContext::CCC_Other,
5607 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005608}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005609
Douglas Gregor408be5a2010-08-25 01:08:01 +00005610// Mapping from selectors to the methods that implement that selector, along
5611// with the "in original class" flag.
5612typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5613 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005614
5615/// \brief Find all of the methods that reside in the given container
5616/// (and its superclasses, protocols, etc.) that meet the given
5617/// criteria. Insert those methods into the map of known methods,
5618/// indexed by selector so they can be easily found.
5619static void FindImplementableMethods(ASTContext &Context,
5620 ObjCContainerDecl *Container,
5621 bool WantInstanceMethods,
5622 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005623 KnownMethodsMap &KnownMethods,
5624 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005625 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5626 // Recurse into protocols.
5627 const ObjCList<ObjCProtocolDecl> &Protocols
5628 = IFace->getReferencedProtocols();
5629 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005630 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005631 I != E; ++I)
5632 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005633 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005634
Douglas Gregorea766182010-10-18 18:21:28 +00005635 // Add methods from any class extensions and categories.
5636 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5637 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005638 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5639 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005640 KnownMethods, false);
5641
5642 // Visit the superclass.
5643 if (IFace->getSuperClass())
5644 FindImplementableMethods(Context, IFace->getSuperClass(),
5645 WantInstanceMethods, ReturnType,
5646 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005647 }
5648
5649 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5650 // Recurse into protocols.
5651 const ObjCList<ObjCProtocolDecl> &Protocols
5652 = Category->getReferencedProtocols();
5653 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005654 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005655 I != E; ++I)
5656 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005657 KnownMethods, InOriginalClass);
5658
5659 // If this category is the original class, jump to the interface.
5660 if (InOriginalClass && Category->getClassInterface())
5661 FindImplementableMethods(Context, Category->getClassInterface(),
5662 WantInstanceMethods, ReturnType, KnownMethods,
5663 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005664 }
5665
5666 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5667 // Recurse into protocols.
5668 const ObjCList<ObjCProtocolDecl> &Protocols
5669 = Protocol->getReferencedProtocols();
5670 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5671 E = Protocols.end();
5672 I != E; ++I)
5673 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005674 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005675 }
5676
5677 // Add methods in this container. This operation occurs last because
5678 // we want the methods from this container to override any methods
5679 // we've previously seen with the same selector.
5680 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5681 MEnd = Container->meth_end();
5682 M != MEnd; ++M) {
5683 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5684 if (!ReturnType.isNull() &&
5685 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5686 continue;
5687
Douglas Gregor408be5a2010-08-25 01:08:01 +00005688 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005689 }
5690 }
5691}
5692
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005693/// \brief Add the parenthesized return or parameter type chunk to a code
5694/// completion string.
5695static void AddObjCPassingTypeChunk(QualType Type,
5696 ASTContext &Context,
5697 CodeCompletionBuilder &Builder) {
5698 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5699 Builder.AddTextChunk(GetCompletionTypeString(Type, Context,
5700 Builder.getAllocator()));
5701 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5702}
5703
5704/// \brief Determine whether the given class is or inherits from a class by
5705/// the given name.
5706static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005707 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005708 if (!Class)
5709 return false;
5710
5711 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5712 return true;
5713
5714 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5715}
5716
5717/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5718/// Key-Value Observing (KVO).
5719static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5720 bool IsInstanceMethod,
5721 QualType ReturnType,
5722 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005723 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005724 ResultBuilder &Results) {
5725 IdentifierInfo *PropName = Property->getIdentifier();
5726 if (!PropName || PropName->getLength() == 0)
5727 return;
5728
5729
5730 // Builder that will create each code completion.
5731 typedef CodeCompletionResult Result;
5732 CodeCompletionAllocator &Allocator = Results.getAllocator();
5733 CodeCompletionBuilder Builder(Allocator);
5734
5735 // The selector table.
5736 SelectorTable &Selectors = Context.Selectors;
5737
5738 // The property name, copied into the code completion allocation region
5739 // on demand.
5740 struct KeyHolder {
5741 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005742 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005743 const char *CopiedKey;
5744
Chris Lattner5f9e2722011-07-23 10:55:15 +00005745 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005746 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5747
5748 operator const char *() {
5749 if (CopiedKey)
5750 return CopiedKey;
5751
5752 return CopiedKey = Allocator.CopyString(Key);
5753 }
5754 } Key(Allocator, PropName->getName());
5755
5756 // The uppercased name of the property name.
5757 std::string UpperKey = PropName->getName();
5758 if (!UpperKey.empty())
5759 UpperKey[0] = toupper(UpperKey[0]);
5760
5761 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5762 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5763 Property->getType());
5764 bool ReturnTypeMatchesVoid
5765 = ReturnType.isNull() || ReturnType->isVoidType();
5766
5767 // Add the normal accessor -(type)key.
5768 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005769 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005770 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5771 if (ReturnType.isNull())
5772 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5773
5774 Builder.AddTypedTextChunk(Key);
5775 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5776 CXCursor_ObjCInstanceMethodDecl));
5777 }
5778
5779 // If we have an integral or boolean property (or the user has provided
5780 // an integral or boolean return type), add the accessor -(type)isKey.
5781 if (IsInstanceMethod &&
5782 ((!ReturnType.isNull() &&
5783 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5784 (ReturnType.isNull() &&
5785 (Property->getType()->isIntegerType() ||
5786 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005787 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005788 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005789 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005790 if (ReturnType.isNull()) {
5791 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5792 Builder.AddTextChunk("BOOL");
5793 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5794 }
5795
5796 Builder.AddTypedTextChunk(
5797 Allocator.CopyString(SelectorId->getName()));
5798 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5799 CXCursor_ObjCInstanceMethodDecl));
5800 }
5801 }
5802
5803 // Add the normal mutator.
5804 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5805 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005806 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005807 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005808 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005809 if (ReturnType.isNull()) {
5810 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5811 Builder.AddTextChunk("void");
5812 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5813 }
5814
5815 Builder.AddTypedTextChunk(
5816 Allocator.CopyString(SelectorId->getName()));
5817 Builder.AddTypedTextChunk(":");
5818 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5819 Builder.AddTextChunk(Key);
5820 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5821 CXCursor_ObjCInstanceMethodDecl));
5822 }
5823 }
5824
5825 // Indexed and unordered accessors
5826 unsigned IndexedGetterPriority = CCP_CodePattern;
5827 unsigned IndexedSetterPriority = CCP_CodePattern;
5828 unsigned UnorderedGetterPriority = CCP_CodePattern;
5829 unsigned UnorderedSetterPriority = CCP_CodePattern;
5830 if (const ObjCObjectPointerType *ObjCPointer
5831 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5832 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5833 // If this interface type is not provably derived from a known
5834 // collection, penalize the corresponding completions.
5835 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5836 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5837 if (!InheritsFromClassNamed(IFace, "NSArray"))
5838 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5839 }
5840
5841 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5842 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5843 if (!InheritsFromClassNamed(IFace, "NSSet"))
5844 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5845 }
5846 }
5847 } else {
5848 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5849 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5850 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5851 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5852 }
5853
5854 // Add -(NSUInteger)countOf<key>
5855 if (IsInstanceMethod &&
5856 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005857 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005858 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005859 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005860 if (ReturnType.isNull()) {
5861 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5862 Builder.AddTextChunk("NSUInteger");
5863 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5864 }
5865
5866 Builder.AddTypedTextChunk(
5867 Allocator.CopyString(SelectorId->getName()));
5868 Results.AddResult(Result(Builder.TakeString(),
5869 std::min(IndexedGetterPriority,
5870 UnorderedGetterPriority),
5871 CXCursor_ObjCInstanceMethodDecl));
5872 }
5873 }
5874
5875 // Indexed getters
5876 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
5877 if (IsInstanceMethod &&
5878 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005879 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005880 = (Twine("objectIn") + UpperKey + "AtIndex").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("id");
5886 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5887 }
5888
5889 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5890 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5891 Builder.AddTextChunk("NSUInteger");
5892 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5893 Builder.AddTextChunk("index");
5894 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5895 CXCursor_ObjCInstanceMethodDecl));
5896 }
5897 }
5898
5899 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
5900 if (IsInstanceMethod &&
5901 (ReturnType.isNull() ||
5902 (ReturnType->isObjCObjectPointerType() &&
5903 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
5904 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
5905 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005906 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005907 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005908 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005909 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005910 if (ReturnType.isNull()) {
5911 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5912 Builder.AddTextChunk("NSArray *");
5913 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5914 }
5915
5916 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5917 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5918 Builder.AddTextChunk("NSIndexSet *");
5919 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5920 Builder.AddTextChunk("indexes");
5921 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5922 CXCursor_ObjCInstanceMethodDecl));
5923 }
5924 }
5925
5926 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
5927 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005928 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005929 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005930 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005931 &Context.Idents.get("range")
5932 };
5933
Douglas Gregore74c25c2011-05-04 23:50:46 +00005934 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005935 if (ReturnType.isNull()) {
5936 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5937 Builder.AddTextChunk("void");
5938 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5939 }
5940
5941 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5942 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5943 Builder.AddPlaceholderChunk("object-type");
5944 Builder.AddTextChunk(" **");
5945 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5946 Builder.AddTextChunk("buffer");
5947 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5948 Builder.AddTypedTextChunk("range:");
5949 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5950 Builder.AddTextChunk("NSRange");
5951 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5952 Builder.AddTextChunk("inRange");
5953 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5954 CXCursor_ObjCInstanceMethodDecl));
5955 }
5956 }
5957
5958 // Mutable indexed accessors
5959
5960 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
5961 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005962 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005963 IdentifierInfo *SelectorIds[2] = {
5964 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00005965 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005966 };
5967
Douglas Gregore74c25c2011-05-04 23:50:46 +00005968 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005969 if (ReturnType.isNull()) {
5970 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5971 Builder.AddTextChunk("void");
5972 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5973 }
5974
5975 Builder.AddTypedTextChunk("insertObject:");
5976 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5977 Builder.AddPlaceholderChunk("object-type");
5978 Builder.AddTextChunk(" *");
5979 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5980 Builder.AddTextChunk("object");
5981 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5982 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5983 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5984 Builder.AddPlaceholderChunk("NSUInteger");
5985 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5986 Builder.AddTextChunk("index");
5987 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5988 CXCursor_ObjCInstanceMethodDecl));
5989 }
5990 }
5991
5992 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
5993 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005994 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005995 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005996 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005997 &Context.Idents.get("atIndexes")
5998 };
5999
Douglas Gregore74c25c2011-05-04 23:50:46 +00006000 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006001 if (ReturnType.isNull()) {
6002 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6003 Builder.AddTextChunk("void");
6004 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6005 }
6006
6007 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6008 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6009 Builder.AddTextChunk("NSArray *");
6010 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6011 Builder.AddTextChunk("array");
6012 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6013 Builder.AddTypedTextChunk("atIndexes:");
6014 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6015 Builder.AddPlaceholderChunk("NSIndexSet *");
6016 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6017 Builder.AddTextChunk("indexes");
6018 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6019 CXCursor_ObjCInstanceMethodDecl));
6020 }
6021 }
6022
6023 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6024 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006025 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006026 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006027 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006028 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006029 if (ReturnType.isNull()) {
6030 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6031 Builder.AddTextChunk("void");
6032 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6033 }
6034
6035 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6036 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6037 Builder.AddTextChunk("NSUInteger");
6038 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6039 Builder.AddTextChunk("index");
6040 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6041 CXCursor_ObjCInstanceMethodDecl));
6042 }
6043 }
6044
6045 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6046 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006047 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006048 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006049 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006050 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006051 if (ReturnType.isNull()) {
6052 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6053 Builder.AddTextChunk("void");
6054 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6055 }
6056
6057 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6058 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6059 Builder.AddTextChunk("NSIndexSet *");
6060 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6061 Builder.AddTextChunk("indexes");
6062 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6063 CXCursor_ObjCInstanceMethodDecl));
6064 }
6065 }
6066
6067 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6068 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006069 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006070 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006071 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006072 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006073 &Context.Idents.get("withObject")
6074 };
6075
Douglas Gregore74c25c2011-05-04 23:50:46 +00006076 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006077 if (ReturnType.isNull()) {
6078 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6079 Builder.AddTextChunk("void");
6080 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6081 }
6082
6083 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6084 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6085 Builder.AddPlaceholderChunk("NSUInteger");
6086 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6087 Builder.AddTextChunk("index");
6088 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6089 Builder.AddTypedTextChunk("withObject:");
6090 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6091 Builder.AddTextChunk("id");
6092 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6093 Builder.AddTextChunk("object");
6094 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6095 CXCursor_ObjCInstanceMethodDecl));
6096 }
6097 }
6098
6099 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6100 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006101 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006102 = (Twine("replace") + UpperKey + "AtIndexes").str();
6103 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006104 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006105 &Context.Idents.get(SelectorName1),
6106 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006107 };
6108
Douglas Gregore74c25c2011-05-04 23:50:46 +00006109 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006110 if (ReturnType.isNull()) {
6111 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6112 Builder.AddTextChunk("void");
6113 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6114 }
6115
6116 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6117 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6118 Builder.AddPlaceholderChunk("NSIndexSet *");
6119 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6120 Builder.AddTextChunk("indexes");
6121 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6122 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6123 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6124 Builder.AddTextChunk("NSArray *");
6125 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6126 Builder.AddTextChunk("array");
6127 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6128 CXCursor_ObjCInstanceMethodDecl));
6129 }
6130 }
6131
6132 // Unordered getters
6133 // - (NSEnumerator *)enumeratorOfKey
6134 if (IsInstanceMethod &&
6135 (ReturnType.isNull() ||
6136 (ReturnType->isObjCObjectPointerType() &&
6137 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6138 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6139 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006140 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006141 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006142 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006143 if (ReturnType.isNull()) {
6144 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6145 Builder.AddTextChunk("NSEnumerator *");
6146 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6147 }
6148
6149 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6150 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6151 CXCursor_ObjCInstanceMethodDecl));
6152 }
6153 }
6154
6155 // - (type *)memberOfKey:(type *)object
6156 if (IsInstanceMethod &&
6157 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006158 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006159 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006160 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006161 if (ReturnType.isNull()) {
6162 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6163 Builder.AddPlaceholderChunk("object-type");
6164 Builder.AddTextChunk(" *");
6165 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6166 }
6167
6168 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6169 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6170 if (ReturnType.isNull()) {
6171 Builder.AddPlaceholderChunk("object-type");
6172 Builder.AddTextChunk(" *");
6173 } else {
6174 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
6175 Builder.getAllocator()));
6176 }
6177 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6178 Builder.AddTextChunk("object");
6179 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6180 CXCursor_ObjCInstanceMethodDecl));
6181 }
6182 }
6183
6184 // Mutable unordered accessors
6185 // - (void)addKeyObject:(type *)object
6186 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006187 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006188 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006189 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006190 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006191 if (ReturnType.isNull()) {
6192 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6193 Builder.AddTextChunk("void");
6194 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6195 }
6196
6197 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6198 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6199 Builder.AddPlaceholderChunk("object-type");
6200 Builder.AddTextChunk(" *");
6201 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6202 Builder.AddTextChunk("object");
6203 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6204 CXCursor_ObjCInstanceMethodDecl));
6205 }
6206 }
6207
6208 // - (void)addKey:(NSSet *)objects
6209 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006210 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006211 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006212 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006213 if (ReturnType.isNull()) {
6214 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6215 Builder.AddTextChunk("void");
6216 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6217 }
6218
6219 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6220 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6221 Builder.AddTextChunk("NSSet *");
6222 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6223 Builder.AddTextChunk("objects");
6224 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6225 CXCursor_ObjCInstanceMethodDecl));
6226 }
6227 }
6228
6229 // - (void)removeKeyObject:(type *)object
6230 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006231 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006232 = (Twine("remove") + UpperKey + Twine("Object")).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.AddTextChunk("void");
6238 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6239 }
6240
6241 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6242 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6243 Builder.AddPlaceholderChunk("object-type");
6244 Builder.AddTextChunk(" *");
6245 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6246 Builder.AddTextChunk("object");
6247 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6248 CXCursor_ObjCInstanceMethodDecl));
6249 }
6250 }
6251
6252 // - (void)removeKey:(NSSet *)objects
6253 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006254 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006255 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006256 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006257 if (ReturnType.isNull()) {
6258 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6259 Builder.AddTextChunk("void");
6260 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6261 }
6262
6263 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6264 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6265 Builder.AddTextChunk("NSSet *");
6266 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6267 Builder.AddTextChunk("objects");
6268 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6269 CXCursor_ObjCInstanceMethodDecl));
6270 }
6271 }
6272
6273 // - (void)intersectKey:(NSSet *)objects
6274 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006275 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006276 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006277 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006278 if (ReturnType.isNull()) {
6279 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6280 Builder.AddTextChunk("void");
6281 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6282 }
6283
6284 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6285 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6286 Builder.AddTextChunk("NSSet *");
6287 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6288 Builder.AddTextChunk("objects");
6289 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6290 CXCursor_ObjCInstanceMethodDecl));
6291 }
6292 }
6293
6294 // Key-Value Observing
6295 // + (NSSet *)keyPathsForValuesAffectingKey
6296 if (!IsInstanceMethod &&
6297 (ReturnType.isNull() ||
6298 (ReturnType->isObjCObjectPointerType() &&
6299 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6300 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6301 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006302 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006303 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006304 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006305 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006306 if (ReturnType.isNull()) {
6307 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6308 Builder.AddTextChunk("NSSet *");
6309 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6310 }
6311
6312 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6313 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006314 CXCursor_ObjCClassMethodDecl));
6315 }
6316 }
6317
6318 // + (BOOL)automaticallyNotifiesObserversForKey
6319 if (!IsInstanceMethod &&
6320 (ReturnType.isNull() ||
6321 ReturnType->isIntegerType() ||
6322 ReturnType->isBooleanType())) {
6323 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006324 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006325 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6326 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6327 if (ReturnType.isNull()) {
6328 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6329 Builder.AddTextChunk("BOOL");
6330 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6331 }
6332
6333 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6334 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6335 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006336 }
6337 }
6338}
6339
Douglas Gregore8f5a172010-04-07 00:21:17 +00006340void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6341 bool IsInstanceMethod,
John McCallb3d87482010-08-24 05:47:05 +00006342 ParsedType ReturnTy,
John McCalld226f652010-08-21 09:40:31 +00006343 Decl *IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006344 // Determine the return type of the method we're declaring, if
6345 // provided.
6346 QualType ReturnType = GetTypeFromParser(ReturnTy);
6347
Douglas Gregorea766182010-10-18 18:21:28 +00006348 // Determine where we should start searching for methods.
6349 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006350 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006351 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006352 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6353 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006354 IsInImplementation = true;
6355 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006356 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006357 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006358 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006359 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006360 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006361 }
6362
6363 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006364 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006365 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006366 }
6367
Douglas Gregorea766182010-10-18 18:21:28 +00006368 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006369 HandleCodeCompleteResults(this, CodeCompleter,
6370 CodeCompletionContext::CCC_Other,
6371 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006372 return;
6373 }
6374
6375 // Find all of the methods that we could declare/implement here.
6376 KnownMethodsMap KnownMethods;
6377 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006378 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006379
Douglas Gregore8f5a172010-04-07 00:21:17 +00006380 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006381 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006382 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6383 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006384 Results.EnterNewScope();
6385 PrintingPolicy Policy(Context.PrintingPolicy);
6386 Policy.AnonymousTagLocations = false;
John McCallf85e1932011-06-15 23:02:42 +00006387 Policy.SuppressStrongLifetime = true;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006388 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6389 MEnd = KnownMethods.end();
6390 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006391 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006392 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006393
6394 // If the result type was not already provided, add it to the
6395 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006396 if (ReturnType.isNull())
6397 AddObjCPassingTypeChunk(Method->getResultType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006398
6399 Selector Sel = Method->getSelector();
6400
6401 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006402 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006403 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006404
6405 // Add parameters to the pattern.
6406 unsigned I = 0;
6407 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6408 PEnd = Method->param_end();
6409 P != PEnd; (void)++P, ++I) {
6410 // Add the part of the selector name.
6411 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006412 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006413 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006414 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6415 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006416 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006417 } else
6418 break;
6419
6420 // Add the parameter type.
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006421 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006422
6423 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006424 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006425 }
6426
6427 if (Method->isVariadic()) {
6428 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006429 Builder.AddChunk(CodeCompletionString::CK_Comma);
6430 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006431 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006432
Douglas Gregor447107d2010-05-28 00:57:46 +00006433 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006434 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006435 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6436 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6437 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006438 if (!Method->getResultType()->isVoidType()) {
6439 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006440 Builder.AddTextChunk("return");
6441 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6442 Builder.AddPlaceholderChunk("expression");
6443 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006444 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006445 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006446
Douglas Gregor218937c2011-02-01 19:23:04 +00006447 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6448 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006449 }
6450
Douglas Gregor408be5a2010-08-25 01:08:01 +00006451 unsigned Priority = CCP_CodePattern;
6452 if (!M->second.second)
6453 Priority += CCD_InBaseClass;
6454
Douglas Gregor218937c2011-02-01 19:23:04 +00006455 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006456 Method->isInstanceMethod()
6457 ? CXCursor_ObjCInstanceMethodDecl
6458 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006459 }
6460
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006461 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6462 // the properties in this class and its categories.
6463 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006464 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006465 Containers.push_back(SearchDecl);
6466
Douglas Gregore74c25c2011-05-04 23:50:46 +00006467 VisitedSelectorSet KnownSelectors;
6468 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6469 MEnd = KnownMethods.end();
6470 M != MEnd; ++M)
6471 KnownSelectors.insert(M->first);
6472
6473
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006474 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6475 if (!IFace)
6476 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6477 IFace = Category->getClassInterface();
6478
6479 if (IFace) {
6480 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6481 Category = Category->getNextClassCategory())
6482 Containers.push_back(Category);
6483 }
6484
6485 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6486 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6487 PEnd = Containers[I]->prop_end();
6488 P != PEnd; ++P) {
6489 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006490 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006491 }
6492 }
6493 }
6494
Douglas Gregore8f5a172010-04-07 00:21:17 +00006495 Results.ExitScope();
6496
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006497 HandleCodeCompleteResults(this, CodeCompleter,
6498 CodeCompletionContext::CCC_Other,
6499 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006500}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006501
6502void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6503 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006504 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006505 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006506 IdentifierInfo **SelIdents,
6507 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006508 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006509 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006510 if (ExternalSource) {
6511 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6512 I != N; ++I) {
6513 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006514 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006515 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006516
6517 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006518 }
6519 }
6520
6521 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006522 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006523 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6524 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006525
6526 if (ReturnTy)
6527 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006528
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006529 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006530 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6531 MEnd = MethodPool.end();
6532 M != MEnd; ++M) {
6533 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6534 &M->second.second;
6535 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006536 MethList = MethList->Next) {
6537 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6538 NumSelIdents))
6539 continue;
6540
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006541 if (AtParameterName) {
6542 // Suggest parameter names we've seen before.
6543 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6544 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6545 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006546 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006547 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006548 Param->getIdentifier()->getName()));
6549 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006550 }
6551 }
6552
6553 continue;
6554 }
6555
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006556 Result R(MethList->Method, 0);
6557 R.StartParameter = NumSelIdents;
6558 R.AllParametersAreInformative = false;
6559 R.DeclaringEntity = true;
6560 Results.MaybeAddResult(R, CurContext);
6561 }
6562 }
6563
6564 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006565 HandleCodeCompleteResults(this, CodeCompleter,
6566 CodeCompletionContext::CCC_Other,
6567 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006568}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006569
Douglas Gregorf29c5232010-08-24 22:20:20 +00006570void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006571 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006572 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006573 Results.EnterNewScope();
6574
6575 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006576 CodeCompletionBuilder Builder(Results.getAllocator());
6577 Builder.AddTypedTextChunk("if");
6578 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6579 Builder.AddPlaceholderChunk("condition");
6580 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006581
6582 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006583 Builder.AddTypedTextChunk("ifdef");
6584 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6585 Builder.AddPlaceholderChunk("macro");
6586 Results.AddResult(Builder.TakeString());
6587
Douglas Gregorf44e8542010-08-24 19:08:16 +00006588 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006589 Builder.AddTypedTextChunk("ifndef");
6590 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6591 Builder.AddPlaceholderChunk("macro");
6592 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006593
6594 if (InConditional) {
6595 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006596 Builder.AddTypedTextChunk("elif");
6597 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6598 Builder.AddPlaceholderChunk("condition");
6599 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006600
6601 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006602 Builder.AddTypedTextChunk("else");
6603 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006604
6605 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006606 Builder.AddTypedTextChunk("endif");
6607 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006608 }
6609
6610 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006611 Builder.AddTypedTextChunk("include");
6612 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6613 Builder.AddTextChunk("\"");
6614 Builder.AddPlaceholderChunk("header");
6615 Builder.AddTextChunk("\"");
6616 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006617
6618 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006619 Builder.AddTypedTextChunk("include");
6620 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6621 Builder.AddTextChunk("<");
6622 Builder.AddPlaceholderChunk("header");
6623 Builder.AddTextChunk(">");
6624 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006625
6626 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006627 Builder.AddTypedTextChunk("define");
6628 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6629 Builder.AddPlaceholderChunk("macro");
6630 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006631
6632 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006633 Builder.AddTypedTextChunk("define");
6634 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6635 Builder.AddPlaceholderChunk("macro");
6636 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6637 Builder.AddPlaceholderChunk("args");
6638 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6639 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006640
6641 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006642 Builder.AddTypedTextChunk("undef");
6643 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6644 Builder.AddPlaceholderChunk("macro");
6645 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006646
6647 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006648 Builder.AddTypedTextChunk("line");
6649 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6650 Builder.AddPlaceholderChunk("number");
6651 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006652
6653 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006654 Builder.AddTypedTextChunk("line");
6655 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6656 Builder.AddPlaceholderChunk("number");
6657 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6658 Builder.AddTextChunk("\"");
6659 Builder.AddPlaceholderChunk("filename");
6660 Builder.AddTextChunk("\"");
6661 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006662
6663 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006664 Builder.AddTypedTextChunk("error");
6665 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6666 Builder.AddPlaceholderChunk("message");
6667 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006668
6669 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006670 Builder.AddTypedTextChunk("pragma");
6671 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6672 Builder.AddPlaceholderChunk("arguments");
6673 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006674
6675 if (getLangOptions().ObjC1) {
6676 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006677 Builder.AddTypedTextChunk("import");
6678 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6679 Builder.AddTextChunk("\"");
6680 Builder.AddPlaceholderChunk("header");
6681 Builder.AddTextChunk("\"");
6682 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006683
6684 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006685 Builder.AddTypedTextChunk("import");
6686 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6687 Builder.AddTextChunk("<");
6688 Builder.AddPlaceholderChunk("header");
6689 Builder.AddTextChunk(">");
6690 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006691 }
6692
6693 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006694 Builder.AddTypedTextChunk("include_next");
6695 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6696 Builder.AddTextChunk("\"");
6697 Builder.AddPlaceholderChunk("header");
6698 Builder.AddTextChunk("\"");
6699 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006700
6701 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006702 Builder.AddTypedTextChunk("include_next");
6703 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6704 Builder.AddTextChunk("<");
6705 Builder.AddPlaceholderChunk("header");
6706 Builder.AddTextChunk(">");
6707 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006708
6709 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006710 Builder.AddTypedTextChunk("warning");
6711 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6712 Builder.AddPlaceholderChunk("message");
6713 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006714
6715 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6716 // completions for them. And __include_macros is a Clang-internal extension
6717 // that we don't want to encourage anyone to use.
6718
6719 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6720 Results.ExitScope();
6721
Douglas Gregorf44e8542010-08-24 19:08:16 +00006722 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006723 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006724 Results.data(), Results.size());
6725}
6726
6727void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006728 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006729 S->getFnParent()? Sema::PCC_RecoveryInFunction
6730 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006731}
6732
Douglas Gregorf29c5232010-08-24 22:20:20 +00006733void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006734 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006735 IsDefinition? CodeCompletionContext::CCC_MacroName
6736 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006737 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6738 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006739 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006740 Results.EnterNewScope();
6741 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6742 MEnd = PP.macro_end();
6743 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006744 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006745 M->first->getName()));
6746 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006747 }
6748 Results.ExitScope();
6749 } else if (IsDefinition) {
6750 // FIXME: Can we detect when the user just wrote an include guard above?
6751 }
6752
Douglas Gregor52779fb2010-09-23 23:01:17 +00006753 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006754 Results.data(), Results.size());
6755}
6756
Douglas Gregorf29c5232010-08-24 22:20:20 +00006757void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006758 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006759 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006760
6761 if (!CodeCompleter || CodeCompleter->includeMacros())
6762 AddMacroResults(PP, Results);
6763
6764 // defined (<macro>)
6765 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006766 CodeCompletionBuilder Builder(Results.getAllocator());
6767 Builder.AddTypedTextChunk("defined");
6768 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6769 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6770 Builder.AddPlaceholderChunk("macro");
6771 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6772 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006773 Results.ExitScope();
6774
6775 HandleCodeCompleteResults(this, CodeCompleter,
6776 CodeCompletionContext::CCC_PreprocessorExpression,
6777 Results.data(), Results.size());
6778}
6779
6780void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6781 IdentifierInfo *Macro,
6782 MacroInfo *MacroInfo,
6783 unsigned Argument) {
6784 // FIXME: In the future, we could provide "overload" results, much like we
6785 // do for function calls.
6786
6787 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006788 S->getFnParent()? Sema::PCC_RecoveryInFunction
6789 : Sema::PCC_Namespace);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006790}
6791
Douglas Gregor55817af2010-08-25 17:04:25 +00006792void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006793 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006794 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006795 0, 0);
6796}
6797
Douglas Gregordae68752011-02-01 22:57:45 +00006798void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006799 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006800 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006801 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6802 CodeCompletionDeclConsumer Consumer(Builder,
6803 Context.getTranslationUnitDecl());
6804 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6805 Consumer);
6806 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006807
6808 if (!CodeCompleter || CodeCompleter->includeMacros())
6809 AddMacroResults(PP, Builder);
6810
6811 Results.clear();
6812 Results.insert(Results.end(),
6813 Builder.data(), Builder.data() + Builder.size());
6814}