blob: 283f4fb731da1c5c46f73d217bfe85bb0f94a6f7 [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 Gregora63f6de2011-02-01 21:15:40 +00001843/// \brief Retrieve the string representation of the given type as a string
1844/// that has the appropriate lifetime for code completion.
1845///
1846/// This routine provides a fast path where we provide constant strings for
1847/// common type names.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001848static const char *GetCompletionTypeString(QualType T,
1849 ASTContext &Context,
1850 CodeCompletionAllocator &Allocator) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001851 PrintingPolicy Policy(Context.PrintingPolicy);
1852 Policy.AnonymousTagLocations = false;
John McCallf85e1932011-06-15 23:02:42 +00001853 Policy.SuppressStrongLifetime = true;
1854
Douglas Gregora63f6de2011-02-01 21:15:40 +00001855 if (!T.getLocalQualifiers()) {
1856 // Built-in type names are constant strings.
1857 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1858 return BT->getName(Context.getLangOptions());
1859
1860 // Anonymous tag types are constant strings.
1861 if (const TagType *TagT = dyn_cast<TagType>(T))
1862 if (TagDecl *Tag = TagT->getDecl())
Richard Smith162e1c12011-04-15 14:24:37 +00001863 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001864 switch (Tag->getTagKind()) {
1865 case TTK_Struct: return "struct <anonymous>";
1866 case TTK_Class: return "class <anonymous>";
1867 case TTK_Union: return "union <anonymous>";
1868 case TTK_Enum: return "enum <anonymous>";
1869 }
1870 }
1871 }
1872
1873 // Slow path: format the type as a string.
1874 std::string Result;
1875 T.getAsStringInternal(Result, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00001876 return Allocator.CopyString(Result);
Douglas Gregora63f6de2011-02-01 21:15:40 +00001877}
1878
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001879/// \brief If the given declaration has an associated type, add it as a result
1880/// type chunk.
1881static void AddResultTypeChunk(ASTContext &Context,
1882 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001883 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001884 if (!ND)
1885 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001886
1887 // Skip constructors and conversion functions, which have their return types
1888 // built into their names.
1889 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1890 return;
1891
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001892 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001893 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001894 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1895 T = Function->getResultType();
1896 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1897 T = Method->getResultType();
1898 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1899 T = FunTmpl->getTemplatedDecl()->getResultType();
1900 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1901 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1902 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1903 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00001904 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001905 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001906 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001907 T = Property->getType();
1908
1909 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1910 return;
1911
Douglas Gregora63f6de2011-02-01 21:15:40 +00001912 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context,
1913 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001914}
1915
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001916static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001917 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001918 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1919 if (Sentinel->getSentinel() == 0) {
1920 if (Context.getLangOptions().ObjC1 &&
1921 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001922 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001923 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001924 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001925 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001926 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001927 }
1928}
1929
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00001930static void appendWithSpace(std::string &Result, StringRef Text) {
1931 if (!Result.empty())
1932 Result += ' ';
1933 Result += Text.str();
1934}
1935static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
1936 std::string Result;
1937 if (ObjCQuals & Decl::OBJC_TQ_In)
1938 appendWithSpace(Result, "in");
1939 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
1940 appendWithSpace(Result, "inout");
1941 else if (ObjCQuals & Decl::OBJC_TQ_Out)
1942 appendWithSpace(Result, "out");
1943 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
1944 appendWithSpace(Result, "bycopy");
1945 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
1946 appendWithSpace(Result, "byref");
1947 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
1948 appendWithSpace(Result, "oneway");
1949 return Result;
1950}
1951
Douglas Gregor83482d12010-08-24 16:15:59 +00001952static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregoraba48082010-08-29 19:47:46 +00001953 ParmVarDecl *Param,
1954 bool SuppressName = false) {
John McCallf85e1932011-06-15 23:02:42 +00001955 PrintingPolicy Policy(Context.PrintingPolicy);
1956 Policy.AnonymousTagLocations = false;
1957 Policy.SuppressStrongLifetime = true;
1958
Douglas Gregor83482d12010-08-24 16:15:59 +00001959 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1960 if (Param->getType()->isDependentType() ||
1961 !Param->getType()->isBlockPointerType()) {
1962 // The argument for a dependent or non-block parameter is a placeholder
1963 // containing that parameter's type.
1964 std::string Result;
1965
Douglas Gregoraba48082010-08-29 19:47:46 +00001966 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001967 Result = Param->getIdentifier()->getName();
1968
John McCallf85e1932011-06-15 23:02:42 +00001969 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00001970
1971 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00001972 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
1973 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001974 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001975 Result += Param->getIdentifier()->getName();
1976 }
1977 return Result;
1978 }
1979
1980 // The argument for a block pointer parameter is a block literal with
1981 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00001982 FunctionTypeLoc *Block = 0;
1983 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00001984 TypeLoc TL;
1985 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1986 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1987 while (true) {
1988 // Look through typedefs.
1989 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1990 if (TypeSourceInfo *InnerTSInfo
Richard Smith162e1c12011-04-15 14:24:37 +00001991 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001992 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1993 continue;
1994 }
1995 }
1996
1997 // Look through qualified types
1998 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1999 TL = QualifiedTL->getUnqualifiedLoc();
2000 continue;
2001 }
2002
2003 // Try to get the function prototype behind the block pointer type,
2004 // then we're done.
2005 if (BlockPointerTypeLoc *BlockPtr
2006 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002007 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002008 Block = dyn_cast<FunctionTypeLoc>(&TL);
2009 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002010 }
2011 break;
2012 }
2013 }
2014
2015 if (!Block) {
2016 // We were unable to find a FunctionProtoTypeLoc with parameter names
2017 // for the block; just use the parameter type as a placeholder.
2018 std::string Result;
John McCallf85e1932011-06-15 23:02:42 +00002019 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002020
2021 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002022 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2023 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002024 if (Param->getIdentifier())
2025 Result += Param->getIdentifier()->getName();
2026 }
2027
2028 return Result;
2029 }
2030
2031 // We have the function prototype behind the block pointer type, as it was
2032 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002033 std::string Result;
2034 QualType ResultType = Block->getTypePtr()->getResultType();
2035 if (!ResultType->isVoidType())
John McCallf85e1932011-06-15 23:02:42 +00002036 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregor38276252010-09-08 22:47:51 +00002037
2038 Result = '^' + Result;
Douglas Gregor830072c2011-02-15 22:37:09 +00002039 if (!BlockProto || Block->getNumArgs() == 0) {
2040 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002041 Result += "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002042 else
2043 Result += "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002044 } else {
2045 Result += "(";
2046 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2047 if (I)
2048 Result += ", ";
2049 Result += FormatFunctionParameter(Context, Block->getArg(I));
2050
Douglas Gregor830072c2011-02-15 22:37:09 +00002051 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002052 Result += ", ...";
2053 }
2054 Result += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002055 }
Douglas Gregor38276252010-09-08 22:47:51 +00002056
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002057 if (Param->getIdentifier())
2058 Result += Param->getIdentifier()->getName();
2059
Douglas Gregor83482d12010-08-24 16:15:59 +00002060 return Result;
2061}
2062
Douglas Gregor86d9a522009-09-21 16:56:56 +00002063/// \brief Add function parameter chunks to the given code completion string.
2064static void AddFunctionParameterChunks(ASTContext &Context,
2065 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002066 CodeCompletionBuilder &Result,
2067 unsigned Start = 0,
2068 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002069 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002070 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002071
Douglas Gregor218937c2011-02-01 19:23:04 +00002072 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002073 ParmVarDecl *Param = Function->getParamDecl(P);
2074
Douglas Gregor218937c2011-02-01 19:23:04 +00002075 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002076 // When we see an optional default argument, put that argument and
2077 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002078 CodeCompletionBuilder Opt(Result.getAllocator());
2079 if (!FirstParameter)
2080 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2081 AddFunctionParameterChunks(Context, Function, Opt, P, true);
2082 Result.AddOptionalChunk(Opt.TakeString());
2083 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002084 }
2085
Douglas Gregor218937c2011-02-01 19:23:04 +00002086 if (FirstParameter)
2087 FirstParameter = false;
2088 else
2089 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2090
2091 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002092
2093 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00002094 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
2095
Douglas Gregore17794f2010-08-31 05:13:43 +00002096 if (Function->isVariadic() && P == N - 1)
2097 PlaceholderStr += ", ...";
2098
Douglas Gregor86d9a522009-09-21 16:56:56 +00002099 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002100 Result.AddPlaceholderChunk(
2101 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002102 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002103
2104 if (const FunctionProtoType *Proto
2105 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002106 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002107 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002108 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002109
Douglas Gregor218937c2011-02-01 19:23:04 +00002110 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002111 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002112}
2113
2114/// \brief Add template parameter chunks to the given code completion string.
2115static void AddTemplateParameterChunks(ASTContext &Context,
2116 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002117 CodeCompletionBuilder &Result,
2118 unsigned MaxParameters = 0,
2119 unsigned Start = 0,
2120 bool InDefaultArg = false) {
John McCallf85e1932011-06-15 23:02:42 +00002121 PrintingPolicy Policy(Context.PrintingPolicy);
2122 Policy.AnonymousTagLocations = false;
2123
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002124 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002125 bool FirstParameter = true;
2126
2127 TemplateParameterList *Params = Template->getTemplateParameters();
2128 TemplateParameterList::iterator PEnd = Params->end();
2129 if (MaxParameters)
2130 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002131 for (TemplateParameterList::iterator P = Params->begin() + Start;
2132 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002133 bool HasDefaultArg = false;
2134 std::string PlaceholderStr;
2135 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2136 if (TTP->wasDeclaredWithTypename())
2137 PlaceholderStr = "typename";
2138 else
2139 PlaceholderStr = "class";
2140
2141 if (TTP->getIdentifier()) {
2142 PlaceholderStr += ' ';
2143 PlaceholderStr += TTP->getIdentifier()->getName();
2144 }
2145
2146 HasDefaultArg = TTP->hasDefaultArgument();
2147 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002148 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002149 if (NTTP->getIdentifier())
2150 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002151 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002152 HasDefaultArg = NTTP->hasDefaultArgument();
2153 } else {
2154 assert(isa<TemplateTemplateParmDecl>(*P));
2155 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2156
2157 // Since putting the template argument list into the placeholder would
2158 // be very, very long, we just use an abbreviation.
2159 PlaceholderStr = "template<...> class";
2160 if (TTP->getIdentifier()) {
2161 PlaceholderStr += ' ';
2162 PlaceholderStr += TTP->getIdentifier()->getName();
2163 }
2164
2165 HasDefaultArg = TTP->hasDefaultArgument();
2166 }
2167
Douglas Gregor218937c2011-02-01 19:23:04 +00002168 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002169 // When we see an optional default argument, put that argument and
2170 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002171 CodeCompletionBuilder Opt(Result.getAllocator());
2172 if (!FirstParameter)
2173 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2174 AddTemplateParameterChunks(Context, Template, Opt, MaxParameters,
2175 P - Params->begin(), true);
2176 Result.AddOptionalChunk(Opt.TakeString());
2177 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002178 }
2179
Douglas Gregor218937c2011-02-01 19:23:04 +00002180 InDefaultArg = false;
2181
Douglas Gregor86d9a522009-09-21 16:56:56 +00002182 if (FirstParameter)
2183 FirstParameter = false;
2184 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002185 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002186
2187 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002188 Result.AddPlaceholderChunk(
2189 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002190 }
2191}
2192
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002193/// \brief Add a qualifier to the given code-completion string, if the
2194/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002195static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002196AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002197 NestedNameSpecifier *Qualifier,
2198 bool QualifierIsInformative,
2199 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002200 if (!Qualifier)
2201 return;
2202
2203 std::string PrintedNNS;
2204 {
2205 llvm::raw_string_ostream OS(PrintedNNS);
2206 Qualifier->print(OS, Context.PrintingPolicy);
2207 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002208 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002209 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002210 else
Douglas Gregordae68752011-02-01 22:57:45 +00002211 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002212}
2213
Douglas Gregor218937c2011-02-01 19:23:04 +00002214static void
2215AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2216 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002217 const FunctionProtoType *Proto
2218 = Function->getType()->getAs<FunctionProtoType>();
2219 if (!Proto || !Proto->getTypeQuals())
2220 return;
2221
Douglas Gregora63f6de2011-02-01 21:15:40 +00002222 // FIXME: Add ref-qualifier!
2223
2224 // Handle single qualifiers without copying
2225 if (Proto->getTypeQuals() == Qualifiers::Const) {
2226 Result.AddInformativeChunk(" const");
2227 return;
2228 }
2229
2230 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2231 Result.AddInformativeChunk(" volatile");
2232 return;
2233 }
2234
2235 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2236 Result.AddInformativeChunk(" restrict");
2237 return;
2238 }
2239
2240 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002241 std::string QualsStr;
2242 if (Proto->getTypeQuals() & Qualifiers::Const)
2243 QualsStr += " const";
2244 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2245 QualsStr += " volatile";
2246 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2247 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002248 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002249}
2250
Douglas Gregor6f942b22010-09-21 16:06:22 +00002251/// \brief Add the name of the given declaration
2252static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00002253 CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002254 typedef CodeCompletionString::Chunk Chunk;
2255
2256 DeclarationName Name = ND->getDeclName();
2257 if (!Name)
2258 return;
2259
2260 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002261 case DeclarationName::CXXOperatorName: {
2262 const char *OperatorName = 0;
2263 switch (Name.getCXXOverloadedOperator()) {
2264 case OO_None:
2265 case OO_Conditional:
2266 case NUM_OVERLOADED_OPERATORS:
2267 OperatorName = "operator";
2268 break;
2269
2270#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2271 case OO_##Name: OperatorName = "operator" Spelling; break;
2272#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2273#include "clang/Basic/OperatorKinds.def"
2274
2275 case OO_New: OperatorName = "operator new"; break;
2276 case OO_Delete: OperatorName = "operator delete"; break;
2277 case OO_Array_New: OperatorName = "operator new[]"; break;
2278 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2279 case OO_Call: OperatorName = "operator()"; break;
2280 case OO_Subscript: OperatorName = "operator[]"; break;
2281 }
2282 Result.AddTypedTextChunk(OperatorName);
2283 break;
2284 }
2285
Douglas Gregor6f942b22010-09-21 16:06:22 +00002286 case DeclarationName::Identifier:
2287 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002288 case DeclarationName::CXXDestructorName:
2289 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002290 Result.AddTypedTextChunk(
2291 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002292 break;
2293
2294 case DeclarationName::CXXUsingDirective:
2295 case DeclarationName::ObjCZeroArgSelector:
2296 case DeclarationName::ObjCOneArgSelector:
2297 case DeclarationName::ObjCMultiArgSelector:
2298 break;
2299
2300 case DeclarationName::CXXConstructorName: {
2301 CXXRecordDecl *Record = 0;
2302 QualType Ty = Name.getCXXNameType();
2303 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2304 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2305 else if (const InjectedClassNameType *InjectedTy
2306 = Ty->getAs<InjectedClassNameType>())
2307 Record = InjectedTy->getDecl();
2308 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002309 Result.AddTypedTextChunk(
2310 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002311 break;
2312 }
2313
Douglas Gregordae68752011-02-01 22:57:45 +00002314 Result.AddTypedTextChunk(
2315 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002316 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002317 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002318 AddTemplateParameterChunks(Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002319 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002320 }
2321 break;
2322 }
2323 }
2324}
2325
Douglas Gregor86d9a522009-09-21 16:56:56 +00002326/// \brief If possible, create a new code completion string for the given
2327/// result.
2328///
2329/// \returns Either a new, heap-allocated code completion string describing
2330/// how to use this result, or NULL to indicate that the string or name of the
2331/// result is all that is needed.
2332CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002333CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002334 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002335 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002336 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002337
John McCallf85e1932011-06-15 23:02:42 +00002338 PrintingPolicy Policy(S.Context.PrintingPolicy);
2339 Policy.AnonymousTagLocations = false;
2340 Policy.SuppressStrongLifetime = true;
2341
Douglas Gregor218937c2011-02-01 19:23:04 +00002342 if (Kind == RK_Pattern) {
2343 Pattern->Priority = Priority;
2344 Pattern->Availability = Availability;
2345 return Pattern;
2346 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002347
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002348 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002349 Result.AddTypedTextChunk(Keyword);
2350 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002351 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002352
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002353 if (Kind == RK_Macro) {
2354 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002355 assert(MI && "Not a macro?");
2356
Douglas Gregordae68752011-02-01 22:57:45 +00002357 Result.AddTypedTextChunk(
2358 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002359
2360 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002361 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002362
2363 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002364 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregore4244702011-07-30 08:17:44 +00002365 bool CombineVariadicArgument = false;
2366 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2367 if (MI->isVariadic() && AEnd - A > 1) {
2368 AEnd -= 2;
2369 CombineVariadicArgument = true;
2370 }
2371 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002372 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002373 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002374
Douglas Gregore4244702011-07-30 08:17:44 +00002375 if (!MI->isVariadic() || A + 1 != AEnd) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002376 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002377 Result.AddPlaceholderChunk(
2378 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002379 continue;
2380 }
2381
Douglas Gregore4244702011-07-30 08:17:44 +00002382 // Variadic argument; cope with the difference between GNU and C99
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002383 // variadic macros, providing a single placeholder for the rest of the
2384 // arguments.
2385 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002386 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002387 else {
2388 std::string Arg = (*A)->getName();
2389 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002390 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002391 }
2392 }
Douglas Gregore4244702011-07-30 08:17:44 +00002393
2394 if (CombineVariadicArgument) {
2395 // Handle the next-to-last argument, combining it with the variadic
2396 // argument.
2397 std::string LastArg = (*A)->getName();
2398 ++A;
2399 if ((*A)->isStr("__VA_ARGS__"))
2400 LastArg += ", ...";
2401 else
2402 LastArg += ", " + (*A)->getName().str() + "...";
2403 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(LastArg));
2404 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002405 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2406 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002407 }
2408
Douglas Gregord8e8a582010-05-25 21:41:55 +00002409 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002410 NamedDecl *ND = Declaration;
2411
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002412 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002413 Result.AddTypedTextChunk(
2414 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002415 Result.AddTextChunk("::");
2416 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002417 }
2418
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002419 AddResultTypeChunk(S.Context, ND, Result);
2420
Douglas Gregor86d9a522009-09-21 16:56:56 +00002421 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002422 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2423 S.Context);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002424 AddTypedNameChunk(S.Context, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002425 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002426 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002427 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002428 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002429 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002430 }
2431
2432 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002433 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2434 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002435 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor6f942b22010-09-21 16:06:22 +00002436 AddTypedNameChunk(S.Context, Function, Result);
2437
Douglas Gregor86d9a522009-09-21 16:56:56 +00002438 // Figure out which template parameters are deduced (or have default
2439 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002440 SmallVector<bool, 16> Deduced;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002441 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2442 unsigned LastDeducibleArgument;
2443 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2444 --LastDeducibleArgument) {
2445 if (!Deduced[LastDeducibleArgument - 1]) {
2446 // C++0x: Figure out if the template argument has a default. If so,
2447 // the user doesn't need to type this argument.
2448 // FIXME: We need to abstract template parameters better!
2449 bool HasDefaultArg = false;
2450 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002451 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002452 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2453 HasDefaultArg = TTP->hasDefaultArgument();
2454 else if (NonTypeTemplateParmDecl *NTTP
2455 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2456 HasDefaultArg = NTTP->hasDefaultArgument();
2457 else {
2458 assert(isa<TemplateTemplateParmDecl>(Param));
2459 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002460 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002461 }
2462
2463 if (!HasDefaultArg)
2464 break;
2465 }
2466 }
2467
2468 if (LastDeducibleArgument) {
2469 // Some of the function template arguments cannot be deduced from a
2470 // function call, so we introduce an explicit template argument list
2471 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002472 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002473 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2474 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002475 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002476 }
2477
2478 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002479 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002480 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002481 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002482 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002483 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002484 }
2485
2486 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002487 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2488 S.Context);
Douglas Gregordae68752011-02-01 22:57:45 +00002489 Result.AddTypedTextChunk(
2490 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002491 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002492 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002493 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2494 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002495 }
2496
Douglas Gregor9630eb62009-11-17 16:44:22 +00002497 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002498 Selector Sel = Method->getSelector();
2499 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002500 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002501 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002502 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002503 }
2504
Douglas Gregor813d8342011-02-18 22:29:55 +00002505 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002506 SelName += ':';
2507 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002508 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002509 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002510 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002511
2512 // If there is only one parameter, and we're past it, add an empty
2513 // typed-text chunk since there is nothing to type.
2514 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002515 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002516 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002517 unsigned Idx = 0;
2518 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2519 PEnd = Method->param_end();
2520 P != PEnd; (void)++P, ++Idx) {
2521 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002522 std::string Keyword;
2523 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002524 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002525 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002526 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002527 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002528 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002529 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002530 else
Douglas Gregordae68752011-02-01 22:57:45 +00002531 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002532 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002533
2534 // If we're before the starting parameter, skip the placeholder.
2535 if (Idx < StartParameter)
2536 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002537
2538 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002539
2540 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregoraba48082010-08-29 19:47:46 +00002541 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002542 else {
John McCallf85e1932011-06-15 23:02:42 +00002543 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002544 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2545 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002546 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002547 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002548 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002549 }
2550
Douglas Gregore17794f2010-08-31 05:13:43 +00002551 if (Method->isVariadic() && (P + 1) == PEnd)
2552 Arg += ", ...";
2553
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002554 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002555 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002556 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002557 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002558 else
Douglas Gregordae68752011-02-01 22:57:45 +00002559 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002560 }
2561
Douglas Gregor2a17af02009-12-23 00:21:46 +00002562 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002563 if (Method->param_size() == 0) {
2564 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002565 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002566 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002567 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002568 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002569 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002570 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002571
2572 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002573 }
2574
Douglas Gregor218937c2011-02-01 19:23:04 +00002575 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002576 }
2577
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002578 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002579 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2580 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002581
Douglas Gregordae68752011-02-01 22:57:45 +00002582 Result.AddTypedTextChunk(
2583 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002584 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002585}
2586
Douglas Gregor86d802e2009-09-23 00:34:09 +00002587CodeCompletionString *
2588CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2589 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002590 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002591 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002592 typedef CodeCompletionString::Chunk Chunk;
John McCallf85e1932011-06-15 23:02:42 +00002593 PrintingPolicy Policy(S.Context.PrintingPolicy);
2594 Policy.AnonymousTagLocations = false;
2595 Policy.SuppressStrongLifetime = true;
2596
Douglas Gregor218937c2011-02-01 19:23:04 +00002597 // FIXME: Set priority, availability appropriately.
2598 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002599 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002600 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002601 const FunctionProtoType *Proto
2602 = dyn_cast<FunctionProtoType>(getFunctionType());
2603 if (!FDecl && !Proto) {
2604 // Function without a prototype. Just give the return type and a
2605 // highlighted ellipsis.
2606 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002607 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
2608 S.Context,
2609 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002610 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2611 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2612 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2613 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002614 }
2615
2616 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002617 Result.AddTextChunk(
2618 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002619 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002620 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002621 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002622 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002623
Douglas Gregor218937c2011-02-01 19:23:04 +00002624 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002625 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2626 for (unsigned I = 0; I != NumParams; ++I) {
2627 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002628 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002629
2630 std::string ArgString;
2631 QualType ArgType;
2632
2633 if (FDecl) {
2634 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2635 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2636 } else {
2637 ArgType = Proto->getArgType(I);
2638 }
2639
John McCallf85e1932011-06-15 23:02:42 +00002640 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002641
2642 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002643 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002644 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002645 else
Douglas Gregordae68752011-02-01 22:57:45 +00002646 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002647 }
2648
2649 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002650 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002651 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002652 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002653 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002654 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002655 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002656 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002657
Douglas Gregor218937c2011-02-01 19:23:04 +00002658 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002659}
2660
Chris Lattner5f9e2722011-07-23 10:55:15 +00002661unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002662 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002663 bool PreferredTypeIsPointer) {
2664 unsigned Priority = CCP_Macro;
2665
Douglas Gregorb05496d2010-09-20 21:11:48 +00002666 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2667 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2668 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002669 Priority = CCP_Constant;
2670 if (PreferredTypeIsPointer)
2671 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002672 }
2673 // Treat "YES", "NO", "true", and "false" as constants.
2674 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2675 MacroName.equals("true") || MacroName.equals("false"))
2676 Priority = CCP_Constant;
2677 // Treat "bool" as a type.
2678 else if (MacroName.equals("bool"))
2679 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2680
Douglas Gregor1827e102010-08-16 16:18:59 +00002681
2682 return Priority;
2683}
2684
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002685CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2686 if (!D)
2687 return CXCursor_UnexposedDecl;
2688
2689 switch (D->getKind()) {
2690 case Decl::Enum: return CXCursor_EnumDecl;
2691 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2692 case Decl::Field: return CXCursor_FieldDecl;
2693 case Decl::Function:
2694 return CXCursor_FunctionDecl;
2695 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2696 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2697 case Decl::ObjCClass:
2698 // FIXME
2699 return CXCursor_UnexposedDecl;
2700 case Decl::ObjCForwardProtocol:
2701 // FIXME
2702 return CXCursor_UnexposedDecl;
2703 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2704 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2705 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2706 case Decl::ObjCMethod:
2707 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2708 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2709 case Decl::CXXMethod: return CXCursor_CXXMethod;
2710 case Decl::CXXConstructor: return CXCursor_Constructor;
2711 case Decl::CXXDestructor: return CXCursor_Destructor;
2712 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2713 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2714 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2715 case Decl::ParmVar: return CXCursor_ParmDecl;
2716 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002717 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002718 case Decl::Var: return CXCursor_VarDecl;
2719 case Decl::Namespace: return CXCursor_Namespace;
2720 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2721 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2722 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2723 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2724 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2725 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2726 case Decl::ClassTemplatePartialSpecialization:
2727 return CXCursor_ClassTemplatePartialSpecialization;
2728 case Decl::UsingDirective: return CXCursor_UsingDirective;
2729
2730 case Decl::Using:
2731 case Decl::UnresolvedUsingValue:
2732 case Decl::UnresolvedUsingTypename:
2733 return CXCursor_UsingDeclaration;
2734
Douglas Gregor352697a2011-06-03 23:08:58 +00002735 case Decl::ObjCPropertyImpl:
2736 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2737 case ObjCPropertyImplDecl::Dynamic:
2738 return CXCursor_ObjCDynamicDecl;
2739
2740 case ObjCPropertyImplDecl::Synthesize:
2741 return CXCursor_ObjCSynthesizeDecl;
2742 }
2743 break;
2744
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002745 default:
2746 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2747 switch (TD->getTagKind()) {
2748 case TTK_Struct: return CXCursor_StructDecl;
2749 case TTK_Class: return CXCursor_ClassDecl;
2750 case TTK_Union: return CXCursor_UnionDecl;
2751 case TTK_Enum: return CXCursor_EnumDecl;
2752 }
2753 }
2754 }
2755
2756 return CXCursor_UnexposedDecl;
2757}
2758
Douglas Gregor590c7d52010-07-08 20:55:51 +00002759static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2760 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002761 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002762
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002763 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002764
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002765 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2766 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002767 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002768 Results.AddResult(Result(M->first,
2769 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002770 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002771 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002772 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002773
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002774 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002775
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002776}
2777
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002778static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2779 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002780 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002781
2782 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002783
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002784 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2785 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2786 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2787 Results.AddResult(Result("__func__", CCP_Constant));
2788 Results.ExitScope();
2789}
2790
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002791static void HandleCodeCompleteResults(Sema *S,
2792 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002793 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002794 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002795 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002796 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002797 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002798}
2799
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002800static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2801 Sema::ParserCompletionContext PCC) {
2802 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002803 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002804 return CodeCompletionContext::CCC_TopLevel;
2805
John McCallf312b1e2010-08-26 23:41:50 +00002806 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002807 return CodeCompletionContext::CCC_ClassStructUnion;
2808
John McCallf312b1e2010-08-26 23:41:50 +00002809 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002810 return CodeCompletionContext::CCC_ObjCInterface;
2811
John McCallf312b1e2010-08-26 23:41:50 +00002812 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002813 return CodeCompletionContext::CCC_ObjCImplementation;
2814
John McCallf312b1e2010-08-26 23:41:50 +00002815 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002816 return CodeCompletionContext::CCC_ObjCIvarList;
2817
John McCallf312b1e2010-08-26 23:41:50 +00002818 case Sema::PCC_Template:
2819 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002820 if (S.CurContext->isFileContext())
2821 return CodeCompletionContext::CCC_TopLevel;
2822 else if (S.CurContext->isRecord())
2823 return CodeCompletionContext::CCC_ClassStructUnion;
2824 else
2825 return CodeCompletionContext::CCC_Other;
2826
John McCallf312b1e2010-08-26 23:41:50 +00002827 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002828 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002829
John McCallf312b1e2010-08-26 23:41:50 +00002830 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002831 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2832 S.getLangOptions().ObjC1)
2833 return CodeCompletionContext::CCC_ParenthesizedExpression;
2834 else
2835 return CodeCompletionContext::CCC_Expression;
2836
2837 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002838 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002839 return CodeCompletionContext::CCC_Expression;
2840
John McCallf312b1e2010-08-26 23:41:50 +00002841 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002842 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002843
John McCallf312b1e2010-08-26 23:41:50 +00002844 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002845 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002846
2847 case Sema::PCC_ParenthesizedExpression:
2848 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002849
2850 case Sema::PCC_LocalDeclarationSpecifiers:
2851 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002852 }
2853
2854 return CodeCompletionContext::CCC_Other;
2855}
2856
Douglas Gregorf6961522010-08-27 21:18:54 +00002857/// \brief If we're in a C++ virtual member function, add completion results
2858/// that invoke the functions we override, since it's common to invoke the
2859/// overridden function as well as adding new functionality.
2860///
2861/// \param S The semantic analysis object for which we are generating results.
2862///
2863/// \param InContext This context in which the nested-name-specifier preceding
2864/// the code-completion point
2865static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2866 ResultBuilder &Results) {
2867 // Look through blocks.
2868 DeclContext *CurContext = S.CurContext;
2869 while (isa<BlockDecl>(CurContext))
2870 CurContext = CurContext->getParent();
2871
2872
2873 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2874 if (!Method || !Method->isVirtual())
2875 return;
2876
2877 // We need to have names for all of the parameters, if we're going to
2878 // generate a forwarding call.
2879 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2880 PEnd = Method->param_end();
2881 P != PEnd;
2882 ++P) {
2883 if (!(*P)->getDeclName())
2884 return;
2885 }
2886
2887 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2888 MEnd = Method->end_overridden_methods();
2889 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002890 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002891 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2892 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2893 continue;
2894
2895 // If we need a nested-name-specifier, add one now.
2896 if (!InContext) {
2897 NestedNameSpecifier *NNS
2898 = getRequiredQualification(S.Context, CurContext,
2899 Overridden->getDeclContext());
2900 if (NNS) {
2901 std::string Str;
2902 llvm::raw_string_ostream OS(Str);
2903 NNS->print(OS, S.Context.PrintingPolicy);
Douglas Gregordae68752011-02-01 22:57:45 +00002904 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002905 }
2906 } else if (!InContext->Equals(Overridden->getDeclContext()))
2907 continue;
2908
Douglas Gregordae68752011-02-01 22:57:45 +00002909 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002910 Overridden->getNameAsString()));
2911 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00002912 bool FirstParam = true;
2913 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2914 PEnd = Method->param_end();
2915 P != PEnd; ++P) {
2916 if (FirstParam)
2917 FirstParam = false;
2918 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002919 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00002920
Douglas Gregordae68752011-02-01 22:57:45 +00002921 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002922 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002923 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002924 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2925 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00002926 CCP_SuperCompletion,
2927 CXCursor_CXXMethod));
2928 Results.Ignore(Overridden);
2929 }
2930}
2931
Douglas Gregor01dfea02010-01-10 23:08:15 +00002932void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002933 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002934 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002935 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002936 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002937 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002938
Douglas Gregor01dfea02010-01-10 23:08:15 +00002939 // Determine how to filter results, e.g., so that the names of
2940 // values (functions, enumerators, function templates, etc.) are
2941 // only allowed where we can have an expression.
2942 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002943 case PCC_Namespace:
2944 case PCC_Class:
2945 case PCC_ObjCInterface:
2946 case PCC_ObjCImplementation:
2947 case PCC_ObjCInstanceVariableList:
2948 case PCC_Template:
2949 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002950 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002951 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002952 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2953 break;
2954
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002955 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002956 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002957 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002958 case PCC_ForInit:
2959 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002960 if (WantTypesInContext(CompletionContext, getLangOptions()))
2961 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2962 else
2963 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002964
2965 if (getLangOptions().CPlusPlus)
2966 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002967 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002968
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002969 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002970 // Unfiltered
2971 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002972 }
2973
Douglas Gregor3cdee122010-08-26 16:36:48 +00002974 // If we are in a C++ non-static member function, check the qualifiers on
2975 // the member function to filter/prioritize the results list.
2976 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2977 if (CurMethod->isInstance())
2978 Results.setObjectTypeQualifiers(
2979 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2980
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002981 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002982 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2983 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002984
Douglas Gregorbca403c2010-01-13 23:51:12 +00002985 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002986 Results.ExitScope();
2987
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002988 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00002989 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00002990 case PCC_Expression:
2991 case PCC_Statement:
2992 case PCC_RecoveryInFunction:
2993 if (S->getFnParent())
2994 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2995 break;
2996
2997 case PCC_Namespace:
2998 case PCC_Class:
2999 case PCC_ObjCInterface:
3000 case PCC_ObjCImplementation:
3001 case PCC_ObjCInstanceVariableList:
3002 case PCC_Template:
3003 case PCC_MemberTemplate:
3004 case PCC_ForInit:
3005 case PCC_Condition:
3006 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003007 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003008 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003009 }
3010
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003011 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003012 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003013
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003014 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003015 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003016}
3017
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003018static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3019 ParsedType Receiver,
3020 IdentifierInfo **SelIdents,
3021 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003022 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003023 bool IsSuper,
3024 ResultBuilder &Results);
3025
3026void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3027 bool AllowNonIdentifiers,
3028 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003029 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003030 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003031 AllowNestedNameSpecifiers
3032 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3033 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003034 Results.EnterNewScope();
3035
3036 // Type qualifiers can come after names.
3037 Results.AddResult(Result("const"));
3038 Results.AddResult(Result("volatile"));
3039 if (getLangOptions().C99)
3040 Results.AddResult(Result("restrict"));
3041
3042 if (getLangOptions().CPlusPlus) {
3043 if (AllowNonIdentifiers) {
3044 Results.AddResult(Result("operator"));
3045 }
3046
3047 // Add nested-name-specifiers.
3048 if (AllowNestedNameSpecifiers) {
3049 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003050 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003051 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3052 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3053 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003054 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003055 }
3056 }
3057 Results.ExitScope();
3058
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003059 // If we're in a context where we might have an expression (rather than a
3060 // declaration), and what we've seen so far is an Objective-C type that could
3061 // be a receiver of a class message, this may be a class message send with
3062 // the initial opening bracket '[' missing. Add appropriate completions.
3063 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3064 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3065 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3066 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3067 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3068 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3069 DS.getTypeQualifiers() == 0 &&
3070 S &&
3071 (S->getFlags() & Scope::DeclScope) != 0 &&
3072 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3073 Scope::FunctionPrototypeScope |
3074 Scope::AtCatchScope)) == 0) {
3075 ParsedType T = DS.getRepAsType();
3076 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003077 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003078 }
3079
Douglas Gregor4497dd42010-08-24 04:59:56 +00003080 // Note that we intentionally suppress macro results here, since we do not
3081 // encourage using macros to produce the names of entities.
3082
Douglas Gregor52779fb2010-09-23 23:01:17 +00003083 HandleCodeCompleteResults(this, CodeCompleter,
3084 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003085 Results.data(), Results.size());
3086}
3087
Douglas Gregorfb629412010-08-23 21:17:50 +00003088struct Sema::CodeCompleteExpressionData {
3089 CodeCompleteExpressionData(QualType PreferredType = QualType())
3090 : PreferredType(PreferredType), IntegralConstantExpression(false),
3091 ObjCCollection(false) { }
3092
3093 QualType PreferredType;
3094 bool IntegralConstantExpression;
3095 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003096 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003097};
3098
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003099/// \brief Perform code-completion in an expression context when we know what
3100/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003101///
3102/// \param IntegralConstantExpression Only permit integral constant
3103/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003104void Sema::CodeCompleteExpression(Scope *S,
3105 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003106 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003107 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3108 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003109 if (Data.ObjCCollection)
3110 Results.setFilter(&ResultBuilder::IsObjCCollection);
3111 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003112 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003113 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003114 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3115 else
3116 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003117
3118 if (!Data.PreferredType.isNull())
3119 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3120
3121 // Ignore any declarations that we were told that we don't care about.
3122 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3123 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003124
3125 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003126 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3127 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003128
3129 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003130 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003131 Results.ExitScope();
3132
Douglas Gregor590c7d52010-07-08 20:55:51 +00003133 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003134 if (!Data.PreferredType.isNull())
3135 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3136 || Data.PreferredType->isMemberPointerType()
3137 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003138
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003139 if (S->getFnParent() &&
3140 !Data.ObjCCollection &&
3141 !Data.IntegralConstantExpression)
3142 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3143
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003144 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003145 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003146 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003147 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3148 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003149 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003150}
3151
Douglas Gregorac5fd842010-09-18 01:28:11 +00003152void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3153 if (E.isInvalid())
3154 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3155 else if (getLangOptions().ObjC1)
3156 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003157}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003158
Douglas Gregor73449212010-12-09 23:01:55 +00003159/// \brief The set of properties that have already been added, referenced by
3160/// property name.
3161typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3162
Douglas Gregor95ac6552009-11-18 01:29:26 +00003163static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003164 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003165 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003166 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003167 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003168 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003169 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003170
3171 // Add properties in this container.
3172 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3173 PEnd = Container->prop_end();
3174 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003175 ++P) {
3176 if (AddedProperties.insert(P->getIdentifier()))
3177 Results.MaybeAddResult(Result(*P, 0), CurContext);
3178 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003179
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003180 // Add nullary methods
3181 if (AllowNullaryMethods) {
3182 ASTContext &Context = Container->getASTContext();
3183 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3184 MEnd = Container->meth_end();
3185 M != MEnd; ++M) {
3186 if (M->getSelector().isUnarySelector())
3187 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3188 if (AddedProperties.insert(Name)) {
3189 CodeCompletionBuilder Builder(Results.getAllocator());
3190 AddResultTypeChunk(Context, *M, Builder);
3191 Builder.AddTypedTextChunk(
3192 Results.getAllocator().CopyString(Name->getName()));
3193
3194 CXAvailabilityKind Availability = CXAvailability_Available;
3195 switch (M->getAvailability()) {
3196 case AR_Available:
3197 case AR_NotYetIntroduced:
3198 Availability = CXAvailability_Available;
3199 break;
3200
3201 case AR_Deprecated:
3202 Availability = CXAvailability_Deprecated;
3203 break;
3204
3205 case AR_Unavailable:
3206 Availability = CXAvailability_NotAvailable;
3207 break;
3208 }
3209
3210 Results.MaybeAddResult(Result(Builder.TakeString(),
3211 CCP_MemberDeclaration + CCD_MethodAsProperty,
3212 M->isInstanceMethod()
3213 ? CXCursor_ObjCInstanceMethodDecl
3214 : CXCursor_ObjCClassMethodDecl,
3215 Availability),
3216 CurContext);
3217 }
3218 }
3219 }
3220
3221
Douglas Gregor95ac6552009-11-18 01:29:26 +00003222 // Add properties in referenced protocols.
3223 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3224 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3225 PEnd = Protocol->protocol_end();
3226 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003227 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3228 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003229 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003230 if (AllowCategories) {
3231 // Look through categories.
3232 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3233 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003234 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3235 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003236 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003237
3238 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003239 for (ObjCInterfaceDecl::all_protocol_iterator
3240 I = IFace->all_referenced_protocol_begin(),
3241 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003242 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3243 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003244
3245 // Look in the superclass.
3246 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003247 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3248 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003249 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003250 } else if (const ObjCCategoryDecl *Category
3251 = dyn_cast<ObjCCategoryDecl>(Container)) {
3252 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003253 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3254 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003255 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003256 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3257 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003258 }
3259}
3260
Richard Trieuf81e5a92011-09-09 02:00:50 +00003261void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *BaseE,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003262 SourceLocation OpLoc,
3263 bool IsArrow) {
3264 if (!BaseE || !CodeCompleter)
3265 return;
3266
John McCall0a2c5e22010-08-25 06:19:51 +00003267 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003268
Douglas Gregor81b747b2009-09-17 21:32:03 +00003269 Expr *Base = static_cast<Expr *>(BaseE);
3270 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003271
3272 if (IsArrow) {
3273 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3274 BaseType = Ptr->getPointeeType();
3275 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003276 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003277 else
3278 return;
3279 }
3280
Douglas Gregor3da626b2011-07-07 16:03:39 +00003281 enum CodeCompletionContext::Kind contextKind;
3282
3283 if (IsArrow) {
3284 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3285 }
3286 else {
3287 if (BaseType->isObjCObjectPointerType() ||
3288 BaseType->isObjCObjectOrInterfaceType()) {
3289 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3290 }
3291 else {
3292 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3293 }
3294 }
3295
Douglas Gregor218937c2011-02-01 19:23:04 +00003296 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003297 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003298 BaseType),
3299 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003300 Results.EnterNewScope();
3301 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003302 // Indicate that we are performing a member access, and the cv-qualifiers
3303 // for the base object type.
3304 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3305
Douglas Gregor95ac6552009-11-18 01:29:26 +00003306 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003307 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003308 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003309 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3310 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003311
Douglas Gregor95ac6552009-11-18 01:29:26 +00003312 if (getLangOptions().CPlusPlus) {
3313 if (!Results.empty()) {
3314 // The "template" keyword can follow "->" or "." in the grammar.
3315 // However, we only want to suggest the template keyword if something
3316 // is dependent.
3317 bool IsDependent = BaseType->isDependentType();
3318 if (!IsDependent) {
3319 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3320 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3321 IsDependent = Ctx->isDependentContext();
3322 break;
3323 }
3324 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003325
Douglas Gregor95ac6552009-11-18 01:29:26 +00003326 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003327 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003328 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003329 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003330 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3331 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003332 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003333
3334 // Add property results based on our interface.
3335 const ObjCObjectPointerType *ObjCPtr
3336 = BaseType->getAsObjCInterfacePointerType();
3337 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003338 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3339 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003340 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003341
3342 // Add properties from the protocols in a qualified interface.
3343 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3344 E = ObjCPtr->qual_end();
3345 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003346 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3347 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003348 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003349 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003350 // Objective-C instance variable access.
3351 ObjCInterfaceDecl *Class = 0;
3352 if (const ObjCObjectPointerType *ObjCPtr
3353 = BaseType->getAs<ObjCObjectPointerType>())
3354 Class = ObjCPtr->getInterfaceDecl();
3355 else
John McCallc12c5bb2010-05-15 11:32:37 +00003356 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003357
3358 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003359 if (Class) {
3360 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3361 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003362 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3363 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003364 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003365 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003366
3367 // FIXME: How do we cope with isa?
3368
3369 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003370
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003371 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003372 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003373 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003374 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003375}
3376
Douglas Gregor374929f2009-09-18 15:37:17 +00003377void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3378 if (!CodeCompleter)
3379 return;
3380
John McCall0a2c5e22010-08-25 06:19:51 +00003381 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003382 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003383 enum CodeCompletionContext::Kind ContextKind
3384 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003385 switch ((DeclSpec::TST)TagSpec) {
3386 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003387 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003388 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003389 break;
3390
3391 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003392 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003393 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003394 break;
3395
3396 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003397 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003398 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003399 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003400 break;
3401
3402 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003403 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003404 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003405
Douglas Gregor218937c2011-02-01 19:23:04 +00003406 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003407 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003408
3409 // First pass: look for tags.
3410 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003411 LookupVisibleDecls(S, LookupTagName, Consumer,
3412 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003413
Douglas Gregor8071e422010-08-15 06:18:01 +00003414 if (CodeCompleter->includeGlobals()) {
3415 // Second pass: look for nested name specifiers.
3416 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3417 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3418 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003419
Douglas Gregor52779fb2010-09-23 23:01:17 +00003420 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003421 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003422}
3423
Douglas Gregor1a480c42010-08-27 17:35:51 +00003424void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003425 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3426 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003427 Results.EnterNewScope();
3428 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3429 Results.AddResult("const");
3430 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3431 Results.AddResult("volatile");
3432 if (getLangOptions().C99 &&
3433 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3434 Results.AddResult("restrict");
3435 Results.ExitScope();
3436 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003437 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003438 Results.data(), Results.size());
3439}
3440
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003441void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003442 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003443 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003444
John McCall781472f2010-08-25 08:40:02 +00003445 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003446 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3447 if (!type->isEnumeralType()) {
3448 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003449 Data.IntegralConstantExpression = true;
3450 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003451 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003452 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003453
3454 // Code-complete the cases of a switch statement over an enumeration type
3455 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003456 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003457
3458 // Determine which enumerators we have already seen in the switch statement.
3459 // FIXME: Ideally, we would also be able to look *past* the code-completion
3460 // token, in case we are code-completing in the middle of the switch and not
3461 // at the end. However, we aren't able to do so at the moment.
3462 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003463 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003464 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3465 SC = SC->getNextSwitchCase()) {
3466 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3467 if (!Case)
3468 continue;
3469
3470 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3471 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3472 if (EnumConstantDecl *Enumerator
3473 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3474 // We look into the AST of the case statement to determine which
3475 // enumerator was named. Alternatively, we could compute the value of
3476 // the integral constant expression, then compare it against the
3477 // values of each enumerator. However, value-based approach would not
3478 // work as well with C++ templates where enumerators declared within a
3479 // template are type- and value-dependent.
3480 EnumeratorsSeen.insert(Enumerator);
3481
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003482 // If this is a qualified-id, keep track of the nested-name-specifier
3483 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003484 //
3485 // switch (TagD.getKind()) {
3486 // case TagDecl::TK_enum:
3487 // break;
3488 // case XXX
3489 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003490 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003491 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3492 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003493 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003494 }
3495 }
3496
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003497 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3498 // If there are no prior enumerators in C++, check whether we have to
3499 // qualify the names of the enumerators that we suggest, because they
3500 // may not be visible in this scope.
3501 Qualifier = getRequiredQualification(Context, CurContext,
3502 Enum->getDeclContext());
3503
3504 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3505 }
3506
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003507 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003508 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3509 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003510 Results.EnterNewScope();
3511 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3512 EEnd = Enum->enumerator_end();
3513 E != EEnd; ++E) {
3514 if (EnumeratorsSeen.count(*E))
3515 continue;
3516
Douglas Gregor5c722c702011-02-18 23:30:37 +00003517 CodeCompletionResult R(*E, Qualifier);
3518 R.Priority = CCP_EnumInCase;
3519 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003520 }
3521 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003522
Douglas Gregor3da626b2011-07-07 16:03:39 +00003523 //We need to make sure we're setting the right context,
3524 //so only say we include macros if the code completer says we do
3525 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3526 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003527 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003528 kind = CodeCompletionContext::CCC_OtherWithMacros;
3529 }
3530
3531
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003532 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003533 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003534 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003535}
3536
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003537namespace {
3538 struct IsBetterOverloadCandidate {
3539 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003540 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003541
3542 public:
John McCall5769d612010-02-08 23:07:23 +00003543 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3544 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003545
3546 bool
3547 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003548 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003549 }
3550 };
3551}
3552
Douglas Gregord28dcd72010-05-30 06:10:08 +00003553static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3554 if (NumArgs && !Args)
3555 return true;
3556
3557 for (unsigned I = 0; I != NumArgs; ++I)
3558 if (!Args[I])
3559 return true;
3560
3561 return false;
3562}
3563
Richard Trieuf81e5a92011-09-09 02:00:50 +00003564void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3565 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003566 if (!CodeCompleter)
3567 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003568
3569 // When we're code-completing for a call, we fall back to ordinary
3570 // name code-completion whenever we can't produce specific
3571 // results. We may want to revisit this strategy in the future,
3572 // e.g., by merging the two kinds of results.
3573
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003574 Expr *Fn = (Expr *)FnIn;
3575 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003576
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003577 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003578 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003579 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003580 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003581 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003582 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003583
John McCall3b4294e2009-12-16 12:17:52 +00003584 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003585 SourceLocation Loc = Fn->getExprLoc();
3586 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003587
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003588 // FIXME: What if we're calling something that isn't a function declaration?
3589 // FIXME: What if we're calling a pseudo-destructor?
3590 // FIXME: What if we're calling a member function?
3591
Douglas Gregorc0265402010-01-21 15:46:19 +00003592 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003593 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003594
John McCall3b4294e2009-12-16 12:17:52 +00003595 Expr *NakedFn = Fn->IgnoreParenCasts();
3596 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3597 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3598 /*PartialOverloading=*/ true);
3599 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3600 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003601 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003602 if (!getLangOptions().CPlusPlus ||
3603 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003604 Results.push_back(ResultCandidate(FDecl));
3605 else
John McCall86820f52010-01-26 01:37:31 +00003606 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003607 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3608 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003609 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003610 }
John McCall3b4294e2009-12-16 12:17:52 +00003611 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003612
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003613 QualType ParamType;
3614
Douglas Gregorc0265402010-01-21 15:46:19 +00003615 if (!CandidateSet.empty()) {
3616 // Sort the overload candidate set by placing the best overloads first.
3617 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003618 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003619
Douglas Gregorc0265402010-01-21 15:46:19 +00003620 // Add the remaining viable overload candidates as code-completion reslults.
3621 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3622 CandEnd = CandidateSet.end();
3623 Cand != CandEnd; ++Cand) {
3624 if (Cand->Viable)
3625 Results.push_back(ResultCandidate(Cand->Function));
3626 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003627
3628 // From the viable candidates, try to determine the type of this parameter.
3629 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3630 if (const FunctionType *FType = Results[I].getFunctionType())
3631 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3632 if (NumArgs < Proto->getNumArgs()) {
3633 if (ParamType.isNull())
3634 ParamType = Proto->getArgType(NumArgs);
3635 else if (!Context.hasSameUnqualifiedType(
3636 ParamType.getNonReferenceType(),
3637 Proto->getArgType(NumArgs).getNonReferenceType())) {
3638 ParamType = QualType();
3639 break;
3640 }
3641 }
3642 }
3643 } else {
3644 // Try to determine the parameter type from the type of the expression
3645 // being called.
3646 QualType FunctionType = Fn->getType();
3647 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3648 FunctionType = Ptr->getPointeeType();
3649 else if (const BlockPointerType *BlockPtr
3650 = FunctionType->getAs<BlockPointerType>())
3651 FunctionType = BlockPtr->getPointeeType();
3652 else if (const MemberPointerType *MemPtr
3653 = FunctionType->getAs<MemberPointerType>())
3654 FunctionType = MemPtr->getPointeeType();
3655
3656 if (const FunctionProtoType *Proto
3657 = FunctionType->getAs<FunctionProtoType>()) {
3658 if (NumArgs < Proto->getNumArgs())
3659 ParamType = Proto->getArgType(NumArgs);
3660 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003661 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003662
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003663 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003664 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003665 else
3666 CodeCompleteExpression(S, ParamType);
3667
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003668 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003669 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3670 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003671}
3672
John McCalld226f652010-08-21 09:40:31 +00003673void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3674 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003675 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003676 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003677 return;
3678 }
3679
3680 CodeCompleteExpression(S, VD->getType());
3681}
3682
3683void Sema::CodeCompleteReturn(Scope *S) {
3684 QualType ResultType;
3685 if (isa<BlockDecl>(CurContext)) {
3686 if (BlockScopeInfo *BSI = getCurBlock())
3687 ResultType = BSI->ReturnType;
3688 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3689 ResultType = Function->getResultType();
3690 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3691 ResultType = Method->getResultType();
3692
3693 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003694 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003695 else
3696 CodeCompleteExpression(S, ResultType);
3697}
3698
Douglas Gregord2d8be62011-07-30 08:36:53 +00003699void Sema::CodeCompleteAfterIf(Scope *S) {
3700 typedef CodeCompletionResult Result;
3701 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3702 mapCodeCompletionContext(*this, PCC_Statement));
3703 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3704 Results.EnterNewScope();
3705
3706 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3707 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3708 CodeCompleter->includeGlobals());
3709
3710 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3711
3712 // "else" block
3713 CodeCompletionBuilder Builder(Results.getAllocator());
3714 Builder.AddTypedTextChunk("else");
3715 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3716 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3717 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3718 Builder.AddPlaceholderChunk("statements");
3719 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3720 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3721 Results.AddResult(Builder.TakeString());
3722
3723 // "else if" block
3724 Builder.AddTypedTextChunk("else");
3725 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3726 Builder.AddTextChunk("if");
3727 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3728 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3729 if (getLangOptions().CPlusPlus)
3730 Builder.AddPlaceholderChunk("condition");
3731 else
3732 Builder.AddPlaceholderChunk("expression");
3733 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3734 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3735 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3736 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3737 Builder.AddPlaceholderChunk("statements");
3738 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3739 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3740 Results.AddResult(Builder.TakeString());
3741
3742 Results.ExitScope();
3743
3744 if (S->getFnParent())
3745 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3746
3747 if (CodeCompleter->includeMacros())
3748 AddMacroResults(PP, Results);
3749
3750 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3751 Results.data(),Results.size());
3752}
3753
Richard Trieuf81e5a92011-09-09 02:00:50 +00003754void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003755 if (LHS)
3756 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3757 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003758 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003759}
3760
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003761void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003762 bool EnteringContext) {
3763 if (!SS.getScopeRep() || !CodeCompleter)
3764 return;
3765
Douglas Gregor86d9a522009-09-21 16:56:56 +00003766 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3767 if (!Ctx)
3768 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003769
3770 // Try to instantiate any non-dependent declaration contexts before
3771 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003772 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003773 return;
3774
Douglas Gregor218937c2011-02-01 19:23:04 +00003775 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3776 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003777 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003778
Douglas Gregor86d9a522009-09-21 16:56:56 +00003779 // The "template" keyword can follow "::" in the grammar, but only
3780 // put it into the grammar if the nested-name-specifier is dependent.
3781 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3782 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003783 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003784
3785 // Add calls to overridden virtual functions, if there are any.
3786 //
3787 // FIXME: This isn't wonderful, because we don't know whether we're actually
3788 // in a context that permits expressions. This is a general issue with
3789 // qualified-id completions.
3790 if (!EnteringContext)
3791 MaybeAddOverrideCalls(*this, Ctx, Results);
3792 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003793
Douglas Gregorf6961522010-08-27 21:18:54 +00003794 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3795 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3796
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003797 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003798 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003799 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003800}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003801
3802void Sema::CodeCompleteUsing(Scope *S) {
3803 if (!CodeCompleter)
3804 return;
3805
Douglas Gregor218937c2011-02-01 19:23:04 +00003806 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003807 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3808 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003809 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003810
3811 // If we aren't in class scope, we could see the "namespace" keyword.
3812 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003813 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003814
3815 // After "using", we can see anything that would start a
3816 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003817 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003818 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3819 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003820 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003821
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003822 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003823 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003824 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003825}
3826
3827void Sema::CodeCompleteUsingDirective(Scope *S) {
3828 if (!CodeCompleter)
3829 return;
3830
Douglas Gregor86d9a522009-09-21 16:56:56 +00003831 // After "using namespace", we expect to see a namespace name or namespace
3832 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003833 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3834 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003835 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003836 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003837 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003838 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3839 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003840 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003841 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003842 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003843 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003844}
3845
3846void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3847 if (!CodeCompleter)
3848 return;
3849
Douglas Gregor86d9a522009-09-21 16:56:56 +00003850 DeclContext *Ctx = (DeclContext *)S->getEntity();
3851 if (!S->getParent())
3852 Ctx = Context.getTranslationUnitDecl();
3853
Douglas Gregor52779fb2010-09-23 23:01:17 +00003854 bool SuppressedGlobalResults
3855 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3856
Douglas Gregor218937c2011-02-01 19:23:04 +00003857 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003858 SuppressedGlobalResults
3859 ? CodeCompletionContext::CCC_Namespace
3860 : CodeCompletionContext::CCC_Other,
3861 &ResultBuilder::IsNamespace);
3862
3863 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003864 // We only want to see those namespaces that have already been defined
3865 // within this scope, because its likely that the user is creating an
3866 // extended namespace declaration. Keep track of the most recent
3867 // definition of each namespace.
3868 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3869 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3870 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3871 NS != NSEnd; ++NS)
3872 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3873
3874 // Add the most recent definition (or extended definition) of each
3875 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003876 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003877 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3878 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3879 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003880 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003881 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003882 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003883 }
3884
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003885 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003886 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003887 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003888}
3889
3890void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3891 if (!CodeCompleter)
3892 return;
3893
Douglas Gregor86d9a522009-09-21 16:56:56 +00003894 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003895 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3896 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003897 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003898 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003899 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3900 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003901 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003902 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003903 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003904}
3905
Douglas Gregored8d3222009-09-18 20:05:18 +00003906void Sema::CodeCompleteOperatorName(Scope *S) {
3907 if (!CodeCompleter)
3908 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003909
John McCall0a2c5e22010-08-25 06:19:51 +00003910 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003911 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3912 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003913 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003914 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003915
Douglas Gregor86d9a522009-09-21 16:56:56 +00003916 // Add the names of overloadable operators.
3917#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3918 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003919 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003920#include "clang/Basic/OperatorKinds.def"
3921
3922 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003923 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003924 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003925 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3926 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003927
3928 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003929 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003930 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003931
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003932 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003933 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003934 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003935}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003936
Douglas Gregor0133f522010-08-28 00:00:50 +00003937void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00003938 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00003939 unsigned NumInitializers) {
John McCallf85e1932011-06-15 23:02:42 +00003940 PrintingPolicy Policy(Context.PrintingPolicy);
3941 Policy.AnonymousTagLocations = false;
3942 Policy.SuppressStrongLifetime = true;
3943
Douglas Gregor0133f522010-08-28 00:00:50 +00003944 CXXConstructorDecl *Constructor
3945 = static_cast<CXXConstructorDecl *>(ConstructorD);
3946 if (!Constructor)
3947 return;
3948
Douglas Gregor218937c2011-02-01 19:23:04 +00003949 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003950 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003951 Results.EnterNewScope();
3952
3953 // Fill in any already-initialized fields or base classes.
3954 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3955 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3956 for (unsigned I = 0; I != NumInitializers; ++I) {
3957 if (Initializers[I]->isBaseInitializer())
3958 InitializedBases.insert(
3959 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3960 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003961 InitializedFields.insert(cast<FieldDecl>(
3962 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00003963 }
3964
3965 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00003966 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00003967 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003968 CXXRecordDecl *ClassDecl = Constructor->getParent();
3969 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3970 BaseEnd = ClassDecl->bases_end();
3971 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003972 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3973 SawLastInitializer
3974 = NumInitializers > 0 &&
3975 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3976 Context.hasSameUnqualifiedType(Base->getType(),
3977 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003978 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003979 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003980
Douglas Gregor218937c2011-02-01 19:23:04 +00003981 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003982 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00003983 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00003984 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3985 Builder.AddPlaceholderChunk("args");
3986 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3987 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003988 SawLastInitializer? CCP_NextInitializer
3989 : CCP_MemberDeclaration));
3990 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003991 }
3992
3993 // Add completions for virtual base classes.
3994 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3995 BaseEnd = ClassDecl->vbases_end();
3996 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003997 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3998 SawLastInitializer
3999 = NumInitializers > 0 &&
4000 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4001 Context.hasSameUnqualifiedType(Base->getType(),
4002 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004003 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004004 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004005
Douglas Gregor218937c2011-02-01 19:23:04 +00004006 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004007 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004008 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004009 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4010 Builder.AddPlaceholderChunk("args");
4011 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4012 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004013 SawLastInitializer? CCP_NextInitializer
4014 : CCP_MemberDeclaration));
4015 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004016 }
4017
4018 // Add completions for members.
4019 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4020 FieldEnd = ClassDecl->field_end();
4021 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004022 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4023 SawLastInitializer
4024 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004025 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4026 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004027 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004028 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004029
4030 if (!Field->getDeclName())
4031 continue;
4032
Douglas Gregordae68752011-02-01 22:57:45 +00004033 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004034 Field->getIdentifier()->getName()));
4035 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4036 Builder.AddPlaceholderChunk("args");
4037 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4038 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004039 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004040 : CCP_MemberDeclaration,
4041 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004042 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004043 }
4044 Results.ExitScope();
4045
Douglas Gregor52779fb2010-09-23 23:01:17 +00004046 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004047 Results.data(), Results.size());
4048}
4049
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004050// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4051// true or false.
4052#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004053static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004054 ResultBuilder &Results,
4055 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004056 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004057 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004058 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004059
Douglas Gregor218937c2011-02-01 19:23:04 +00004060 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004061 if (LangOpts.ObjC2) {
4062 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004063 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
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 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004069 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4070 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4071 Builder.AddPlaceholderChunk("property");
4072 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004073 }
4074}
4075
Douglas Gregorbca403c2010-01-13 23:51:12 +00004076static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004077 ResultBuilder &Results,
4078 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004079 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004080
4081 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004082 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004083
4084 if (LangOpts.ObjC2) {
4085 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004086 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004087
4088 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004089 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004090
4091 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004092 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004093 }
4094}
4095
Douglas Gregorbca403c2010-01-13 23:51:12 +00004096static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004097 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004098 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004099
4100 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004101 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4102 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4103 Builder.AddPlaceholderChunk("name");
4104 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004105
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004106 if (Results.includeCodePatterns()) {
4107 // @interface name
4108 // FIXME: Could introduce the whole pattern, including superclasses and
4109 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004110 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4111 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4112 Builder.AddPlaceholderChunk("class");
4113 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004114
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004115 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004116 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4117 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4118 Builder.AddPlaceholderChunk("protocol");
4119 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004120
4121 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004122 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4123 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4124 Builder.AddPlaceholderChunk("class");
4125 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004126 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004127
4128 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004129 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4130 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4131 Builder.AddPlaceholderChunk("alias");
4132 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4133 Builder.AddPlaceholderChunk("class");
4134 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004135}
4136
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004137void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004138 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004139 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4140 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004141 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004142 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorbca403c2010-01-13 23:51:12 +00004143 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004144 else if (CurContext->isObjCContainer())
Douglas Gregorbca403c2010-01-13 23:51:12 +00004145 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004146 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004147 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004148 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004149 HandleCodeCompleteResults(this, CodeCompleter,
4150 CodeCompletionContext::CCC_Other,
4151 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004152}
4153
Douglas Gregorbca403c2010-01-13 23:51:12 +00004154static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004155 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004156 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004157
4158 // @encode ( type-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004159 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4160 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4161 Builder.AddPlaceholderChunk("type-name");
4162 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4163 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004164
4165 // @protocol ( protocol-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004166 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4167 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4168 Builder.AddPlaceholderChunk("protocol-name");
4169 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4170 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004171
4172 // @selector ( selector )
Douglas Gregor218937c2011-02-01 19:23:04 +00004173 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4174 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4175 Builder.AddPlaceholderChunk("selector");
4176 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4177 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004178}
4179
Douglas Gregorbca403c2010-01-13 23:51:12 +00004180static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004181 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004182 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004183
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004184 if (Results.includeCodePatterns()) {
4185 // @try { statements } @catch ( declaration ) { statements } @finally
4186 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004187 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4188 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4189 Builder.AddPlaceholderChunk("statements");
4190 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4191 Builder.AddTextChunk("@catch");
4192 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4193 Builder.AddPlaceholderChunk("parameter");
4194 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4195 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4196 Builder.AddPlaceholderChunk("statements");
4197 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4198 Builder.AddTextChunk("@finally");
4199 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4200 Builder.AddPlaceholderChunk("statements");
4201 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4202 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004203 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004204
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004205 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004206 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4207 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4208 Builder.AddPlaceholderChunk("expression");
4209 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004210
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004211 if (Results.includeCodePatterns()) {
4212 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004213 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4214 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4215 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4216 Builder.AddPlaceholderChunk("expression");
4217 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4218 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4219 Builder.AddPlaceholderChunk("statements");
4220 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4221 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004222 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004223}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004224
Douglas Gregorbca403c2010-01-13 23:51:12 +00004225static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004226 ResultBuilder &Results,
4227 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004228 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004229 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4230 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4231 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004232 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004233 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004234}
4235
4236void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004237 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4238 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004239 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004240 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004241 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004242 HandleCodeCompleteResults(this, CodeCompleter,
4243 CodeCompletionContext::CCC_Other,
4244 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004245}
4246
4247void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004248 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4249 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004250 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004251 AddObjCStatementResults(Results, false);
4252 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004253 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004254 HandleCodeCompleteResults(this, CodeCompleter,
4255 CodeCompletionContext::CCC_Other,
4256 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004257}
4258
4259void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004260 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4261 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004262 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004263 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004264 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004265 HandleCodeCompleteResults(this, CodeCompleter,
4266 CodeCompletionContext::CCC_Other,
4267 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004268}
4269
Douglas Gregor988358f2009-11-19 00:14:45 +00004270/// \brief Determine whether the addition of the given flag to an Objective-C
4271/// property's attributes will cause a conflict.
4272static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4273 // Check if we've already added this flag.
4274 if (Attributes & NewFlag)
4275 return true;
4276
4277 Attributes |= NewFlag;
4278
4279 // Check for collisions with "readonly".
4280 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4281 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4282 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004283 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004284 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004285 ObjCDeclSpec::DQ_PR_retain |
4286 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004287 return true;
4288
John McCallf85e1932011-06-15 23:02:42 +00004289 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004290 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004291 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004292 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004293 ObjCDeclSpec::DQ_PR_retain|
4294 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004295 if (AssignCopyRetMask &&
4296 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004297 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004298 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004299 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4300 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004301 return true;
4302
4303 return false;
4304}
4305
Douglas Gregora93b1082009-11-18 23:08:07 +00004306void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004307 if (!CodeCompleter)
4308 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004309
Steve Naroffece8e712009-10-08 21:55:05 +00004310 unsigned Attributes = ODS.getPropertyAttributes();
4311
John McCall0a2c5e22010-08-25 06:19:51 +00004312 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004313 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4314 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004315 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004316 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004317 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004318 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004319 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004320 if (!ObjCPropertyFlagConflicts(Attributes,
4321 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4322 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004323 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004324 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004325 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004326 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004327 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4328 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004329 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004330 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004331 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004332 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004333 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4334 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004335 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004336 CodeCompletionBuilder Setter(Results.getAllocator());
4337 Setter.AddTypedTextChunk("setter");
4338 Setter.AddTextChunk(" = ");
4339 Setter.AddPlaceholderChunk("method");
4340 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004341 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004342 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004343 CodeCompletionBuilder Getter(Results.getAllocator());
4344 Getter.AddTypedTextChunk("getter");
4345 Getter.AddTextChunk(" = ");
4346 Getter.AddPlaceholderChunk("method");
4347 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004348 }
Steve Naroffece8e712009-10-08 21:55:05 +00004349 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004350 HandleCodeCompleteResults(this, CodeCompleter,
4351 CodeCompletionContext::CCC_Other,
4352 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004353}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004354
Douglas Gregor4ad96852009-11-19 07:41:15 +00004355/// \brief Descripts the kind of Objective-C method that we want to find
4356/// via code completion.
4357enum ObjCMethodKind {
4358 MK_Any, //< Any kind of method, provided it means other specified criteria.
4359 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4360 MK_OneArgSelector //< One-argument selector.
4361};
4362
Douglas Gregor458433d2010-08-26 15:07:07 +00004363static bool isAcceptableObjCSelector(Selector Sel,
4364 ObjCMethodKind WantKind,
4365 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004366 unsigned NumSelIdents,
4367 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004368 if (NumSelIdents > Sel.getNumArgs())
4369 return false;
4370
4371 switch (WantKind) {
4372 case MK_Any: break;
4373 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4374 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4375 }
4376
Douglas Gregorcf544262010-11-17 21:36:08 +00004377 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4378 return false;
4379
Douglas Gregor458433d2010-08-26 15:07:07 +00004380 for (unsigned I = 0; I != NumSelIdents; ++I)
4381 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4382 return false;
4383
4384 return true;
4385}
4386
Douglas Gregor4ad96852009-11-19 07:41:15 +00004387static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4388 ObjCMethodKind WantKind,
4389 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004390 unsigned NumSelIdents,
4391 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004392 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004393 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004394}
Douglas Gregord36adf52010-09-16 16:06:31 +00004395
4396namespace {
4397 /// \brief A set of selectors, which is used to avoid introducing multiple
4398 /// completions with the same selector into the result set.
4399 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4400}
4401
Douglas Gregor36ecb042009-11-17 23:22:23 +00004402/// \brief Add all of the Objective-C methods in the given Objective-C
4403/// container to the set of results.
4404///
4405/// The container will be a class, protocol, category, or implementation of
4406/// any of the above. This mether will recurse to include methods from
4407/// the superclasses of classes along with their categories, protocols, and
4408/// implementations.
4409///
4410/// \param Container the container in which we'll look to find methods.
4411///
4412/// \param WantInstance whether to add instance methods (only); if false, this
4413/// routine will add factory methods (only).
4414///
4415/// \param CurContext the context in which we're performing the lookup that
4416/// finds methods.
4417///
Douglas Gregorcf544262010-11-17 21:36:08 +00004418/// \param AllowSameLength Whether we allow a method to be added to the list
4419/// when it has the same number of parameters as we have selector identifiers.
4420///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004421/// \param Results the structure into which we'll add results.
4422static void AddObjCMethods(ObjCContainerDecl *Container,
4423 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004424 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004425 IdentifierInfo **SelIdents,
4426 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004427 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004428 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004429 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004430 ResultBuilder &Results,
4431 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004432 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004433 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4434 MEnd = Container->meth_end();
4435 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004436 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4437 // Check whether the selector identifiers we've been given are a
4438 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004439 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4440 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004441 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004442
Douglas Gregord36adf52010-09-16 16:06:31 +00004443 if (!Selectors.insert((*M)->getSelector()))
4444 continue;
4445
Douglas Gregord3c68542009-11-19 01:08:35 +00004446 Result R = Result(*M, 0);
4447 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004448 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004449 if (!InOriginalClass)
4450 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004451 Results.MaybeAddResult(R, CurContext);
4452 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004453 }
4454
Douglas Gregore396c7b2010-09-16 15:34:59 +00004455 // Visit the protocols of protocols.
4456 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4457 const ObjCList<ObjCProtocolDecl> &Protocols
4458 = Protocol->getReferencedProtocols();
4459 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4460 E = Protocols.end();
4461 I != E; ++I)
4462 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004463 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004464 }
4465
Douglas Gregor36ecb042009-11-17 23:22:23 +00004466 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4467 if (!IFace)
4468 return;
4469
4470 // Add methods in protocols.
4471 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4472 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4473 E = Protocols.end();
4474 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004475 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004476 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004477
4478 // Add methods in categories.
4479 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4480 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004481 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004482 NumSelIdents, CurContext, Selectors, AllowSameLength,
4483 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004484
4485 // Add a categories protocol methods.
4486 const ObjCList<ObjCProtocolDecl> &Protocols
4487 = CatDecl->getReferencedProtocols();
4488 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4489 E = Protocols.end();
4490 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004491 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004492 NumSelIdents, CurContext, Selectors, AllowSameLength,
4493 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004494
4495 // Add methods in category implementations.
4496 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004497 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004498 NumSelIdents, CurContext, Selectors, AllowSameLength,
4499 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004500 }
4501
4502 // Add methods in superclass.
4503 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004504 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004505 SelIdents, NumSelIdents, CurContext, Selectors,
4506 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004507
4508 // Add methods in our implementation, if any.
4509 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004510 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004511 NumSelIdents, CurContext, Selectors, AllowSameLength,
4512 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004513}
4514
4515
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004516void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004517 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004518
4519 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004520 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004521 if (!Class) {
4522 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004523 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004524 Class = Category->getClassInterface();
4525
4526 if (!Class)
4527 return;
4528 }
4529
4530 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004531 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4532 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004533 Results.EnterNewScope();
4534
Douglas Gregord36adf52010-09-16 16:06:31 +00004535 VisitedSelectorSet Selectors;
4536 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004537 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004538 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004539 HandleCodeCompleteResults(this, CodeCompleter,
4540 CodeCompletionContext::CCC_Other,
4541 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004542}
4543
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004544void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004545 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004546
4547 // Try to find the interface where setters might live.
4548 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004549 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004550 if (!Class) {
4551 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004552 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004553 Class = Category->getClassInterface();
4554
4555 if (!Class)
4556 return;
4557 }
4558
4559 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004560 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4561 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004562 Results.EnterNewScope();
4563
Douglas Gregord36adf52010-09-16 16:06:31 +00004564 VisitedSelectorSet Selectors;
4565 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004566 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004567
4568 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004569 HandleCodeCompleteResults(this, CodeCompleter,
4570 CodeCompletionContext::CCC_Other,
4571 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004572}
4573
Douglas Gregorafc45782011-02-15 22:19:42 +00004574void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4575 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004576 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004577 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4578 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004579 Results.EnterNewScope();
4580
4581 // Add context-sensitive, Objective-C parameter-passing keywords.
4582 bool AddedInOut = false;
4583 if ((DS.getObjCDeclQualifier() &
4584 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4585 Results.AddResult("in");
4586 Results.AddResult("inout");
4587 AddedInOut = true;
4588 }
4589 if ((DS.getObjCDeclQualifier() &
4590 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4591 Results.AddResult("out");
4592 if (!AddedInOut)
4593 Results.AddResult("inout");
4594 }
4595 if ((DS.getObjCDeclQualifier() &
4596 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4597 ObjCDeclSpec::DQ_Oneway)) == 0) {
4598 Results.AddResult("bycopy");
4599 Results.AddResult("byref");
4600 Results.AddResult("oneway");
4601 }
4602
Douglas Gregorafc45782011-02-15 22:19:42 +00004603 // If we're completing the return type of an Objective-C method and the
4604 // identifier IBAction refers to a macro, provide a completion item for
4605 // an action, e.g.,
4606 // IBAction)<#selector#>:(id)sender
4607 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4608 Context.Idents.get("IBAction").hasMacroDefinition()) {
4609 typedef CodeCompletionString::Chunk Chunk;
4610 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4611 CXAvailability_Available);
4612 Builder.AddTypedTextChunk("IBAction");
4613 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4614 Builder.AddPlaceholderChunk("selector");
4615 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4616 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4617 Builder.AddTextChunk("id");
4618 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4619 Builder.AddTextChunk("sender");
4620 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4621 }
4622
Douglas Gregord32b0222010-08-24 01:06:58 +00004623 // Add various builtin type names and specifiers.
4624 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4625 Results.ExitScope();
4626
4627 // Add the various type names
4628 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4629 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4630 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4631 CodeCompleter->includeGlobals());
4632
4633 if (CodeCompleter->includeMacros())
4634 AddMacroResults(PP, Results);
4635
4636 HandleCodeCompleteResults(this, CodeCompleter,
4637 CodeCompletionContext::CCC_Type,
4638 Results.data(), Results.size());
4639}
4640
Douglas Gregor22f56992010-04-06 19:22:33 +00004641/// \brief When we have an expression with type "id", we may assume
4642/// that it has some more-specific class type based on knowledge of
4643/// common uses of Objective-C. This routine returns that class type,
4644/// or NULL if no better result could be determined.
4645static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004646 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004647 if (!Msg)
4648 return 0;
4649
4650 Selector Sel = Msg->getSelector();
4651 if (Sel.isNull())
4652 return 0;
4653
4654 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4655 if (!Id)
4656 return 0;
4657
4658 ObjCMethodDecl *Method = Msg->getMethodDecl();
4659 if (!Method)
4660 return 0;
4661
4662 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004663 ObjCInterfaceDecl *IFace = 0;
4664 switch (Msg->getReceiverKind()) {
4665 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004666 if (const ObjCObjectType *ObjType
4667 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4668 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004669 break;
4670
4671 case ObjCMessageExpr::Instance: {
4672 QualType T = Msg->getInstanceReceiver()->getType();
4673 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4674 IFace = Ptr->getInterfaceDecl();
4675 break;
4676 }
4677
4678 case ObjCMessageExpr::SuperInstance:
4679 case ObjCMessageExpr::SuperClass:
4680 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004681 }
4682
4683 if (!IFace)
4684 return 0;
4685
4686 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4687 if (Method->isInstanceMethod())
4688 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4689 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004690 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004691 .Case("autorelease", IFace)
4692 .Case("copy", IFace)
4693 .Case("copyWithZone", IFace)
4694 .Case("mutableCopy", IFace)
4695 .Case("mutableCopyWithZone", IFace)
4696 .Case("awakeFromCoder", IFace)
4697 .Case("replacementObjectFromCoder", IFace)
4698 .Case("class", IFace)
4699 .Case("classForCoder", IFace)
4700 .Case("superclass", Super)
4701 .Default(0);
4702
4703 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4704 .Case("new", IFace)
4705 .Case("alloc", IFace)
4706 .Case("allocWithZone", IFace)
4707 .Case("class", IFace)
4708 .Case("superclass", Super)
4709 .Default(0);
4710}
4711
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004712// Add a special completion for a message send to "super", which fills in the
4713// most likely case of forwarding all of our arguments to the superclass
4714// function.
4715///
4716/// \param S The semantic analysis object.
4717///
4718/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4719/// the "super" keyword. Otherwise, we just need to provide the arguments.
4720///
4721/// \param SelIdents The identifiers in the selector that have already been
4722/// provided as arguments for a send to "super".
4723///
4724/// \param NumSelIdents The number of identifiers in \p SelIdents.
4725///
4726/// \param Results The set of results to augment.
4727///
4728/// \returns the Objective-C method declaration that would be invoked by
4729/// this "super" completion. If NULL, no completion was added.
4730static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4731 IdentifierInfo **SelIdents,
4732 unsigned NumSelIdents,
4733 ResultBuilder &Results) {
4734 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4735 if (!CurMethod)
4736 return 0;
4737
4738 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4739 if (!Class)
4740 return 0;
4741
4742 // Try to find a superclass method with the same selector.
4743 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004744 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4745 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004746 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4747 CurMethod->isInstanceMethod());
4748
Douglas Gregor78bcd912011-02-16 00:51:18 +00004749 // Check in categories or class extensions.
4750 if (!SuperMethod) {
4751 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4752 Category = Category->getNextClassCategory())
4753 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4754 CurMethod->isInstanceMethod())))
4755 break;
4756 }
4757 }
4758
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004759 if (!SuperMethod)
4760 return 0;
4761
4762 // Check whether the superclass method has the same signature.
4763 if (CurMethod->param_size() != SuperMethod->param_size() ||
4764 CurMethod->isVariadic() != SuperMethod->isVariadic())
4765 return 0;
4766
4767 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4768 CurPEnd = CurMethod->param_end(),
4769 SuperP = SuperMethod->param_begin();
4770 CurP != CurPEnd; ++CurP, ++SuperP) {
4771 // Make sure the parameter types are compatible.
4772 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4773 (*SuperP)->getType()))
4774 return 0;
4775
4776 // Make sure we have a parameter name to forward!
4777 if (!(*CurP)->getIdentifier())
4778 return 0;
4779 }
4780
4781 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004782 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004783
4784 // Give this completion a return type.
Douglas Gregor218937c2011-02-01 19:23:04 +00004785 AddResultTypeChunk(S.Context, SuperMethod, Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004786
4787 // If we need the "super" keyword, add it (plus some spacing).
4788 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004789 Builder.AddTypedTextChunk("super");
4790 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004791 }
4792
4793 Selector Sel = CurMethod->getSelector();
4794 if (Sel.isUnarySelector()) {
4795 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004796 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004797 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004798 else
Douglas Gregordae68752011-02-01 22:57:45 +00004799 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004800 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004801 } else {
4802 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4803 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4804 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004805 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004806
4807 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004808 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004809 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004810 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004811 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004812 Builder.AddTextChunk(
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 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004818 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004819 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004820 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004821 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004822 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004823 }
4824 }
4825 }
4826
Douglas Gregor218937c2011-02-01 19:23:04 +00004827 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004828 SuperMethod->isInstanceMethod()
4829 ? CXCursor_ObjCInstanceMethodDecl
4830 : CXCursor_ObjCClassMethodDecl));
4831 return SuperMethod;
4832}
4833
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004834void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004835 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004836 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4837 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004838 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004839
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004840 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4841 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004842 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4843 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004844
4845 // If we are in an Objective-C method inside a class that has a superclass,
4846 // add "super" as an option.
4847 if (ObjCMethodDecl *Method = getCurMethodDecl())
4848 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004849 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004850 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004851
4852 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4853 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004854
4855 Results.ExitScope();
4856
4857 if (CodeCompleter->includeMacros())
4858 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004859 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004860 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004861
4862}
4863
Douglas Gregor2725ca82010-04-21 19:57:20 +00004864void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4865 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004866 unsigned NumSelIdents,
4867 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004868 ObjCInterfaceDecl *CDecl = 0;
4869 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4870 // Figure out which interface we're in.
4871 CDecl = CurMethod->getClassInterface();
4872 if (!CDecl)
4873 return;
4874
4875 // Find the superclass of this class.
4876 CDecl = CDecl->getSuperClass();
4877 if (!CDecl)
4878 return;
4879
4880 if (CurMethod->isInstanceMethod()) {
4881 // We are inside an instance method, which means that the message
4882 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004883 // current object.
4884 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004885 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004886 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004887 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004888 }
4889
4890 // Fall through to send to the superclass in CDecl.
4891 } else {
4892 // "super" may be the name of a type or variable. Figure out which
4893 // it is.
4894 IdentifierInfo *Super = &Context.Idents.get("super");
4895 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4896 LookupOrdinaryName);
4897 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4898 // "super" names an interface. Use it.
4899 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004900 if (const ObjCObjectType *Iface
4901 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4902 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004903 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4904 // "super" names an unresolved type; we can't be more specific.
4905 } else {
4906 // Assume that "super" names some kind of value and parse that way.
4907 CXXScopeSpec SS;
4908 UnqualifiedId id;
4909 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004910 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004911 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004912 SelIdents, NumSelIdents,
4913 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004914 }
4915
4916 // Fall through
4917 }
4918
John McCallb3d87482010-08-24 05:47:05 +00004919 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004920 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004921 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004922 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004923 NumSelIdents, AtArgumentExpression,
4924 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004925}
4926
Douglas Gregorb9d77572010-09-21 00:03:25 +00004927/// \brief Given a set of code-completion results for the argument of a message
4928/// send, determine the preferred type (if any) for that argument expression.
4929static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4930 unsigned NumSelIdents) {
4931 typedef CodeCompletionResult Result;
4932 ASTContext &Context = Results.getSema().Context;
4933
4934 QualType PreferredType;
4935 unsigned BestPriority = CCP_Unlikely * 2;
4936 Result *ResultsData = Results.data();
4937 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4938 Result &R = ResultsData[I];
4939 if (R.Kind == Result::RK_Declaration &&
4940 isa<ObjCMethodDecl>(R.Declaration)) {
4941 if (R.Priority <= BestPriority) {
4942 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4943 if (NumSelIdents <= Method->param_size()) {
4944 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4945 ->getType();
4946 if (R.Priority < BestPriority || PreferredType.isNull()) {
4947 BestPriority = R.Priority;
4948 PreferredType = MyPreferredType;
4949 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4950 MyPreferredType)) {
4951 PreferredType = QualType();
4952 }
4953 }
4954 }
4955 }
4956 }
4957
4958 return PreferredType;
4959}
4960
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004961static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4962 ParsedType Receiver,
4963 IdentifierInfo **SelIdents,
4964 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004965 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004966 bool IsSuper,
4967 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004968 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004969 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004970
Douglas Gregor24a069f2009-11-17 17:59:40 +00004971 // If the given name refers to an interface type, retrieve the
4972 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004973 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004974 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004975 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004976 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4977 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004978 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004979
Douglas Gregor36ecb042009-11-17 23:22:23 +00004980 // Add all of the factory methods in this Objective-C class, its protocols,
4981 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004982 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004983
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004984 // If this is a send-to-super, try to add the special "super" send
4985 // completion.
4986 if (IsSuper) {
4987 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004988 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4989 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004990 Results.Ignore(SuperMethod);
4991 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004992
Douglas Gregor265f7492010-08-27 15:29:55 +00004993 // If we're inside an Objective-C method definition, prefer its selector to
4994 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004995 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00004996 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004997
Douglas Gregord36adf52010-09-16 16:06:31 +00004998 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00004999 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005000 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005001 SemaRef.CurContext, Selectors, AtArgumentExpression,
5002 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005003 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005004 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005005
Douglas Gregor719770d2010-04-06 17:30:22 +00005006 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005007 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005008 if (SemaRef.ExternalSource) {
5009 for (uint32_t I = 0,
5010 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005011 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005012 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5013 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005014 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005015
5016 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005017 }
5018 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005019
5020 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5021 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005022 M != MEnd; ++M) {
5023 for (ObjCMethodList *MethList = &M->second.second;
5024 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005025 MethList = MethList->Next) {
5026 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5027 NumSelIdents))
5028 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005029
Douglas Gregor13438f92010-04-06 16:40:00 +00005030 Result R(MethList->Method, 0);
5031 R.StartParameter = NumSelIdents;
5032 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005033 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005034 }
5035 }
5036 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005037
5038 Results.ExitScope();
5039}
Douglas Gregor13438f92010-04-06 16:40:00 +00005040
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005041void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5042 IdentifierInfo **SelIdents,
5043 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005044 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005045 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005046
5047 QualType T = this->GetTypeFromParser(Receiver);
5048
Douglas Gregor218937c2011-02-01 19:23:04 +00005049 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005050 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005051 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005052
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005053 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5054 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005055
5056 // If we're actually at the argument expression (rather than prior to the
5057 // selector), we're actually performing code completion for an expression.
5058 // Determine whether we have a single, best method. If so, we can
5059 // code-complete the expression using the corresponding parameter type as
5060 // our preferred type, improving completion results.
5061 if (AtArgumentExpression) {
5062 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005063 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005064 if (PreferredType.isNull())
5065 CodeCompleteOrdinaryName(S, PCC_Expression);
5066 else
5067 CodeCompleteExpression(S, PreferredType);
5068 return;
5069 }
5070
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005071 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005072 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005073 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005074}
5075
Richard Trieuf81e5a92011-09-09 02:00:50 +00005076void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005077 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005078 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005079 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005080 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005081 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005082
5083 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005084
Douglas Gregor36ecb042009-11-17 23:22:23 +00005085 // If necessary, apply function/array conversion to the receiver.
5086 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005087 if (RecExpr) {
5088 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5089 if (Conv.isInvalid()) // conversion failed. bail.
5090 return;
5091 RecExpr = Conv.take();
5092 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005093 QualType ReceiverType = RecExpr? RecExpr->getType()
5094 : Super? Context.getObjCObjectPointerType(
5095 Context.getObjCInterfaceType(Super))
5096 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005097
Douglas Gregorda892642010-11-08 21:12:30 +00005098 // If we're messaging an expression with type "id" or "Class", check
5099 // whether we know something special about the receiver that allows
5100 // us to assume a more-specific receiver type.
5101 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5102 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5103 if (ReceiverType->isObjCClassType())
5104 return CodeCompleteObjCClassMessage(S,
5105 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5106 SelIdents, NumSelIdents,
5107 AtArgumentExpression, Super);
5108
5109 ReceiverType = Context.getObjCObjectPointerType(
5110 Context.getObjCInterfaceType(IFace));
5111 }
5112
Douglas Gregor36ecb042009-11-17 23:22:23 +00005113 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005114 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005115 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005116 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005117
Douglas Gregor36ecb042009-11-17 23:22:23 +00005118 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005119
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005120 // If this is a send-to-super, try to add the special "super" send
5121 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005122 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005123 if (ObjCMethodDecl *SuperMethod
5124 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5125 Results))
5126 Results.Ignore(SuperMethod);
5127 }
5128
Douglas Gregor265f7492010-08-27 15:29:55 +00005129 // If we're inside an Objective-C method definition, prefer its selector to
5130 // others.
5131 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5132 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005133
Douglas Gregord36adf52010-09-16 16:06:31 +00005134 // Keep track of the selectors we've already added.
5135 VisitedSelectorSet Selectors;
5136
Douglas Gregorf74a4192009-11-18 00:06:18 +00005137 // Handle messages to Class. This really isn't a message to an instance
5138 // method, so we treat it the same way we would treat a message send to a
5139 // class method.
5140 if (ReceiverType->isObjCClassType() ||
5141 ReceiverType->isObjCQualifiedClassType()) {
5142 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5143 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005144 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005145 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005146 }
5147 }
5148 // Handle messages to a qualified ID ("id<foo>").
5149 else if (const ObjCObjectPointerType *QualID
5150 = ReceiverType->getAsObjCQualifiedIdType()) {
5151 // Search protocols for instance methods.
5152 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5153 E = QualID->qual_end();
5154 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005155 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005156 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005157 }
5158 // Handle messages to a pointer to interface type.
5159 else if (const ObjCObjectPointerType *IFacePtr
5160 = ReceiverType->getAsObjCInterfacePointerType()) {
5161 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005162 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005163 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5164 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005165
5166 // Search protocols for instance methods.
5167 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5168 E = IFacePtr->qual_end();
5169 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005170 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005171 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005172 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005173 // Handle messages to "id".
5174 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005175 // We're messaging "id", so provide all instance methods we know
5176 // about as code-completion results.
5177
5178 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005179 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005180 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005181 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5182 I != N; ++I) {
5183 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005184 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005185 continue;
5186
Sebastian Redldb9d2142010-08-02 23:18:59 +00005187 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005188 }
5189 }
5190
Sebastian Redldb9d2142010-08-02 23:18:59 +00005191 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5192 MEnd = MethodPool.end();
5193 M != MEnd; ++M) {
5194 for (ObjCMethodList *MethList = &M->second.first;
5195 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005196 MethList = MethList->Next) {
5197 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5198 NumSelIdents))
5199 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005200
5201 if (!Selectors.insert(MethList->Method->getSelector()))
5202 continue;
5203
Douglas Gregor13438f92010-04-06 16:40:00 +00005204 Result R(MethList->Method, 0);
5205 R.StartParameter = NumSelIdents;
5206 R.AllParametersAreInformative = false;
5207 Results.MaybeAddResult(R, CurContext);
5208 }
5209 }
5210 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005211 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005212
5213
5214 // If we're actually at the argument expression (rather than prior to the
5215 // selector), we're actually performing code completion for an expression.
5216 // Determine whether we have a single, best method. If so, we can
5217 // code-complete the expression using the corresponding parameter type as
5218 // our preferred type, improving completion results.
5219 if (AtArgumentExpression) {
5220 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5221 NumSelIdents);
5222 if (PreferredType.isNull())
5223 CodeCompleteOrdinaryName(S, PCC_Expression);
5224 else
5225 CodeCompleteExpression(S, PreferredType);
5226 return;
5227 }
5228
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005229 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005230 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005231 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005232}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005233
Douglas Gregorfb629412010-08-23 21:17:50 +00005234void Sema::CodeCompleteObjCForCollection(Scope *S,
5235 DeclGroupPtrTy IterationVar) {
5236 CodeCompleteExpressionData Data;
5237 Data.ObjCCollection = true;
5238
5239 if (IterationVar.getAsOpaquePtr()) {
5240 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5241 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5242 if (*I)
5243 Data.IgnoreDecls.push_back(*I);
5244 }
5245 }
5246
5247 CodeCompleteExpression(S, Data);
5248}
5249
Douglas Gregor458433d2010-08-26 15:07:07 +00005250void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5251 unsigned NumSelIdents) {
5252 // If we have an external source, load the entire class method
5253 // pool from the AST file.
5254 if (ExternalSource) {
5255 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5256 I != N; ++I) {
5257 Selector Sel = ExternalSource->GetExternalSelector(I);
5258 if (Sel.isNull() || MethodPool.count(Sel))
5259 continue;
5260
5261 ReadMethodPool(Sel);
5262 }
5263 }
5264
Douglas Gregor218937c2011-02-01 19:23:04 +00005265 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5266 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005267 Results.EnterNewScope();
5268 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5269 MEnd = MethodPool.end();
5270 M != MEnd; ++M) {
5271
5272 Selector Sel = M->first;
5273 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5274 continue;
5275
Douglas Gregor218937c2011-02-01 19:23:04 +00005276 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005277 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005278 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005279 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005280 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005281 continue;
5282 }
5283
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005284 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005285 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005286 if (I == NumSelIdents) {
5287 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005288 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005289 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005290 Accumulator.clear();
5291 }
5292 }
5293
Benjamin Kramera0651c52011-07-26 16:59:25 +00005294 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005295 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005296 }
Douglas Gregordae68752011-02-01 22:57:45 +00005297 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005298 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005299 }
5300 Results.ExitScope();
5301
5302 HandleCodeCompleteResults(this, CodeCompleter,
5303 CodeCompletionContext::CCC_SelectorName,
5304 Results.data(), Results.size());
5305}
5306
Douglas Gregor55385fe2009-11-18 04:19:12 +00005307/// \brief Add all of the protocol declarations that we find in the given
5308/// (translation unit) context.
5309static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005310 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005311 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005312 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005313
5314 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5315 DEnd = Ctx->decls_end();
5316 D != DEnd; ++D) {
5317 // Record any protocols we find.
5318 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005319 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005320 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005321
5322 // Record any forward-declared protocols we find.
5323 if (ObjCForwardProtocolDecl *Forward
5324 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5325 for (ObjCForwardProtocolDecl::protocol_iterator
5326 P = Forward->protocol_begin(),
5327 PEnd = Forward->protocol_end();
5328 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005329 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005330 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005331 }
5332 }
5333}
5334
5335void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5336 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005337 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5338 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005339
Douglas Gregor70c23352010-12-09 21:44:02 +00005340 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5341 Results.EnterNewScope();
5342
5343 // Tell the result set to ignore all of the protocols we have
5344 // already seen.
5345 // FIXME: This doesn't work when caching code-completion results.
5346 for (unsigned I = 0; I != NumProtocols; ++I)
5347 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5348 Protocols[I].second))
5349 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005350
Douglas Gregor70c23352010-12-09 21:44:02 +00005351 // Add all protocols.
5352 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5353 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005354
Douglas Gregor70c23352010-12-09 21:44:02 +00005355 Results.ExitScope();
5356 }
5357
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005358 HandleCodeCompleteResults(this, CodeCompleter,
5359 CodeCompletionContext::CCC_ObjCProtocolName,
5360 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005361}
5362
5363void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005364 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5365 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005366
Douglas Gregor70c23352010-12-09 21:44:02 +00005367 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5368 Results.EnterNewScope();
5369
5370 // Add all protocols.
5371 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5372 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005373
Douglas Gregor70c23352010-12-09 21:44:02 +00005374 Results.ExitScope();
5375 }
5376
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005377 HandleCodeCompleteResults(this, CodeCompleter,
5378 CodeCompletionContext::CCC_ObjCProtocolName,
5379 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005380}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005381
5382/// \brief Add all of the Objective-C interface declarations that we find in
5383/// the given (translation unit) context.
5384static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5385 bool OnlyForwardDeclarations,
5386 bool OnlyUnimplemented,
5387 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005388 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005389
5390 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5391 DEnd = Ctx->decls_end();
5392 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005393 // Record any interfaces we find.
5394 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5395 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5396 (!OnlyUnimplemented || !Class->getImplementation()))
5397 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005398
5399 // Record any forward-declared interfaces we find.
5400 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005401 ObjCInterfaceDecl *IDecl = Forward->getForwardInterfaceDecl();
5402 if ((!OnlyForwardDeclarations || IDecl->isForwardDecl()) &&
5403 (!OnlyUnimplemented || !IDecl->getImplementation()))
5404 Results.AddResult(Result(IDecl, 0), CurContext,
5405 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005406 }
5407 }
5408}
5409
5410void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005411 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5412 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005413 Results.EnterNewScope();
5414
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005415 if (CodeCompleter->includeGlobals()) {
5416 // Add all classes.
5417 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5418 false, Results);
5419 }
5420
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005421 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005422
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005423 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005424 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005425 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005426}
5427
Douglas Gregorc83c6872010-04-15 22:33:43 +00005428void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5429 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005430 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005431 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005432 Results.EnterNewScope();
5433
5434 // Make sure that we ignore the class we're currently defining.
5435 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005436 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005437 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005438 Results.Ignore(CurClass);
5439
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005440 if (CodeCompleter->includeGlobals()) {
5441 // Add all classes.
5442 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5443 false, Results);
5444 }
5445
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005446 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005447
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005448 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005449 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005450 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005451}
5452
5453void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005454 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5455 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005456 Results.EnterNewScope();
5457
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005458 if (CodeCompleter->includeGlobals()) {
5459 // Add all unimplemented classes.
5460 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5461 true, Results);
5462 }
5463
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005464 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005465
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005466 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005467 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005468 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005469}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005470
5471void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005472 IdentifierInfo *ClassName,
5473 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005474 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005475
Douglas Gregor218937c2011-02-01 19:23:04 +00005476 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005477 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005478
5479 // Ignore any categories we find that have already been implemented by this
5480 // interface.
5481 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5482 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005483 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005484 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5485 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5486 Category = Category->getNextClassCategory())
5487 CategoryNames.insert(Category->getIdentifier());
5488
5489 // Add all of the categories we know about.
5490 Results.EnterNewScope();
5491 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5492 for (DeclContext::decl_iterator D = TU->decls_begin(),
5493 DEnd = TU->decls_end();
5494 D != DEnd; ++D)
5495 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5496 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005497 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005498 Results.ExitScope();
5499
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005500 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005501 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005502 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005503}
5504
5505void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005506 IdentifierInfo *ClassName,
5507 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005508 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005509
5510 // Find the corresponding interface. If we couldn't find the interface, the
5511 // program itself is ill-formed. However, we'll try to be helpful still by
5512 // providing the list of all of the categories we know about.
5513 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005514 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005515 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5516 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005517 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005518
Douglas Gregor218937c2011-02-01 19:23:04 +00005519 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005520 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005521
5522 // Add all of the categories that have have corresponding interface
5523 // declarations in this class and any of its superclasses, except for
5524 // already-implemented categories in the class itself.
5525 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5526 Results.EnterNewScope();
5527 bool IgnoreImplemented = true;
5528 while (Class) {
5529 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5530 Category = Category->getNextClassCategory())
5531 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5532 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005533 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005534
5535 Class = Class->getSuperClass();
5536 IgnoreImplemented = false;
5537 }
5538 Results.ExitScope();
5539
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005540 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005541 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005542 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005543}
Douglas Gregor322328b2009-11-18 22:32:06 +00005544
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005545void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005546 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005547 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5548 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005549
5550 // Figure out where this @synthesize lives.
5551 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005552 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005553 if (!Container ||
5554 (!isa<ObjCImplementationDecl>(Container) &&
5555 !isa<ObjCCategoryImplDecl>(Container)))
5556 return;
5557
5558 // Ignore any properties that have already been implemented.
5559 for (DeclContext::decl_iterator D = Container->decls_begin(),
5560 DEnd = Container->decls_end();
5561 D != DEnd; ++D)
5562 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5563 Results.Ignore(PropertyImpl->getPropertyDecl());
5564
5565 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005566 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005567 Results.EnterNewScope();
5568 if (ObjCImplementationDecl *ClassImpl
5569 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005570 AddObjCProperties(ClassImpl->getClassInterface(), false,
5571 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005572 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005573 else
5574 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005575 false, /*AllowNullaryMethods=*/false, CurContext,
5576 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005577 Results.ExitScope();
5578
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005579 HandleCodeCompleteResults(this, CodeCompleter,
5580 CodeCompletionContext::CCC_Other,
5581 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005582}
5583
5584void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005585 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005586 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005587 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5588 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005589
5590 // Figure out where this @synthesize lives.
5591 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005592 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005593 if (!Container ||
5594 (!isa<ObjCImplementationDecl>(Container) &&
5595 !isa<ObjCCategoryImplDecl>(Container)))
5596 return;
5597
5598 // Figure out which interface we're looking into.
5599 ObjCInterfaceDecl *Class = 0;
5600 if (ObjCImplementationDecl *ClassImpl
5601 = dyn_cast<ObjCImplementationDecl>(Container))
5602 Class = ClassImpl->getClassInterface();
5603 else
5604 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5605 ->getClassInterface();
5606
Douglas Gregore8426052011-04-18 14:40:46 +00005607 // Determine the type of the property we're synthesizing.
5608 QualType PropertyType = Context.getObjCIdType();
5609 if (Class) {
5610 if (ObjCPropertyDecl *Property
5611 = Class->FindPropertyDeclaration(PropertyName)) {
5612 PropertyType
5613 = Property->getType().getNonReferenceType().getUnqualifiedType();
5614
5615 // Give preference to ivars
5616 Results.setPreferredType(PropertyType);
5617 }
5618 }
5619
Douglas Gregor322328b2009-11-18 22:32:06 +00005620 // Add all of the instance variables in this class and its superclasses.
5621 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005622 bool SawSimilarlyNamedIvar = false;
5623 std::string NameWithPrefix;
5624 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005625 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005626 std::string NameWithSuffix = PropertyName->getName().str();
5627 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005628 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005629 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5630 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005631 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5632
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005633 // Determine whether we've seen an ivar with a name similar to the
5634 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005635 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005636 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005637 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005638 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005639
5640 // Reduce the priority of this result by one, to give it a slight
5641 // advantage over other results whose names don't match so closely.
5642 if (Results.size() &&
5643 Results.data()[Results.size() - 1].Kind
5644 == CodeCompletionResult::RK_Declaration &&
5645 Results.data()[Results.size() - 1].Declaration == Ivar)
5646 Results.data()[Results.size() - 1].Priority--;
5647 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005648 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005649 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005650
5651 if (!SawSimilarlyNamedIvar) {
5652 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005653 // an ivar of the appropriate type.
5654 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005655 typedef CodeCompletionResult Result;
5656 CodeCompletionAllocator &Allocator = Results.getAllocator();
5657 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5658
Douglas Gregore8426052011-04-18 14:40:46 +00005659 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
5660 Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005661 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5662 Results.AddResult(Result(Builder.TakeString(), Priority,
5663 CXCursor_ObjCIvarDecl));
5664 }
5665
Douglas Gregor322328b2009-11-18 22:32:06 +00005666 Results.ExitScope();
5667
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005668 HandleCodeCompleteResults(this, CodeCompleter,
5669 CodeCompletionContext::CCC_Other,
5670 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005671}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005672
Douglas Gregor408be5a2010-08-25 01:08:01 +00005673// Mapping from selectors to the methods that implement that selector, along
5674// with the "in original class" flag.
5675typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5676 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005677
5678/// \brief Find all of the methods that reside in the given container
5679/// (and its superclasses, protocols, etc.) that meet the given
5680/// criteria. Insert those methods into the map of known methods,
5681/// indexed by selector so they can be easily found.
5682static void FindImplementableMethods(ASTContext &Context,
5683 ObjCContainerDecl *Container,
5684 bool WantInstanceMethods,
5685 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005686 KnownMethodsMap &KnownMethods,
5687 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005688 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5689 // Recurse into protocols.
5690 const ObjCList<ObjCProtocolDecl> &Protocols
5691 = IFace->getReferencedProtocols();
5692 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005693 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005694 I != E; ++I)
5695 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005696 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005697
Douglas Gregorea766182010-10-18 18:21:28 +00005698 // Add methods from any class extensions and categories.
5699 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5700 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005701 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5702 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005703 KnownMethods, false);
5704
5705 // Visit the superclass.
5706 if (IFace->getSuperClass())
5707 FindImplementableMethods(Context, IFace->getSuperClass(),
5708 WantInstanceMethods, ReturnType,
5709 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005710 }
5711
5712 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5713 // Recurse into protocols.
5714 const ObjCList<ObjCProtocolDecl> &Protocols
5715 = Category->getReferencedProtocols();
5716 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005717 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005718 I != E; ++I)
5719 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005720 KnownMethods, InOriginalClass);
5721
5722 // If this category is the original class, jump to the interface.
5723 if (InOriginalClass && Category->getClassInterface())
5724 FindImplementableMethods(Context, Category->getClassInterface(),
5725 WantInstanceMethods, ReturnType, KnownMethods,
5726 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005727 }
5728
5729 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5730 // Recurse into protocols.
5731 const ObjCList<ObjCProtocolDecl> &Protocols
5732 = Protocol->getReferencedProtocols();
5733 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5734 E = Protocols.end();
5735 I != E; ++I)
5736 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005737 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005738 }
5739
5740 // Add methods in this container. This operation occurs last because
5741 // we want the methods from this container to override any methods
5742 // we've previously seen with the same selector.
5743 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5744 MEnd = Container->meth_end();
5745 M != MEnd; ++M) {
5746 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5747 if (!ReturnType.isNull() &&
5748 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5749 continue;
5750
Douglas Gregor408be5a2010-08-25 01:08:01 +00005751 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005752 }
5753 }
5754}
5755
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005756/// \brief Add the parenthesized return or parameter type chunk to a code
5757/// completion string.
5758static void AddObjCPassingTypeChunk(QualType Type,
5759 ASTContext &Context,
5760 CodeCompletionBuilder &Builder) {
5761 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5762 Builder.AddTextChunk(GetCompletionTypeString(Type, Context,
5763 Builder.getAllocator()));
5764 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5765}
5766
5767/// \brief Determine whether the given class is or inherits from a class by
5768/// the given name.
5769static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005770 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005771 if (!Class)
5772 return false;
5773
5774 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5775 return true;
5776
5777 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5778}
5779
5780/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5781/// Key-Value Observing (KVO).
5782static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5783 bool IsInstanceMethod,
5784 QualType ReturnType,
5785 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005786 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005787 ResultBuilder &Results) {
5788 IdentifierInfo *PropName = Property->getIdentifier();
5789 if (!PropName || PropName->getLength() == 0)
5790 return;
5791
5792
5793 // Builder that will create each code completion.
5794 typedef CodeCompletionResult Result;
5795 CodeCompletionAllocator &Allocator = Results.getAllocator();
5796 CodeCompletionBuilder Builder(Allocator);
5797
5798 // The selector table.
5799 SelectorTable &Selectors = Context.Selectors;
5800
5801 // The property name, copied into the code completion allocation region
5802 // on demand.
5803 struct KeyHolder {
5804 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005805 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005806 const char *CopiedKey;
5807
Chris Lattner5f9e2722011-07-23 10:55:15 +00005808 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005809 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5810
5811 operator const char *() {
5812 if (CopiedKey)
5813 return CopiedKey;
5814
5815 return CopiedKey = Allocator.CopyString(Key);
5816 }
5817 } Key(Allocator, PropName->getName());
5818
5819 // The uppercased name of the property name.
5820 std::string UpperKey = PropName->getName();
5821 if (!UpperKey.empty())
5822 UpperKey[0] = toupper(UpperKey[0]);
5823
5824 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5825 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5826 Property->getType());
5827 bool ReturnTypeMatchesVoid
5828 = ReturnType.isNull() || ReturnType->isVoidType();
5829
5830 // Add the normal accessor -(type)key.
5831 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005832 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005833 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5834 if (ReturnType.isNull())
5835 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5836
5837 Builder.AddTypedTextChunk(Key);
5838 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5839 CXCursor_ObjCInstanceMethodDecl));
5840 }
5841
5842 // If we have an integral or boolean property (or the user has provided
5843 // an integral or boolean return type), add the accessor -(type)isKey.
5844 if (IsInstanceMethod &&
5845 ((!ReturnType.isNull() &&
5846 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5847 (ReturnType.isNull() &&
5848 (Property->getType()->isIntegerType() ||
5849 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005850 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005851 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005852 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005853 if (ReturnType.isNull()) {
5854 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5855 Builder.AddTextChunk("BOOL");
5856 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5857 }
5858
5859 Builder.AddTypedTextChunk(
5860 Allocator.CopyString(SelectorId->getName()));
5861 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5862 CXCursor_ObjCInstanceMethodDecl));
5863 }
5864 }
5865
5866 // Add the normal mutator.
5867 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5868 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005869 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005870 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005871 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005872 if (ReturnType.isNull()) {
5873 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5874 Builder.AddTextChunk("void");
5875 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5876 }
5877
5878 Builder.AddTypedTextChunk(
5879 Allocator.CopyString(SelectorId->getName()));
5880 Builder.AddTypedTextChunk(":");
5881 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5882 Builder.AddTextChunk(Key);
5883 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5884 CXCursor_ObjCInstanceMethodDecl));
5885 }
5886 }
5887
5888 // Indexed and unordered accessors
5889 unsigned IndexedGetterPriority = CCP_CodePattern;
5890 unsigned IndexedSetterPriority = CCP_CodePattern;
5891 unsigned UnorderedGetterPriority = CCP_CodePattern;
5892 unsigned UnorderedSetterPriority = CCP_CodePattern;
5893 if (const ObjCObjectPointerType *ObjCPointer
5894 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5895 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5896 // If this interface type is not provably derived from a known
5897 // collection, penalize the corresponding completions.
5898 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5899 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5900 if (!InheritsFromClassNamed(IFace, "NSArray"))
5901 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5902 }
5903
5904 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5905 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5906 if (!InheritsFromClassNamed(IFace, "NSSet"))
5907 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5908 }
5909 }
5910 } else {
5911 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5912 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5913 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5914 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5915 }
5916
5917 // Add -(NSUInteger)countOf<key>
5918 if (IsInstanceMethod &&
5919 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005920 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005921 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005922 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005923 if (ReturnType.isNull()) {
5924 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5925 Builder.AddTextChunk("NSUInteger");
5926 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5927 }
5928
5929 Builder.AddTypedTextChunk(
5930 Allocator.CopyString(SelectorId->getName()));
5931 Results.AddResult(Result(Builder.TakeString(),
5932 std::min(IndexedGetterPriority,
5933 UnorderedGetterPriority),
5934 CXCursor_ObjCInstanceMethodDecl));
5935 }
5936 }
5937
5938 // Indexed getters
5939 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
5940 if (IsInstanceMethod &&
5941 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005942 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005943 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005944 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005945 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005946 if (ReturnType.isNull()) {
5947 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5948 Builder.AddTextChunk("id");
5949 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5950 }
5951
5952 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5953 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5954 Builder.AddTextChunk("NSUInteger");
5955 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5956 Builder.AddTextChunk("index");
5957 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5958 CXCursor_ObjCInstanceMethodDecl));
5959 }
5960 }
5961
5962 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
5963 if (IsInstanceMethod &&
5964 (ReturnType.isNull() ||
5965 (ReturnType->isObjCObjectPointerType() &&
5966 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
5967 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
5968 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005969 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005970 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005971 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005972 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005973 if (ReturnType.isNull()) {
5974 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5975 Builder.AddTextChunk("NSArray *");
5976 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5977 }
5978
5979 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5980 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5981 Builder.AddTextChunk("NSIndexSet *");
5982 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5983 Builder.AddTextChunk("indexes");
5984 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5985 CXCursor_ObjCInstanceMethodDecl));
5986 }
5987 }
5988
5989 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
5990 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005991 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005992 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005993 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005994 &Context.Idents.get("range")
5995 };
5996
Douglas Gregore74c25c2011-05-04 23:50:46 +00005997 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005998 if (ReturnType.isNull()) {
5999 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6000 Builder.AddTextChunk("void");
6001 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6002 }
6003
6004 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6005 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6006 Builder.AddPlaceholderChunk("object-type");
6007 Builder.AddTextChunk(" **");
6008 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6009 Builder.AddTextChunk("buffer");
6010 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6011 Builder.AddTypedTextChunk("range:");
6012 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6013 Builder.AddTextChunk("NSRange");
6014 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6015 Builder.AddTextChunk("inRange");
6016 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6017 CXCursor_ObjCInstanceMethodDecl));
6018 }
6019 }
6020
6021 // Mutable indexed accessors
6022
6023 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6024 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006025 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006026 IdentifierInfo *SelectorIds[2] = {
6027 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006028 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006029 };
6030
Douglas Gregore74c25c2011-05-04 23:50:46 +00006031 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006032 if (ReturnType.isNull()) {
6033 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6034 Builder.AddTextChunk("void");
6035 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6036 }
6037
6038 Builder.AddTypedTextChunk("insertObject:");
6039 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6040 Builder.AddPlaceholderChunk("object-type");
6041 Builder.AddTextChunk(" *");
6042 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6043 Builder.AddTextChunk("object");
6044 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6045 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6046 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6047 Builder.AddPlaceholderChunk("NSUInteger");
6048 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6049 Builder.AddTextChunk("index");
6050 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6051 CXCursor_ObjCInstanceMethodDecl));
6052 }
6053 }
6054
6055 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6056 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006057 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006058 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006059 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006060 &Context.Idents.get("atIndexes")
6061 };
6062
Douglas Gregore74c25c2011-05-04 23:50:46 +00006063 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006064 if (ReturnType.isNull()) {
6065 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6066 Builder.AddTextChunk("void");
6067 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6068 }
6069
6070 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6071 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6072 Builder.AddTextChunk("NSArray *");
6073 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6074 Builder.AddTextChunk("array");
6075 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6076 Builder.AddTypedTextChunk("atIndexes:");
6077 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6078 Builder.AddPlaceholderChunk("NSIndexSet *");
6079 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6080 Builder.AddTextChunk("indexes");
6081 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6082 CXCursor_ObjCInstanceMethodDecl));
6083 }
6084 }
6085
6086 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6087 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006088 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006089 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006090 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006091 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006092 if (ReturnType.isNull()) {
6093 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6094 Builder.AddTextChunk("void");
6095 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6096 }
6097
6098 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6099 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6100 Builder.AddTextChunk("NSUInteger");
6101 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6102 Builder.AddTextChunk("index");
6103 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6104 CXCursor_ObjCInstanceMethodDecl));
6105 }
6106 }
6107
6108 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6109 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006110 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006111 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006112 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006113 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006114 if (ReturnType.isNull()) {
6115 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6116 Builder.AddTextChunk("void");
6117 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6118 }
6119
6120 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6121 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6122 Builder.AddTextChunk("NSIndexSet *");
6123 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6124 Builder.AddTextChunk("indexes");
6125 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6126 CXCursor_ObjCInstanceMethodDecl));
6127 }
6128 }
6129
6130 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6131 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006132 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006133 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006134 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006135 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006136 &Context.Idents.get("withObject")
6137 };
6138
Douglas Gregore74c25c2011-05-04 23:50:46 +00006139 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006140 if (ReturnType.isNull()) {
6141 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6142 Builder.AddTextChunk("void");
6143 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6144 }
6145
6146 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6147 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6148 Builder.AddPlaceholderChunk("NSUInteger");
6149 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6150 Builder.AddTextChunk("index");
6151 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6152 Builder.AddTypedTextChunk("withObject:");
6153 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6154 Builder.AddTextChunk("id");
6155 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6156 Builder.AddTextChunk("object");
6157 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6158 CXCursor_ObjCInstanceMethodDecl));
6159 }
6160 }
6161
6162 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6163 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006164 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006165 = (Twine("replace") + UpperKey + "AtIndexes").str();
6166 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006167 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006168 &Context.Idents.get(SelectorName1),
6169 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006170 };
6171
Douglas Gregore74c25c2011-05-04 23:50:46 +00006172 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006173 if (ReturnType.isNull()) {
6174 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6175 Builder.AddTextChunk("void");
6176 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6177 }
6178
6179 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6180 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6181 Builder.AddPlaceholderChunk("NSIndexSet *");
6182 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6183 Builder.AddTextChunk("indexes");
6184 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6185 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6186 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6187 Builder.AddTextChunk("NSArray *");
6188 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6189 Builder.AddTextChunk("array");
6190 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6191 CXCursor_ObjCInstanceMethodDecl));
6192 }
6193 }
6194
6195 // Unordered getters
6196 // - (NSEnumerator *)enumeratorOfKey
6197 if (IsInstanceMethod &&
6198 (ReturnType.isNull() ||
6199 (ReturnType->isObjCObjectPointerType() &&
6200 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6201 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6202 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006203 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006204 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006205 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006206 if (ReturnType.isNull()) {
6207 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6208 Builder.AddTextChunk("NSEnumerator *");
6209 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6210 }
6211
6212 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6213 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6214 CXCursor_ObjCInstanceMethodDecl));
6215 }
6216 }
6217
6218 // - (type *)memberOfKey:(type *)object
6219 if (IsInstanceMethod &&
6220 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006221 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006222 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006223 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006224 if (ReturnType.isNull()) {
6225 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6226 Builder.AddPlaceholderChunk("object-type");
6227 Builder.AddTextChunk(" *");
6228 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6229 }
6230
6231 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6232 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6233 if (ReturnType.isNull()) {
6234 Builder.AddPlaceholderChunk("object-type");
6235 Builder.AddTextChunk(" *");
6236 } else {
6237 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
6238 Builder.getAllocator()));
6239 }
6240 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6241 Builder.AddTextChunk("object");
6242 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6243 CXCursor_ObjCInstanceMethodDecl));
6244 }
6245 }
6246
6247 // Mutable unordered accessors
6248 // - (void)addKeyObject:(type *)object
6249 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006250 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006251 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006252 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006253 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006254 if (ReturnType.isNull()) {
6255 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6256 Builder.AddTextChunk("void");
6257 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6258 }
6259
6260 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6261 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6262 Builder.AddPlaceholderChunk("object-type");
6263 Builder.AddTextChunk(" *");
6264 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6265 Builder.AddTextChunk("object");
6266 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6267 CXCursor_ObjCInstanceMethodDecl));
6268 }
6269 }
6270
6271 // - (void)addKey:(NSSet *)objects
6272 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006273 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006274 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006275 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006276 if (ReturnType.isNull()) {
6277 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6278 Builder.AddTextChunk("void");
6279 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6280 }
6281
6282 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6283 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6284 Builder.AddTextChunk("NSSet *");
6285 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6286 Builder.AddTextChunk("objects");
6287 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6288 CXCursor_ObjCInstanceMethodDecl));
6289 }
6290 }
6291
6292 // - (void)removeKeyObject:(type *)object
6293 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006294 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006295 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006296 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006297 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006298 if (ReturnType.isNull()) {
6299 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6300 Builder.AddTextChunk("void");
6301 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6302 }
6303
6304 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6305 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6306 Builder.AddPlaceholderChunk("object-type");
6307 Builder.AddTextChunk(" *");
6308 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6309 Builder.AddTextChunk("object");
6310 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6311 CXCursor_ObjCInstanceMethodDecl));
6312 }
6313 }
6314
6315 // - (void)removeKey:(NSSet *)objects
6316 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006317 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006318 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006319 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006320 if (ReturnType.isNull()) {
6321 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6322 Builder.AddTextChunk("void");
6323 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6324 }
6325
6326 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6327 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6328 Builder.AddTextChunk("NSSet *");
6329 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6330 Builder.AddTextChunk("objects");
6331 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6332 CXCursor_ObjCInstanceMethodDecl));
6333 }
6334 }
6335
6336 // - (void)intersectKey:(NSSet *)objects
6337 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006338 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006339 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006340 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006341 if (ReturnType.isNull()) {
6342 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6343 Builder.AddTextChunk("void");
6344 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6345 }
6346
6347 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6348 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6349 Builder.AddTextChunk("NSSet *");
6350 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6351 Builder.AddTextChunk("objects");
6352 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6353 CXCursor_ObjCInstanceMethodDecl));
6354 }
6355 }
6356
6357 // Key-Value Observing
6358 // + (NSSet *)keyPathsForValuesAffectingKey
6359 if (!IsInstanceMethod &&
6360 (ReturnType.isNull() ||
6361 (ReturnType->isObjCObjectPointerType() &&
6362 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6363 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6364 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006365 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006366 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006367 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006368 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006369 if (ReturnType.isNull()) {
6370 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6371 Builder.AddTextChunk("NSSet *");
6372 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6373 }
6374
6375 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6376 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006377 CXCursor_ObjCClassMethodDecl));
6378 }
6379 }
6380
6381 // + (BOOL)automaticallyNotifiesObserversForKey
6382 if (!IsInstanceMethod &&
6383 (ReturnType.isNull() ||
6384 ReturnType->isIntegerType() ||
6385 ReturnType->isBooleanType())) {
6386 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006387 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006388 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6389 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6390 if (ReturnType.isNull()) {
6391 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6392 Builder.AddTextChunk("BOOL");
6393 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6394 }
6395
6396 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6397 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6398 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006399 }
6400 }
6401}
6402
Douglas Gregore8f5a172010-04-07 00:21:17 +00006403void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6404 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006405 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006406 // Determine the return type of the method we're declaring, if
6407 // provided.
6408 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006409 Decl *IDecl = 0;
6410 if (CurContext->isObjCContainer()) {
6411 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6412 IDecl = cast<Decl>(OCD);
6413 }
Douglas Gregorea766182010-10-18 18:21:28 +00006414 // Determine where we should start searching for methods.
6415 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006416 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006417 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006418 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6419 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006420 IsInImplementation = true;
6421 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006422 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006423 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006424 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006425 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006426 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006427 }
6428
6429 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006430 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006431 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006432 }
6433
Douglas Gregorea766182010-10-18 18:21:28 +00006434 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006435 HandleCodeCompleteResults(this, CodeCompleter,
6436 CodeCompletionContext::CCC_Other,
6437 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006438 return;
6439 }
6440
6441 // Find all of the methods that we could declare/implement here.
6442 KnownMethodsMap KnownMethods;
6443 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006444 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006445
Douglas Gregore8f5a172010-04-07 00:21:17 +00006446 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006447 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006448 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6449 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006450 Results.EnterNewScope();
6451 PrintingPolicy Policy(Context.PrintingPolicy);
6452 Policy.AnonymousTagLocations = false;
John McCallf85e1932011-06-15 23:02:42 +00006453 Policy.SuppressStrongLifetime = true;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006454 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6455 MEnd = KnownMethods.end();
6456 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006457 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006458 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006459
6460 // If the result type was not already provided, add it to the
6461 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006462 if (ReturnType.isNull())
6463 AddObjCPassingTypeChunk(Method->getResultType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006464
6465 Selector Sel = Method->getSelector();
6466
6467 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006468 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006469 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006470
6471 // Add parameters to the pattern.
6472 unsigned I = 0;
6473 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6474 PEnd = Method->param_end();
6475 P != PEnd; (void)++P, ++I) {
6476 // Add the part of the selector name.
6477 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006478 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006479 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006480 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6481 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006482 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006483 } else
6484 break;
6485
6486 // Add the parameter type.
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006487 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006488
6489 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006490 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006491 }
6492
6493 if (Method->isVariadic()) {
6494 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006495 Builder.AddChunk(CodeCompletionString::CK_Comma);
6496 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006497 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006498
Douglas Gregor447107d2010-05-28 00:57:46 +00006499 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006500 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006501 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6502 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6503 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006504 if (!Method->getResultType()->isVoidType()) {
6505 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006506 Builder.AddTextChunk("return");
6507 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6508 Builder.AddPlaceholderChunk("expression");
6509 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006510 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006511 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006512
Douglas Gregor218937c2011-02-01 19:23:04 +00006513 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6514 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006515 }
6516
Douglas Gregor408be5a2010-08-25 01:08:01 +00006517 unsigned Priority = CCP_CodePattern;
6518 if (!M->second.second)
6519 Priority += CCD_InBaseClass;
6520
Douglas Gregor218937c2011-02-01 19:23:04 +00006521 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006522 Method->isInstanceMethod()
6523 ? CXCursor_ObjCInstanceMethodDecl
6524 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006525 }
6526
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006527 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6528 // the properties in this class and its categories.
6529 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006530 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006531 Containers.push_back(SearchDecl);
6532
Douglas Gregore74c25c2011-05-04 23:50:46 +00006533 VisitedSelectorSet KnownSelectors;
6534 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6535 MEnd = KnownMethods.end();
6536 M != MEnd; ++M)
6537 KnownSelectors.insert(M->first);
6538
6539
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006540 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6541 if (!IFace)
6542 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6543 IFace = Category->getClassInterface();
6544
6545 if (IFace) {
6546 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6547 Category = Category->getNextClassCategory())
6548 Containers.push_back(Category);
6549 }
6550
6551 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6552 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6553 PEnd = Containers[I]->prop_end();
6554 P != PEnd; ++P) {
6555 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006556 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006557 }
6558 }
6559 }
6560
Douglas Gregore8f5a172010-04-07 00:21:17 +00006561 Results.ExitScope();
6562
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006563 HandleCodeCompleteResults(this, CodeCompleter,
6564 CodeCompletionContext::CCC_Other,
6565 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006566}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006567
6568void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6569 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006570 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006571 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006572 IdentifierInfo **SelIdents,
6573 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006574 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006575 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006576 if (ExternalSource) {
6577 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6578 I != N; ++I) {
6579 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006580 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006581 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006582
6583 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006584 }
6585 }
6586
6587 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006588 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006589 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6590 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006591
6592 if (ReturnTy)
6593 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006594
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006595 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006596 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6597 MEnd = MethodPool.end();
6598 M != MEnd; ++M) {
6599 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6600 &M->second.second;
6601 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006602 MethList = MethList->Next) {
6603 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6604 NumSelIdents))
6605 continue;
6606
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006607 if (AtParameterName) {
6608 // Suggest parameter names we've seen before.
6609 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6610 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6611 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006612 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006613 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006614 Param->getIdentifier()->getName()));
6615 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006616 }
6617 }
6618
6619 continue;
6620 }
6621
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006622 Result R(MethList->Method, 0);
6623 R.StartParameter = NumSelIdents;
6624 R.AllParametersAreInformative = false;
6625 R.DeclaringEntity = true;
6626 Results.MaybeAddResult(R, CurContext);
6627 }
6628 }
6629
6630 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006631 HandleCodeCompleteResults(this, CodeCompleter,
6632 CodeCompletionContext::CCC_Other,
6633 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006634}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006635
Douglas Gregorf29c5232010-08-24 22:20:20 +00006636void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006637 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006638 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006639 Results.EnterNewScope();
6640
6641 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006642 CodeCompletionBuilder Builder(Results.getAllocator());
6643 Builder.AddTypedTextChunk("if");
6644 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6645 Builder.AddPlaceholderChunk("condition");
6646 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006647
6648 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006649 Builder.AddTypedTextChunk("ifdef");
6650 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6651 Builder.AddPlaceholderChunk("macro");
6652 Results.AddResult(Builder.TakeString());
6653
Douglas Gregorf44e8542010-08-24 19:08:16 +00006654 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006655 Builder.AddTypedTextChunk("ifndef");
6656 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6657 Builder.AddPlaceholderChunk("macro");
6658 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006659
6660 if (InConditional) {
6661 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006662 Builder.AddTypedTextChunk("elif");
6663 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6664 Builder.AddPlaceholderChunk("condition");
6665 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006666
6667 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006668 Builder.AddTypedTextChunk("else");
6669 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006670
6671 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006672 Builder.AddTypedTextChunk("endif");
6673 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006674 }
6675
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 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006685 Builder.AddTypedTextChunk("include");
6686 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6687 Builder.AddTextChunk("<");
6688 Builder.AddPlaceholderChunk("header");
6689 Builder.AddTextChunk(">");
6690 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006691
6692 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006693 Builder.AddTypedTextChunk("define");
6694 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6695 Builder.AddPlaceholderChunk("macro");
6696 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006697
6698 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006699 Builder.AddTypedTextChunk("define");
6700 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6701 Builder.AddPlaceholderChunk("macro");
6702 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6703 Builder.AddPlaceholderChunk("args");
6704 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6705 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006706
6707 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006708 Builder.AddTypedTextChunk("undef");
6709 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6710 Builder.AddPlaceholderChunk("macro");
6711 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006712
6713 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006714 Builder.AddTypedTextChunk("line");
6715 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6716 Builder.AddPlaceholderChunk("number");
6717 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006718
6719 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006720 Builder.AddTypedTextChunk("line");
6721 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6722 Builder.AddPlaceholderChunk("number");
6723 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6724 Builder.AddTextChunk("\"");
6725 Builder.AddPlaceholderChunk("filename");
6726 Builder.AddTextChunk("\"");
6727 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006728
6729 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006730 Builder.AddTypedTextChunk("error");
6731 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6732 Builder.AddPlaceholderChunk("message");
6733 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006734
6735 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006736 Builder.AddTypedTextChunk("pragma");
6737 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6738 Builder.AddPlaceholderChunk("arguments");
6739 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006740
6741 if (getLangOptions().ObjC1) {
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 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006751 Builder.AddTypedTextChunk("import");
6752 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6753 Builder.AddTextChunk("<");
6754 Builder.AddPlaceholderChunk("header");
6755 Builder.AddTextChunk(">");
6756 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006757 }
6758
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 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006768 Builder.AddTypedTextChunk("include_next");
6769 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6770 Builder.AddTextChunk("<");
6771 Builder.AddPlaceholderChunk("header");
6772 Builder.AddTextChunk(">");
6773 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006774
6775 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006776 Builder.AddTypedTextChunk("warning");
6777 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6778 Builder.AddPlaceholderChunk("message");
6779 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006780
6781 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6782 // completions for them. And __include_macros is a Clang-internal extension
6783 // that we don't want to encourage anyone to use.
6784
6785 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6786 Results.ExitScope();
6787
Douglas Gregorf44e8542010-08-24 19:08:16 +00006788 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006789 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006790 Results.data(), Results.size());
6791}
6792
6793void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006794 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006795 S->getFnParent()? Sema::PCC_RecoveryInFunction
6796 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006797}
6798
Douglas Gregorf29c5232010-08-24 22:20:20 +00006799void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006800 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006801 IsDefinition? CodeCompletionContext::CCC_MacroName
6802 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006803 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6804 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006805 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006806 Results.EnterNewScope();
6807 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6808 MEnd = PP.macro_end();
6809 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006810 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006811 M->first->getName()));
6812 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006813 }
6814 Results.ExitScope();
6815 } else if (IsDefinition) {
6816 // FIXME: Can we detect when the user just wrote an include guard above?
6817 }
6818
Douglas Gregor52779fb2010-09-23 23:01:17 +00006819 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006820 Results.data(), Results.size());
6821}
6822
Douglas Gregorf29c5232010-08-24 22:20:20 +00006823void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006824 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006825 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006826
6827 if (!CodeCompleter || CodeCompleter->includeMacros())
6828 AddMacroResults(PP, Results);
6829
6830 // defined (<macro>)
6831 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006832 CodeCompletionBuilder Builder(Results.getAllocator());
6833 Builder.AddTypedTextChunk("defined");
6834 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6835 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6836 Builder.AddPlaceholderChunk("macro");
6837 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6838 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006839 Results.ExitScope();
6840
6841 HandleCodeCompleteResults(this, CodeCompleter,
6842 CodeCompletionContext::CCC_PreprocessorExpression,
6843 Results.data(), Results.size());
6844}
6845
6846void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6847 IdentifierInfo *Macro,
6848 MacroInfo *MacroInfo,
6849 unsigned Argument) {
6850 // FIXME: In the future, we could provide "overload" results, much like we
6851 // do for function calls.
6852
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00006853 // Now just ignore this. There will be another code-completion callback
6854 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00006855}
6856
Douglas Gregor55817af2010-08-25 17:04:25 +00006857void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006858 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006859 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006860 0, 0);
6861}
6862
Douglas Gregordae68752011-02-01 22:57:45 +00006863void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006864 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006865 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006866 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6867 CodeCompletionDeclConsumer Consumer(Builder,
6868 Context.getTranslationUnitDecl());
6869 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6870 Consumer);
6871 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006872
6873 if (!CodeCompleter || CodeCompleter->includeMacros())
6874 AddMacroResults(PP, Builder);
6875
6876 Results.clear();
6877 Results.insert(Results.end(),
6878 Builder.data(), Builder.data() + Builder.size());
6879}