blob: 307472504401e8bd8a1c22b5f37f8a9c4aad024f [file] [log] [blame]
Douglas Gregor81b747b2009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
John McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
John McCall120d63c2010-08-24 20:38:10 +000015#include "clang/Sema/Overload.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000016#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregor719770d2010-04-06 17:30:22 +000017#include "clang/Sema/ExternalSemaSource.h"
John McCall5f1e0942010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000023#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
Douglas Gregord36adf52010-09-16 16:06:31 +000025#include "llvm/ADT/DenseSet.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000026#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000027#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000028#include "llvm/ADT/StringSwitch.h"
Douglas Gregor458433d2010-08-26 15:07:07 +000029#include "llvm/ADT/Twine.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000030#include <list>
31#include <map>
32#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000033
34using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000035using namespace sema;
Douglas Gregor81b747b2009-09-17 21:32:03 +000036
Douglas Gregor86d9a522009-09-21 16:56:56 +000037namespace {
38 /// \brief A container of code-completion results.
39 class ResultBuilder {
40 public:
41 /// \brief The type of a name-lookup filter, which can be provided to the
42 /// name-lookup routines to specify which declarations should be included in
43 /// the result set (when it returns true) and which declarations should be
44 /// filtered out (returns false).
45 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
46
John McCall0a2c5e22010-08-25 06:19:51 +000047 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +000048
49 private:
50 /// \brief The actual results we have found.
51 std::vector<Result> Results;
52
53 /// \brief A record of all of the declarations we have found and placed
54 /// into the result set, used to ensure that no declaration ever gets into
55 /// the result set twice.
56 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
57
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000058 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
59
60 /// \brief An entry in the shadow map, which is optimized to store
61 /// a single (declaration, index) mapping (the common case) but
62 /// can also store a list of (declaration, index) mappings.
63 class ShadowMapEntry {
Chris Lattner5f9e2722011-07-23 10:55:15 +000064 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000065
66 /// \brief Contains either the solitary NamedDecl * or a vector
67 /// of (declaration, index) pairs.
68 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
69
70 /// \brief When the entry contains a single declaration, this is
71 /// the index associated with that entry.
72 unsigned SingleDeclIndex;
73
74 public:
75 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
76
77 void Add(NamedDecl *ND, unsigned Index) {
78 if (DeclOrVector.isNull()) {
79 // 0 - > 1 elements: just set the single element information.
80 DeclOrVector = ND;
81 SingleDeclIndex = Index;
82 return;
83 }
84
85 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
86 // 1 -> 2 elements: create the vector of results and push in the
87 // existing declaration.
88 DeclIndexPairVector *Vec = new DeclIndexPairVector;
89 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
90 DeclOrVector = Vec;
91 }
92
93 // Add the new element to the end of the vector.
94 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
95 DeclIndexPair(ND, Index));
96 }
97
98 void Destroy() {
99 if (DeclIndexPairVector *Vec
100 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
101 delete Vec;
102 DeclOrVector = ((NamedDecl *)0);
103 }
104 }
105
106 // Iteration.
107 class iterator;
108 iterator begin() const;
109 iterator end() const;
110 };
111
Douglas Gregor86d9a522009-09-21 16:56:56 +0000112 /// \brief A mapping from declaration names to the declarations that have
113 /// this name within a particular scope and their index within the list of
114 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000115 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000116
117 /// \brief The semantic analysis object for which results are being
118 /// produced.
119 Sema &SemaRef;
Douglas Gregor218937c2011-02-01 19:23:04 +0000120
121 /// \brief The allocator used to allocate new code-completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000122 CodeCompletionAllocator &Allocator;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000123
124 /// \brief If non-NULL, a filter function used to remove any code-completion
125 /// results that are not desirable.
126 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000127
128 /// \brief Whether we should allow declarations as
129 /// nested-name-specifiers that would otherwise be filtered out.
130 bool AllowNestedNameSpecifiers;
131
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000132 /// \brief If set, the type that we would prefer our resulting value
133 /// declarations to have.
134 ///
135 /// Closely matching the preferred type gives a boost to a result's
136 /// priority.
137 CanQualType PreferredType;
138
Douglas Gregor86d9a522009-09-21 16:56:56 +0000139 /// \brief A list of shadow maps, which is used to model name hiding at
140 /// different levels of, e.g., the inheritance hierarchy.
141 std::list<ShadowMap> ShadowMaps;
142
Douglas Gregor3cdee122010-08-26 16:36:48 +0000143 /// \brief If we're potentially referring to a C++ member function, the set
144 /// of qualifiers applied to the object type.
145 Qualifiers ObjectTypeQualifiers;
146
147 /// \brief Whether the \p ObjectTypeQualifiers field is active.
148 bool HasObjectTypeQualifiers;
149
Douglas Gregor265f7492010-08-27 15:29:55 +0000150 /// \brief The selector that we prefer.
151 Selector PreferredSelector;
152
Douglas Gregorca45da02010-11-02 20:36:02 +0000153 /// \brief The completion context in which we are gathering results.
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000154 CodeCompletionContext CompletionContext;
155
Douglas Gregorca45da02010-11-02 20:36:02 +0000156 /// \brief If we are in an instance method definition, the @implementation
157 /// object.
158 ObjCImplementationDecl *ObjCImplementation;
159
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000160 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000161
Douglas Gregor6f942b22010-09-21 16:06:22 +0000162 void MaybeAddConstructorResults(Result R);
163
Douglas Gregor86d9a522009-09-21 16:56:56 +0000164 public:
Douglas Gregordae68752011-02-01 22:57:45 +0000165 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Douglas Gregor52779fb2010-09-23 23:01:17 +0000166 const CodeCompletionContext &CompletionContext,
167 LookupFilter Filter = 0)
Douglas Gregor218937c2011-02-01 19:23:04 +0000168 : SemaRef(SemaRef), Allocator(Allocator), Filter(Filter),
169 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregorca45da02010-11-02 20:36:02 +0000170 CompletionContext(CompletionContext),
171 ObjCImplementation(0)
172 {
173 // If this is an Objective-C instance method definition, dig out the
174 // corresponding implementation.
175 switch (CompletionContext.getKind()) {
176 case CodeCompletionContext::CCC_Expression:
177 case CodeCompletionContext::CCC_ObjCMessageReceiver:
178 case CodeCompletionContext::CCC_ParenthesizedExpression:
179 case CodeCompletionContext::CCC_Statement:
180 case CodeCompletionContext::CCC_Recovery:
181 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
182 if (Method->isInstanceMethod())
183 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
184 ObjCImplementation = Interface->getImplementation();
185 break;
186
187 default:
188 break;
189 }
190 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000191
Douglas Gregord8e8a582010-05-25 21:41:55 +0000192 /// \brief Whether we should include code patterns in the completion
193 /// results.
194 bool includeCodePatterns() const {
195 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000196 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000197 }
198
Douglas Gregor86d9a522009-09-21 16:56:56 +0000199 /// \brief Set the filter used for code-completion results.
200 void setFilter(LookupFilter Filter) {
201 this->Filter = Filter;
202 }
203
Douglas Gregor86d9a522009-09-21 16:56:56 +0000204 Result *data() { return Results.empty()? 0 : &Results.front(); }
205 unsigned size() const { return Results.size(); }
206 bool empty() const { return Results.empty(); }
207
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000208 /// \brief Specify the preferred type.
209 void setPreferredType(QualType T) {
210 PreferredType = SemaRef.Context.getCanonicalType(T);
211 }
212
Douglas Gregor3cdee122010-08-26 16:36:48 +0000213 /// \brief Set the cv-qualifiers on the object type, for us in filtering
214 /// calls to member functions.
215 ///
216 /// When there are qualifiers in this set, they will be used to filter
217 /// out member functions that aren't available (because there will be a
218 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
219 /// match.
220 void setObjectTypeQualifiers(Qualifiers Quals) {
221 ObjectTypeQualifiers = Quals;
222 HasObjectTypeQualifiers = true;
223 }
224
Douglas Gregor265f7492010-08-27 15:29:55 +0000225 /// \brief Set the preferred selector.
226 ///
227 /// When an Objective-C method declaration result is added, and that
228 /// method's selector matches this preferred selector, we give that method
229 /// a slight priority boost.
230 void setPreferredSelector(Selector Sel) {
231 PreferredSelector = Sel;
232 }
Douglas Gregorca45da02010-11-02 20:36:02 +0000233
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000234 /// \brief Retrieve the code-completion context for which results are
235 /// being collected.
236 const CodeCompletionContext &getCompletionContext() const {
237 return CompletionContext;
238 }
239
Douglas Gregor45bcd432010-01-14 03:21:49 +0000240 /// \brief Specify whether nested-name-specifiers are allowed.
241 void allowNestedNameSpecifiers(bool Allow = true) {
242 AllowNestedNameSpecifiers = Allow;
243 }
244
Douglas Gregorb9d77572010-09-21 00:03:25 +0000245 /// \brief Return the semantic analysis object for which we are collecting
246 /// code completion results.
247 Sema &getSema() const { return SemaRef; }
248
Douglas Gregor218937c2011-02-01 19:23:04 +0000249 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000250 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Douglas Gregor218937c2011-02-01 19:23:04 +0000251
Douglas Gregore495b7f2010-01-14 00:20:49 +0000252 /// \brief Determine whether the given declaration is at all interesting
253 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000254 ///
255 /// \param ND the declaration that we are inspecting.
256 ///
257 /// \param AsNestedNameSpecifier will be set true if this declaration is
258 /// only interesting when it is a nested-name-specifier.
259 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000260
261 /// \brief Check whether the result is hidden by the Hiding declaration.
262 ///
263 /// \returns true if the result is hidden and cannot be found, false if
264 /// the hidden result could still be found. When false, \p R may be
265 /// modified to describe how the result can be found (e.g., via extra
266 /// qualification).
267 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
268 NamedDecl *Hiding);
269
Douglas Gregor86d9a522009-09-21 16:56:56 +0000270 /// \brief Add a new result to this result set (if it isn't already in one
271 /// of the shadow maps), or replace an existing result (for, e.g., a
272 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000273 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000274 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000275 ///
276 /// \param R the context in which this result will be named.
277 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000278
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000279 /// \brief Add a new result to this result set, where we already know
280 /// the hiding declation (if any).
281 ///
282 /// \param R the result to add (if it is unique).
283 ///
284 /// \param CurContext the context in which this result will be named.
285 ///
286 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000287 ///
288 /// \param InBaseClass whether the result was found in a base
289 /// class of the searched context.
290 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
291 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000292
Douglas Gregora4477812010-01-14 16:01:26 +0000293 /// \brief Add a new non-declaration result to this result set.
294 void AddResult(Result R);
295
Douglas Gregor86d9a522009-09-21 16:56:56 +0000296 /// \brief Enter into a new scope.
297 void EnterNewScope();
298
299 /// \brief Exit from the current scope.
300 void ExitScope();
301
Douglas Gregor55385fe2009-11-18 04:19:12 +0000302 /// \brief Ignore this declaration, if it is seen again.
303 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
304
Douglas Gregor86d9a522009-09-21 16:56:56 +0000305 /// \name Name lookup predicates
306 ///
307 /// These predicates can be passed to the name lookup functions to filter the
308 /// results of name lookup. All of the predicates have the same type, so that
309 ///
310 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000311 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000312 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000313 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000314 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000315 bool IsNestedNameSpecifier(NamedDecl *ND) const;
316 bool IsEnum(NamedDecl *ND) const;
317 bool IsClassOrStruct(NamedDecl *ND) const;
318 bool IsUnion(NamedDecl *ND) const;
319 bool IsNamespace(NamedDecl *ND) const;
320 bool IsNamespaceOrAlias(NamedDecl *ND) const;
321 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000322 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000323 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000324 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000325 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000326 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000327 //@}
328 };
329}
330
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000331class ResultBuilder::ShadowMapEntry::iterator {
332 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
333 unsigned SingleDeclIndex;
334
335public:
336 typedef DeclIndexPair value_type;
337 typedef value_type reference;
338 typedef std::ptrdiff_t difference_type;
339 typedef std::input_iterator_tag iterator_category;
340
341 class pointer {
342 DeclIndexPair Value;
343
344 public:
345 pointer(const DeclIndexPair &Value) : Value(Value) { }
346
347 const DeclIndexPair *operator->() const {
348 return &Value;
349 }
350 };
351
352 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
353
354 iterator(NamedDecl *SingleDecl, unsigned Index)
355 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
356
357 iterator(const DeclIndexPair *Iterator)
358 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
359
360 iterator &operator++() {
361 if (DeclOrIterator.is<NamedDecl *>()) {
362 DeclOrIterator = (NamedDecl *)0;
363 SingleDeclIndex = 0;
364 return *this;
365 }
366
367 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
368 ++I;
369 DeclOrIterator = I;
370 return *this;
371 }
372
Chris Lattner66392d42010-09-04 18:12:20 +0000373 /*iterator operator++(int) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000374 iterator tmp(*this);
375 ++(*this);
376 return tmp;
Chris Lattner66392d42010-09-04 18:12:20 +0000377 }*/
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000378
379 reference operator*() const {
380 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
381 return reference(ND, SingleDeclIndex);
382
Douglas Gregord490f952009-12-06 21:27:58 +0000383 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000384 }
385
386 pointer operator->() const {
387 return pointer(**this);
388 }
389
390 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000391 return X.DeclOrIterator.getOpaqueValue()
392 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000393 X.SingleDeclIndex == Y.SingleDeclIndex;
394 }
395
396 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000397 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000398 }
399};
400
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000401ResultBuilder::ShadowMapEntry::iterator
402ResultBuilder::ShadowMapEntry::begin() const {
403 if (DeclOrVector.isNull())
404 return iterator();
405
406 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
407 return iterator(ND, SingleDeclIndex);
408
409 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
410}
411
412ResultBuilder::ShadowMapEntry::iterator
413ResultBuilder::ShadowMapEntry::end() const {
414 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
415 return iterator();
416
417 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
418}
419
Douglas Gregor456c4a12009-09-21 20:12:40 +0000420/// \brief Compute the qualification required to get from the current context
421/// (\p CurContext) to the target context (\p TargetContext).
422///
423/// \param Context the AST context in which the qualification will be used.
424///
425/// \param CurContext the context where an entity is being named, which is
426/// typically based on the current scope.
427///
428/// \param TargetContext the context in which the named entity actually
429/// resides.
430///
431/// \returns a nested name specifier that refers into the target context, or
432/// NULL if no qualification is needed.
433static NestedNameSpecifier *
434getRequiredQualification(ASTContext &Context,
435 DeclContext *CurContext,
436 DeclContext *TargetContext) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000437 SmallVector<DeclContext *, 4> TargetParents;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000438
439 for (DeclContext *CommonAncestor = TargetContext;
440 CommonAncestor && !CommonAncestor->Encloses(CurContext);
441 CommonAncestor = CommonAncestor->getLookupParent()) {
442 if (CommonAncestor->isTransparentContext() ||
443 CommonAncestor->isFunctionOrMethod())
444 continue;
445
446 TargetParents.push_back(CommonAncestor);
447 }
448
449 NestedNameSpecifier *Result = 0;
450 while (!TargetParents.empty()) {
451 DeclContext *Parent = TargetParents.back();
452 TargetParents.pop_back();
453
Douglas Gregorfb629412010-08-23 21:17:50 +0000454 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
455 if (!Namespace->getIdentifier())
456 continue;
457
Douglas Gregor456c4a12009-09-21 20:12:40 +0000458 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000459 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000460 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
461 Result = NestedNameSpecifier::Create(Context, Result,
462 false,
463 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000464 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000465 return Result;
466}
467
Douglas Gregor45bcd432010-01-14 03:21:49 +0000468bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
469 bool &AsNestedNameSpecifier) const {
470 AsNestedNameSpecifier = false;
471
Douglas Gregore495b7f2010-01-14 00:20:49 +0000472 ND = ND->getUnderlyingDecl();
473 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000474
475 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000476 if (!ND->getDeclName())
477 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000478
479 // Friend declarations and declarations introduced due to friends are never
480 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000481 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000482 return false;
483
Douglas Gregor76282942009-12-11 17:31:05 +0000484 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000485 if (isa<ClassTemplateSpecializationDecl>(ND) ||
486 isa<ClassTemplatePartialSpecializationDecl>(ND))
487 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000488
Douglas Gregor76282942009-12-11 17:31:05 +0000489 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000490 if (isa<UsingDecl>(ND))
491 return false;
492
493 // Some declarations have reserved names that we don't want to ever show.
494 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000495 // __va_list_tag is a freak of nature. Find it and skip it.
496 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000497 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000498
Douglas Gregorf52cede2009-10-09 22:16:47 +0000499 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000500 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000501 //
502 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000503 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000504 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000505 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000506 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
507 (ND->getLocation().isInvalid() ||
508 SemaRef.SourceMgr.isInSystemHeader(
509 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000510 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000511 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000512 }
Douglas Gregor6f942b22010-09-21 16:06:22 +0000513
Douglas Gregor9b0ba872010-11-09 03:59:40 +0000514 // Skip out-of-line declarations and definitions.
515 // NOTE: Unless it's an Objective-C property, method, or ivar, where
516 // the contexts can be messy.
517 if (!ND->getDeclContext()->Equals(ND->getLexicalDeclContext()) &&
518 !(isa<ObjCPropertyDecl>(ND) || isa<ObjCIvarDecl>(ND) ||
519 isa<ObjCMethodDecl>(ND)))
520 return false;
521
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000522 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
523 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
524 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor52779fb2010-09-23 23:01:17 +0000525 Filter != &ResultBuilder::IsNamespaceOrAlias &&
526 Filter != 0))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000527 AsNestedNameSpecifier = true;
528
Douglas Gregor86d9a522009-09-21 16:56:56 +0000529 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000530 if (Filter && !(this->*Filter)(ND)) {
531 // Check whether it is interesting as a nested-name-specifier.
532 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
533 IsNestedNameSpecifier(ND) &&
534 (Filter != &ResultBuilder::IsMember ||
535 (isa<CXXRecordDecl>(ND) &&
536 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
537 AsNestedNameSpecifier = true;
538 return true;
539 }
540
Douglas Gregore495b7f2010-01-14 00:20:49 +0000541 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000542 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000543 // ... then it must be interesting!
544 return true;
545}
546
Douglas Gregor6660d842010-01-14 00:41:07 +0000547bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
548 NamedDecl *Hiding) {
549 // In C, there is no way to refer to a hidden name.
550 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
551 // name if we introduce the tag type.
552 if (!SemaRef.getLangOptions().CPlusPlus)
553 return true;
554
Sebastian Redl7a126a42010-08-31 00:36:30 +0000555 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregor6660d842010-01-14 00:41:07 +0000556
557 // There is no way to qualify a name declared in a function or method.
558 if (HiddenCtx->isFunctionOrMethod())
559 return true;
560
Sebastian Redl7a126a42010-08-31 00:36:30 +0000561 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregor6660d842010-01-14 00:41:07 +0000562 return true;
563
564 // We can refer to the result with the appropriate qualification. Do it.
565 R.Hidden = true;
566 R.QualifierIsInformative = false;
567
568 if (!R.Qualifier)
569 R.Qualifier = getRequiredQualification(SemaRef.Context,
570 CurContext,
571 R.Declaration->getDeclContext());
572 return false;
573}
574
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000575/// \brief A simplified classification of types used to determine whether two
576/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000577SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000578 switch (T->getTypeClass()) {
579 case Type::Builtin:
580 switch (cast<BuiltinType>(T)->getKind()) {
581 case BuiltinType::Void:
582 return STC_Void;
583
584 case BuiltinType::NullPtr:
585 return STC_Pointer;
586
587 case BuiltinType::Overload:
588 case BuiltinType::Dependent:
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000589 return STC_Other;
590
591 case BuiltinType::ObjCId:
592 case BuiltinType::ObjCClass:
593 case BuiltinType::ObjCSel:
594 return STC_ObjectiveC;
595
596 default:
597 return STC_Arithmetic;
598 }
599 return STC_Other;
600
601 case Type::Complex:
602 return STC_Arithmetic;
603
604 case Type::Pointer:
605 return STC_Pointer;
606
607 case Type::BlockPointer:
608 return STC_Block;
609
610 case Type::LValueReference:
611 case Type::RValueReference:
612 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
613
614 case Type::ConstantArray:
615 case Type::IncompleteArray:
616 case Type::VariableArray:
617 case Type::DependentSizedArray:
618 return STC_Array;
619
620 case Type::DependentSizedExtVector:
621 case Type::Vector:
622 case Type::ExtVector:
623 return STC_Arithmetic;
624
625 case Type::FunctionProto:
626 case Type::FunctionNoProto:
627 return STC_Function;
628
629 case Type::Record:
630 return STC_Record;
631
632 case Type::Enum:
633 return STC_Arithmetic;
634
635 case Type::ObjCObject:
636 case Type::ObjCInterface:
637 case Type::ObjCObjectPointer:
638 return STC_ObjectiveC;
639
640 default:
641 return STC_Other;
642 }
643}
644
645/// \brief Get the type that a given expression will have if this declaration
646/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000647QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000648 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
649
650 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
651 return C.getTypeDeclType(Type);
652 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
653 return C.getObjCInterfaceType(Iface);
654
655 QualType T;
656 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000657 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000658 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000659 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000660 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000661 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000662 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
663 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
664 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
665 T = Property->getType();
666 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
667 T = Value->getType();
668 else
669 return QualType();
Douglas Gregor3e64d562011-04-14 20:33:34 +0000670
671 // Dig through references, function pointers, and block pointers to
672 // get down to the likely type of an expression when the entity is
673 // used.
674 do {
675 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
676 T = Ref->getPointeeType();
677 continue;
678 }
679
680 if (const PointerType *Pointer = T->getAs<PointerType>()) {
681 if (Pointer->getPointeeType()->isFunctionType()) {
682 T = Pointer->getPointeeType();
683 continue;
684 }
685
686 break;
687 }
688
689 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
690 T = Block->getPointeeType();
691 continue;
692 }
693
694 if (const FunctionType *Function = T->getAs<FunctionType>()) {
695 T = Function->getResultType();
696 continue;
697 }
698
699 break;
700 } while (true);
701
702 return T;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000703}
704
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000705void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
706 // If this is an Objective-C method declaration whose selector matches our
707 // preferred selector, give it a priority boost.
708 if (!PreferredSelector.isNull())
709 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
710 if (PreferredSelector == Method->getSelector())
711 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000712
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000713 // If we have a preferred type, adjust the priority for results with exactly-
714 // matching or nearly-matching types.
715 if (!PreferredType.isNull()) {
716 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
717 if (!T.isNull()) {
718 CanQualType TC = SemaRef.Context.getCanonicalType(T);
719 // Check for exactly-matching types (modulo qualifiers).
720 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
721 R.Priority /= CCF_ExactTypeMatch;
722 // Check for nearly-matching types, based on classification of each.
723 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000724 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000725 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
726 R.Priority /= CCF_SimilarTypeMatch;
727 }
728 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000729}
730
Douglas Gregor6f942b22010-09-21 16:06:22 +0000731void ResultBuilder::MaybeAddConstructorResults(Result R) {
732 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
733 !CompletionContext.wantConstructorResults())
734 return;
735
736 ASTContext &Context = SemaRef.Context;
737 NamedDecl *D = R.Declaration;
738 CXXRecordDecl *Record = 0;
739 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
740 Record = ClassTemplate->getTemplatedDecl();
741 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
742 // Skip specializations and partial specializations.
743 if (isa<ClassTemplateSpecializationDecl>(Record))
744 return;
745 } else {
746 // There are no constructors here.
747 return;
748 }
749
750 Record = Record->getDefinition();
751 if (!Record)
752 return;
753
754
755 QualType RecordTy = Context.getTypeDeclType(Record);
756 DeclarationName ConstructorName
757 = Context.DeclarationNames.getCXXConstructorName(
758 Context.getCanonicalType(RecordTy));
759 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
760 Ctors.first != Ctors.second; ++Ctors.first) {
761 R.Declaration = *Ctors.first;
762 R.CursorKind = getCursorKindForDecl(R.Declaration);
763 Results.push_back(R);
764 }
765}
766
Douglas Gregore495b7f2010-01-14 00:20:49 +0000767void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
768 assert(!ShadowMaps.empty() && "Must enter into a results scope");
769
770 if (R.Kind != Result::RK_Declaration) {
771 // For non-declaration results, just add the result.
772 Results.push_back(R);
773 return;
774 }
775
776 // Look through using declarations.
777 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
778 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
779 return;
780 }
781
782 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
783 unsigned IDNS = CanonDecl->getIdentifierNamespace();
784
Douglas Gregor45bcd432010-01-14 03:21:49 +0000785 bool AsNestedNameSpecifier = false;
786 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000787 return;
788
Douglas Gregor6f942b22010-09-21 16:06:22 +0000789 // C++ constructors are never found by name lookup.
790 if (isa<CXXConstructorDecl>(R.Declaration))
791 return;
792
Douglas Gregor86d9a522009-09-21 16:56:56 +0000793 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000794 ShadowMapEntry::iterator I, IEnd;
795 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
796 if (NamePos != SMap.end()) {
797 I = NamePos->second.begin();
798 IEnd = NamePos->second.end();
799 }
800
801 for (; I != IEnd; ++I) {
802 NamedDecl *ND = I->first;
803 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000804 if (ND->getCanonicalDecl() == CanonDecl) {
805 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000806 Results[Index].Declaration = R.Declaration;
807
Douglas Gregor86d9a522009-09-21 16:56:56 +0000808 // We're done.
809 return;
810 }
811 }
812
813 // This is a new declaration in this scope. However, check whether this
814 // declaration name is hidden by a similarly-named declaration in an outer
815 // scope.
816 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
817 --SMEnd;
818 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000819 ShadowMapEntry::iterator I, IEnd;
820 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
821 if (NamePos != SM->end()) {
822 I = NamePos->second.begin();
823 IEnd = NamePos->second.end();
824 }
825 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000826 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000827 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000828 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
829 Decl::IDNS_ObjCProtocol)))
830 continue;
831
832 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000833 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000834 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000835 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000836 continue;
837
838 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000839 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000840 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000841
842 break;
843 }
844 }
845
846 // Make sure that any given declaration only shows up in the result set once.
847 if (!AllDeclsFound.insert(CanonDecl))
848 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000849
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000850 // If the filter is for nested-name-specifiers, then this result starts a
851 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000852 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000853 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000854 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000855 } else
856 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000857
Douglas Gregor0563c262009-09-22 23:15:58 +0000858 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000859 if (R.QualifierIsInformative && !R.Qualifier &&
860 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000861 DeclContext *Ctx = R.Declaration->getDeclContext();
862 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
863 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
864 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
865 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
866 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
867 else
868 R.QualifierIsInformative = false;
869 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000870
Douglas Gregor86d9a522009-09-21 16:56:56 +0000871 // Insert this result into the set of results and into the current shadow
872 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000873 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000874 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000875
876 if (!AsNestedNameSpecifier)
877 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000878}
879
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000880void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000881 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000882 if (R.Kind != Result::RK_Declaration) {
883 // For non-declaration results, just add the result.
884 Results.push_back(R);
885 return;
886 }
887
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000888 // Look through using declarations.
889 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
890 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
891 return;
892 }
893
Douglas Gregor45bcd432010-01-14 03:21:49 +0000894 bool AsNestedNameSpecifier = false;
895 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000896 return;
897
Douglas Gregor6f942b22010-09-21 16:06:22 +0000898 // C++ constructors are never found by name lookup.
899 if (isa<CXXConstructorDecl>(R.Declaration))
900 return;
901
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000902 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
903 return;
904
905 // Make sure that any given declaration only shows up in the result set once.
906 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
907 return;
908
909 // If the filter is for nested-name-specifiers, then this result starts a
910 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000911 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000912 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000913 R.Priority = CCP_NestedNameSpecifier;
914 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000915 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
916 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000917 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000918 R.QualifierIsInformative = true;
919
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000920 // If this result is supposed to have an informative qualifier, add one.
921 if (R.QualifierIsInformative && !R.Qualifier &&
922 !R.StartsNestedNameSpecifier) {
923 DeclContext *Ctx = R.Declaration->getDeclContext();
924 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
925 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
926 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
927 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000928 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000929 else
930 R.QualifierIsInformative = false;
931 }
932
Douglas Gregor12e13132010-05-26 22:00:08 +0000933 // Adjust the priority if this result comes from a base class.
934 if (InBaseClass)
935 R.Priority += CCD_InBaseClass;
936
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000937 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000938
Douglas Gregor3cdee122010-08-26 16:36:48 +0000939 if (HasObjectTypeQualifiers)
940 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
941 if (Method->isInstance()) {
942 Qualifiers MethodQuals
943 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
944 if (ObjectTypeQualifiers == MethodQuals)
945 R.Priority += CCD_ObjectQualifierMatch;
946 else if (ObjectTypeQualifiers - MethodQuals) {
947 // The method cannot be invoked, because doing so would drop
948 // qualifiers.
949 return;
950 }
951 }
952
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000953 // Insert this result into the set of results.
954 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000955
956 if (!AsNestedNameSpecifier)
957 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000958}
959
Douglas Gregora4477812010-01-14 16:01:26 +0000960void ResultBuilder::AddResult(Result R) {
961 assert(R.Kind != Result::RK_Declaration &&
962 "Declaration results need more context");
963 Results.push_back(R);
964}
965
Douglas Gregor86d9a522009-09-21 16:56:56 +0000966/// \brief Enter into a new scope.
967void ResultBuilder::EnterNewScope() {
968 ShadowMaps.push_back(ShadowMap());
969}
970
971/// \brief Exit from the current scope.
972void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000973 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
974 EEnd = ShadowMaps.back().end();
975 E != EEnd;
976 ++E)
977 E->second.Destroy();
978
Douglas Gregor86d9a522009-09-21 16:56:56 +0000979 ShadowMaps.pop_back();
980}
981
Douglas Gregor791215b2009-09-21 20:51:25 +0000982/// \brief Determines whether this given declaration will be found by
983/// ordinary name lookup.
984bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000985 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
986
Douglas Gregor791215b2009-09-21 20:51:25 +0000987 unsigned IDNS = Decl::IDNS_Ordinary;
988 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000989 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000990 else if (SemaRef.getLangOptions().ObjC1) {
991 if (isa<ObjCIvarDecl>(ND))
992 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +0000993 }
994
Douglas Gregor791215b2009-09-21 20:51:25 +0000995 return ND->getIdentifierNamespace() & IDNS;
996}
997
Douglas Gregor01dfea02010-01-10 23:08:15 +0000998/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000999/// ordinary name lookup but is not a type name.
1000bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
1001 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1002 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1003 return false;
1004
1005 unsigned IDNS = Decl::IDNS_Ordinary;
1006 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +00001007 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +00001008 else if (SemaRef.getLangOptions().ObjC1) {
1009 if (isa<ObjCIvarDecl>(ND))
1010 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +00001011 }
1012
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001013 return ND->getIdentifierNamespace() & IDNS;
1014}
1015
Douglas Gregorf9578432010-07-28 21:50:18 +00001016bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
1017 if (!IsOrdinaryNonTypeName(ND))
1018 return 0;
1019
1020 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1021 if (VD->getType()->isIntegralOrEnumerationType())
1022 return true;
1023
1024 return false;
1025}
1026
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001027/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +00001028/// ordinary name lookup.
1029bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001030 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1031
Douglas Gregor01dfea02010-01-10 23:08:15 +00001032 unsigned IDNS = Decl::IDNS_Ordinary;
1033 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +00001034 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001035
1036 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001037 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1038 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001039}
1040
Douglas Gregor86d9a522009-09-21 16:56:56 +00001041/// \brief Determines whether the given declaration is suitable as the
1042/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1043bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1044 // Allow us to find class templates, too.
1045 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1046 ND = ClassTemplate->getTemplatedDecl();
1047
1048 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1049}
1050
1051/// \brief Determines whether the given declaration is an enumeration.
1052bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1053 return isa<EnumDecl>(ND);
1054}
1055
1056/// \brief Determines whether the given declaration is a class or struct.
1057bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1058 // Allow us to find class templates, too.
1059 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1060 ND = ClassTemplate->getTemplatedDecl();
1061
1062 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001063 return RD->getTagKind() == TTK_Class ||
1064 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001065
1066 return false;
1067}
1068
1069/// \brief Determines whether the given declaration is a union.
1070bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1071 // Allow us to find class templates, too.
1072 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1073 ND = ClassTemplate->getTemplatedDecl();
1074
1075 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001076 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001077
1078 return false;
1079}
1080
1081/// \brief Determines whether the given declaration is a namespace.
1082bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1083 return isa<NamespaceDecl>(ND);
1084}
1085
1086/// \brief Determines whether the given declaration is a namespace or
1087/// namespace alias.
1088bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1089 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1090}
1091
Douglas Gregor76282942009-12-11 17:31:05 +00001092/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001093bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001094 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1095 ND = Using->getTargetDecl();
1096
1097 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001098}
1099
Douglas Gregor76282942009-12-11 17:31:05 +00001100/// \brief Determines which members of a class should be visible via
1101/// "." or "->". Only value declarations, nested name specifiers, and
1102/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001103bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001104 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1105 ND = Using->getTargetDecl();
1106
Douglas Gregorce821962009-12-11 18:14:22 +00001107 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1108 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001109}
1110
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001111static bool isObjCReceiverType(ASTContext &C, QualType T) {
1112 T = C.getCanonicalType(T);
1113 switch (T->getTypeClass()) {
1114 case Type::ObjCObject:
1115 case Type::ObjCInterface:
1116 case Type::ObjCObjectPointer:
1117 return true;
1118
1119 case Type::Builtin:
1120 switch (cast<BuiltinType>(T)->getKind()) {
1121 case BuiltinType::ObjCId:
1122 case BuiltinType::ObjCClass:
1123 case BuiltinType::ObjCSel:
1124 return true;
1125
1126 default:
1127 break;
1128 }
1129 return false;
1130
1131 default:
1132 break;
1133 }
1134
1135 if (!C.getLangOptions().CPlusPlus)
1136 return false;
1137
1138 // FIXME: We could perform more analysis here to determine whether a
1139 // particular class type has any conversions to Objective-C types. For now,
1140 // just accept all class types.
1141 return T->isDependentType() || T->isRecordType();
1142}
1143
1144bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1145 QualType T = getDeclUsageType(SemaRef.Context, ND);
1146 if (T.isNull())
1147 return false;
1148
1149 T = SemaRef.Context.getBaseElementType(T);
1150 return isObjCReceiverType(SemaRef.Context, T);
1151}
1152
Douglas Gregorfb629412010-08-23 21:17:50 +00001153bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1154 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1155 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1156 return false;
1157
1158 QualType T = getDeclUsageType(SemaRef.Context, ND);
1159 if (T.isNull())
1160 return false;
1161
1162 T = SemaRef.Context.getBaseElementType(T);
1163 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1164 T->isObjCIdType() ||
1165 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1166}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001167
Douglas Gregor52779fb2010-09-23 23:01:17 +00001168bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1169 return false;
1170}
1171
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001172/// \rief Determines whether the given declaration is an Objective-C
1173/// instance variable.
1174bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1175 return isa<ObjCIvarDecl>(ND);
1176}
1177
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001178namespace {
1179 /// \brief Visible declaration consumer that adds a code-completion result
1180 /// for each visible declaration.
1181 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1182 ResultBuilder &Results;
1183 DeclContext *CurContext;
1184
1185 public:
1186 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1187 : Results(Results), CurContext(CurContext) { }
1188
Douglas Gregor0cc84042010-01-14 15:47:35 +00001189 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1190 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001191 }
1192 };
1193}
1194
Douglas Gregor86d9a522009-09-21 16:56:56 +00001195/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001196static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001197 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001198 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001199 Results.AddResult(Result("short", CCP_Type));
1200 Results.AddResult(Result("long", CCP_Type));
1201 Results.AddResult(Result("signed", CCP_Type));
1202 Results.AddResult(Result("unsigned", CCP_Type));
1203 Results.AddResult(Result("void", CCP_Type));
1204 Results.AddResult(Result("char", CCP_Type));
1205 Results.AddResult(Result("int", CCP_Type));
1206 Results.AddResult(Result("float", CCP_Type));
1207 Results.AddResult(Result("double", CCP_Type));
1208 Results.AddResult(Result("enum", CCP_Type));
1209 Results.AddResult(Result("struct", CCP_Type));
1210 Results.AddResult(Result("union", CCP_Type));
1211 Results.AddResult(Result("const", CCP_Type));
1212 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001213
Douglas Gregor86d9a522009-09-21 16:56:56 +00001214 if (LangOpts.C99) {
1215 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001216 Results.AddResult(Result("_Complex", CCP_Type));
1217 Results.AddResult(Result("_Imaginary", CCP_Type));
1218 Results.AddResult(Result("_Bool", CCP_Type));
1219 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001220 }
1221
Douglas Gregor218937c2011-02-01 19:23:04 +00001222 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001223 if (LangOpts.CPlusPlus) {
1224 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001225 Results.AddResult(Result("bool", CCP_Type +
1226 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001227 Results.AddResult(Result("class", CCP_Type));
1228 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001229
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001230 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001231 Builder.AddTypedTextChunk("typename");
1232 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1233 Builder.AddPlaceholderChunk("qualifier");
1234 Builder.AddTextChunk("::");
1235 Builder.AddPlaceholderChunk("name");
1236 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001237
Douglas Gregor86d9a522009-09-21 16:56:56 +00001238 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001239 Results.AddResult(Result("auto", CCP_Type));
1240 Results.AddResult(Result("char16_t", CCP_Type));
1241 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001242
Douglas Gregor218937c2011-02-01 19:23:04 +00001243 Builder.AddTypedTextChunk("decltype");
1244 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1245 Builder.AddPlaceholderChunk("expression");
1246 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1247 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001248 }
1249 }
1250
1251 // GNU extensions
1252 if (LangOpts.GNUMode) {
1253 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001254 // Results.AddResult(Result("_Decimal32"));
1255 // Results.AddResult(Result("_Decimal64"));
1256 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001257
Douglas Gregor218937c2011-02-01 19:23:04 +00001258 Builder.AddTypedTextChunk("typeof");
1259 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1260 Builder.AddPlaceholderChunk("expression");
1261 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001262
Douglas Gregor218937c2011-02-01 19:23:04 +00001263 Builder.AddTypedTextChunk("typeof");
1264 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1265 Builder.AddPlaceholderChunk("type");
1266 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1267 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001268 }
1269}
1270
John McCallf312b1e2010-08-26 23:41:50 +00001271static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001272 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001273 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001274 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001275 // Note: we don't suggest either "auto" or "register", because both
1276 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1277 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001278 Results.AddResult(Result("extern"));
1279 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001280}
1281
John McCallf312b1e2010-08-26 23:41:50 +00001282static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001283 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001284 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001285 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001286 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001287 case Sema::PCC_Class:
1288 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001289 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001290 Results.AddResult(Result("explicit"));
1291 Results.AddResult(Result("friend"));
1292 Results.AddResult(Result("mutable"));
1293 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001294 }
1295 // Fall through
1296
John McCallf312b1e2010-08-26 23:41:50 +00001297 case Sema::PCC_ObjCInterface:
1298 case Sema::PCC_ObjCImplementation:
1299 case Sema::PCC_Namespace:
1300 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001301 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001302 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001303 break;
1304
John McCallf312b1e2010-08-26 23:41:50 +00001305 case Sema::PCC_ObjCInstanceVariableList:
1306 case Sema::PCC_Expression:
1307 case Sema::PCC_Statement:
1308 case Sema::PCC_ForInit:
1309 case Sema::PCC_Condition:
1310 case Sema::PCC_RecoveryInFunction:
1311 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001312 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001313 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001314 break;
1315 }
1316}
1317
Douglas Gregorbca403c2010-01-13 23:51:12 +00001318static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1319static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1320static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001321 ResultBuilder &Results,
1322 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001323static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001324 ResultBuilder &Results,
1325 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001326static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001327 ResultBuilder &Results,
1328 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001329static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001330
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001331static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001332 CodeCompletionBuilder Builder(Results.getAllocator());
1333 Builder.AddTypedTextChunk("typedef");
1334 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1335 Builder.AddPlaceholderChunk("type");
1336 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1337 Builder.AddPlaceholderChunk("name");
1338 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001339}
1340
John McCallf312b1e2010-08-26 23:41:50 +00001341static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001342 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001343 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001344 case Sema::PCC_Namespace:
1345 case Sema::PCC_Class:
1346 case Sema::PCC_ObjCInstanceVariableList:
1347 case Sema::PCC_Template:
1348 case Sema::PCC_MemberTemplate:
1349 case Sema::PCC_Statement:
1350 case Sema::PCC_RecoveryInFunction:
1351 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001352 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001353 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001354 return true;
1355
John McCallf312b1e2010-08-26 23:41:50 +00001356 case Sema::PCC_Expression:
1357 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001358 return LangOpts.CPlusPlus;
1359
1360 case Sema::PCC_ObjCInterface:
1361 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001362 return false;
1363
John McCallf312b1e2010-08-26 23:41:50 +00001364 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001365 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001366 }
1367
1368 return false;
1369}
1370
Douglas Gregor01dfea02010-01-10 23:08:15 +00001371/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001372static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001373 Scope *S,
1374 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001375 ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001376 CodeCompletionBuilder Builder(Results.getAllocator());
1377
John McCall0a2c5e22010-08-25 06:19:51 +00001378 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001379 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001380 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001381 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001382 if (Results.includeCodePatterns()) {
1383 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001384 Builder.AddTypedTextChunk("namespace");
1385 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1386 Builder.AddPlaceholderChunk("identifier");
1387 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1388 Builder.AddPlaceholderChunk("declarations");
1389 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1390 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1391 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001392 }
1393
Douglas Gregor01dfea02010-01-10 23:08:15 +00001394 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001395 Builder.AddTypedTextChunk("namespace");
1396 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1397 Builder.AddPlaceholderChunk("name");
1398 Builder.AddChunk(CodeCompletionString::CK_Equal);
1399 Builder.AddPlaceholderChunk("namespace");
1400 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001401
1402 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001403 Builder.AddTypedTextChunk("using");
1404 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1405 Builder.AddTextChunk("namespace");
1406 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1407 Builder.AddPlaceholderChunk("identifier");
1408 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001409
1410 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001411 Builder.AddTypedTextChunk("asm");
1412 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1413 Builder.AddPlaceholderChunk("string-literal");
1414 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1415 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001416
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001417 if (Results.includeCodePatterns()) {
1418 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001419 Builder.AddTypedTextChunk("template");
1420 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1421 Builder.AddPlaceholderChunk("declaration");
1422 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001423 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001424 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001425
1426 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001427 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001428
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001429 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001430 // Fall through
1431
John McCallf312b1e2010-08-26 23:41:50 +00001432 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001433 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001434 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001435 Builder.AddTypedTextChunk("using");
1436 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1437 Builder.AddPlaceholderChunk("qualifier");
1438 Builder.AddTextChunk("::");
1439 Builder.AddPlaceholderChunk("name");
1440 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001441
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001442 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001443 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001444 Builder.AddTypedTextChunk("using");
1445 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1446 Builder.AddTextChunk("typename");
1447 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1448 Builder.AddPlaceholderChunk("qualifier");
1449 Builder.AddTextChunk("::");
1450 Builder.AddPlaceholderChunk("name");
1451 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001452 }
1453
John McCallf312b1e2010-08-26 23:41:50 +00001454 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001455 AddTypedefResult(Results);
1456
Douglas Gregor01dfea02010-01-10 23:08:15 +00001457 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001458 Builder.AddTypedTextChunk("public");
1459 Builder.AddChunk(CodeCompletionString::CK_Colon);
1460 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001461
1462 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001463 Builder.AddTypedTextChunk("protected");
1464 Builder.AddChunk(CodeCompletionString::CK_Colon);
1465 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001466
1467 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001468 Builder.AddTypedTextChunk("private");
1469 Builder.AddChunk(CodeCompletionString::CK_Colon);
1470 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001471 }
1472 }
1473 // Fall through
1474
John McCallf312b1e2010-08-26 23:41:50 +00001475 case Sema::PCC_Template:
1476 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001477 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001478 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001479 Builder.AddTypedTextChunk("template");
1480 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1481 Builder.AddPlaceholderChunk("parameters");
1482 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1483 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001484 }
1485
Douglas Gregorbca403c2010-01-13 23:51:12 +00001486 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1487 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001488 break;
1489
John McCallf312b1e2010-08-26 23:41:50 +00001490 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001491 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1492 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1493 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001494 break;
1495
John McCallf312b1e2010-08-26 23:41:50 +00001496 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001497 AddObjCImplementationResults(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_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001503 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001504 break;
1505
John McCallf312b1e2010-08-26 23:41:50 +00001506 case Sema::PCC_RecoveryInFunction:
1507 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001508 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001509
Douglas Gregorec3310a2011-04-12 02:47:21 +00001510 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1511 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001512 Builder.AddTypedTextChunk("try");
1513 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1514 Builder.AddPlaceholderChunk("statements");
1515 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1516 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1517 Builder.AddTextChunk("catch");
1518 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1519 Builder.AddPlaceholderChunk("declaration");
1520 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1521 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1522 Builder.AddPlaceholderChunk("statements");
1523 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1524 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1525 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001526 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001527 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001528 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001529
Douglas Gregord8e8a582010-05-25 21:41:55 +00001530 if (Results.includeCodePatterns()) {
1531 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001532 Builder.AddTypedTextChunk("if");
1533 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001534 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001535 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001536 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001537 Builder.AddPlaceholderChunk("expression");
1538 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1539 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1540 Builder.AddPlaceholderChunk("statements");
1541 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1542 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1543 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001544
Douglas Gregord8e8a582010-05-25 21:41:55 +00001545 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001546 Builder.AddTypedTextChunk("switch");
1547 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001548 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001549 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001550 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001551 Builder.AddPlaceholderChunk("expression");
1552 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1553 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1554 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1555 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1556 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001557 }
1558
Douglas Gregor01dfea02010-01-10 23:08:15 +00001559 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001560 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001561 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001562 Builder.AddTypedTextChunk("case");
1563 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1564 Builder.AddPlaceholderChunk("expression");
1565 Builder.AddChunk(CodeCompletionString::CK_Colon);
1566 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001567
1568 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001569 Builder.AddTypedTextChunk("default");
1570 Builder.AddChunk(CodeCompletionString::CK_Colon);
1571 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001572 }
1573
Douglas Gregord8e8a582010-05-25 21:41:55 +00001574 if (Results.includeCodePatterns()) {
1575 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001576 Builder.AddTypedTextChunk("while");
1577 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001578 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001579 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001580 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001581 Builder.AddPlaceholderChunk("expression");
1582 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1583 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1584 Builder.AddPlaceholderChunk("statements");
1585 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1586 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1587 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001588
1589 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001590 Builder.AddTypedTextChunk("do");
1591 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1592 Builder.AddPlaceholderChunk("statements");
1593 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1594 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1595 Builder.AddTextChunk("while");
1596 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1597 Builder.AddPlaceholderChunk("expression");
1598 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1599 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001600
Douglas Gregord8e8a582010-05-25 21:41:55 +00001601 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001602 Builder.AddTypedTextChunk("for");
1603 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001604 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001605 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001606 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001607 Builder.AddPlaceholderChunk("init-expression");
1608 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1609 Builder.AddPlaceholderChunk("condition");
1610 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1611 Builder.AddPlaceholderChunk("inc-expression");
1612 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1613 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1614 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1615 Builder.AddPlaceholderChunk("statements");
1616 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1617 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1618 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001619 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001620
1621 if (S->getContinueParent()) {
1622 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001623 Builder.AddTypedTextChunk("continue");
1624 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001625 }
1626
1627 if (S->getBreakParent()) {
1628 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001629 Builder.AddTypedTextChunk("break");
1630 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001631 }
1632
1633 // "return expression ;" or "return ;", depending on whether we
1634 // know the function is void or not.
1635 bool isVoid = false;
1636 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1637 isVoid = Function->getResultType()->isVoidType();
1638 else if (ObjCMethodDecl *Method
1639 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1640 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001641 else if (SemaRef.getCurBlock() &&
1642 !SemaRef.getCurBlock()->ReturnType.isNull())
1643 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001644 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001645 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001646 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1647 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001648 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001649 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001650
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001651 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001652 Builder.AddTypedTextChunk("goto");
1653 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1654 Builder.AddPlaceholderChunk("label");
1655 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001656
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001657 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001658 Builder.AddTypedTextChunk("using");
1659 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1660 Builder.AddTextChunk("namespace");
1661 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1662 Builder.AddPlaceholderChunk("identifier");
1663 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001664 }
1665
1666 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001667 case Sema::PCC_ForInit:
1668 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001669 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001670 // Fall through: conditions and statements can have expressions.
1671
Douglas Gregor02688102010-09-14 23:59:36 +00001672 case Sema::PCC_ParenthesizedExpression:
John McCallf85e1932011-06-15 23:02:42 +00001673 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1674 CCC == Sema::PCC_ParenthesizedExpression) {
1675 // (__bridge <type>)<expression>
1676 Builder.AddTypedTextChunk("__bridge");
1677 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1678 Builder.AddPlaceholderChunk("type");
1679 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1680 Builder.AddPlaceholderChunk("expression");
1681 Results.AddResult(Result(Builder.TakeString()));
1682
1683 // (__bridge_transfer <Objective-C type>)<expression>
1684 Builder.AddTypedTextChunk("__bridge_transfer");
1685 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1686 Builder.AddPlaceholderChunk("Objective-C type");
1687 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1688 Builder.AddPlaceholderChunk("expression");
1689 Results.AddResult(Result(Builder.TakeString()));
1690
1691 // (__bridge_retained <CF type>)<expression>
1692 Builder.AddTypedTextChunk("__bridge_retained");
1693 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1694 Builder.AddPlaceholderChunk("CF type");
1695 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1696 Builder.AddPlaceholderChunk("expression");
1697 Results.AddResult(Result(Builder.TakeString()));
1698 }
1699 // Fall through
1700
John McCallf312b1e2010-08-26 23:41:50 +00001701 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001702 if (SemaRef.getLangOptions().CPlusPlus) {
1703 // 'this', if we're in a non-static member function.
1704 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1705 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001706 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001707
1708 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001709 Results.AddResult(Result("true"));
1710 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001711
Douglas Gregorec3310a2011-04-12 02:47:21 +00001712 if (SemaRef.getLangOptions().RTTI) {
1713 // dynamic_cast < type-id > ( expression )
1714 Builder.AddTypedTextChunk("dynamic_cast");
1715 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1716 Builder.AddPlaceholderChunk("type");
1717 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1718 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1719 Builder.AddPlaceholderChunk("expression");
1720 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1721 Results.AddResult(Result(Builder.TakeString()));
1722 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001723
1724 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001725 Builder.AddTypedTextChunk("static_cast");
1726 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1727 Builder.AddPlaceholderChunk("type");
1728 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1729 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1730 Builder.AddPlaceholderChunk("expression");
1731 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1732 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001733
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001734 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001735 Builder.AddTypedTextChunk("reinterpret_cast");
1736 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1737 Builder.AddPlaceholderChunk("type");
1738 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1739 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1740 Builder.AddPlaceholderChunk("expression");
1741 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1742 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001743
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001744 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001745 Builder.AddTypedTextChunk("const_cast");
1746 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1747 Builder.AddPlaceholderChunk("type");
1748 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1749 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1750 Builder.AddPlaceholderChunk("expression");
1751 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1752 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001753
Douglas Gregorec3310a2011-04-12 02:47:21 +00001754 if (SemaRef.getLangOptions().RTTI) {
1755 // typeid ( expression-or-type )
1756 Builder.AddTypedTextChunk("typeid");
1757 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1758 Builder.AddPlaceholderChunk("expression-or-type");
1759 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1760 Results.AddResult(Result(Builder.TakeString()));
1761 }
1762
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001763 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001764 Builder.AddTypedTextChunk("new");
1765 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1766 Builder.AddPlaceholderChunk("type");
1767 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1768 Builder.AddPlaceholderChunk("expressions");
1769 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1770 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001771
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001772 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001773 Builder.AddTypedTextChunk("new");
1774 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1775 Builder.AddPlaceholderChunk("type");
1776 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1777 Builder.AddPlaceholderChunk("size");
1778 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1779 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1780 Builder.AddPlaceholderChunk("expressions");
1781 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1782 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001783
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001784 // delete expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001785 Builder.AddTypedTextChunk("delete");
1786 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1787 Builder.AddPlaceholderChunk("expression");
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.AddChunk(CodeCompletionString::CK_LeftBracket);
1794 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1795 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1796 Builder.AddPlaceholderChunk("expression");
1797 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001798
Douglas Gregorec3310a2011-04-12 02:47:21 +00001799 if (SemaRef.getLangOptions().CXXExceptions) {
1800 // throw expression
1801 Builder.AddTypedTextChunk("throw");
1802 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1803 Builder.AddPlaceholderChunk("expression");
1804 Results.AddResult(Result(Builder.TakeString()));
1805 }
Douglas Gregor12e13132010-05-26 22:00:08 +00001806
1807 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001808 }
1809
1810 if (SemaRef.getLangOptions().ObjC1) {
1811 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001812 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1813 // The interface can be NULL.
1814 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1815 if (ID->getSuperClass())
1816 Results.AddResult(Result("super"));
1817 }
1818
Douglas Gregorbca403c2010-01-13 23:51:12 +00001819 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001820 }
1821
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001822 // sizeof expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001823 Builder.AddTypedTextChunk("sizeof");
1824 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1825 Builder.AddPlaceholderChunk("expression-or-type");
1826 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1827 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001828 break;
1829 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001830
John McCallf312b1e2010-08-26 23:41:50 +00001831 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001832 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001833 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001834 }
1835
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001836 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1837 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001838
John McCallf312b1e2010-08-26 23:41:50 +00001839 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001840 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001841}
1842
Douglas Gregor30c42402011-09-27 22:38:19 +00001843/// \brief Retrieve a printing policy suitable for code completion.
1844static PrintingPolicy getCompletionPrintingPolicy(ASTContext &Context) {
1845 PrintingPolicy Policy(Context.getPrintingPolicy());
1846 Policy.AnonymousTagLocations = false;
1847 Policy.SuppressStrongLifetime = true;
1848 return Policy;
1849}
1850
Douglas Gregora63f6de2011-02-01 21:15:40 +00001851/// \brief Retrieve the string representation of the given type as a string
1852/// that has the appropriate lifetime for code completion.
1853///
1854/// This routine provides a fast path where we provide constant strings for
1855/// common type names.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001856static const char *GetCompletionTypeString(QualType T,
1857 ASTContext &Context,
1858 CodeCompletionAllocator &Allocator) {
Douglas Gregor30c42402011-09-27 22:38:19 +00001859 PrintingPolicy Policy = getCompletionPrintingPolicy(Context);
John McCallf85e1932011-06-15 23:02:42 +00001860
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))
Douglas Gregor30c42402011-09-27 22:38:19 +00001864 return BT->getName(Policy);
Douglas Gregora63f6de2011-02-01 21:15:40 +00001865
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) {
Douglas Gregor30c42402011-09-27 22:38:19 +00001961 PrintingPolicy Policy = getCompletionPrintingPolicy(Context);
Douglas Gregor83482d12010-08-24 16:15:59 +00001962 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1963 if (Param->getType()->isDependentType() ||
1964 !Param->getType()->isBlockPointerType()) {
1965 // The argument for a dependent or non-block parameter is a placeholder
1966 // containing that parameter's type.
1967 std::string Result;
1968
Douglas Gregoraba48082010-08-29 19:47:46 +00001969 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001970 Result = Param->getIdentifier()->getName();
1971
John McCallf85e1932011-06-15 23:02:42 +00001972 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00001973
1974 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00001975 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
1976 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001977 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001978 Result += Param->getIdentifier()->getName();
1979 }
1980 return Result;
1981 }
1982
1983 // The argument for a block pointer parameter is a block literal with
1984 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00001985 FunctionTypeLoc *Block = 0;
1986 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00001987 TypeLoc TL;
1988 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1989 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1990 while (true) {
1991 // Look through typedefs.
1992 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1993 if (TypeSourceInfo *InnerTSInfo
Richard Smith162e1c12011-04-15 14:24:37 +00001994 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001995 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1996 continue;
1997 }
1998 }
1999
2000 // Look through qualified types
2001 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2002 TL = QualifiedTL->getUnqualifiedLoc();
2003 continue;
2004 }
2005
2006 // Try to get the function prototype behind the block pointer type,
2007 // then we're done.
2008 if (BlockPointerTypeLoc *BlockPtr
2009 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002010 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002011 Block = dyn_cast<FunctionTypeLoc>(&TL);
2012 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002013 }
2014 break;
2015 }
2016 }
2017
2018 if (!Block) {
2019 // We were unable to find a FunctionProtoTypeLoc with parameter names
2020 // for the block; just use the parameter type as a placeholder.
2021 std::string Result;
John McCallf85e1932011-06-15 23:02:42 +00002022 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002023
2024 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002025 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2026 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002027 if (Param->getIdentifier())
2028 Result += Param->getIdentifier()->getName();
2029 }
2030
2031 return Result;
2032 }
2033
2034 // We have the function prototype behind the block pointer type, as it was
2035 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002036 std::string Result;
2037 QualType ResultType = Block->getTypePtr()->getResultType();
2038 if (!ResultType->isVoidType())
John McCallf85e1932011-06-15 23:02:42 +00002039 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregor38276252010-09-08 22:47:51 +00002040
2041 Result = '^' + Result;
Douglas Gregor830072c2011-02-15 22:37:09 +00002042 if (!BlockProto || Block->getNumArgs() == 0) {
2043 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002044 Result += "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002045 else
2046 Result += "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002047 } else {
2048 Result += "(";
2049 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2050 if (I)
2051 Result += ", ";
2052 Result += FormatFunctionParameter(Context, Block->getArg(I));
2053
Douglas Gregor830072c2011-02-15 22:37:09 +00002054 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002055 Result += ", ...";
2056 }
2057 Result += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002058 }
Douglas Gregor38276252010-09-08 22:47:51 +00002059
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002060 if (Param->getIdentifier())
2061 Result += Param->getIdentifier()->getName();
2062
Douglas Gregor83482d12010-08-24 16:15:59 +00002063 return Result;
2064}
2065
Douglas Gregor86d9a522009-09-21 16:56:56 +00002066/// \brief Add function parameter chunks to the given code completion string.
2067static void AddFunctionParameterChunks(ASTContext &Context,
2068 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002069 CodeCompletionBuilder &Result,
2070 unsigned Start = 0,
2071 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002072 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002073 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002074
Douglas Gregor218937c2011-02-01 19:23:04 +00002075 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002076 ParmVarDecl *Param = Function->getParamDecl(P);
2077
Douglas Gregor218937c2011-02-01 19:23:04 +00002078 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002079 // When we see an optional default argument, put that argument and
2080 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002081 CodeCompletionBuilder Opt(Result.getAllocator());
2082 if (!FirstParameter)
2083 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2084 AddFunctionParameterChunks(Context, Function, Opt, P, true);
2085 Result.AddOptionalChunk(Opt.TakeString());
2086 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002087 }
2088
Douglas Gregor218937c2011-02-01 19:23:04 +00002089 if (FirstParameter)
2090 FirstParameter = false;
2091 else
2092 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2093
2094 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002095
2096 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00002097 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
2098
Douglas Gregore17794f2010-08-31 05:13:43 +00002099 if (Function->isVariadic() && P == N - 1)
2100 PlaceholderStr += ", ...";
2101
Douglas Gregor86d9a522009-09-21 16:56:56 +00002102 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002103 Result.AddPlaceholderChunk(
2104 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002105 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002106
2107 if (const FunctionProtoType *Proto
2108 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002109 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002110 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002111 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002112
Douglas Gregor218937c2011-02-01 19:23:04 +00002113 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002114 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002115}
2116
2117/// \brief Add template parameter chunks to the given code completion string.
2118static void AddTemplateParameterChunks(ASTContext &Context,
2119 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002120 CodeCompletionBuilder &Result,
2121 unsigned MaxParameters = 0,
2122 unsigned Start = 0,
2123 bool InDefaultArg = false) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002124 PrintingPolicy Policy = getCompletionPrintingPolicy(Context);
John McCallf85e1932011-06-15 23:02:42 +00002125
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002126 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002127 bool FirstParameter = true;
2128
2129 TemplateParameterList *Params = Template->getTemplateParameters();
2130 TemplateParameterList::iterator PEnd = Params->end();
2131 if (MaxParameters)
2132 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002133 for (TemplateParameterList::iterator P = Params->begin() + Start;
2134 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002135 bool HasDefaultArg = false;
2136 std::string PlaceholderStr;
2137 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2138 if (TTP->wasDeclaredWithTypename())
2139 PlaceholderStr = "typename";
2140 else
2141 PlaceholderStr = "class";
2142
2143 if (TTP->getIdentifier()) {
2144 PlaceholderStr += ' ';
2145 PlaceholderStr += TTP->getIdentifier()->getName();
2146 }
2147
2148 HasDefaultArg = TTP->hasDefaultArgument();
2149 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002150 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002151 if (NTTP->getIdentifier())
2152 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002153 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002154 HasDefaultArg = NTTP->hasDefaultArgument();
2155 } else {
2156 assert(isa<TemplateTemplateParmDecl>(*P));
2157 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2158
2159 // Since putting the template argument list into the placeholder would
2160 // be very, very long, we just use an abbreviation.
2161 PlaceholderStr = "template<...> class";
2162 if (TTP->getIdentifier()) {
2163 PlaceholderStr += ' ';
2164 PlaceholderStr += TTP->getIdentifier()->getName();
2165 }
2166
2167 HasDefaultArg = TTP->hasDefaultArgument();
2168 }
2169
Douglas Gregor218937c2011-02-01 19:23:04 +00002170 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002171 // When we see an optional default argument, put that argument and
2172 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002173 CodeCompletionBuilder Opt(Result.getAllocator());
2174 if (!FirstParameter)
2175 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2176 AddTemplateParameterChunks(Context, Template, Opt, MaxParameters,
2177 P - Params->begin(), true);
2178 Result.AddOptionalChunk(Opt.TakeString());
2179 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002180 }
2181
Douglas Gregor218937c2011-02-01 19:23:04 +00002182 InDefaultArg = false;
2183
Douglas Gregor86d9a522009-09-21 16:56:56 +00002184 if (FirstParameter)
2185 FirstParameter = false;
2186 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002187 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002188
2189 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002190 Result.AddPlaceholderChunk(
2191 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002192 }
2193}
2194
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002195/// \brief Add a qualifier to the given code-completion string, if the
2196/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002197static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002198AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002199 NestedNameSpecifier *Qualifier,
2200 bool QualifierIsInformative,
2201 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002202 if (!Qualifier)
2203 return;
2204
2205 std::string PrintedNNS;
2206 {
2207 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor30c42402011-09-27 22:38:19 +00002208 Qualifier->print(OS, getCompletionPrintingPolicy(Context));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002209 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002210 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002211 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002212 else
Douglas Gregordae68752011-02-01 22:57:45 +00002213 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002214}
2215
Douglas Gregor218937c2011-02-01 19:23:04 +00002216static void
2217AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2218 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002219 const FunctionProtoType *Proto
2220 = Function->getType()->getAs<FunctionProtoType>();
2221 if (!Proto || !Proto->getTypeQuals())
2222 return;
2223
Douglas Gregora63f6de2011-02-01 21:15:40 +00002224 // FIXME: Add ref-qualifier!
2225
2226 // Handle single qualifiers without copying
2227 if (Proto->getTypeQuals() == Qualifiers::Const) {
2228 Result.AddInformativeChunk(" const");
2229 return;
2230 }
2231
2232 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2233 Result.AddInformativeChunk(" volatile");
2234 return;
2235 }
2236
2237 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2238 Result.AddInformativeChunk(" restrict");
2239 return;
2240 }
2241
2242 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002243 std::string QualsStr;
2244 if (Proto->getTypeQuals() & Qualifiers::Const)
2245 QualsStr += " const";
2246 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2247 QualsStr += " volatile";
2248 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2249 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002250 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002251}
2252
Douglas Gregor6f942b22010-09-21 16:06:22 +00002253/// \brief Add the name of the given declaration
2254static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00002255 CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002256 typedef CodeCompletionString::Chunk Chunk;
2257
2258 DeclarationName Name = ND->getDeclName();
2259 if (!Name)
2260 return;
2261
2262 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002263 case DeclarationName::CXXOperatorName: {
2264 const char *OperatorName = 0;
2265 switch (Name.getCXXOverloadedOperator()) {
2266 case OO_None:
2267 case OO_Conditional:
2268 case NUM_OVERLOADED_OPERATORS:
2269 OperatorName = "operator";
2270 break;
2271
2272#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2273 case OO_##Name: OperatorName = "operator" Spelling; break;
2274#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2275#include "clang/Basic/OperatorKinds.def"
2276
2277 case OO_New: OperatorName = "operator new"; break;
2278 case OO_Delete: OperatorName = "operator delete"; break;
2279 case OO_Array_New: OperatorName = "operator new[]"; break;
2280 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2281 case OO_Call: OperatorName = "operator()"; break;
2282 case OO_Subscript: OperatorName = "operator[]"; break;
2283 }
2284 Result.AddTypedTextChunk(OperatorName);
2285 break;
2286 }
2287
Douglas Gregor6f942b22010-09-21 16:06:22 +00002288 case DeclarationName::Identifier:
2289 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002290 case DeclarationName::CXXDestructorName:
2291 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002292 Result.AddTypedTextChunk(
2293 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002294 break;
2295
2296 case DeclarationName::CXXUsingDirective:
2297 case DeclarationName::ObjCZeroArgSelector:
2298 case DeclarationName::ObjCOneArgSelector:
2299 case DeclarationName::ObjCMultiArgSelector:
2300 break;
2301
2302 case DeclarationName::CXXConstructorName: {
2303 CXXRecordDecl *Record = 0;
2304 QualType Ty = Name.getCXXNameType();
2305 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2306 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2307 else if (const InjectedClassNameType *InjectedTy
2308 = Ty->getAs<InjectedClassNameType>())
2309 Record = InjectedTy->getDecl();
2310 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002311 Result.AddTypedTextChunk(
2312 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002313 break;
2314 }
2315
Douglas Gregordae68752011-02-01 22:57:45 +00002316 Result.AddTypedTextChunk(
2317 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002318 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002319 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002320 AddTemplateParameterChunks(Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002321 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002322 }
2323 break;
2324 }
2325 }
2326}
2327
Douglas Gregor86d9a522009-09-21 16:56:56 +00002328/// \brief If possible, create a new code completion string for the given
2329/// result.
2330///
2331/// \returns Either a new, heap-allocated code completion string describing
2332/// how to use this result, or NULL to indicate that the string or name of the
2333/// result is all that is needed.
2334CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002335CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002336 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002337 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002338 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002339
Douglas Gregor30c42402011-09-27 22:38:19 +00002340 PrintingPolicy Policy = getCompletionPrintingPolicy(S.Context);
Douglas Gregor218937c2011-02-01 19:23:04 +00002341 if (Kind == RK_Pattern) {
2342 Pattern->Priority = Priority;
2343 Pattern->Availability = Availability;
2344 return Pattern;
2345 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002346
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002347 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002348 Result.AddTypedTextChunk(Keyword);
2349 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002350 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002351
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002352 if (Kind == RK_Macro) {
2353 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002354 assert(MI && "Not a macro?");
2355
Douglas Gregordae68752011-02-01 22:57:45 +00002356 Result.AddTypedTextChunk(
2357 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002358
2359 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002360 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002361
2362 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002363 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregore4244702011-07-30 08:17:44 +00002364 bool CombineVariadicArgument = false;
2365 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2366 if (MI->isVariadic() && AEnd - A > 1) {
2367 AEnd -= 2;
2368 CombineVariadicArgument = true;
2369 }
2370 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002371 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002372 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002373
Douglas Gregore4244702011-07-30 08:17:44 +00002374 if (!MI->isVariadic() || A + 1 != AEnd) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002375 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002376 Result.AddPlaceholderChunk(
2377 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002378 continue;
2379 }
2380
Douglas Gregore4244702011-07-30 08:17:44 +00002381 // Variadic argument; cope with the difference between GNU and C99
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002382 // variadic macros, providing a single placeholder for the rest of the
2383 // arguments.
2384 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002385 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002386 else {
2387 std::string Arg = (*A)->getName();
2388 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002389 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002390 }
2391 }
Douglas Gregore4244702011-07-30 08:17:44 +00002392
2393 if (CombineVariadicArgument) {
2394 // Handle the next-to-last argument, combining it with the variadic
2395 // argument.
2396 std::string LastArg = (*A)->getName();
2397 ++A;
2398 if ((*A)->isStr("__VA_ARGS__"))
2399 LastArg += ", ...";
2400 else
2401 LastArg += ", " + (*A)->getName().str() + "...";
2402 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(LastArg));
2403 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002404 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2405 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002406 }
2407
Douglas Gregord8e8a582010-05-25 21:41:55 +00002408 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002409 NamedDecl *ND = Declaration;
2410
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002411 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002412 Result.AddTypedTextChunk(
2413 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002414 Result.AddTextChunk("::");
2415 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002416 }
2417
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002418 AddResultTypeChunk(S.Context, ND, Result);
2419
Douglas Gregor86d9a522009-09-21 16:56:56 +00002420 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002421 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2422 S.Context);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002423 AddTypedNameChunk(S.Context, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002424 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002425 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002426 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002427 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002428 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002429 }
2430
2431 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002432 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2433 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002434 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor6f942b22010-09-21 16:06:22 +00002435 AddTypedNameChunk(S.Context, Function, Result);
2436
Douglas Gregor86d9a522009-09-21 16:56:56 +00002437 // Figure out which template parameters are deduced (or have default
2438 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002439 SmallVector<bool, 16> Deduced;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002440 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2441 unsigned LastDeducibleArgument;
2442 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2443 --LastDeducibleArgument) {
2444 if (!Deduced[LastDeducibleArgument - 1]) {
2445 // C++0x: Figure out if the template argument has a default. If so,
2446 // the user doesn't need to type this argument.
2447 // FIXME: We need to abstract template parameters better!
2448 bool HasDefaultArg = false;
2449 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002450 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002451 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2452 HasDefaultArg = TTP->hasDefaultArgument();
2453 else if (NonTypeTemplateParmDecl *NTTP
2454 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2455 HasDefaultArg = NTTP->hasDefaultArgument();
2456 else {
2457 assert(isa<TemplateTemplateParmDecl>(Param));
2458 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002459 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002460 }
2461
2462 if (!HasDefaultArg)
2463 break;
2464 }
2465 }
2466
2467 if (LastDeducibleArgument) {
2468 // Some of the function template arguments cannot be deduced from a
2469 // function call, so we introduce an explicit template argument list
2470 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002471 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002472 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2473 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002474 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002475 }
2476
2477 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002478 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002479 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002480 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002481 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002482 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002483 }
2484
2485 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002486 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2487 S.Context);
Douglas Gregordae68752011-02-01 22:57:45 +00002488 Result.AddTypedTextChunk(
2489 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002490 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002491 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002492 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2493 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002494 }
2495
Douglas Gregor9630eb62009-11-17 16:44:22 +00002496 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002497 Selector Sel = Method->getSelector();
2498 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002499 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002500 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002501 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002502 }
2503
Douglas Gregor813d8342011-02-18 22:29:55 +00002504 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002505 SelName += ':';
2506 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002507 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002508 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002509 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002510
2511 // If there is only one parameter, and we're past it, add an empty
2512 // typed-text chunk since there is nothing to type.
2513 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002514 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002515 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002516 unsigned Idx = 0;
2517 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2518 PEnd = Method->param_end();
2519 P != PEnd; (void)++P, ++Idx) {
2520 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002521 std::string Keyword;
2522 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002523 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002524 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002525 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002526 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002527 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002528 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002529 else
Douglas Gregordae68752011-02-01 22:57:45 +00002530 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002531 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002532
2533 // If we're before the starting parameter, skip the placeholder.
2534 if (Idx < StartParameter)
2535 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002536
2537 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002538
2539 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregoraba48082010-08-29 19:47:46 +00002540 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002541 else {
John McCallf85e1932011-06-15 23:02:42 +00002542 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002543 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2544 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002545 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002546 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002547 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002548 }
2549
Douglas Gregore17794f2010-08-31 05:13:43 +00002550 if (Method->isVariadic() && (P + 1) == PEnd)
2551 Arg += ", ...";
2552
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002553 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002554 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002555 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002556 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002557 else
Douglas Gregordae68752011-02-01 22:57:45 +00002558 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002559 }
2560
Douglas Gregor2a17af02009-12-23 00:21:46 +00002561 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002562 if (Method->param_size() == 0) {
2563 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002564 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002565 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002566 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002567 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002568 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002569 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002570
2571 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002572 }
2573
Douglas Gregor218937c2011-02-01 19:23:04 +00002574 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002575 }
2576
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002577 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002578 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2579 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002580
Douglas Gregordae68752011-02-01 22:57:45 +00002581 Result.AddTypedTextChunk(
2582 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002583 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002584}
2585
Douglas Gregor86d802e2009-09-23 00:34:09 +00002586CodeCompletionString *
2587CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2588 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002589 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002590 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002591 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor30c42402011-09-27 22:38:19 +00002592 PrintingPolicy Policy = getCompletionPrintingPolicy(S.Context);
John McCallf85e1932011-06-15 23:02:42 +00002593
Douglas Gregor218937c2011-02-01 19:23:04 +00002594 // FIXME: Set priority, availability appropriately.
2595 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002596 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002597 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002598 const FunctionProtoType *Proto
2599 = dyn_cast<FunctionProtoType>(getFunctionType());
2600 if (!FDecl && !Proto) {
2601 // Function without a prototype. Just give the return type and a
2602 // highlighted ellipsis.
2603 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002604 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
2605 S.Context,
2606 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002607 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2608 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2609 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2610 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002611 }
2612
2613 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002614 Result.AddTextChunk(
2615 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002616 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002617 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002618 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002619 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002620
Douglas Gregor218937c2011-02-01 19:23:04 +00002621 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002622 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2623 for (unsigned I = 0; I != NumParams; ++I) {
2624 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002625 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002626
2627 std::string ArgString;
2628 QualType ArgType;
2629
2630 if (FDecl) {
2631 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2632 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2633 } else {
2634 ArgType = Proto->getArgType(I);
2635 }
2636
John McCallf85e1932011-06-15 23:02:42 +00002637 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002638
2639 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002640 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002641 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002642 else
Douglas Gregordae68752011-02-01 22:57:45 +00002643 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002644 }
2645
2646 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002647 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002648 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002649 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002650 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002651 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002652 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002653 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002654
Douglas Gregor218937c2011-02-01 19:23:04 +00002655 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002656}
2657
Chris Lattner5f9e2722011-07-23 10:55:15 +00002658unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002659 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002660 bool PreferredTypeIsPointer) {
2661 unsigned Priority = CCP_Macro;
2662
Douglas Gregorb05496d2010-09-20 21:11:48 +00002663 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2664 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2665 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002666 Priority = CCP_Constant;
2667 if (PreferredTypeIsPointer)
2668 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002669 }
2670 // Treat "YES", "NO", "true", and "false" as constants.
2671 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2672 MacroName.equals("true") || MacroName.equals("false"))
2673 Priority = CCP_Constant;
2674 // Treat "bool" as a type.
2675 else if (MacroName.equals("bool"))
2676 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2677
Douglas Gregor1827e102010-08-16 16:18:59 +00002678
2679 return Priority;
2680}
2681
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002682CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2683 if (!D)
2684 return CXCursor_UnexposedDecl;
2685
2686 switch (D->getKind()) {
2687 case Decl::Enum: return CXCursor_EnumDecl;
2688 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2689 case Decl::Field: return CXCursor_FieldDecl;
2690 case Decl::Function:
2691 return CXCursor_FunctionDecl;
2692 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2693 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2694 case Decl::ObjCClass:
2695 // FIXME
2696 return CXCursor_UnexposedDecl;
2697 case Decl::ObjCForwardProtocol:
2698 // FIXME
2699 return CXCursor_UnexposedDecl;
2700 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2701 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2702 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2703 case Decl::ObjCMethod:
2704 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2705 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2706 case Decl::CXXMethod: return CXCursor_CXXMethod;
2707 case Decl::CXXConstructor: return CXCursor_Constructor;
2708 case Decl::CXXDestructor: return CXCursor_Destructor;
2709 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2710 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2711 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2712 case Decl::ParmVar: return CXCursor_ParmDecl;
2713 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002714 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002715 case Decl::Var: return CXCursor_VarDecl;
2716 case Decl::Namespace: return CXCursor_Namespace;
2717 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2718 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2719 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2720 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2721 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2722 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2723 case Decl::ClassTemplatePartialSpecialization:
2724 return CXCursor_ClassTemplatePartialSpecialization;
2725 case Decl::UsingDirective: return CXCursor_UsingDirective;
2726
2727 case Decl::Using:
2728 case Decl::UnresolvedUsingValue:
2729 case Decl::UnresolvedUsingTypename:
2730 return CXCursor_UsingDeclaration;
2731
Douglas Gregor352697a2011-06-03 23:08:58 +00002732 case Decl::ObjCPropertyImpl:
2733 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2734 case ObjCPropertyImplDecl::Dynamic:
2735 return CXCursor_ObjCDynamicDecl;
2736
2737 case ObjCPropertyImplDecl::Synthesize:
2738 return CXCursor_ObjCSynthesizeDecl;
2739 }
2740 break;
2741
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002742 default:
2743 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2744 switch (TD->getTagKind()) {
2745 case TTK_Struct: return CXCursor_StructDecl;
2746 case TTK_Class: return CXCursor_ClassDecl;
2747 case TTK_Union: return CXCursor_UnionDecl;
2748 case TTK_Enum: return CXCursor_EnumDecl;
2749 }
2750 }
2751 }
2752
2753 return CXCursor_UnexposedDecl;
2754}
2755
Douglas Gregor590c7d52010-07-08 20:55:51 +00002756static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2757 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002758 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002759
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002760 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002761
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002762 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2763 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002764 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002765 Results.AddResult(Result(M->first,
2766 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002767 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002768 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002769 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002770
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002771 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002772
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002773}
2774
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002775static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2776 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002777 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002778
2779 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002780
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002781 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2782 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2783 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2784 Results.AddResult(Result("__func__", CCP_Constant));
2785 Results.ExitScope();
2786}
2787
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002788static void HandleCodeCompleteResults(Sema *S,
2789 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002790 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002791 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002792 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002793 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002794 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002795}
2796
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002797static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2798 Sema::ParserCompletionContext PCC) {
2799 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002800 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002801 return CodeCompletionContext::CCC_TopLevel;
2802
John McCallf312b1e2010-08-26 23:41:50 +00002803 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002804 return CodeCompletionContext::CCC_ClassStructUnion;
2805
John McCallf312b1e2010-08-26 23:41:50 +00002806 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002807 return CodeCompletionContext::CCC_ObjCInterface;
2808
John McCallf312b1e2010-08-26 23:41:50 +00002809 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002810 return CodeCompletionContext::CCC_ObjCImplementation;
2811
John McCallf312b1e2010-08-26 23:41:50 +00002812 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002813 return CodeCompletionContext::CCC_ObjCIvarList;
2814
John McCallf312b1e2010-08-26 23:41:50 +00002815 case Sema::PCC_Template:
2816 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002817 if (S.CurContext->isFileContext())
2818 return CodeCompletionContext::CCC_TopLevel;
2819 else if (S.CurContext->isRecord())
2820 return CodeCompletionContext::CCC_ClassStructUnion;
2821 else
2822 return CodeCompletionContext::CCC_Other;
2823
John McCallf312b1e2010-08-26 23:41:50 +00002824 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002825 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002826
John McCallf312b1e2010-08-26 23:41:50 +00002827 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002828 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2829 S.getLangOptions().ObjC1)
2830 return CodeCompletionContext::CCC_ParenthesizedExpression;
2831 else
2832 return CodeCompletionContext::CCC_Expression;
2833
2834 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002835 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002836 return CodeCompletionContext::CCC_Expression;
2837
John McCallf312b1e2010-08-26 23:41:50 +00002838 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002839 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002840
John McCallf312b1e2010-08-26 23:41:50 +00002841 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002842 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002843
2844 case Sema::PCC_ParenthesizedExpression:
2845 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002846
2847 case Sema::PCC_LocalDeclarationSpecifiers:
2848 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002849 }
2850
2851 return CodeCompletionContext::CCC_Other;
2852}
2853
Douglas Gregorf6961522010-08-27 21:18:54 +00002854/// \brief If we're in a C++ virtual member function, add completion results
2855/// that invoke the functions we override, since it's common to invoke the
2856/// overridden function as well as adding new functionality.
2857///
2858/// \param S The semantic analysis object for which we are generating results.
2859///
2860/// \param InContext This context in which the nested-name-specifier preceding
2861/// the code-completion point
2862static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2863 ResultBuilder &Results) {
2864 // Look through blocks.
2865 DeclContext *CurContext = S.CurContext;
2866 while (isa<BlockDecl>(CurContext))
2867 CurContext = CurContext->getParent();
2868
2869
2870 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2871 if (!Method || !Method->isVirtual())
2872 return;
2873
2874 // We need to have names for all of the parameters, if we're going to
2875 // generate a forwarding call.
2876 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2877 PEnd = Method->param_end();
2878 P != PEnd;
2879 ++P) {
2880 if (!(*P)->getDeclName())
2881 return;
2882 }
2883
2884 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2885 MEnd = Method->end_overridden_methods();
2886 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002887 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002888 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2889 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2890 continue;
2891
2892 // If we need a nested-name-specifier, add one now.
2893 if (!InContext) {
2894 NestedNameSpecifier *NNS
2895 = getRequiredQualification(S.Context, CurContext,
2896 Overridden->getDeclContext());
2897 if (NNS) {
2898 std::string Str;
2899 llvm::raw_string_ostream OS(Str);
Douglas Gregor30c42402011-09-27 22:38:19 +00002900 NNS->print(OS, getCompletionPrintingPolicy(S.Context));
Douglas Gregordae68752011-02-01 22:57:45 +00002901 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002902 }
2903 } else if (!InContext->Equals(Overridden->getDeclContext()))
2904 continue;
2905
Douglas Gregordae68752011-02-01 22:57:45 +00002906 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002907 Overridden->getNameAsString()));
2908 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00002909 bool FirstParam = true;
2910 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2911 PEnd = Method->param_end();
2912 P != PEnd; ++P) {
2913 if (FirstParam)
2914 FirstParam = false;
2915 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002916 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00002917
Douglas Gregordae68752011-02-01 22:57:45 +00002918 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002919 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002920 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002921 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2922 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00002923 CCP_SuperCompletion,
2924 CXCursor_CXXMethod));
2925 Results.Ignore(Overridden);
2926 }
2927}
2928
Douglas Gregor01dfea02010-01-10 23:08:15 +00002929void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002930 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002931 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002932 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002933 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002934 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002935
Douglas Gregor01dfea02010-01-10 23:08:15 +00002936 // Determine how to filter results, e.g., so that the names of
2937 // values (functions, enumerators, function templates, etc.) are
2938 // only allowed where we can have an expression.
2939 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002940 case PCC_Namespace:
2941 case PCC_Class:
2942 case PCC_ObjCInterface:
2943 case PCC_ObjCImplementation:
2944 case PCC_ObjCInstanceVariableList:
2945 case PCC_Template:
2946 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002947 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002948 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002949 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2950 break;
2951
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002952 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002953 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002954 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002955 case PCC_ForInit:
2956 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002957 if (WantTypesInContext(CompletionContext, getLangOptions()))
2958 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2959 else
2960 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002961
2962 if (getLangOptions().CPlusPlus)
2963 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002964 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002965
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002966 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002967 // Unfiltered
2968 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002969 }
2970
Douglas Gregor3cdee122010-08-26 16:36:48 +00002971 // If we are in a C++ non-static member function, check the qualifiers on
2972 // the member function to filter/prioritize the results list.
2973 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2974 if (CurMethod->isInstance())
2975 Results.setObjectTypeQualifiers(
2976 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2977
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002978 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002979 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2980 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002981
Douglas Gregorbca403c2010-01-13 23:51:12 +00002982 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002983 Results.ExitScope();
2984
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002985 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00002986 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00002987 case PCC_Expression:
2988 case PCC_Statement:
2989 case PCC_RecoveryInFunction:
2990 if (S->getFnParent())
2991 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2992 break;
2993
2994 case PCC_Namespace:
2995 case PCC_Class:
2996 case PCC_ObjCInterface:
2997 case PCC_ObjCImplementation:
2998 case PCC_ObjCInstanceVariableList:
2999 case PCC_Template:
3000 case PCC_MemberTemplate:
3001 case PCC_ForInit:
3002 case PCC_Condition:
3003 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003004 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003005 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003006 }
3007
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003008 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003009 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003010
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003011 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003012 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003013}
3014
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003015static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3016 ParsedType Receiver,
3017 IdentifierInfo **SelIdents,
3018 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003019 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003020 bool IsSuper,
3021 ResultBuilder &Results);
3022
3023void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3024 bool AllowNonIdentifiers,
3025 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003026 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003027 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003028 AllowNestedNameSpecifiers
3029 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3030 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003031 Results.EnterNewScope();
3032
3033 // Type qualifiers can come after names.
3034 Results.AddResult(Result("const"));
3035 Results.AddResult(Result("volatile"));
3036 if (getLangOptions().C99)
3037 Results.AddResult(Result("restrict"));
3038
3039 if (getLangOptions().CPlusPlus) {
3040 if (AllowNonIdentifiers) {
3041 Results.AddResult(Result("operator"));
3042 }
3043
3044 // Add nested-name-specifiers.
3045 if (AllowNestedNameSpecifiers) {
3046 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003047 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003048 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3049 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3050 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003051 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003052 }
3053 }
3054 Results.ExitScope();
3055
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003056 // If we're in a context where we might have an expression (rather than a
3057 // declaration), and what we've seen so far is an Objective-C type that could
3058 // be a receiver of a class message, this may be a class message send with
3059 // the initial opening bracket '[' missing. Add appropriate completions.
3060 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3061 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3062 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3063 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3064 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3065 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3066 DS.getTypeQualifiers() == 0 &&
3067 S &&
3068 (S->getFlags() & Scope::DeclScope) != 0 &&
3069 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3070 Scope::FunctionPrototypeScope |
3071 Scope::AtCatchScope)) == 0) {
3072 ParsedType T = DS.getRepAsType();
3073 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003074 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003075 }
3076
Douglas Gregor4497dd42010-08-24 04:59:56 +00003077 // Note that we intentionally suppress macro results here, since we do not
3078 // encourage using macros to produce the names of entities.
3079
Douglas Gregor52779fb2010-09-23 23:01:17 +00003080 HandleCodeCompleteResults(this, CodeCompleter,
3081 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003082 Results.data(), Results.size());
3083}
3084
Douglas Gregorfb629412010-08-23 21:17:50 +00003085struct Sema::CodeCompleteExpressionData {
3086 CodeCompleteExpressionData(QualType PreferredType = QualType())
3087 : PreferredType(PreferredType), IntegralConstantExpression(false),
3088 ObjCCollection(false) { }
3089
3090 QualType PreferredType;
3091 bool IntegralConstantExpression;
3092 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003093 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003094};
3095
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003096/// \brief Perform code-completion in an expression context when we know what
3097/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003098///
3099/// \param IntegralConstantExpression Only permit integral constant
3100/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003101void Sema::CodeCompleteExpression(Scope *S,
3102 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003103 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003104 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3105 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003106 if (Data.ObjCCollection)
3107 Results.setFilter(&ResultBuilder::IsObjCCollection);
3108 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003109 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003110 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003111 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3112 else
3113 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003114
3115 if (!Data.PreferredType.isNull())
3116 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3117
3118 // Ignore any declarations that we were told that we don't care about.
3119 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3120 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003121
3122 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003123 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3124 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003125
3126 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003127 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003128 Results.ExitScope();
3129
Douglas Gregor590c7d52010-07-08 20:55:51 +00003130 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003131 if (!Data.PreferredType.isNull())
3132 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3133 || Data.PreferredType->isMemberPointerType()
3134 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003135
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003136 if (S->getFnParent() &&
3137 !Data.ObjCCollection &&
3138 !Data.IntegralConstantExpression)
3139 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3140
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003141 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003142 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003143 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003144 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3145 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003146 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003147}
3148
Douglas Gregorac5fd842010-09-18 01:28:11 +00003149void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3150 if (E.isInvalid())
3151 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3152 else if (getLangOptions().ObjC1)
3153 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003154}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003155
Douglas Gregor73449212010-12-09 23:01:55 +00003156/// \brief The set of properties that have already been added, referenced by
3157/// property name.
3158typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3159
Douglas Gregor95ac6552009-11-18 01:29:26 +00003160static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003161 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003162 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003163 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003164 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003165 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003166 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003167
3168 // Add properties in this container.
3169 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3170 PEnd = Container->prop_end();
3171 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003172 ++P) {
3173 if (AddedProperties.insert(P->getIdentifier()))
3174 Results.MaybeAddResult(Result(*P, 0), CurContext);
3175 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003176
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003177 // Add nullary methods
3178 if (AllowNullaryMethods) {
3179 ASTContext &Context = Container->getASTContext();
3180 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3181 MEnd = Container->meth_end();
3182 M != MEnd; ++M) {
3183 if (M->getSelector().isUnarySelector())
3184 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3185 if (AddedProperties.insert(Name)) {
3186 CodeCompletionBuilder Builder(Results.getAllocator());
3187 AddResultTypeChunk(Context, *M, Builder);
3188 Builder.AddTypedTextChunk(
3189 Results.getAllocator().CopyString(Name->getName()));
3190
3191 CXAvailabilityKind Availability = CXAvailability_Available;
3192 switch (M->getAvailability()) {
3193 case AR_Available:
3194 case AR_NotYetIntroduced:
3195 Availability = CXAvailability_Available;
3196 break;
3197
3198 case AR_Deprecated:
3199 Availability = CXAvailability_Deprecated;
3200 break;
3201
3202 case AR_Unavailable:
3203 Availability = CXAvailability_NotAvailable;
3204 break;
3205 }
3206
3207 Results.MaybeAddResult(Result(Builder.TakeString(),
3208 CCP_MemberDeclaration + CCD_MethodAsProperty,
3209 M->isInstanceMethod()
3210 ? CXCursor_ObjCInstanceMethodDecl
3211 : CXCursor_ObjCClassMethodDecl,
3212 Availability),
3213 CurContext);
3214 }
3215 }
3216 }
3217
3218
Douglas Gregor95ac6552009-11-18 01:29:26 +00003219 // Add properties in referenced protocols.
3220 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3221 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3222 PEnd = Protocol->protocol_end();
3223 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003224 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3225 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003226 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003227 if (AllowCategories) {
3228 // Look through categories.
3229 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3230 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003231 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3232 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003233 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003234
3235 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003236 for (ObjCInterfaceDecl::all_protocol_iterator
3237 I = IFace->all_referenced_protocol_begin(),
3238 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003239 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3240 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003241
3242 // Look in the superclass.
3243 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003244 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3245 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003246 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003247 } else if (const ObjCCategoryDecl *Category
3248 = dyn_cast<ObjCCategoryDecl>(Container)) {
3249 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003250 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3251 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003252 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003253 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3254 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003255 }
3256}
3257
Richard Trieuf81e5a92011-09-09 02:00:50 +00003258void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *BaseE,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003259 SourceLocation OpLoc,
3260 bool IsArrow) {
3261 if (!BaseE || !CodeCompleter)
3262 return;
3263
John McCall0a2c5e22010-08-25 06:19:51 +00003264 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003265
Douglas Gregor81b747b2009-09-17 21:32:03 +00003266 Expr *Base = static_cast<Expr *>(BaseE);
3267 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003268
3269 if (IsArrow) {
3270 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3271 BaseType = Ptr->getPointeeType();
3272 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003273 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003274 else
3275 return;
3276 }
3277
Douglas Gregor3da626b2011-07-07 16:03:39 +00003278 enum CodeCompletionContext::Kind contextKind;
3279
3280 if (IsArrow) {
3281 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3282 }
3283 else {
3284 if (BaseType->isObjCObjectPointerType() ||
3285 BaseType->isObjCObjectOrInterfaceType()) {
3286 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3287 }
3288 else {
3289 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3290 }
3291 }
3292
Douglas Gregor218937c2011-02-01 19:23:04 +00003293 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003294 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003295 BaseType),
3296 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003297 Results.EnterNewScope();
3298 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003299 // Indicate that we are performing a member access, and the cv-qualifiers
3300 // for the base object type.
3301 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3302
Douglas Gregor95ac6552009-11-18 01:29:26 +00003303 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003304 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003305 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003306 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3307 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003308
Douglas Gregor95ac6552009-11-18 01:29:26 +00003309 if (getLangOptions().CPlusPlus) {
3310 if (!Results.empty()) {
3311 // The "template" keyword can follow "->" or "." in the grammar.
3312 // However, we only want to suggest the template keyword if something
3313 // is dependent.
3314 bool IsDependent = BaseType->isDependentType();
3315 if (!IsDependent) {
3316 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3317 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3318 IsDependent = Ctx->isDependentContext();
3319 break;
3320 }
3321 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003322
Douglas Gregor95ac6552009-11-18 01:29:26 +00003323 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003324 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003325 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003326 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003327 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3328 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003329 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003330
3331 // Add property results based on our interface.
3332 const ObjCObjectPointerType *ObjCPtr
3333 = BaseType->getAsObjCInterfacePointerType();
3334 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003335 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3336 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003337 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003338
3339 // Add properties from the protocols in a qualified interface.
3340 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3341 E = ObjCPtr->qual_end();
3342 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003343 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3344 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003345 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003346 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003347 // Objective-C instance variable access.
3348 ObjCInterfaceDecl *Class = 0;
3349 if (const ObjCObjectPointerType *ObjCPtr
3350 = BaseType->getAs<ObjCObjectPointerType>())
3351 Class = ObjCPtr->getInterfaceDecl();
3352 else
John McCallc12c5bb2010-05-15 11:32:37 +00003353 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003354
3355 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003356 if (Class) {
3357 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3358 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003359 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3360 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003361 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003362 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003363
3364 // FIXME: How do we cope with isa?
3365
3366 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003367
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003368 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003369 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003370 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003371 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003372}
3373
Douglas Gregor374929f2009-09-18 15:37:17 +00003374void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3375 if (!CodeCompleter)
3376 return;
3377
John McCall0a2c5e22010-08-25 06:19:51 +00003378 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003379 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003380 enum CodeCompletionContext::Kind ContextKind
3381 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003382 switch ((DeclSpec::TST)TagSpec) {
3383 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003384 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003385 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003386 break;
3387
3388 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003389 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003390 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003391 break;
3392
3393 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003394 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003395 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003396 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003397 break;
3398
3399 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003400 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003401 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003402
Douglas Gregor218937c2011-02-01 19:23:04 +00003403 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003404 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003405
3406 // First pass: look for tags.
3407 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003408 LookupVisibleDecls(S, LookupTagName, Consumer,
3409 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003410
Douglas Gregor8071e422010-08-15 06:18:01 +00003411 if (CodeCompleter->includeGlobals()) {
3412 // Second pass: look for nested name specifiers.
3413 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3414 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3415 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003416
Douglas Gregor52779fb2010-09-23 23:01:17 +00003417 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003418 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003419}
3420
Douglas Gregor1a480c42010-08-27 17:35:51 +00003421void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003422 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3423 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003424 Results.EnterNewScope();
3425 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3426 Results.AddResult("const");
3427 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3428 Results.AddResult("volatile");
3429 if (getLangOptions().C99 &&
3430 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3431 Results.AddResult("restrict");
3432 Results.ExitScope();
3433 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003434 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003435 Results.data(), Results.size());
3436}
3437
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003438void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003439 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003440 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003441
John McCall781472f2010-08-25 08:40:02 +00003442 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003443 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3444 if (!type->isEnumeralType()) {
3445 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003446 Data.IntegralConstantExpression = true;
3447 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003448 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003449 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003450
3451 // Code-complete the cases of a switch statement over an enumeration type
3452 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003453 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003454
3455 // Determine which enumerators we have already seen in the switch statement.
3456 // FIXME: Ideally, we would also be able to look *past* the code-completion
3457 // token, in case we are code-completing in the middle of the switch and not
3458 // at the end. However, we aren't able to do so at the moment.
3459 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003460 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003461 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3462 SC = SC->getNextSwitchCase()) {
3463 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3464 if (!Case)
3465 continue;
3466
3467 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3468 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3469 if (EnumConstantDecl *Enumerator
3470 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3471 // We look into the AST of the case statement to determine which
3472 // enumerator was named. Alternatively, we could compute the value of
3473 // the integral constant expression, then compare it against the
3474 // values of each enumerator. However, value-based approach would not
3475 // work as well with C++ templates where enumerators declared within a
3476 // template are type- and value-dependent.
3477 EnumeratorsSeen.insert(Enumerator);
3478
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003479 // If this is a qualified-id, keep track of the nested-name-specifier
3480 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003481 //
3482 // switch (TagD.getKind()) {
3483 // case TagDecl::TK_enum:
3484 // break;
3485 // case XXX
3486 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003487 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003488 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3489 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003490 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003491 }
3492 }
3493
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003494 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3495 // If there are no prior enumerators in C++, check whether we have to
3496 // qualify the names of the enumerators that we suggest, because they
3497 // may not be visible in this scope.
3498 Qualifier = getRequiredQualification(Context, CurContext,
3499 Enum->getDeclContext());
3500
3501 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3502 }
3503
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003504 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003505 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3506 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003507 Results.EnterNewScope();
3508 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3509 EEnd = Enum->enumerator_end();
3510 E != EEnd; ++E) {
3511 if (EnumeratorsSeen.count(*E))
3512 continue;
3513
Douglas Gregor5c722c702011-02-18 23:30:37 +00003514 CodeCompletionResult R(*E, Qualifier);
3515 R.Priority = CCP_EnumInCase;
3516 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003517 }
3518 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003519
Douglas Gregor3da626b2011-07-07 16:03:39 +00003520 //We need to make sure we're setting the right context,
3521 //so only say we include macros if the code completer says we do
3522 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3523 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003524 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003525 kind = CodeCompletionContext::CCC_OtherWithMacros;
3526 }
3527
3528
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003529 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003530 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003531 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003532}
3533
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003534namespace {
3535 struct IsBetterOverloadCandidate {
3536 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003537 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003538
3539 public:
John McCall5769d612010-02-08 23:07:23 +00003540 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3541 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003542
3543 bool
3544 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003545 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003546 }
3547 };
3548}
3549
Douglas Gregord28dcd72010-05-30 06:10:08 +00003550static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3551 if (NumArgs && !Args)
3552 return true;
3553
3554 for (unsigned I = 0; I != NumArgs; ++I)
3555 if (!Args[I])
3556 return true;
3557
3558 return false;
3559}
3560
Richard Trieuf81e5a92011-09-09 02:00:50 +00003561void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3562 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003563 if (!CodeCompleter)
3564 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003565
3566 // When we're code-completing for a call, we fall back to ordinary
3567 // name code-completion whenever we can't produce specific
3568 // results. We may want to revisit this strategy in the future,
3569 // e.g., by merging the two kinds of results.
3570
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003571 Expr *Fn = (Expr *)FnIn;
3572 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003573
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003574 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003575 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003576 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003577 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003578 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003579 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003580
John McCall3b4294e2009-12-16 12:17:52 +00003581 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003582 SourceLocation Loc = Fn->getExprLoc();
3583 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003584
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003585 // FIXME: What if we're calling something that isn't a function declaration?
3586 // FIXME: What if we're calling a pseudo-destructor?
3587 // FIXME: What if we're calling a member function?
3588
Douglas Gregorc0265402010-01-21 15:46:19 +00003589 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003590 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003591
John McCall3b4294e2009-12-16 12:17:52 +00003592 Expr *NakedFn = Fn->IgnoreParenCasts();
3593 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3594 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3595 /*PartialOverloading=*/ true);
3596 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3597 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003598 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003599 if (!getLangOptions().CPlusPlus ||
3600 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003601 Results.push_back(ResultCandidate(FDecl));
3602 else
John McCall86820f52010-01-26 01:37:31 +00003603 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003604 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3605 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003606 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003607 }
John McCall3b4294e2009-12-16 12:17:52 +00003608 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003609
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003610 QualType ParamType;
3611
Douglas Gregorc0265402010-01-21 15:46:19 +00003612 if (!CandidateSet.empty()) {
3613 // Sort the overload candidate set by placing the best overloads first.
3614 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003615 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003616
Douglas Gregorc0265402010-01-21 15:46:19 +00003617 // Add the remaining viable overload candidates as code-completion reslults.
3618 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3619 CandEnd = CandidateSet.end();
3620 Cand != CandEnd; ++Cand) {
3621 if (Cand->Viable)
3622 Results.push_back(ResultCandidate(Cand->Function));
3623 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003624
3625 // From the viable candidates, try to determine the type of this parameter.
3626 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3627 if (const FunctionType *FType = Results[I].getFunctionType())
3628 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3629 if (NumArgs < Proto->getNumArgs()) {
3630 if (ParamType.isNull())
3631 ParamType = Proto->getArgType(NumArgs);
3632 else if (!Context.hasSameUnqualifiedType(
3633 ParamType.getNonReferenceType(),
3634 Proto->getArgType(NumArgs).getNonReferenceType())) {
3635 ParamType = QualType();
3636 break;
3637 }
3638 }
3639 }
3640 } else {
3641 // Try to determine the parameter type from the type of the expression
3642 // being called.
3643 QualType FunctionType = Fn->getType();
3644 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3645 FunctionType = Ptr->getPointeeType();
3646 else if (const BlockPointerType *BlockPtr
3647 = FunctionType->getAs<BlockPointerType>())
3648 FunctionType = BlockPtr->getPointeeType();
3649 else if (const MemberPointerType *MemPtr
3650 = FunctionType->getAs<MemberPointerType>())
3651 FunctionType = MemPtr->getPointeeType();
3652
3653 if (const FunctionProtoType *Proto
3654 = FunctionType->getAs<FunctionProtoType>()) {
3655 if (NumArgs < Proto->getNumArgs())
3656 ParamType = Proto->getArgType(NumArgs);
3657 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003658 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003659
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003660 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003661 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003662 else
3663 CodeCompleteExpression(S, ParamType);
3664
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003665 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003666 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3667 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003668}
3669
John McCalld226f652010-08-21 09:40:31 +00003670void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3671 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003672 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003673 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003674 return;
3675 }
3676
3677 CodeCompleteExpression(S, VD->getType());
3678}
3679
3680void Sema::CodeCompleteReturn(Scope *S) {
3681 QualType ResultType;
3682 if (isa<BlockDecl>(CurContext)) {
3683 if (BlockScopeInfo *BSI = getCurBlock())
3684 ResultType = BSI->ReturnType;
3685 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3686 ResultType = Function->getResultType();
3687 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3688 ResultType = Method->getResultType();
3689
3690 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003691 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003692 else
3693 CodeCompleteExpression(S, ResultType);
3694}
3695
Douglas Gregord2d8be62011-07-30 08:36:53 +00003696void Sema::CodeCompleteAfterIf(Scope *S) {
3697 typedef CodeCompletionResult Result;
3698 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3699 mapCodeCompletionContext(*this, PCC_Statement));
3700 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3701 Results.EnterNewScope();
3702
3703 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3704 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3705 CodeCompleter->includeGlobals());
3706
3707 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3708
3709 // "else" block
3710 CodeCompletionBuilder Builder(Results.getAllocator());
3711 Builder.AddTypedTextChunk("else");
3712 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3713 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3714 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3715 Builder.AddPlaceholderChunk("statements");
3716 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3717 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3718 Results.AddResult(Builder.TakeString());
3719
3720 // "else if" block
3721 Builder.AddTypedTextChunk("else");
3722 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3723 Builder.AddTextChunk("if");
3724 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3725 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3726 if (getLangOptions().CPlusPlus)
3727 Builder.AddPlaceholderChunk("condition");
3728 else
3729 Builder.AddPlaceholderChunk("expression");
3730 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3731 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3732 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3733 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3734 Builder.AddPlaceholderChunk("statements");
3735 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3736 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3737 Results.AddResult(Builder.TakeString());
3738
3739 Results.ExitScope();
3740
3741 if (S->getFnParent())
3742 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3743
3744 if (CodeCompleter->includeMacros())
3745 AddMacroResults(PP, Results);
3746
3747 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3748 Results.data(),Results.size());
3749}
3750
Richard Trieuf81e5a92011-09-09 02:00:50 +00003751void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003752 if (LHS)
3753 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3754 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003755 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003756}
3757
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003758void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003759 bool EnteringContext) {
3760 if (!SS.getScopeRep() || !CodeCompleter)
3761 return;
3762
Douglas Gregor86d9a522009-09-21 16:56:56 +00003763 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3764 if (!Ctx)
3765 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003766
3767 // Try to instantiate any non-dependent declaration contexts before
3768 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003769 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003770 return;
3771
Douglas Gregor218937c2011-02-01 19:23:04 +00003772 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3773 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003774 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003775
Douglas Gregor86d9a522009-09-21 16:56:56 +00003776 // The "template" keyword can follow "::" in the grammar, but only
3777 // put it into the grammar if the nested-name-specifier is dependent.
3778 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3779 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003780 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003781
3782 // Add calls to overridden virtual functions, if there are any.
3783 //
3784 // FIXME: This isn't wonderful, because we don't know whether we're actually
3785 // in a context that permits expressions. This is a general issue with
3786 // qualified-id completions.
3787 if (!EnteringContext)
3788 MaybeAddOverrideCalls(*this, Ctx, Results);
3789 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003790
Douglas Gregorf6961522010-08-27 21:18:54 +00003791 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3792 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3793
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003794 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003795 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003796 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003797}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003798
3799void Sema::CodeCompleteUsing(Scope *S) {
3800 if (!CodeCompleter)
3801 return;
3802
Douglas Gregor218937c2011-02-01 19:23:04 +00003803 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003804 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3805 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003806 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003807
3808 // If we aren't in class scope, we could see the "namespace" keyword.
3809 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003810 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003811
3812 // After "using", we can see anything that would start a
3813 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003814 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003815 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3816 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003817 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003818
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003819 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003820 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003821 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003822}
3823
3824void Sema::CodeCompleteUsingDirective(Scope *S) {
3825 if (!CodeCompleter)
3826 return;
3827
Douglas Gregor86d9a522009-09-21 16:56:56 +00003828 // After "using namespace", we expect to see a namespace name or namespace
3829 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003830 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3831 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003832 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003833 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003834 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003835 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3836 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003837 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003838 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003839 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003840 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003841}
3842
3843void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3844 if (!CodeCompleter)
3845 return;
3846
Douglas Gregor86d9a522009-09-21 16:56:56 +00003847 DeclContext *Ctx = (DeclContext *)S->getEntity();
3848 if (!S->getParent())
3849 Ctx = Context.getTranslationUnitDecl();
3850
Douglas Gregor52779fb2010-09-23 23:01:17 +00003851 bool SuppressedGlobalResults
3852 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3853
Douglas Gregor218937c2011-02-01 19:23:04 +00003854 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003855 SuppressedGlobalResults
3856 ? CodeCompletionContext::CCC_Namespace
3857 : CodeCompletionContext::CCC_Other,
3858 &ResultBuilder::IsNamespace);
3859
3860 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003861 // We only want to see those namespaces that have already been defined
3862 // within this scope, because its likely that the user is creating an
3863 // extended namespace declaration. Keep track of the most recent
3864 // definition of each namespace.
3865 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3866 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3867 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3868 NS != NSEnd; ++NS)
3869 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3870
3871 // Add the most recent definition (or extended definition) of each
3872 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003873 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003874 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3875 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3876 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003877 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003878 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003879 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003880 }
3881
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003882 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003883 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003884 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003885}
3886
3887void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3888 if (!CodeCompleter)
3889 return;
3890
Douglas Gregor86d9a522009-09-21 16:56:56 +00003891 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003892 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3893 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003894 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003895 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003896 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3897 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003898 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003899 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003900 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003901}
3902
Douglas Gregored8d3222009-09-18 20:05:18 +00003903void Sema::CodeCompleteOperatorName(Scope *S) {
3904 if (!CodeCompleter)
3905 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003906
John McCall0a2c5e22010-08-25 06:19:51 +00003907 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003908 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3909 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003910 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003911 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003912
Douglas Gregor86d9a522009-09-21 16:56:56 +00003913 // Add the names of overloadable operators.
3914#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3915 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003916 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003917#include "clang/Basic/OperatorKinds.def"
3918
3919 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003920 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003921 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003922 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3923 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003924
3925 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003926 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003927 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003928
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003929 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003930 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003931 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003932}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003933
Douglas Gregor0133f522010-08-28 00:00:50 +00003934void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00003935 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00003936 unsigned NumInitializers) {
Douglas Gregor30c42402011-09-27 22:38:19 +00003937 PrintingPolicy Policy = getCompletionPrintingPolicy(Context);
Douglas Gregor0133f522010-08-28 00:00:50 +00003938 CXXConstructorDecl *Constructor
3939 = static_cast<CXXConstructorDecl *>(ConstructorD);
3940 if (!Constructor)
3941 return;
3942
Douglas Gregor218937c2011-02-01 19:23:04 +00003943 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003944 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003945 Results.EnterNewScope();
3946
3947 // Fill in any already-initialized fields or base classes.
3948 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3949 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3950 for (unsigned I = 0; I != NumInitializers; ++I) {
3951 if (Initializers[I]->isBaseInitializer())
3952 InitializedBases.insert(
3953 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3954 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003955 InitializedFields.insert(cast<FieldDecl>(
3956 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00003957 }
3958
3959 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00003960 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00003961 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003962 CXXRecordDecl *ClassDecl = Constructor->getParent();
3963 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3964 BaseEnd = ClassDecl->bases_end();
3965 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003966 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3967 SawLastInitializer
3968 = NumInitializers > 0 &&
3969 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3970 Context.hasSameUnqualifiedType(Base->getType(),
3971 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003972 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003973 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003974
Douglas Gregor218937c2011-02-01 19:23:04 +00003975 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003976 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00003977 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00003978 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3979 Builder.AddPlaceholderChunk("args");
3980 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3981 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003982 SawLastInitializer? CCP_NextInitializer
3983 : CCP_MemberDeclaration));
3984 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003985 }
3986
3987 // Add completions for virtual base classes.
3988 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3989 BaseEnd = ClassDecl->vbases_end();
3990 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003991 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3992 SawLastInitializer
3993 = NumInitializers > 0 &&
3994 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3995 Context.hasSameUnqualifiedType(Base->getType(),
3996 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003997 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003998 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003999
Douglas Gregor218937c2011-02-01 19:23:04 +00004000 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004001 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004002 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004003 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4004 Builder.AddPlaceholderChunk("args");
4005 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4006 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004007 SawLastInitializer? CCP_NextInitializer
4008 : CCP_MemberDeclaration));
4009 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004010 }
4011
4012 // Add completions for members.
4013 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4014 FieldEnd = ClassDecl->field_end();
4015 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004016 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4017 SawLastInitializer
4018 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004019 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4020 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004021 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004022 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004023
4024 if (!Field->getDeclName())
4025 continue;
4026
Douglas Gregordae68752011-02-01 22:57:45 +00004027 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004028 Field->getIdentifier()->getName()));
4029 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4030 Builder.AddPlaceholderChunk("args");
4031 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4032 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004033 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004034 : CCP_MemberDeclaration,
4035 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004036 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004037 }
4038 Results.ExitScope();
4039
Douglas Gregor52779fb2010-09-23 23:01:17 +00004040 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004041 Results.data(), Results.size());
4042}
4043
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004044// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4045// true or false.
4046#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004047static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004048 ResultBuilder &Results,
4049 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004050 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004051 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004052 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004053
Douglas Gregor218937c2011-02-01 19:23:04 +00004054 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004055 if (LangOpts.ObjC2) {
4056 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004057 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4058 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4059 Builder.AddPlaceholderChunk("property");
4060 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004061
4062 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004063 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4064 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4065 Builder.AddPlaceholderChunk("property");
4066 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004067 }
4068}
4069
Douglas Gregorbca403c2010-01-13 23:51:12 +00004070static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004071 ResultBuilder &Results,
4072 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004073 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004074
4075 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004076 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004077
4078 if (LangOpts.ObjC2) {
4079 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004080 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004081
4082 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004083 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004084
4085 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004086 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004087 }
4088}
4089
Douglas Gregorbca403c2010-01-13 23:51:12 +00004090static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004091 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004092 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004093
4094 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004095 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4096 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4097 Builder.AddPlaceholderChunk("name");
4098 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004099
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004100 if (Results.includeCodePatterns()) {
4101 // @interface name
4102 // FIXME: Could introduce the whole pattern, including superclasses and
4103 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004104 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4105 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4106 Builder.AddPlaceholderChunk("class");
4107 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004108
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004109 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004110 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4111 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4112 Builder.AddPlaceholderChunk("protocol");
4113 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004114
4115 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004116 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4117 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4118 Builder.AddPlaceholderChunk("class");
4119 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004120 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004121
4122 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004123 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4124 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4125 Builder.AddPlaceholderChunk("alias");
4126 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4127 Builder.AddPlaceholderChunk("class");
4128 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004129}
4130
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004131void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004132 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004133 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4134 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004135 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004136 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorbca403c2010-01-13 23:51:12 +00004137 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004138 else if (CurContext->isObjCContainer())
Douglas Gregorbca403c2010-01-13 23:51:12 +00004139 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004140 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004141 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004142 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004143 HandleCodeCompleteResults(this, CodeCompleter,
4144 CodeCompletionContext::CCC_Other,
4145 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004146}
4147
Douglas Gregorbca403c2010-01-13 23:51:12 +00004148static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004149 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004150 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004151
4152 // @encode ( type-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004153 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4154 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4155 Builder.AddPlaceholderChunk("type-name");
4156 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4157 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004158
4159 // @protocol ( protocol-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004160 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4161 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4162 Builder.AddPlaceholderChunk("protocol-name");
4163 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4164 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004165
4166 // @selector ( selector )
Douglas Gregor218937c2011-02-01 19:23:04 +00004167 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4168 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4169 Builder.AddPlaceholderChunk("selector");
4170 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4171 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004172}
4173
Douglas Gregorbca403c2010-01-13 23:51:12 +00004174static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004175 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004176 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004177
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004178 if (Results.includeCodePatterns()) {
4179 // @try { statements } @catch ( declaration ) { statements } @finally
4180 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004181 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4182 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4183 Builder.AddPlaceholderChunk("statements");
4184 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4185 Builder.AddTextChunk("@catch");
4186 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4187 Builder.AddPlaceholderChunk("parameter");
4188 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4189 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4190 Builder.AddPlaceholderChunk("statements");
4191 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4192 Builder.AddTextChunk("@finally");
4193 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4194 Builder.AddPlaceholderChunk("statements");
4195 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4196 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004197 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004198
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004199 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004200 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4201 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4202 Builder.AddPlaceholderChunk("expression");
4203 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004204
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004205 if (Results.includeCodePatterns()) {
4206 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004207 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4208 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4209 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4210 Builder.AddPlaceholderChunk("expression");
4211 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4212 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4213 Builder.AddPlaceholderChunk("statements");
4214 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4215 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004216 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004217}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004218
Douglas Gregorbca403c2010-01-13 23:51:12 +00004219static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004220 ResultBuilder &Results,
4221 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004222 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004223 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4224 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4225 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004226 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004227 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004228}
4229
4230void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004231 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4232 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004233 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004234 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004235 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004236 HandleCodeCompleteResults(this, CodeCompleter,
4237 CodeCompletionContext::CCC_Other,
4238 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004239}
4240
4241void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004242 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4243 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004244 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004245 AddObjCStatementResults(Results, false);
4246 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004247 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004248 HandleCodeCompleteResults(this, CodeCompleter,
4249 CodeCompletionContext::CCC_Other,
4250 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004251}
4252
4253void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004254 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4255 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004256 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004257 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004258 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004259 HandleCodeCompleteResults(this, CodeCompleter,
4260 CodeCompletionContext::CCC_Other,
4261 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004262}
4263
Douglas Gregor988358f2009-11-19 00:14:45 +00004264/// \brief Determine whether the addition of the given flag to an Objective-C
4265/// property's attributes will cause a conflict.
4266static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4267 // Check if we've already added this flag.
4268 if (Attributes & NewFlag)
4269 return true;
4270
4271 Attributes |= NewFlag;
4272
4273 // Check for collisions with "readonly".
4274 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4275 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4276 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004277 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004278 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004279 ObjCDeclSpec::DQ_PR_retain |
4280 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004281 return true;
4282
John McCallf85e1932011-06-15 23:02:42 +00004283 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004284 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004285 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004286 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004287 ObjCDeclSpec::DQ_PR_retain|
4288 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004289 if (AssignCopyRetMask &&
4290 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004291 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004292 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004293 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4294 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004295 return true;
4296
4297 return false;
4298}
4299
Douglas Gregora93b1082009-11-18 23:08:07 +00004300void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004301 if (!CodeCompleter)
4302 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004303
Steve Naroffece8e712009-10-08 21:55:05 +00004304 unsigned Attributes = ODS.getPropertyAttributes();
4305
John McCall0a2c5e22010-08-25 06:19:51 +00004306 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004307 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4308 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004309 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004310 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004311 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004312 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004313 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004314 if (!ObjCPropertyFlagConflicts(Attributes,
4315 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4316 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004317 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004318 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004319 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004320 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004321 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4322 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004323 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004324 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004325 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004326 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004327 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4328 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004329 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004330 CodeCompletionBuilder Setter(Results.getAllocator());
4331 Setter.AddTypedTextChunk("setter");
4332 Setter.AddTextChunk(" = ");
4333 Setter.AddPlaceholderChunk("method");
4334 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004335 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004336 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004337 CodeCompletionBuilder Getter(Results.getAllocator());
4338 Getter.AddTypedTextChunk("getter");
4339 Getter.AddTextChunk(" = ");
4340 Getter.AddPlaceholderChunk("method");
4341 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004342 }
Steve Naroffece8e712009-10-08 21:55:05 +00004343 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004344 HandleCodeCompleteResults(this, CodeCompleter,
4345 CodeCompletionContext::CCC_Other,
4346 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004347}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004348
Douglas Gregor4ad96852009-11-19 07:41:15 +00004349/// \brief Descripts the kind of Objective-C method that we want to find
4350/// via code completion.
4351enum ObjCMethodKind {
4352 MK_Any, //< Any kind of method, provided it means other specified criteria.
4353 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4354 MK_OneArgSelector //< One-argument selector.
4355};
4356
Douglas Gregor458433d2010-08-26 15:07:07 +00004357static bool isAcceptableObjCSelector(Selector Sel,
4358 ObjCMethodKind WantKind,
4359 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004360 unsigned NumSelIdents,
4361 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004362 if (NumSelIdents > Sel.getNumArgs())
4363 return false;
4364
4365 switch (WantKind) {
4366 case MK_Any: break;
4367 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4368 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4369 }
4370
Douglas Gregorcf544262010-11-17 21:36:08 +00004371 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4372 return false;
4373
Douglas Gregor458433d2010-08-26 15:07:07 +00004374 for (unsigned I = 0; I != NumSelIdents; ++I)
4375 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4376 return false;
4377
4378 return true;
4379}
4380
Douglas Gregor4ad96852009-11-19 07:41:15 +00004381static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4382 ObjCMethodKind WantKind,
4383 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004384 unsigned NumSelIdents,
4385 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004386 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004387 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004388}
Douglas Gregord36adf52010-09-16 16:06:31 +00004389
4390namespace {
4391 /// \brief A set of selectors, which is used to avoid introducing multiple
4392 /// completions with the same selector into the result set.
4393 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4394}
4395
Douglas Gregor36ecb042009-11-17 23:22:23 +00004396/// \brief Add all of the Objective-C methods in the given Objective-C
4397/// container to the set of results.
4398///
4399/// The container will be a class, protocol, category, or implementation of
4400/// any of the above. This mether will recurse to include methods from
4401/// the superclasses of classes along with their categories, protocols, and
4402/// implementations.
4403///
4404/// \param Container the container in which we'll look to find methods.
4405///
4406/// \param WantInstance whether to add instance methods (only); if false, this
4407/// routine will add factory methods (only).
4408///
4409/// \param CurContext the context in which we're performing the lookup that
4410/// finds methods.
4411///
Douglas Gregorcf544262010-11-17 21:36:08 +00004412/// \param AllowSameLength Whether we allow a method to be added to the list
4413/// when it has the same number of parameters as we have selector identifiers.
4414///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004415/// \param Results the structure into which we'll add results.
4416static void AddObjCMethods(ObjCContainerDecl *Container,
4417 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004418 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004419 IdentifierInfo **SelIdents,
4420 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004421 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004422 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004423 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004424 ResultBuilder &Results,
4425 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004426 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004427 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4428 MEnd = Container->meth_end();
4429 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004430 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4431 // Check whether the selector identifiers we've been given are a
4432 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004433 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4434 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004435 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004436
Douglas Gregord36adf52010-09-16 16:06:31 +00004437 if (!Selectors.insert((*M)->getSelector()))
4438 continue;
4439
Douglas Gregord3c68542009-11-19 01:08:35 +00004440 Result R = Result(*M, 0);
4441 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004442 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004443 if (!InOriginalClass)
4444 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004445 Results.MaybeAddResult(R, CurContext);
4446 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004447 }
4448
Douglas Gregore396c7b2010-09-16 15:34:59 +00004449 // Visit the protocols of protocols.
4450 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4451 const ObjCList<ObjCProtocolDecl> &Protocols
4452 = Protocol->getReferencedProtocols();
4453 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4454 E = Protocols.end();
4455 I != E; ++I)
4456 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004457 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004458 }
4459
Douglas Gregor36ecb042009-11-17 23:22:23 +00004460 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4461 if (!IFace)
4462 return;
4463
4464 // Add methods in protocols.
4465 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4466 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4467 E = Protocols.end();
4468 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004469 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004470 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004471
4472 // Add methods in categories.
4473 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4474 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004475 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004476 NumSelIdents, CurContext, Selectors, AllowSameLength,
4477 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004478
4479 // Add a categories protocol methods.
4480 const ObjCList<ObjCProtocolDecl> &Protocols
4481 = CatDecl->getReferencedProtocols();
4482 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4483 E = Protocols.end();
4484 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004485 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004486 NumSelIdents, CurContext, Selectors, AllowSameLength,
4487 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004488
4489 // Add methods in category implementations.
4490 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004491 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004492 NumSelIdents, CurContext, Selectors, AllowSameLength,
4493 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004494 }
4495
4496 // Add methods in superclass.
4497 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004498 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004499 SelIdents, NumSelIdents, CurContext, Selectors,
4500 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004501
4502 // Add methods in our implementation, if any.
4503 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004504 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004505 NumSelIdents, CurContext, Selectors, AllowSameLength,
4506 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004507}
4508
4509
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004510void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004511 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004512
4513 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004514 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004515 if (!Class) {
4516 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004517 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004518 Class = Category->getClassInterface();
4519
4520 if (!Class)
4521 return;
4522 }
4523
4524 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004525 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4526 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004527 Results.EnterNewScope();
4528
Douglas Gregord36adf52010-09-16 16:06:31 +00004529 VisitedSelectorSet Selectors;
4530 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004531 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004532 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004533 HandleCodeCompleteResults(this, CodeCompleter,
4534 CodeCompletionContext::CCC_Other,
4535 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004536}
4537
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004538void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004539 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004540
4541 // Try to find the interface where setters might live.
4542 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004543 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004544 if (!Class) {
4545 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004546 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004547 Class = Category->getClassInterface();
4548
4549 if (!Class)
4550 return;
4551 }
4552
4553 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004554 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4555 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004556 Results.EnterNewScope();
4557
Douglas Gregord36adf52010-09-16 16:06:31 +00004558 VisitedSelectorSet Selectors;
4559 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004560 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004561
4562 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004563 HandleCodeCompleteResults(this, CodeCompleter,
4564 CodeCompletionContext::CCC_Other,
4565 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004566}
4567
Douglas Gregorafc45782011-02-15 22:19:42 +00004568void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4569 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004570 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004571 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4572 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004573 Results.EnterNewScope();
4574
4575 // Add context-sensitive, Objective-C parameter-passing keywords.
4576 bool AddedInOut = false;
4577 if ((DS.getObjCDeclQualifier() &
4578 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4579 Results.AddResult("in");
4580 Results.AddResult("inout");
4581 AddedInOut = true;
4582 }
4583 if ((DS.getObjCDeclQualifier() &
4584 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4585 Results.AddResult("out");
4586 if (!AddedInOut)
4587 Results.AddResult("inout");
4588 }
4589 if ((DS.getObjCDeclQualifier() &
4590 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4591 ObjCDeclSpec::DQ_Oneway)) == 0) {
4592 Results.AddResult("bycopy");
4593 Results.AddResult("byref");
4594 Results.AddResult("oneway");
4595 }
4596
Douglas Gregorafc45782011-02-15 22:19:42 +00004597 // If we're completing the return type of an Objective-C method and the
4598 // identifier IBAction refers to a macro, provide a completion item for
4599 // an action, e.g.,
4600 // IBAction)<#selector#>:(id)sender
4601 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4602 Context.Idents.get("IBAction").hasMacroDefinition()) {
4603 typedef CodeCompletionString::Chunk Chunk;
4604 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4605 CXAvailability_Available);
4606 Builder.AddTypedTextChunk("IBAction");
4607 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4608 Builder.AddPlaceholderChunk("selector");
4609 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4610 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4611 Builder.AddTextChunk("id");
4612 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4613 Builder.AddTextChunk("sender");
4614 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4615 }
4616
Douglas Gregord32b0222010-08-24 01:06:58 +00004617 // Add various builtin type names and specifiers.
4618 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4619 Results.ExitScope();
4620
4621 // Add the various type names
4622 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4623 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4624 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4625 CodeCompleter->includeGlobals());
4626
4627 if (CodeCompleter->includeMacros())
4628 AddMacroResults(PP, Results);
4629
4630 HandleCodeCompleteResults(this, CodeCompleter,
4631 CodeCompletionContext::CCC_Type,
4632 Results.data(), Results.size());
4633}
4634
Douglas Gregor22f56992010-04-06 19:22:33 +00004635/// \brief When we have an expression with type "id", we may assume
4636/// that it has some more-specific class type based on knowledge of
4637/// common uses of Objective-C. This routine returns that class type,
4638/// or NULL if no better result could be determined.
4639static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004640 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004641 if (!Msg)
4642 return 0;
4643
4644 Selector Sel = Msg->getSelector();
4645 if (Sel.isNull())
4646 return 0;
4647
4648 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4649 if (!Id)
4650 return 0;
4651
4652 ObjCMethodDecl *Method = Msg->getMethodDecl();
4653 if (!Method)
4654 return 0;
4655
4656 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004657 ObjCInterfaceDecl *IFace = 0;
4658 switch (Msg->getReceiverKind()) {
4659 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004660 if (const ObjCObjectType *ObjType
4661 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4662 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004663 break;
4664
4665 case ObjCMessageExpr::Instance: {
4666 QualType T = Msg->getInstanceReceiver()->getType();
4667 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4668 IFace = Ptr->getInterfaceDecl();
4669 break;
4670 }
4671
4672 case ObjCMessageExpr::SuperInstance:
4673 case ObjCMessageExpr::SuperClass:
4674 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004675 }
4676
4677 if (!IFace)
4678 return 0;
4679
4680 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4681 if (Method->isInstanceMethod())
4682 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4683 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004684 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004685 .Case("autorelease", IFace)
4686 .Case("copy", IFace)
4687 .Case("copyWithZone", IFace)
4688 .Case("mutableCopy", IFace)
4689 .Case("mutableCopyWithZone", IFace)
4690 .Case("awakeFromCoder", IFace)
4691 .Case("replacementObjectFromCoder", IFace)
4692 .Case("class", IFace)
4693 .Case("classForCoder", IFace)
4694 .Case("superclass", Super)
4695 .Default(0);
4696
4697 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4698 .Case("new", IFace)
4699 .Case("alloc", IFace)
4700 .Case("allocWithZone", IFace)
4701 .Case("class", IFace)
4702 .Case("superclass", Super)
4703 .Default(0);
4704}
4705
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004706// Add a special completion for a message send to "super", which fills in the
4707// most likely case of forwarding all of our arguments to the superclass
4708// function.
4709///
4710/// \param S The semantic analysis object.
4711///
4712/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4713/// the "super" keyword. Otherwise, we just need to provide the arguments.
4714///
4715/// \param SelIdents The identifiers in the selector that have already been
4716/// provided as arguments for a send to "super".
4717///
4718/// \param NumSelIdents The number of identifiers in \p SelIdents.
4719///
4720/// \param Results The set of results to augment.
4721///
4722/// \returns the Objective-C method declaration that would be invoked by
4723/// this "super" completion. If NULL, no completion was added.
4724static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4725 IdentifierInfo **SelIdents,
4726 unsigned NumSelIdents,
4727 ResultBuilder &Results) {
4728 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4729 if (!CurMethod)
4730 return 0;
4731
4732 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4733 if (!Class)
4734 return 0;
4735
4736 // Try to find a superclass method with the same selector.
4737 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004738 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4739 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004740 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4741 CurMethod->isInstanceMethod());
4742
Douglas Gregor78bcd912011-02-16 00:51:18 +00004743 // Check in categories or class extensions.
4744 if (!SuperMethod) {
4745 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4746 Category = Category->getNextClassCategory())
4747 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4748 CurMethod->isInstanceMethod())))
4749 break;
4750 }
4751 }
4752
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004753 if (!SuperMethod)
4754 return 0;
4755
4756 // Check whether the superclass method has the same signature.
4757 if (CurMethod->param_size() != SuperMethod->param_size() ||
4758 CurMethod->isVariadic() != SuperMethod->isVariadic())
4759 return 0;
4760
4761 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4762 CurPEnd = CurMethod->param_end(),
4763 SuperP = SuperMethod->param_begin();
4764 CurP != CurPEnd; ++CurP, ++SuperP) {
4765 // Make sure the parameter types are compatible.
4766 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4767 (*SuperP)->getType()))
4768 return 0;
4769
4770 // Make sure we have a parameter name to forward!
4771 if (!(*CurP)->getIdentifier())
4772 return 0;
4773 }
4774
4775 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004776 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004777
4778 // Give this completion a return type.
Douglas Gregor218937c2011-02-01 19:23:04 +00004779 AddResultTypeChunk(S.Context, SuperMethod, Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004780
4781 // If we need the "super" keyword, add it (plus some spacing).
4782 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004783 Builder.AddTypedTextChunk("super");
4784 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004785 }
4786
4787 Selector Sel = CurMethod->getSelector();
4788 if (Sel.isUnarySelector()) {
4789 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004790 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004791 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004792 else
Douglas Gregordae68752011-02-01 22:57:45 +00004793 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004794 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004795 } else {
4796 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4797 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4798 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004799 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004800
4801 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004802 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004803 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004804 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004805 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004806 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004807 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004808 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004809 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004810 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004811 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004812 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004813 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004814 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004815 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004816 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004817 }
4818 }
4819 }
4820
Douglas Gregor218937c2011-02-01 19:23:04 +00004821 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004822 SuperMethod->isInstanceMethod()
4823 ? CXCursor_ObjCInstanceMethodDecl
4824 : CXCursor_ObjCClassMethodDecl));
4825 return SuperMethod;
4826}
4827
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004828void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004829 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004830 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4831 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004832 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004833
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004834 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4835 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004836 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4837 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004838
4839 // If we are in an Objective-C method inside a class that has a superclass,
4840 // add "super" as an option.
4841 if (ObjCMethodDecl *Method = getCurMethodDecl())
4842 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004843 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004844 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004845
4846 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4847 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004848
4849 Results.ExitScope();
4850
4851 if (CodeCompleter->includeMacros())
4852 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004853 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004854 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004855
4856}
4857
Douglas Gregor2725ca82010-04-21 19:57:20 +00004858void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4859 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004860 unsigned NumSelIdents,
4861 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004862 ObjCInterfaceDecl *CDecl = 0;
4863 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4864 // Figure out which interface we're in.
4865 CDecl = CurMethod->getClassInterface();
4866 if (!CDecl)
4867 return;
4868
4869 // Find the superclass of this class.
4870 CDecl = CDecl->getSuperClass();
4871 if (!CDecl)
4872 return;
4873
4874 if (CurMethod->isInstanceMethod()) {
4875 // We are inside an instance method, which means that the message
4876 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004877 // current object.
4878 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004879 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004880 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004881 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004882 }
4883
4884 // Fall through to send to the superclass in CDecl.
4885 } else {
4886 // "super" may be the name of a type or variable. Figure out which
4887 // it is.
4888 IdentifierInfo *Super = &Context.Idents.get("super");
4889 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4890 LookupOrdinaryName);
4891 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4892 // "super" names an interface. Use it.
4893 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004894 if (const ObjCObjectType *Iface
4895 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4896 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004897 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4898 // "super" names an unresolved type; we can't be more specific.
4899 } else {
4900 // Assume that "super" names some kind of value and parse that way.
4901 CXXScopeSpec SS;
4902 UnqualifiedId id;
4903 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004904 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004905 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004906 SelIdents, NumSelIdents,
4907 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004908 }
4909
4910 // Fall through
4911 }
4912
John McCallb3d87482010-08-24 05:47:05 +00004913 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004914 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004915 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004916 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004917 NumSelIdents, AtArgumentExpression,
4918 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004919}
4920
Douglas Gregorb9d77572010-09-21 00:03:25 +00004921/// \brief Given a set of code-completion results for the argument of a message
4922/// send, determine the preferred type (if any) for that argument expression.
4923static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4924 unsigned NumSelIdents) {
4925 typedef CodeCompletionResult Result;
4926 ASTContext &Context = Results.getSema().Context;
4927
4928 QualType PreferredType;
4929 unsigned BestPriority = CCP_Unlikely * 2;
4930 Result *ResultsData = Results.data();
4931 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4932 Result &R = ResultsData[I];
4933 if (R.Kind == Result::RK_Declaration &&
4934 isa<ObjCMethodDecl>(R.Declaration)) {
4935 if (R.Priority <= BestPriority) {
4936 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4937 if (NumSelIdents <= Method->param_size()) {
4938 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4939 ->getType();
4940 if (R.Priority < BestPriority || PreferredType.isNull()) {
4941 BestPriority = R.Priority;
4942 PreferredType = MyPreferredType;
4943 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4944 MyPreferredType)) {
4945 PreferredType = QualType();
4946 }
4947 }
4948 }
4949 }
4950 }
4951
4952 return PreferredType;
4953}
4954
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004955static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4956 ParsedType Receiver,
4957 IdentifierInfo **SelIdents,
4958 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004959 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004960 bool IsSuper,
4961 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004962 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004963 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004964
Douglas Gregor24a069f2009-11-17 17:59:40 +00004965 // If the given name refers to an interface type, retrieve the
4966 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004967 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004968 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004969 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004970 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4971 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004972 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004973
Douglas Gregor36ecb042009-11-17 23:22:23 +00004974 // Add all of the factory methods in this Objective-C class, its protocols,
4975 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004976 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004977
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004978 // If this is a send-to-super, try to add the special "super" send
4979 // completion.
4980 if (IsSuper) {
4981 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004982 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4983 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004984 Results.Ignore(SuperMethod);
4985 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004986
Douglas Gregor265f7492010-08-27 15:29:55 +00004987 // If we're inside an Objective-C method definition, prefer its selector to
4988 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004989 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00004990 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004991
Douglas Gregord36adf52010-09-16 16:06:31 +00004992 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00004993 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004994 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004995 SemaRef.CurContext, Selectors, AtArgumentExpression,
4996 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004997 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00004998 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004999
Douglas Gregor719770d2010-04-06 17:30:22 +00005000 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005001 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005002 if (SemaRef.ExternalSource) {
5003 for (uint32_t I = 0,
5004 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005005 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005006 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5007 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005008 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005009
5010 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005011 }
5012 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005013
5014 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5015 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005016 M != MEnd; ++M) {
5017 for (ObjCMethodList *MethList = &M->second.second;
5018 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005019 MethList = MethList->Next) {
5020 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5021 NumSelIdents))
5022 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005023
Douglas Gregor13438f92010-04-06 16:40:00 +00005024 Result R(MethList->Method, 0);
5025 R.StartParameter = NumSelIdents;
5026 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005027 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005028 }
5029 }
5030 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005031
5032 Results.ExitScope();
5033}
Douglas Gregor13438f92010-04-06 16:40:00 +00005034
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005035void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5036 IdentifierInfo **SelIdents,
5037 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005038 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005039 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005040
5041 QualType T = this->GetTypeFromParser(Receiver);
5042
Douglas Gregor218937c2011-02-01 19:23:04 +00005043 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005044 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005045 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005046
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005047 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5048 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005049
5050 // If we're actually at the argument expression (rather than prior to the
5051 // selector), we're actually performing code completion for an expression.
5052 // Determine whether we have a single, best method. If so, we can
5053 // code-complete the expression using the corresponding parameter type as
5054 // our preferred type, improving completion results.
5055 if (AtArgumentExpression) {
5056 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005057 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005058 if (PreferredType.isNull())
5059 CodeCompleteOrdinaryName(S, PCC_Expression);
5060 else
5061 CodeCompleteExpression(S, PreferredType);
5062 return;
5063 }
5064
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005065 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005066 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005067 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005068}
5069
Richard Trieuf81e5a92011-09-09 02:00:50 +00005070void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005071 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005072 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005073 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005074 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005075 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005076
5077 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005078
Douglas Gregor36ecb042009-11-17 23:22:23 +00005079 // If necessary, apply function/array conversion to the receiver.
5080 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005081 if (RecExpr) {
5082 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5083 if (Conv.isInvalid()) // conversion failed. bail.
5084 return;
5085 RecExpr = Conv.take();
5086 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005087 QualType ReceiverType = RecExpr? RecExpr->getType()
5088 : Super? Context.getObjCObjectPointerType(
5089 Context.getObjCInterfaceType(Super))
5090 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005091
Douglas Gregorda892642010-11-08 21:12:30 +00005092 // If we're messaging an expression with type "id" or "Class", check
5093 // whether we know something special about the receiver that allows
5094 // us to assume a more-specific receiver type.
5095 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5096 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5097 if (ReceiverType->isObjCClassType())
5098 return CodeCompleteObjCClassMessage(S,
5099 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5100 SelIdents, NumSelIdents,
5101 AtArgumentExpression, Super);
5102
5103 ReceiverType = Context.getObjCObjectPointerType(
5104 Context.getObjCInterfaceType(IFace));
5105 }
5106
Douglas Gregor36ecb042009-11-17 23:22:23 +00005107 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005108 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005109 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005110 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005111
Douglas Gregor36ecb042009-11-17 23:22:23 +00005112 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005113
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005114 // If this is a send-to-super, try to add the special "super" send
5115 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005116 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005117 if (ObjCMethodDecl *SuperMethod
5118 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5119 Results))
5120 Results.Ignore(SuperMethod);
5121 }
5122
Douglas Gregor265f7492010-08-27 15:29:55 +00005123 // If we're inside an Objective-C method definition, prefer its selector to
5124 // others.
5125 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5126 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005127
Douglas Gregord36adf52010-09-16 16:06:31 +00005128 // Keep track of the selectors we've already added.
5129 VisitedSelectorSet Selectors;
5130
Douglas Gregorf74a4192009-11-18 00:06:18 +00005131 // Handle messages to Class. This really isn't a message to an instance
5132 // method, so we treat it the same way we would treat a message send to a
5133 // class method.
5134 if (ReceiverType->isObjCClassType() ||
5135 ReceiverType->isObjCQualifiedClassType()) {
5136 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5137 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005138 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005139 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005140 }
5141 }
5142 // Handle messages to a qualified ID ("id<foo>").
5143 else if (const ObjCObjectPointerType *QualID
5144 = ReceiverType->getAsObjCQualifiedIdType()) {
5145 // Search protocols for instance methods.
5146 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5147 E = QualID->qual_end();
5148 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005149 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005150 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005151 }
5152 // Handle messages to a pointer to interface type.
5153 else if (const ObjCObjectPointerType *IFacePtr
5154 = ReceiverType->getAsObjCInterfacePointerType()) {
5155 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005156 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005157 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5158 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005159
5160 // Search protocols for instance methods.
5161 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5162 E = IFacePtr->qual_end();
5163 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005164 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005165 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005166 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005167 // Handle messages to "id".
5168 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005169 // We're messaging "id", so provide all instance methods we know
5170 // about as code-completion results.
5171
5172 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005173 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005174 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005175 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5176 I != N; ++I) {
5177 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005178 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005179 continue;
5180
Sebastian Redldb9d2142010-08-02 23:18:59 +00005181 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005182 }
5183 }
5184
Sebastian Redldb9d2142010-08-02 23:18:59 +00005185 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5186 MEnd = MethodPool.end();
5187 M != MEnd; ++M) {
5188 for (ObjCMethodList *MethList = &M->second.first;
5189 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005190 MethList = MethList->Next) {
5191 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5192 NumSelIdents))
5193 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005194
5195 if (!Selectors.insert(MethList->Method->getSelector()))
5196 continue;
5197
Douglas Gregor13438f92010-04-06 16:40:00 +00005198 Result R(MethList->Method, 0);
5199 R.StartParameter = NumSelIdents;
5200 R.AllParametersAreInformative = false;
5201 Results.MaybeAddResult(R, CurContext);
5202 }
5203 }
5204 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005205 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005206
5207
5208 // If we're actually at the argument expression (rather than prior to the
5209 // selector), we're actually performing code completion for an expression.
5210 // Determine whether we have a single, best method. If so, we can
5211 // code-complete the expression using the corresponding parameter type as
5212 // our preferred type, improving completion results.
5213 if (AtArgumentExpression) {
5214 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5215 NumSelIdents);
5216 if (PreferredType.isNull())
5217 CodeCompleteOrdinaryName(S, PCC_Expression);
5218 else
5219 CodeCompleteExpression(S, PreferredType);
5220 return;
5221 }
5222
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005223 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005224 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005225 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005226}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005227
Douglas Gregorfb629412010-08-23 21:17:50 +00005228void Sema::CodeCompleteObjCForCollection(Scope *S,
5229 DeclGroupPtrTy IterationVar) {
5230 CodeCompleteExpressionData Data;
5231 Data.ObjCCollection = true;
5232
5233 if (IterationVar.getAsOpaquePtr()) {
5234 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5235 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5236 if (*I)
5237 Data.IgnoreDecls.push_back(*I);
5238 }
5239 }
5240
5241 CodeCompleteExpression(S, Data);
5242}
5243
Douglas Gregor458433d2010-08-26 15:07:07 +00005244void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5245 unsigned NumSelIdents) {
5246 // If we have an external source, load the entire class method
5247 // pool from the AST file.
5248 if (ExternalSource) {
5249 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5250 I != N; ++I) {
5251 Selector Sel = ExternalSource->GetExternalSelector(I);
5252 if (Sel.isNull() || MethodPool.count(Sel))
5253 continue;
5254
5255 ReadMethodPool(Sel);
5256 }
5257 }
5258
Douglas Gregor218937c2011-02-01 19:23:04 +00005259 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5260 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005261 Results.EnterNewScope();
5262 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5263 MEnd = MethodPool.end();
5264 M != MEnd; ++M) {
5265
5266 Selector Sel = M->first;
5267 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5268 continue;
5269
Douglas Gregor218937c2011-02-01 19:23:04 +00005270 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005271 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005272 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005273 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005274 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005275 continue;
5276 }
5277
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005278 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005279 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005280 if (I == NumSelIdents) {
5281 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005282 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005283 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005284 Accumulator.clear();
5285 }
5286 }
5287
Benjamin Kramera0651c52011-07-26 16:59:25 +00005288 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005289 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005290 }
Douglas Gregordae68752011-02-01 22:57:45 +00005291 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005292 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005293 }
5294 Results.ExitScope();
5295
5296 HandleCodeCompleteResults(this, CodeCompleter,
5297 CodeCompletionContext::CCC_SelectorName,
5298 Results.data(), Results.size());
5299}
5300
Douglas Gregor55385fe2009-11-18 04:19:12 +00005301/// \brief Add all of the protocol declarations that we find in the given
5302/// (translation unit) context.
5303static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005304 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005305 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005306 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005307
5308 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5309 DEnd = Ctx->decls_end();
5310 D != DEnd; ++D) {
5311 // Record any protocols we find.
5312 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005313 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005314 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005315
5316 // Record any forward-declared protocols we find.
5317 if (ObjCForwardProtocolDecl *Forward
5318 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5319 for (ObjCForwardProtocolDecl::protocol_iterator
5320 P = Forward->protocol_begin(),
5321 PEnd = Forward->protocol_end();
5322 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005323 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005324 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005325 }
5326 }
5327}
5328
5329void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5330 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005331 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5332 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005333
Douglas Gregor70c23352010-12-09 21:44:02 +00005334 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5335 Results.EnterNewScope();
5336
5337 // Tell the result set to ignore all of the protocols we have
5338 // already seen.
5339 // FIXME: This doesn't work when caching code-completion results.
5340 for (unsigned I = 0; I != NumProtocols; ++I)
5341 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5342 Protocols[I].second))
5343 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005344
Douglas Gregor70c23352010-12-09 21:44:02 +00005345 // Add all protocols.
5346 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5347 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005348
Douglas Gregor70c23352010-12-09 21:44:02 +00005349 Results.ExitScope();
5350 }
5351
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005352 HandleCodeCompleteResults(this, CodeCompleter,
5353 CodeCompletionContext::CCC_ObjCProtocolName,
5354 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005355}
5356
5357void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005358 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5359 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005360
Douglas Gregor70c23352010-12-09 21:44:02 +00005361 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5362 Results.EnterNewScope();
5363
5364 // Add all protocols.
5365 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5366 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005367
Douglas Gregor70c23352010-12-09 21:44:02 +00005368 Results.ExitScope();
5369 }
5370
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005371 HandleCodeCompleteResults(this, CodeCompleter,
5372 CodeCompletionContext::CCC_ObjCProtocolName,
5373 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005374}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005375
5376/// \brief Add all of the Objective-C interface declarations that we find in
5377/// the given (translation unit) context.
5378static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5379 bool OnlyForwardDeclarations,
5380 bool OnlyUnimplemented,
5381 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005382 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005383
5384 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5385 DEnd = Ctx->decls_end();
5386 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005387 // Record any interfaces we find.
5388 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5389 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5390 (!OnlyUnimplemented || !Class->getImplementation()))
5391 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005392
5393 // Record any forward-declared interfaces we find.
5394 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005395 ObjCInterfaceDecl *IDecl = Forward->getForwardInterfaceDecl();
5396 if ((!OnlyForwardDeclarations || IDecl->isForwardDecl()) &&
5397 (!OnlyUnimplemented || !IDecl->getImplementation()))
5398 Results.AddResult(Result(IDecl, 0), CurContext,
5399 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005400 }
5401 }
5402}
5403
5404void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005405 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5406 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005407 Results.EnterNewScope();
5408
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005409 if (CodeCompleter->includeGlobals()) {
5410 // Add all classes.
5411 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5412 false, Results);
5413 }
5414
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005415 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005416
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005417 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005418 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005419 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005420}
5421
Douglas Gregorc83c6872010-04-15 22:33:43 +00005422void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5423 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005424 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005425 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005426 Results.EnterNewScope();
5427
5428 // Make sure that we ignore the class we're currently defining.
5429 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005430 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005431 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005432 Results.Ignore(CurClass);
5433
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005434 if (CodeCompleter->includeGlobals()) {
5435 // Add all classes.
5436 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5437 false, Results);
5438 }
5439
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005440 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005441
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005442 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005443 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005444 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005445}
5446
5447void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005448 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5449 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005450 Results.EnterNewScope();
5451
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005452 if (CodeCompleter->includeGlobals()) {
5453 // Add all unimplemented classes.
5454 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5455 true, Results);
5456 }
5457
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005458 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005459
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005460 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005461 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005462 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005463}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005464
5465void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005466 IdentifierInfo *ClassName,
5467 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005468 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005469
Douglas Gregor218937c2011-02-01 19:23:04 +00005470 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005471 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005472
5473 // Ignore any categories we find that have already been implemented by this
5474 // interface.
5475 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5476 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005477 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005478 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5479 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5480 Category = Category->getNextClassCategory())
5481 CategoryNames.insert(Category->getIdentifier());
5482
5483 // Add all of the categories we know about.
5484 Results.EnterNewScope();
5485 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5486 for (DeclContext::decl_iterator D = TU->decls_begin(),
5487 DEnd = TU->decls_end();
5488 D != DEnd; ++D)
5489 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5490 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005491 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005492 Results.ExitScope();
5493
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005494 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005495 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005496 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005497}
5498
5499void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005500 IdentifierInfo *ClassName,
5501 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005502 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005503
5504 // Find the corresponding interface. If we couldn't find the interface, the
5505 // program itself is ill-formed. However, we'll try to be helpful still by
5506 // providing the list of all of the categories we know about.
5507 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005508 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005509 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5510 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005511 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005512
Douglas Gregor218937c2011-02-01 19:23:04 +00005513 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005514 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005515
5516 // Add all of the categories that have have corresponding interface
5517 // declarations in this class and any of its superclasses, except for
5518 // already-implemented categories in the class itself.
5519 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5520 Results.EnterNewScope();
5521 bool IgnoreImplemented = true;
5522 while (Class) {
5523 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5524 Category = Category->getNextClassCategory())
5525 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5526 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005527 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005528
5529 Class = Class->getSuperClass();
5530 IgnoreImplemented = false;
5531 }
5532 Results.ExitScope();
5533
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005534 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005535 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005536 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005537}
Douglas Gregor322328b2009-11-18 22:32:06 +00005538
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005539void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005540 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005541 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5542 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005543
5544 // Figure out where this @synthesize lives.
5545 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005546 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005547 if (!Container ||
5548 (!isa<ObjCImplementationDecl>(Container) &&
5549 !isa<ObjCCategoryImplDecl>(Container)))
5550 return;
5551
5552 // Ignore any properties that have already been implemented.
5553 for (DeclContext::decl_iterator D = Container->decls_begin(),
5554 DEnd = Container->decls_end();
5555 D != DEnd; ++D)
5556 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5557 Results.Ignore(PropertyImpl->getPropertyDecl());
5558
5559 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005560 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005561 Results.EnterNewScope();
5562 if (ObjCImplementationDecl *ClassImpl
5563 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005564 AddObjCProperties(ClassImpl->getClassInterface(), false,
5565 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005566 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005567 else
5568 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005569 false, /*AllowNullaryMethods=*/false, CurContext,
5570 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005571 Results.ExitScope();
5572
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005573 HandleCodeCompleteResults(this, CodeCompleter,
5574 CodeCompletionContext::CCC_Other,
5575 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005576}
5577
5578void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005579 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005580 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005581 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5582 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005583
5584 // Figure out where this @synthesize lives.
5585 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005586 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005587 if (!Container ||
5588 (!isa<ObjCImplementationDecl>(Container) &&
5589 !isa<ObjCCategoryImplDecl>(Container)))
5590 return;
5591
5592 // Figure out which interface we're looking into.
5593 ObjCInterfaceDecl *Class = 0;
5594 if (ObjCImplementationDecl *ClassImpl
5595 = dyn_cast<ObjCImplementationDecl>(Container))
5596 Class = ClassImpl->getClassInterface();
5597 else
5598 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5599 ->getClassInterface();
5600
Douglas Gregore8426052011-04-18 14:40:46 +00005601 // Determine the type of the property we're synthesizing.
5602 QualType PropertyType = Context.getObjCIdType();
5603 if (Class) {
5604 if (ObjCPropertyDecl *Property
5605 = Class->FindPropertyDeclaration(PropertyName)) {
5606 PropertyType
5607 = Property->getType().getNonReferenceType().getUnqualifiedType();
5608
5609 // Give preference to ivars
5610 Results.setPreferredType(PropertyType);
5611 }
5612 }
5613
Douglas Gregor322328b2009-11-18 22:32:06 +00005614 // Add all of the instance variables in this class and its superclasses.
5615 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005616 bool SawSimilarlyNamedIvar = false;
5617 std::string NameWithPrefix;
5618 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005619 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005620 std::string NameWithSuffix = PropertyName->getName().str();
5621 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005622 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005623 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5624 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005625 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5626
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005627 // Determine whether we've seen an ivar with a name similar to the
5628 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005629 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005630 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005631 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005632 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005633
5634 // Reduce the priority of this result by one, to give it a slight
5635 // advantage over other results whose names don't match so closely.
5636 if (Results.size() &&
5637 Results.data()[Results.size() - 1].Kind
5638 == CodeCompletionResult::RK_Declaration &&
5639 Results.data()[Results.size() - 1].Declaration == Ivar)
5640 Results.data()[Results.size() - 1].Priority--;
5641 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005642 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005643 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005644
5645 if (!SawSimilarlyNamedIvar) {
5646 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005647 // an ivar of the appropriate type.
5648 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005649 typedef CodeCompletionResult Result;
5650 CodeCompletionAllocator &Allocator = Results.getAllocator();
5651 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5652
Douglas Gregore8426052011-04-18 14:40:46 +00005653 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
5654 Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005655 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5656 Results.AddResult(Result(Builder.TakeString(), Priority,
5657 CXCursor_ObjCIvarDecl));
5658 }
5659
Douglas Gregor322328b2009-11-18 22:32:06 +00005660 Results.ExitScope();
5661
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005662 HandleCodeCompleteResults(this, CodeCompleter,
5663 CodeCompletionContext::CCC_Other,
5664 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005665}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005666
Douglas Gregor408be5a2010-08-25 01:08:01 +00005667// Mapping from selectors to the methods that implement that selector, along
5668// with the "in original class" flag.
5669typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5670 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005671
5672/// \brief Find all of the methods that reside in the given container
5673/// (and its superclasses, protocols, etc.) that meet the given
5674/// criteria. Insert those methods into the map of known methods,
5675/// indexed by selector so they can be easily found.
5676static void FindImplementableMethods(ASTContext &Context,
5677 ObjCContainerDecl *Container,
5678 bool WantInstanceMethods,
5679 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005680 KnownMethodsMap &KnownMethods,
5681 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005682 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5683 // Recurse into protocols.
5684 const ObjCList<ObjCProtocolDecl> &Protocols
5685 = IFace->getReferencedProtocols();
5686 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005687 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005688 I != E; ++I)
5689 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005690 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005691
Douglas Gregorea766182010-10-18 18:21:28 +00005692 // Add methods from any class extensions and categories.
5693 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5694 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005695 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5696 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005697 KnownMethods, false);
5698
5699 // Visit the superclass.
5700 if (IFace->getSuperClass())
5701 FindImplementableMethods(Context, IFace->getSuperClass(),
5702 WantInstanceMethods, ReturnType,
5703 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005704 }
5705
5706 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5707 // Recurse into protocols.
5708 const ObjCList<ObjCProtocolDecl> &Protocols
5709 = Category->getReferencedProtocols();
5710 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005711 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005712 I != E; ++I)
5713 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005714 KnownMethods, InOriginalClass);
5715
5716 // If this category is the original class, jump to the interface.
5717 if (InOriginalClass && Category->getClassInterface())
5718 FindImplementableMethods(Context, Category->getClassInterface(),
5719 WantInstanceMethods, ReturnType, KnownMethods,
5720 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005721 }
5722
5723 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5724 // Recurse into protocols.
5725 const ObjCList<ObjCProtocolDecl> &Protocols
5726 = Protocol->getReferencedProtocols();
5727 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5728 E = Protocols.end();
5729 I != E; ++I)
5730 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005731 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005732 }
5733
5734 // Add methods in this container. This operation occurs last because
5735 // we want the methods from this container to override any methods
5736 // we've previously seen with the same selector.
5737 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5738 MEnd = Container->meth_end();
5739 M != MEnd; ++M) {
5740 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5741 if (!ReturnType.isNull() &&
5742 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5743 continue;
5744
Douglas Gregor408be5a2010-08-25 01:08:01 +00005745 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005746 }
5747 }
5748}
5749
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005750/// \brief Add the parenthesized return or parameter type chunk to a code
5751/// completion string.
5752static void AddObjCPassingTypeChunk(QualType Type,
5753 ASTContext &Context,
5754 CodeCompletionBuilder &Builder) {
5755 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5756 Builder.AddTextChunk(GetCompletionTypeString(Type, Context,
5757 Builder.getAllocator()));
5758 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5759}
5760
5761/// \brief Determine whether the given class is or inherits from a class by
5762/// the given name.
5763static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005764 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005765 if (!Class)
5766 return false;
5767
5768 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5769 return true;
5770
5771 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5772}
5773
5774/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5775/// Key-Value Observing (KVO).
5776static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5777 bool IsInstanceMethod,
5778 QualType ReturnType,
5779 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005780 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005781 ResultBuilder &Results) {
5782 IdentifierInfo *PropName = Property->getIdentifier();
5783 if (!PropName || PropName->getLength() == 0)
5784 return;
5785
5786
5787 // Builder that will create each code completion.
5788 typedef CodeCompletionResult Result;
5789 CodeCompletionAllocator &Allocator = Results.getAllocator();
5790 CodeCompletionBuilder Builder(Allocator);
5791
5792 // The selector table.
5793 SelectorTable &Selectors = Context.Selectors;
5794
5795 // The property name, copied into the code completion allocation region
5796 // on demand.
5797 struct KeyHolder {
5798 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005799 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005800 const char *CopiedKey;
5801
Chris Lattner5f9e2722011-07-23 10:55:15 +00005802 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005803 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5804
5805 operator const char *() {
5806 if (CopiedKey)
5807 return CopiedKey;
5808
5809 return CopiedKey = Allocator.CopyString(Key);
5810 }
5811 } Key(Allocator, PropName->getName());
5812
5813 // The uppercased name of the property name.
5814 std::string UpperKey = PropName->getName();
5815 if (!UpperKey.empty())
5816 UpperKey[0] = toupper(UpperKey[0]);
5817
5818 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5819 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5820 Property->getType());
5821 bool ReturnTypeMatchesVoid
5822 = ReturnType.isNull() || ReturnType->isVoidType();
5823
5824 // Add the normal accessor -(type)key.
5825 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005826 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005827 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5828 if (ReturnType.isNull())
5829 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5830
5831 Builder.AddTypedTextChunk(Key);
5832 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5833 CXCursor_ObjCInstanceMethodDecl));
5834 }
5835
5836 // If we have an integral or boolean property (or the user has provided
5837 // an integral or boolean return type), add the accessor -(type)isKey.
5838 if (IsInstanceMethod &&
5839 ((!ReturnType.isNull() &&
5840 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5841 (ReturnType.isNull() &&
5842 (Property->getType()->isIntegerType() ||
5843 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005844 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005845 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005846 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005847 if (ReturnType.isNull()) {
5848 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5849 Builder.AddTextChunk("BOOL");
5850 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5851 }
5852
5853 Builder.AddTypedTextChunk(
5854 Allocator.CopyString(SelectorId->getName()));
5855 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5856 CXCursor_ObjCInstanceMethodDecl));
5857 }
5858 }
5859
5860 // Add the normal mutator.
5861 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5862 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005863 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005864 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005865 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005866 if (ReturnType.isNull()) {
5867 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5868 Builder.AddTextChunk("void");
5869 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5870 }
5871
5872 Builder.AddTypedTextChunk(
5873 Allocator.CopyString(SelectorId->getName()));
5874 Builder.AddTypedTextChunk(":");
5875 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5876 Builder.AddTextChunk(Key);
5877 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5878 CXCursor_ObjCInstanceMethodDecl));
5879 }
5880 }
5881
5882 // Indexed and unordered accessors
5883 unsigned IndexedGetterPriority = CCP_CodePattern;
5884 unsigned IndexedSetterPriority = CCP_CodePattern;
5885 unsigned UnorderedGetterPriority = CCP_CodePattern;
5886 unsigned UnorderedSetterPriority = CCP_CodePattern;
5887 if (const ObjCObjectPointerType *ObjCPointer
5888 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5889 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5890 // If this interface type is not provably derived from a known
5891 // collection, penalize the corresponding completions.
5892 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5893 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5894 if (!InheritsFromClassNamed(IFace, "NSArray"))
5895 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5896 }
5897
5898 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5899 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5900 if (!InheritsFromClassNamed(IFace, "NSSet"))
5901 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5902 }
5903 }
5904 } else {
5905 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5906 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5907 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5908 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5909 }
5910
5911 // Add -(NSUInteger)countOf<key>
5912 if (IsInstanceMethod &&
5913 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005914 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005915 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005916 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005917 if (ReturnType.isNull()) {
5918 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5919 Builder.AddTextChunk("NSUInteger");
5920 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5921 }
5922
5923 Builder.AddTypedTextChunk(
5924 Allocator.CopyString(SelectorId->getName()));
5925 Results.AddResult(Result(Builder.TakeString(),
5926 std::min(IndexedGetterPriority,
5927 UnorderedGetterPriority),
5928 CXCursor_ObjCInstanceMethodDecl));
5929 }
5930 }
5931
5932 // Indexed getters
5933 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
5934 if (IsInstanceMethod &&
5935 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005936 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005937 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005938 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005939 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005940 if (ReturnType.isNull()) {
5941 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5942 Builder.AddTextChunk("id");
5943 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5944 }
5945
5946 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5947 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5948 Builder.AddTextChunk("NSUInteger");
5949 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5950 Builder.AddTextChunk("index");
5951 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5952 CXCursor_ObjCInstanceMethodDecl));
5953 }
5954 }
5955
5956 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
5957 if (IsInstanceMethod &&
5958 (ReturnType.isNull() ||
5959 (ReturnType->isObjCObjectPointerType() &&
5960 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
5961 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
5962 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005963 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005964 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005965 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005966 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005967 if (ReturnType.isNull()) {
5968 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5969 Builder.AddTextChunk("NSArray *");
5970 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5971 }
5972
5973 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5974 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5975 Builder.AddTextChunk("NSIndexSet *");
5976 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5977 Builder.AddTextChunk("indexes");
5978 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5979 CXCursor_ObjCInstanceMethodDecl));
5980 }
5981 }
5982
5983 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
5984 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005985 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005986 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005987 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005988 &Context.Idents.get("range")
5989 };
5990
Douglas Gregore74c25c2011-05-04 23:50:46 +00005991 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005992 if (ReturnType.isNull()) {
5993 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5994 Builder.AddTextChunk("void");
5995 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5996 }
5997
5998 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5999 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6000 Builder.AddPlaceholderChunk("object-type");
6001 Builder.AddTextChunk(" **");
6002 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6003 Builder.AddTextChunk("buffer");
6004 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6005 Builder.AddTypedTextChunk("range:");
6006 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6007 Builder.AddTextChunk("NSRange");
6008 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6009 Builder.AddTextChunk("inRange");
6010 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6011 CXCursor_ObjCInstanceMethodDecl));
6012 }
6013 }
6014
6015 // Mutable indexed accessors
6016
6017 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6018 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006019 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006020 IdentifierInfo *SelectorIds[2] = {
6021 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006022 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006023 };
6024
Douglas Gregore74c25c2011-05-04 23:50:46 +00006025 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006026 if (ReturnType.isNull()) {
6027 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6028 Builder.AddTextChunk("void");
6029 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6030 }
6031
6032 Builder.AddTypedTextChunk("insertObject:");
6033 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6034 Builder.AddPlaceholderChunk("object-type");
6035 Builder.AddTextChunk(" *");
6036 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6037 Builder.AddTextChunk("object");
6038 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6039 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6040 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6041 Builder.AddPlaceholderChunk("NSUInteger");
6042 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6043 Builder.AddTextChunk("index");
6044 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6045 CXCursor_ObjCInstanceMethodDecl));
6046 }
6047 }
6048
6049 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6050 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006051 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006052 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006053 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006054 &Context.Idents.get("atIndexes")
6055 };
6056
Douglas Gregore74c25c2011-05-04 23:50:46 +00006057 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006058 if (ReturnType.isNull()) {
6059 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6060 Builder.AddTextChunk("void");
6061 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6062 }
6063
6064 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6065 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6066 Builder.AddTextChunk("NSArray *");
6067 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6068 Builder.AddTextChunk("array");
6069 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6070 Builder.AddTypedTextChunk("atIndexes:");
6071 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6072 Builder.AddPlaceholderChunk("NSIndexSet *");
6073 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6074 Builder.AddTextChunk("indexes");
6075 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6076 CXCursor_ObjCInstanceMethodDecl));
6077 }
6078 }
6079
6080 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6081 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006082 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006083 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006084 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006085 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006086 if (ReturnType.isNull()) {
6087 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6088 Builder.AddTextChunk("void");
6089 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6090 }
6091
6092 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6093 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6094 Builder.AddTextChunk("NSUInteger");
6095 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6096 Builder.AddTextChunk("index");
6097 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6098 CXCursor_ObjCInstanceMethodDecl));
6099 }
6100 }
6101
6102 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6103 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006104 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006105 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006106 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006107 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006108 if (ReturnType.isNull()) {
6109 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6110 Builder.AddTextChunk("void");
6111 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6112 }
6113
6114 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6115 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6116 Builder.AddTextChunk("NSIndexSet *");
6117 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6118 Builder.AddTextChunk("indexes");
6119 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6120 CXCursor_ObjCInstanceMethodDecl));
6121 }
6122 }
6123
6124 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6125 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006126 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006127 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006128 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006129 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006130 &Context.Idents.get("withObject")
6131 };
6132
Douglas Gregore74c25c2011-05-04 23:50:46 +00006133 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006134 if (ReturnType.isNull()) {
6135 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6136 Builder.AddTextChunk("void");
6137 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6138 }
6139
6140 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6141 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6142 Builder.AddPlaceholderChunk("NSUInteger");
6143 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6144 Builder.AddTextChunk("index");
6145 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6146 Builder.AddTypedTextChunk("withObject:");
6147 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6148 Builder.AddTextChunk("id");
6149 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6150 Builder.AddTextChunk("object");
6151 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6152 CXCursor_ObjCInstanceMethodDecl));
6153 }
6154 }
6155
6156 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6157 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006158 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006159 = (Twine("replace") + UpperKey + "AtIndexes").str();
6160 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006161 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006162 &Context.Idents.get(SelectorName1),
6163 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006164 };
6165
Douglas Gregore74c25c2011-05-04 23:50:46 +00006166 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006167 if (ReturnType.isNull()) {
6168 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6169 Builder.AddTextChunk("void");
6170 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6171 }
6172
6173 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6174 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6175 Builder.AddPlaceholderChunk("NSIndexSet *");
6176 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6177 Builder.AddTextChunk("indexes");
6178 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6179 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6180 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6181 Builder.AddTextChunk("NSArray *");
6182 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6183 Builder.AddTextChunk("array");
6184 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6185 CXCursor_ObjCInstanceMethodDecl));
6186 }
6187 }
6188
6189 // Unordered getters
6190 // - (NSEnumerator *)enumeratorOfKey
6191 if (IsInstanceMethod &&
6192 (ReturnType.isNull() ||
6193 (ReturnType->isObjCObjectPointerType() &&
6194 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6195 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6196 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006197 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006198 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006199 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006200 if (ReturnType.isNull()) {
6201 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6202 Builder.AddTextChunk("NSEnumerator *");
6203 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6204 }
6205
6206 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6207 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6208 CXCursor_ObjCInstanceMethodDecl));
6209 }
6210 }
6211
6212 // - (type *)memberOfKey:(type *)object
6213 if (IsInstanceMethod &&
6214 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006215 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006216 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006217 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006218 if (ReturnType.isNull()) {
6219 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6220 Builder.AddPlaceholderChunk("object-type");
6221 Builder.AddTextChunk(" *");
6222 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6223 }
6224
6225 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6226 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6227 if (ReturnType.isNull()) {
6228 Builder.AddPlaceholderChunk("object-type");
6229 Builder.AddTextChunk(" *");
6230 } else {
6231 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
6232 Builder.getAllocator()));
6233 }
6234 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6235 Builder.AddTextChunk("object");
6236 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6237 CXCursor_ObjCInstanceMethodDecl));
6238 }
6239 }
6240
6241 // Mutable unordered accessors
6242 // - (void)addKeyObject:(type *)object
6243 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006244 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006245 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006246 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006247 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006248 if (ReturnType.isNull()) {
6249 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6250 Builder.AddTextChunk("void");
6251 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6252 }
6253
6254 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6255 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6256 Builder.AddPlaceholderChunk("object-type");
6257 Builder.AddTextChunk(" *");
6258 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6259 Builder.AddTextChunk("object");
6260 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6261 CXCursor_ObjCInstanceMethodDecl));
6262 }
6263 }
6264
6265 // - (void)addKey:(NSSet *)objects
6266 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006267 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006268 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006269 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006270 if (ReturnType.isNull()) {
6271 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6272 Builder.AddTextChunk("void");
6273 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6274 }
6275
6276 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6277 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6278 Builder.AddTextChunk("NSSet *");
6279 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6280 Builder.AddTextChunk("objects");
6281 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6282 CXCursor_ObjCInstanceMethodDecl));
6283 }
6284 }
6285
6286 // - (void)removeKeyObject:(type *)object
6287 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006288 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006289 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006290 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006291 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006292 if (ReturnType.isNull()) {
6293 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6294 Builder.AddTextChunk("void");
6295 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6296 }
6297
6298 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6299 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6300 Builder.AddPlaceholderChunk("object-type");
6301 Builder.AddTextChunk(" *");
6302 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6303 Builder.AddTextChunk("object");
6304 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6305 CXCursor_ObjCInstanceMethodDecl));
6306 }
6307 }
6308
6309 // - (void)removeKey:(NSSet *)objects
6310 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006311 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006312 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006313 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006314 if (ReturnType.isNull()) {
6315 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6316 Builder.AddTextChunk("void");
6317 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6318 }
6319
6320 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6321 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6322 Builder.AddTextChunk("NSSet *");
6323 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6324 Builder.AddTextChunk("objects");
6325 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6326 CXCursor_ObjCInstanceMethodDecl));
6327 }
6328 }
6329
6330 // - (void)intersectKey:(NSSet *)objects
6331 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006332 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006333 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006334 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006335 if (ReturnType.isNull()) {
6336 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6337 Builder.AddTextChunk("void");
6338 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6339 }
6340
6341 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6342 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6343 Builder.AddTextChunk("NSSet *");
6344 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6345 Builder.AddTextChunk("objects");
6346 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6347 CXCursor_ObjCInstanceMethodDecl));
6348 }
6349 }
6350
6351 // Key-Value Observing
6352 // + (NSSet *)keyPathsForValuesAffectingKey
6353 if (!IsInstanceMethod &&
6354 (ReturnType.isNull() ||
6355 (ReturnType->isObjCObjectPointerType() &&
6356 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6357 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6358 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006359 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006360 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006361 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006362 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006363 if (ReturnType.isNull()) {
6364 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6365 Builder.AddTextChunk("NSSet *");
6366 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6367 }
6368
6369 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6370 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006371 CXCursor_ObjCClassMethodDecl));
6372 }
6373 }
6374
6375 // + (BOOL)automaticallyNotifiesObserversForKey
6376 if (!IsInstanceMethod &&
6377 (ReturnType.isNull() ||
6378 ReturnType->isIntegerType() ||
6379 ReturnType->isBooleanType())) {
6380 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006381 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006382 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6383 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6384 if (ReturnType.isNull()) {
6385 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6386 Builder.AddTextChunk("BOOL");
6387 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6388 }
6389
6390 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6391 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6392 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006393 }
6394 }
6395}
6396
Douglas Gregore8f5a172010-04-07 00:21:17 +00006397void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6398 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006399 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006400 // Determine the return type of the method we're declaring, if
6401 // provided.
6402 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006403 Decl *IDecl = 0;
6404 if (CurContext->isObjCContainer()) {
6405 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6406 IDecl = cast<Decl>(OCD);
6407 }
Douglas Gregorea766182010-10-18 18:21:28 +00006408 // Determine where we should start searching for methods.
6409 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006410 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006411 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006412 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6413 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006414 IsInImplementation = true;
6415 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006416 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006417 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006418 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006419 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006420 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006421 }
6422
6423 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006424 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006425 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006426 }
6427
Douglas Gregorea766182010-10-18 18:21:28 +00006428 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006429 HandleCodeCompleteResults(this, CodeCompleter,
6430 CodeCompletionContext::CCC_Other,
6431 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006432 return;
6433 }
6434
6435 // Find all of the methods that we could declare/implement here.
6436 KnownMethodsMap KnownMethods;
6437 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006438 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006439
Douglas Gregore8f5a172010-04-07 00:21:17 +00006440 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006441 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006442 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6443 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006444 Results.EnterNewScope();
Douglas Gregor30c42402011-09-27 22:38:19 +00006445 PrintingPolicy Policy = getCompletionPrintingPolicy(Context);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006446 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6447 MEnd = KnownMethods.end();
6448 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006449 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006450 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006451
6452 // If the result type was not already provided, add it to the
6453 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006454 if (ReturnType.isNull())
6455 AddObjCPassingTypeChunk(Method->getResultType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006456
6457 Selector Sel = Method->getSelector();
6458
6459 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006460 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006461 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006462
6463 // Add parameters to the pattern.
6464 unsigned I = 0;
6465 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6466 PEnd = Method->param_end();
6467 P != PEnd; (void)++P, ++I) {
6468 // Add the part of the selector name.
6469 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006470 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006471 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006472 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6473 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006474 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006475 } else
6476 break;
6477
6478 // Add the parameter type.
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006479 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006480
6481 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006482 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006483 }
6484
6485 if (Method->isVariadic()) {
6486 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006487 Builder.AddChunk(CodeCompletionString::CK_Comma);
6488 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006489 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006490
Douglas Gregor447107d2010-05-28 00:57:46 +00006491 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006492 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006493 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6494 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6495 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006496 if (!Method->getResultType()->isVoidType()) {
6497 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006498 Builder.AddTextChunk("return");
6499 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6500 Builder.AddPlaceholderChunk("expression");
6501 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006502 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006503 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006504
Douglas Gregor218937c2011-02-01 19:23:04 +00006505 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6506 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006507 }
6508
Douglas Gregor408be5a2010-08-25 01:08:01 +00006509 unsigned Priority = CCP_CodePattern;
6510 if (!M->second.second)
6511 Priority += CCD_InBaseClass;
6512
Douglas Gregor218937c2011-02-01 19:23:04 +00006513 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006514 Method->isInstanceMethod()
6515 ? CXCursor_ObjCInstanceMethodDecl
6516 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006517 }
6518
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006519 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6520 // the properties in this class and its categories.
6521 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006522 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006523 Containers.push_back(SearchDecl);
6524
Douglas Gregore74c25c2011-05-04 23:50:46 +00006525 VisitedSelectorSet KnownSelectors;
6526 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6527 MEnd = KnownMethods.end();
6528 M != MEnd; ++M)
6529 KnownSelectors.insert(M->first);
6530
6531
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006532 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6533 if (!IFace)
6534 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6535 IFace = Category->getClassInterface();
6536
6537 if (IFace) {
6538 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6539 Category = Category->getNextClassCategory())
6540 Containers.push_back(Category);
6541 }
6542
6543 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6544 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6545 PEnd = Containers[I]->prop_end();
6546 P != PEnd; ++P) {
6547 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006548 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006549 }
6550 }
6551 }
6552
Douglas Gregore8f5a172010-04-07 00:21:17 +00006553 Results.ExitScope();
6554
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006555 HandleCodeCompleteResults(this, CodeCompleter,
6556 CodeCompletionContext::CCC_Other,
6557 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006558}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006559
6560void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6561 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006562 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006563 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006564 IdentifierInfo **SelIdents,
6565 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006566 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006567 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006568 if (ExternalSource) {
6569 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6570 I != N; ++I) {
6571 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006572 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006573 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006574
6575 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006576 }
6577 }
6578
6579 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006580 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006581 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6582 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006583
6584 if (ReturnTy)
6585 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006586
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006587 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006588 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6589 MEnd = MethodPool.end();
6590 M != MEnd; ++M) {
6591 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6592 &M->second.second;
6593 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006594 MethList = MethList->Next) {
6595 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6596 NumSelIdents))
6597 continue;
6598
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006599 if (AtParameterName) {
6600 // Suggest parameter names we've seen before.
6601 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6602 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6603 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006604 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006605 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006606 Param->getIdentifier()->getName()));
6607 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006608 }
6609 }
6610
6611 continue;
6612 }
6613
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006614 Result R(MethList->Method, 0);
6615 R.StartParameter = NumSelIdents;
6616 R.AllParametersAreInformative = false;
6617 R.DeclaringEntity = true;
6618 Results.MaybeAddResult(R, CurContext);
6619 }
6620 }
6621
6622 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006623 HandleCodeCompleteResults(this, CodeCompleter,
6624 CodeCompletionContext::CCC_Other,
6625 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006626}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006627
Douglas Gregorf29c5232010-08-24 22:20:20 +00006628void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006629 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006630 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006631 Results.EnterNewScope();
6632
6633 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006634 CodeCompletionBuilder Builder(Results.getAllocator());
6635 Builder.AddTypedTextChunk("if");
6636 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6637 Builder.AddPlaceholderChunk("condition");
6638 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006639
6640 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006641 Builder.AddTypedTextChunk("ifdef");
6642 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6643 Builder.AddPlaceholderChunk("macro");
6644 Results.AddResult(Builder.TakeString());
6645
Douglas Gregorf44e8542010-08-24 19:08:16 +00006646 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006647 Builder.AddTypedTextChunk("ifndef");
6648 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6649 Builder.AddPlaceholderChunk("macro");
6650 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006651
6652 if (InConditional) {
6653 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006654 Builder.AddTypedTextChunk("elif");
6655 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6656 Builder.AddPlaceholderChunk("condition");
6657 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006658
6659 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006660 Builder.AddTypedTextChunk("else");
6661 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006662
6663 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006664 Builder.AddTypedTextChunk("endif");
6665 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006666 }
6667
6668 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006669 Builder.AddTypedTextChunk("include");
6670 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6671 Builder.AddTextChunk("\"");
6672 Builder.AddPlaceholderChunk("header");
6673 Builder.AddTextChunk("\"");
6674 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006675
6676 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006677 Builder.AddTypedTextChunk("include");
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 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006685 Builder.AddTypedTextChunk("define");
6686 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6687 Builder.AddPlaceholderChunk("macro");
6688 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006689
6690 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006691 Builder.AddTypedTextChunk("define");
6692 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6693 Builder.AddPlaceholderChunk("macro");
6694 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6695 Builder.AddPlaceholderChunk("args");
6696 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6697 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006698
6699 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006700 Builder.AddTypedTextChunk("undef");
6701 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6702 Builder.AddPlaceholderChunk("macro");
6703 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006704
6705 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006706 Builder.AddTypedTextChunk("line");
6707 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6708 Builder.AddPlaceholderChunk("number");
6709 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006710
6711 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006712 Builder.AddTypedTextChunk("line");
6713 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6714 Builder.AddPlaceholderChunk("number");
6715 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6716 Builder.AddTextChunk("\"");
6717 Builder.AddPlaceholderChunk("filename");
6718 Builder.AddTextChunk("\"");
6719 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006720
6721 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006722 Builder.AddTypedTextChunk("error");
6723 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6724 Builder.AddPlaceholderChunk("message");
6725 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006726
6727 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006728 Builder.AddTypedTextChunk("pragma");
6729 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6730 Builder.AddPlaceholderChunk("arguments");
6731 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006732
6733 if (getLangOptions().ObjC1) {
6734 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006735 Builder.AddTypedTextChunk("import");
6736 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6737 Builder.AddTextChunk("\"");
6738 Builder.AddPlaceholderChunk("header");
6739 Builder.AddTextChunk("\"");
6740 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006741
6742 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006743 Builder.AddTypedTextChunk("import");
6744 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6745 Builder.AddTextChunk("<");
6746 Builder.AddPlaceholderChunk("header");
6747 Builder.AddTextChunk(">");
6748 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006749 }
6750
6751 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006752 Builder.AddTypedTextChunk("include_next");
6753 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6754 Builder.AddTextChunk("\"");
6755 Builder.AddPlaceholderChunk("header");
6756 Builder.AddTextChunk("\"");
6757 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006758
6759 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006760 Builder.AddTypedTextChunk("include_next");
6761 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6762 Builder.AddTextChunk("<");
6763 Builder.AddPlaceholderChunk("header");
6764 Builder.AddTextChunk(">");
6765 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006766
6767 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006768 Builder.AddTypedTextChunk("warning");
6769 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6770 Builder.AddPlaceholderChunk("message");
6771 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006772
6773 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6774 // completions for them. And __include_macros is a Clang-internal extension
6775 // that we don't want to encourage anyone to use.
6776
6777 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6778 Results.ExitScope();
6779
Douglas Gregorf44e8542010-08-24 19:08:16 +00006780 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006781 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006782 Results.data(), Results.size());
6783}
6784
6785void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006786 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006787 S->getFnParent()? Sema::PCC_RecoveryInFunction
6788 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006789}
6790
Douglas Gregorf29c5232010-08-24 22:20:20 +00006791void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006792 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006793 IsDefinition? CodeCompletionContext::CCC_MacroName
6794 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006795 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6796 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006797 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006798 Results.EnterNewScope();
6799 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6800 MEnd = PP.macro_end();
6801 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006802 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006803 M->first->getName()));
6804 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006805 }
6806 Results.ExitScope();
6807 } else if (IsDefinition) {
6808 // FIXME: Can we detect when the user just wrote an include guard above?
6809 }
6810
Douglas Gregor52779fb2010-09-23 23:01:17 +00006811 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006812 Results.data(), Results.size());
6813}
6814
Douglas Gregorf29c5232010-08-24 22:20:20 +00006815void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006816 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006817 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006818
6819 if (!CodeCompleter || CodeCompleter->includeMacros())
6820 AddMacroResults(PP, Results);
6821
6822 // defined (<macro>)
6823 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006824 CodeCompletionBuilder Builder(Results.getAllocator());
6825 Builder.AddTypedTextChunk("defined");
6826 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6827 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6828 Builder.AddPlaceholderChunk("macro");
6829 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6830 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006831 Results.ExitScope();
6832
6833 HandleCodeCompleteResults(this, CodeCompleter,
6834 CodeCompletionContext::CCC_PreprocessorExpression,
6835 Results.data(), Results.size());
6836}
6837
6838void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6839 IdentifierInfo *Macro,
6840 MacroInfo *MacroInfo,
6841 unsigned Argument) {
6842 // FIXME: In the future, we could provide "overload" results, much like we
6843 // do for function calls.
6844
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00006845 // Now just ignore this. There will be another code-completion callback
6846 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00006847}
6848
Douglas Gregor55817af2010-08-25 17:04:25 +00006849void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006850 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006851 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006852 0, 0);
6853}
6854
Douglas Gregordae68752011-02-01 22:57:45 +00006855void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006856 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006857 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006858 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6859 CodeCompletionDeclConsumer Consumer(Builder,
6860 Context.getTranslationUnitDecl());
6861 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6862 Consumer);
6863 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006864
6865 if (!CodeCompleter || CodeCompleter->includeMacros())
6866 AddMacroResults(PP, Builder);
6867
6868 Results.clear();
6869 Results.insert(Results.end(),
6870 Builder.data(), Builder.data() + Builder.size());
6871}