blob: 01e95174e2cd4e96b986600fbd5c6b908c5e1d16 [file] [log] [blame]
Douglas Gregor81b747b2009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
John McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
John McCall120d63c2010-08-24 20:38:10 +000015#include "clang/Sema/Overload.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000016#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregor719770d2010-04-06 17:30:22 +000017#include "clang/Sema/ExternalSemaSource.h"
John McCall5f1e0942010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000023#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
Douglas Gregord36adf52010-09-16 16:06:31 +000025#include "llvm/ADT/DenseSet.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000026#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000027#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000028#include "llvm/ADT/StringSwitch.h"
Douglas Gregor458433d2010-08-26 15:07:07 +000029#include "llvm/ADT/Twine.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000030#include <list>
31#include <map>
32#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000033
34using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000035using namespace sema;
Douglas Gregor81b747b2009-09-17 21:32:03 +000036
Douglas Gregor86d9a522009-09-21 16:56:56 +000037namespace {
38 /// \brief A container of code-completion results.
39 class ResultBuilder {
40 public:
41 /// \brief The type of a name-lookup filter, which can be provided to the
42 /// name-lookup routines to specify which declarations should be included in
43 /// the result set (when it returns true) and which declarations should be
44 /// filtered out (returns false).
45 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
46
John McCall0a2c5e22010-08-25 06:19:51 +000047 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +000048
49 private:
50 /// \brief The actual results we have found.
51 std::vector<Result> Results;
52
53 /// \brief A record of all of the declarations we have found and placed
54 /// into the result set, used to ensure that no declaration ever gets into
55 /// the result set twice.
56 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
57
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000058 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
59
60 /// \brief An entry in the shadow map, which is optimized to store
61 /// a single (declaration, index) mapping (the common case) but
62 /// can also store a list of (declaration, index) mappings.
63 class ShadowMapEntry {
Chris Lattner5f9e2722011-07-23 10:55:15 +000064 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000065
66 /// \brief Contains either the solitary NamedDecl * or a vector
67 /// of (declaration, index) pairs.
68 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
69
70 /// \brief When the entry contains a single declaration, this is
71 /// the index associated with that entry.
72 unsigned SingleDeclIndex;
73
74 public:
75 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
76
77 void Add(NamedDecl *ND, unsigned Index) {
78 if (DeclOrVector.isNull()) {
79 // 0 - > 1 elements: just set the single element information.
80 DeclOrVector = ND;
81 SingleDeclIndex = Index;
82 return;
83 }
84
85 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
86 // 1 -> 2 elements: create the vector of results and push in the
87 // existing declaration.
88 DeclIndexPairVector *Vec = new DeclIndexPairVector;
89 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
90 DeclOrVector = Vec;
91 }
92
93 // Add the new element to the end of the vector.
94 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
95 DeclIndexPair(ND, Index));
96 }
97
98 void Destroy() {
99 if (DeclIndexPairVector *Vec
100 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
101 delete Vec;
102 DeclOrVector = ((NamedDecl *)0);
103 }
104 }
105
106 // Iteration.
107 class iterator;
108 iterator begin() const;
109 iterator end() const;
110 };
111
Douglas Gregor86d9a522009-09-21 16:56:56 +0000112 /// \brief A mapping from declaration names to the declarations that have
113 /// this name within a particular scope and their index within the list of
114 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000115 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000116
117 /// \brief The semantic analysis object for which results are being
118 /// produced.
119 Sema &SemaRef;
Douglas Gregor218937c2011-02-01 19:23:04 +0000120
121 /// \brief The allocator used to allocate new code-completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000122 CodeCompletionAllocator &Allocator;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000123
124 /// \brief If non-NULL, a filter function used to remove any code-completion
125 /// results that are not desirable.
126 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000127
128 /// \brief Whether we should allow declarations as
129 /// nested-name-specifiers that would otherwise be filtered out.
130 bool AllowNestedNameSpecifiers;
131
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000132 /// \brief If set, the type that we would prefer our resulting value
133 /// declarations to have.
134 ///
135 /// Closely matching the preferred type gives a boost to a result's
136 /// priority.
137 CanQualType PreferredType;
138
Douglas Gregor86d9a522009-09-21 16:56:56 +0000139 /// \brief A list of shadow maps, which is used to model name hiding at
140 /// different levels of, e.g., the inheritance hierarchy.
141 std::list<ShadowMap> ShadowMaps;
142
Douglas Gregor3cdee122010-08-26 16:36:48 +0000143 /// \brief If we're potentially referring to a C++ member function, the set
144 /// of qualifiers applied to the object type.
145 Qualifiers ObjectTypeQualifiers;
146
147 /// \brief Whether the \p ObjectTypeQualifiers field is active.
148 bool HasObjectTypeQualifiers;
149
Douglas Gregor265f7492010-08-27 15:29:55 +0000150 /// \brief The selector that we prefer.
151 Selector PreferredSelector;
152
Douglas Gregorca45da02010-11-02 20:36:02 +0000153 /// \brief The completion context in which we are gathering results.
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000154 CodeCompletionContext CompletionContext;
155
Douglas Gregorca45da02010-11-02 20:36:02 +0000156 /// \brief If we are in an instance method definition, the @implementation
157 /// object.
158 ObjCImplementationDecl *ObjCImplementation;
159
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000160 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000161
Douglas Gregor6f942b22010-09-21 16:06:22 +0000162 void MaybeAddConstructorResults(Result R);
163
Douglas Gregor86d9a522009-09-21 16:56:56 +0000164 public:
Douglas Gregordae68752011-02-01 22:57:45 +0000165 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Douglas Gregor52779fb2010-09-23 23:01:17 +0000166 const CodeCompletionContext &CompletionContext,
167 LookupFilter Filter = 0)
Douglas Gregor218937c2011-02-01 19:23:04 +0000168 : SemaRef(SemaRef), Allocator(Allocator), Filter(Filter),
169 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregorca45da02010-11-02 20:36:02 +0000170 CompletionContext(CompletionContext),
171 ObjCImplementation(0)
172 {
173 // If this is an Objective-C instance method definition, dig out the
174 // corresponding implementation.
175 switch (CompletionContext.getKind()) {
176 case CodeCompletionContext::CCC_Expression:
177 case CodeCompletionContext::CCC_ObjCMessageReceiver:
178 case CodeCompletionContext::CCC_ParenthesizedExpression:
179 case CodeCompletionContext::CCC_Statement:
180 case CodeCompletionContext::CCC_Recovery:
181 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
182 if (Method->isInstanceMethod())
183 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
184 ObjCImplementation = Interface->getImplementation();
185 break;
186
187 default:
188 break;
189 }
190 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000191
Douglas Gregord8e8a582010-05-25 21:41:55 +0000192 /// \brief Whether we should include code patterns in the completion
193 /// results.
194 bool includeCodePatterns() const {
195 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000196 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000197 }
198
Douglas Gregor86d9a522009-09-21 16:56:56 +0000199 /// \brief Set the filter used for code-completion results.
200 void setFilter(LookupFilter Filter) {
201 this->Filter = Filter;
202 }
203
Douglas Gregor86d9a522009-09-21 16:56:56 +0000204 Result *data() { return Results.empty()? 0 : &Results.front(); }
205 unsigned size() const { return Results.size(); }
206 bool empty() const { return Results.empty(); }
207
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000208 /// \brief Specify the preferred type.
209 void setPreferredType(QualType T) {
210 PreferredType = SemaRef.Context.getCanonicalType(T);
211 }
212
Douglas Gregor3cdee122010-08-26 16:36:48 +0000213 /// \brief Set the cv-qualifiers on the object type, for us in filtering
214 /// calls to member functions.
215 ///
216 /// When there are qualifiers in this set, they will be used to filter
217 /// out member functions that aren't available (because there will be a
218 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
219 /// match.
220 void setObjectTypeQualifiers(Qualifiers Quals) {
221 ObjectTypeQualifiers = Quals;
222 HasObjectTypeQualifiers = true;
223 }
224
Douglas Gregor265f7492010-08-27 15:29:55 +0000225 /// \brief Set the preferred selector.
226 ///
227 /// When an Objective-C method declaration result is added, and that
228 /// method's selector matches this preferred selector, we give that method
229 /// a slight priority boost.
230 void setPreferredSelector(Selector Sel) {
231 PreferredSelector = Sel;
232 }
Douglas Gregorca45da02010-11-02 20:36:02 +0000233
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000234 /// \brief Retrieve the code-completion context for which results are
235 /// being collected.
236 const CodeCompletionContext &getCompletionContext() const {
237 return CompletionContext;
238 }
239
Douglas Gregor45bcd432010-01-14 03:21:49 +0000240 /// \brief Specify whether nested-name-specifiers are allowed.
241 void allowNestedNameSpecifiers(bool Allow = true) {
242 AllowNestedNameSpecifiers = Allow;
243 }
244
Douglas Gregorb9d77572010-09-21 00:03:25 +0000245 /// \brief Return the semantic analysis object for which we are collecting
246 /// code completion results.
247 Sema &getSema() const { return SemaRef; }
248
Douglas Gregor218937c2011-02-01 19:23:04 +0000249 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000250 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Douglas Gregor218937c2011-02-01 19:23:04 +0000251
Douglas Gregore495b7f2010-01-14 00:20:49 +0000252 /// \brief Determine whether the given declaration is at all interesting
253 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000254 ///
255 /// \param ND the declaration that we are inspecting.
256 ///
257 /// \param AsNestedNameSpecifier will be set true if this declaration is
258 /// only interesting when it is a nested-name-specifier.
259 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000260
261 /// \brief Check whether the result is hidden by the Hiding declaration.
262 ///
263 /// \returns true if the result is hidden and cannot be found, false if
264 /// the hidden result could still be found. When false, \p R may be
265 /// modified to describe how the result can be found (e.g., via extra
266 /// qualification).
267 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
268 NamedDecl *Hiding);
269
Douglas Gregor86d9a522009-09-21 16:56:56 +0000270 /// \brief Add a new result to this result set (if it isn't already in one
271 /// of the shadow maps), or replace an existing result (for, e.g., a
272 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000273 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000274 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000275 ///
276 /// \param R the context in which this result will be named.
277 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000278
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000279 /// \brief Add a new result to this result set, where we already know
280 /// the hiding declation (if any).
281 ///
282 /// \param R the result to add (if it is unique).
283 ///
284 /// \param CurContext the context in which this result will be named.
285 ///
286 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000287 ///
288 /// \param InBaseClass whether the result was found in a base
289 /// class of the searched context.
290 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
291 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000292
Douglas Gregora4477812010-01-14 16:01:26 +0000293 /// \brief Add a new non-declaration result to this result set.
294 void AddResult(Result R);
295
Douglas Gregor86d9a522009-09-21 16:56:56 +0000296 /// \brief Enter into a new scope.
297 void EnterNewScope();
298
299 /// \brief Exit from the current scope.
300 void ExitScope();
301
Douglas Gregor55385fe2009-11-18 04:19:12 +0000302 /// \brief Ignore this declaration, if it is seen again.
303 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
304
Douglas Gregor86d9a522009-09-21 16:56:56 +0000305 /// \name Name lookup predicates
306 ///
307 /// These predicates can be passed to the name lookup functions to filter the
308 /// results of name lookup. All of the predicates have the same type, so that
309 ///
310 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000311 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000312 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000313 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000314 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000315 bool IsNestedNameSpecifier(NamedDecl *ND) const;
316 bool IsEnum(NamedDecl *ND) const;
317 bool IsClassOrStruct(NamedDecl *ND) const;
318 bool IsUnion(NamedDecl *ND) const;
319 bool IsNamespace(NamedDecl *ND) const;
320 bool IsNamespaceOrAlias(NamedDecl *ND) const;
321 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000322 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000323 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000324 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000325 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000326 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000327 //@}
328 };
329}
330
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000331class ResultBuilder::ShadowMapEntry::iterator {
332 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
333 unsigned SingleDeclIndex;
334
335public:
336 typedef DeclIndexPair value_type;
337 typedef value_type reference;
338 typedef std::ptrdiff_t difference_type;
339 typedef std::input_iterator_tag iterator_category;
340
341 class pointer {
342 DeclIndexPair Value;
343
344 public:
345 pointer(const DeclIndexPair &Value) : Value(Value) { }
346
347 const DeclIndexPair *operator->() const {
348 return &Value;
349 }
350 };
351
352 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
353
354 iterator(NamedDecl *SingleDecl, unsigned Index)
355 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
356
357 iterator(const DeclIndexPair *Iterator)
358 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
359
360 iterator &operator++() {
361 if (DeclOrIterator.is<NamedDecl *>()) {
362 DeclOrIterator = (NamedDecl *)0;
363 SingleDeclIndex = 0;
364 return *this;
365 }
366
367 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
368 ++I;
369 DeclOrIterator = I;
370 return *this;
371 }
372
Chris Lattner66392d42010-09-04 18:12:20 +0000373 /*iterator operator++(int) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000374 iterator tmp(*this);
375 ++(*this);
376 return tmp;
Chris Lattner66392d42010-09-04 18:12:20 +0000377 }*/
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000378
379 reference operator*() const {
380 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
381 return reference(ND, SingleDeclIndex);
382
Douglas Gregord490f952009-12-06 21:27:58 +0000383 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000384 }
385
386 pointer operator->() const {
387 return pointer(**this);
388 }
389
390 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000391 return X.DeclOrIterator.getOpaqueValue()
392 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000393 X.SingleDeclIndex == Y.SingleDeclIndex;
394 }
395
396 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000397 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000398 }
399};
400
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000401ResultBuilder::ShadowMapEntry::iterator
402ResultBuilder::ShadowMapEntry::begin() const {
403 if (DeclOrVector.isNull())
404 return iterator();
405
406 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
407 return iterator(ND, SingleDeclIndex);
408
409 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
410}
411
412ResultBuilder::ShadowMapEntry::iterator
413ResultBuilder::ShadowMapEntry::end() const {
414 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
415 return iterator();
416
417 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
418}
419
Douglas Gregor456c4a12009-09-21 20:12:40 +0000420/// \brief Compute the qualification required to get from the current context
421/// (\p CurContext) to the target context (\p TargetContext).
422///
423/// \param Context the AST context in which the qualification will be used.
424///
425/// \param CurContext the context where an entity is being named, which is
426/// typically based on the current scope.
427///
428/// \param TargetContext the context in which the named entity actually
429/// resides.
430///
431/// \returns a nested name specifier that refers into the target context, or
432/// NULL if no qualification is needed.
433static NestedNameSpecifier *
434getRequiredQualification(ASTContext &Context,
435 DeclContext *CurContext,
436 DeclContext *TargetContext) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000437 SmallVector<DeclContext *, 4> TargetParents;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000438
439 for (DeclContext *CommonAncestor = TargetContext;
440 CommonAncestor && !CommonAncestor->Encloses(CurContext);
441 CommonAncestor = CommonAncestor->getLookupParent()) {
442 if (CommonAncestor->isTransparentContext() ||
443 CommonAncestor->isFunctionOrMethod())
444 continue;
445
446 TargetParents.push_back(CommonAncestor);
447 }
448
449 NestedNameSpecifier *Result = 0;
450 while (!TargetParents.empty()) {
451 DeclContext *Parent = TargetParents.back();
452 TargetParents.pop_back();
453
Douglas Gregorfb629412010-08-23 21:17:50 +0000454 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
455 if (!Namespace->getIdentifier())
456 continue;
457
Douglas Gregor456c4a12009-09-21 20:12:40 +0000458 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000459 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000460 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
461 Result = NestedNameSpecifier::Create(Context, Result,
462 false,
463 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000464 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000465 return Result;
466}
467
Douglas Gregor45bcd432010-01-14 03:21:49 +0000468bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
469 bool &AsNestedNameSpecifier) const {
470 AsNestedNameSpecifier = false;
471
Douglas Gregore495b7f2010-01-14 00:20:49 +0000472 ND = ND->getUnderlyingDecl();
473 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000474
475 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000476 if (!ND->getDeclName())
477 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000478
479 // Friend declarations and declarations introduced due to friends are never
480 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000481 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000482 return false;
483
Douglas Gregor76282942009-12-11 17:31:05 +0000484 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000485 if (isa<ClassTemplateSpecializationDecl>(ND) ||
486 isa<ClassTemplatePartialSpecializationDecl>(ND))
487 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000488
Douglas Gregor76282942009-12-11 17:31:05 +0000489 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000490 if (isa<UsingDecl>(ND))
491 return false;
492
493 // Some declarations have reserved names that we don't want to ever show.
494 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000495 // __va_list_tag is a freak of nature. Find it and skip it.
496 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000497 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000498
Douglas Gregorf52cede2009-10-09 22:16:47 +0000499 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000500 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000501 //
502 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000503 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000504 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000505 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000506 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
507 (ND->getLocation().isInvalid() ||
508 SemaRef.SourceMgr.isInSystemHeader(
509 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000510 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000511 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000512 }
Douglas Gregor6f942b22010-09-21 16:06:22 +0000513
Douglas Gregor9b0ba872010-11-09 03:59:40 +0000514 // Skip out-of-line declarations and definitions.
515 // NOTE: Unless it's an Objective-C property, method, or ivar, where
516 // the contexts can be messy.
517 if (!ND->getDeclContext()->Equals(ND->getLexicalDeclContext()) &&
518 !(isa<ObjCPropertyDecl>(ND) || isa<ObjCIvarDecl>(ND) ||
519 isa<ObjCMethodDecl>(ND)))
520 return false;
521
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000522 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
523 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
524 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor52779fb2010-09-23 23:01:17 +0000525 Filter != &ResultBuilder::IsNamespaceOrAlias &&
526 Filter != 0))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000527 AsNestedNameSpecifier = true;
528
Douglas Gregor86d9a522009-09-21 16:56:56 +0000529 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000530 if (Filter && !(this->*Filter)(ND)) {
531 // Check whether it is interesting as a nested-name-specifier.
532 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
533 IsNestedNameSpecifier(ND) &&
534 (Filter != &ResultBuilder::IsMember ||
535 (isa<CXXRecordDecl>(ND) &&
536 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
537 AsNestedNameSpecifier = true;
538 return true;
539 }
540
Douglas Gregore495b7f2010-01-14 00:20:49 +0000541 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000542 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000543 // ... then it must be interesting!
544 return true;
545}
546
Douglas Gregor6660d842010-01-14 00:41:07 +0000547bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
548 NamedDecl *Hiding) {
549 // In C, there is no way to refer to a hidden name.
550 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
551 // name if we introduce the tag type.
552 if (!SemaRef.getLangOptions().CPlusPlus)
553 return true;
554
Sebastian Redl7a126a42010-08-31 00:36:30 +0000555 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregor6660d842010-01-14 00:41:07 +0000556
557 // There is no way to qualify a name declared in a function or method.
558 if (HiddenCtx->isFunctionOrMethod())
559 return true;
560
Sebastian Redl7a126a42010-08-31 00:36:30 +0000561 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregor6660d842010-01-14 00:41:07 +0000562 return true;
563
564 // We can refer to the result with the appropriate qualification. Do it.
565 R.Hidden = true;
566 R.QualifierIsInformative = false;
567
568 if (!R.Qualifier)
569 R.Qualifier = getRequiredQualification(SemaRef.Context,
570 CurContext,
571 R.Declaration->getDeclContext());
572 return false;
573}
574
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000575/// \brief A simplified classification of types used to determine whether two
576/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000577SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000578 switch (T->getTypeClass()) {
579 case Type::Builtin:
580 switch (cast<BuiltinType>(T)->getKind()) {
581 case BuiltinType::Void:
582 return STC_Void;
583
584 case BuiltinType::NullPtr:
585 return STC_Pointer;
586
587 case BuiltinType::Overload:
588 case BuiltinType::Dependent:
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000589 return STC_Other;
590
591 case BuiltinType::ObjCId:
592 case BuiltinType::ObjCClass:
593 case BuiltinType::ObjCSel:
594 return STC_ObjectiveC;
595
596 default:
597 return STC_Arithmetic;
598 }
599 return STC_Other;
600
601 case Type::Complex:
602 return STC_Arithmetic;
603
604 case Type::Pointer:
605 return STC_Pointer;
606
607 case Type::BlockPointer:
608 return STC_Block;
609
610 case Type::LValueReference:
611 case Type::RValueReference:
612 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
613
614 case Type::ConstantArray:
615 case Type::IncompleteArray:
616 case Type::VariableArray:
617 case Type::DependentSizedArray:
618 return STC_Array;
619
620 case Type::DependentSizedExtVector:
621 case Type::Vector:
622 case Type::ExtVector:
623 return STC_Arithmetic;
624
625 case Type::FunctionProto:
626 case Type::FunctionNoProto:
627 return STC_Function;
628
629 case Type::Record:
630 return STC_Record;
631
632 case Type::Enum:
633 return STC_Arithmetic;
634
635 case Type::ObjCObject:
636 case Type::ObjCInterface:
637 case Type::ObjCObjectPointer:
638 return STC_ObjectiveC;
639
640 default:
641 return STC_Other;
642 }
643}
644
645/// \brief Get the type that a given expression will have if this declaration
646/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000647QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000648 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
649
650 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
651 return C.getTypeDeclType(Type);
652 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
653 return C.getObjCInterfaceType(Iface);
654
655 QualType T;
656 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000657 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000658 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000659 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000660 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000661 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000662 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
663 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
664 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
665 T = Property->getType();
666 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
667 T = Value->getType();
668 else
669 return QualType();
Douglas Gregor3e64d562011-04-14 20:33:34 +0000670
671 // Dig through references, function pointers, and block pointers to
672 // get down to the likely type of an expression when the entity is
673 // used.
674 do {
675 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
676 T = Ref->getPointeeType();
677 continue;
678 }
679
680 if (const PointerType *Pointer = T->getAs<PointerType>()) {
681 if (Pointer->getPointeeType()->isFunctionType()) {
682 T = Pointer->getPointeeType();
683 continue;
684 }
685
686 break;
687 }
688
689 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
690 T = Block->getPointeeType();
691 continue;
692 }
693
694 if (const FunctionType *Function = T->getAs<FunctionType>()) {
695 T = Function->getResultType();
696 continue;
697 }
698
699 break;
700 } while (true);
701
702 return T;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000703}
704
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000705void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
706 // If this is an Objective-C method declaration whose selector matches our
707 // preferred selector, give it a priority boost.
708 if (!PreferredSelector.isNull())
709 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
710 if (PreferredSelector == Method->getSelector())
711 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000712
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000713 // If we have a preferred type, adjust the priority for results with exactly-
714 // matching or nearly-matching types.
715 if (!PreferredType.isNull()) {
716 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
717 if (!T.isNull()) {
718 CanQualType TC = SemaRef.Context.getCanonicalType(T);
719 // Check for exactly-matching types (modulo qualifiers).
720 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
721 R.Priority /= CCF_ExactTypeMatch;
722 // Check for nearly-matching types, based on classification of each.
723 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000724 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000725 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
726 R.Priority /= CCF_SimilarTypeMatch;
727 }
728 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000729}
730
Douglas Gregor6f942b22010-09-21 16:06:22 +0000731void ResultBuilder::MaybeAddConstructorResults(Result R) {
732 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
733 !CompletionContext.wantConstructorResults())
734 return;
735
736 ASTContext &Context = SemaRef.Context;
737 NamedDecl *D = R.Declaration;
738 CXXRecordDecl *Record = 0;
739 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
740 Record = ClassTemplate->getTemplatedDecl();
741 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
742 // Skip specializations and partial specializations.
743 if (isa<ClassTemplateSpecializationDecl>(Record))
744 return;
745 } else {
746 // There are no constructors here.
747 return;
748 }
749
750 Record = Record->getDefinition();
751 if (!Record)
752 return;
753
754
755 QualType RecordTy = Context.getTypeDeclType(Record);
756 DeclarationName ConstructorName
757 = Context.DeclarationNames.getCXXConstructorName(
758 Context.getCanonicalType(RecordTy));
759 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
760 Ctors.first != Ctors.second; ++Ctors.first) {
761 R.Declaration = *Ctors.first;
762 R.CursorKind = getCursorKindForDecl(R.Declaration);
763 Results.push_back(R);
764 }
765}
766
Douglas Gregore495b7f2010-01-14 00:20:49 +0000767void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
768 assert(!ShadowMaps.empty() && "Must enter into a results scope");
769
770 if (R.Kind != Result::RK_Declaration) {
771 // For non-declaration results, just add the result.
772 Results.push_back(R);
773 return;
774 }
775
776 // Look through using declarations.
777 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
778 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
779 return;
780 }
781
782 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
783 unsigned IDNS = CanonDecl->getIdentifierNamespace();
784
Douglas Gregor45bcd432010-01-14 03:21:49 +0000785 bool AsNestedNameSpecifier = false;
786 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000787 return;
788
Douglas Gregor6f942b22010-09-21 16:06:22 +0000789 // C++ constructors are never found by name lookup.
790 if (isa<CXXConstructorDecl>(R.Declaration))
791 return;
792
Douglas Gregor86d9a522009-09-21 16:56:56 +0000793 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000794 ShadowMapEntry::iterator I, IEnd;
795 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
796 if (NamePos != SMap.end()) {
797 I = NamePos->second.begin();
798 IEnd = NamePos->second.end();
799 }
800
801 for (; I != IEnd; ++I) {
802 NamedDecl *ND = I->first;
803 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000804 if (ND->getCanonicalDecl() == CanonDecl) {
805 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000806 Results[Index].Declaration = R.Declaration;
807
Douglas Gregor86d9a522009-09-21 16:56:56 +0000808 // We're done.
809 return;
810 }
811 }
812
813 // This is a new declaration in this scope. However, check whether this
814 // declaration name is hidden by a similarly-named declaration in an outer
815 // scope.
816 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
817 --SMEnd;
818 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000819 ShadowMapEntry::iterator I, IEnd;
820 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
821 if (NamePos != SM->end()) {
822 I = NamePos->second.begin();
823 IEnd = NamePos->second.end();
824 }
825 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000826 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000827 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000828 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
829 Decl::IDNS_ObjCProtocol)))
830 continue;
831
832 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000833 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000834 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000835 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000836 continue;
837
838 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000839 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000840 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000841
842 break;
843 }
844 }
845
846 // Make sure that any given declaration only shows up in the result set once.
847 if (!AllDeclsFound.insert(CanonDecl))
848 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000849
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000850 // If the filter is for nested-name-specifiers, then this result starts a
851 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000852 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000853 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000854 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000855 } else
856 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000857
Douglas Gregor0563c262009-09-22 23:15:58 +0000858 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000859 if (R.QualifierIsInformative && !R.Qualifier &&
860 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000861 DeclContext *Ctx = R.Declaration->getDeclContext();
862 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
863 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
864 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
865 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
866 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
867 else
868 R.QualifierIsInformative = false;
869 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000870
Douglas Gregor86d9a522009-09-21 16:56:56 +0000871 // Insert this result into the set of results and into the current shadow
872 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000873 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000874 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000875
876 if (!AsNestedNameSpecifier)
877 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000878}
879
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000880void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000881 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000882 if (R.Kind != Result::RK_Declaration) {
883 // For non-declaration results, just add the result.
884 Results.push_back(R);
885 return;
886 }
887
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000888 // Look through using declarations.
889 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
890 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
891 return;
892 }
893
Douglas Gregor45bcd432010-01-14 03:21:49 +0000894 bool AsNestedNameSpecifier = false;
895 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000896 return;
897
Douglas Gregor6f942b22010-09-21 16:06:22 +0000898 // C++ constructors are never found by name lookup.
899 if (isa<CXXConstructorDecl>(R.Declaration))
900 return;
901
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000902 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
903 return;
904
905 // Make sure that any given declaration only shows up in the result set once.
906 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
907 return;
908
909 // If the filter is for nested-name-specifiers, then this result starts a
910 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000911 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000912 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000913 R.Priority = CCP_NestedNameSpecifier;
914 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000915 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
916 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000917 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000918 R.QualifierIsInformative = true;
919
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000920 // If this result is supposed to have an informative qualifier, add one.
921 if (R.QualifierIsInformative && !R.Qualifier &&
922 !R.StartsNestedNameSpecifier) {
923 DeclContext *Ctx = R.Declaration->getDeclContext();
924 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
925 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
926 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
927 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000928 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000929 else
930 R.QualifierIsInformative = false;
931 }
932
Douglas Gregor12e13132010-05-26 22:00:08 +0000933 // Adjust the priority if this result comes from a base class.
934 if (InBaseClass)
935 R.Priority += CCD_InBaseClass;
936
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000937 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000938
Douglas Gregor3cdee122010-08-26 16:36:48 +0000939 if (HasObjectTypeQualifiers)
940 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
941 if (Method->isInstance()) {
942 Qualifiers MethodQuals
943 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
944 if (ObjectTypeQualifiers == MethodQuals)
945 R.Priority += CCD_ObjectQualifierMatch;
946 else if (ObjectTypeQualifiers - MethodQuals) {
947 // The method cannot be invoked, because doing so would drop
948 // qualifiers.
949 return;
950 }
951 }
952
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000953 // Insert this result into the set of results.
954 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000955
956 if (!AsNestedNameSpecifier)
957 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000958}
959
Douglas Gregora4477812010-01-14 16:01:26 +0000960void ResultBuilder::AddResult(Result R) {
961 assert(R.Kind != Result::RK_Declaration &&
962 "Declaration results need more context");
963 Results.push_back(R);
964}
965
Douglas Gregor86d9a522009-09-21 16:56:56 +0000966/// \brief Enter into a new scope.
967void ResultBuilder::EnterNewScope() {
968 ShadowMaps.push_back(ShadowMap());
969}
970
971/// \brief Exit from the current scope.
972void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000973 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
974 EEnd = ShadowMaps.back().end();
975 E != EEnd;
976 ++E)
977 E->second.Destroy();
978
Douglas Gregor86d9a522009-09-21 16:56:56 +0000979 ShadowMaps.pop_back();
980}
981
Douglas Gregor791215b2009-09-21 20:51:25 +0000982/// \brief Determines whether this given declaration will be found by
983/// ordinary name lookup.
984bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000985 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
986
Douglas Gregor791215b2009-09-21 20:51:25 +0000987 unsigned IDNS = Decl::IDNS_Ordinary;
988 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000989 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000990 else if (SemaRef.getLangOptions().ObjC1) {
991 if (isa<ObjCIvarDecl>(ND))
992 return true;
993 if (isa<ObjCPropertyDecl>(ND) &&
994 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
995 return true;
996 }
997
Douglas Gregor791215b2009-09-21 20:51:25 +0000998 return ND->getIdentifierNamespace() & IDNS;
999}
1000
Douglas Gregor01dfea02010-01-10 23:08:15 +00001001/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001002/// ordinary name lookup but is not a type name.
1003bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
1004 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1005 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1006 return false;
1007
1008 unsigned IDNS = Decl::IDNS_Ordinary;
1009 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +00001010 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +00001011 else if (SemaRef.getLangOptions().ObjC1) {
1012 if (isa<ObjCIvarDecl>(ND))
1013 return true;
1014 if (isa<ObjCPropertyDecl>(ND) &&
1015 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
1016 return true;
1017 }
1018
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001019 return ND->getIdentifierNamespace() & IDNS;
1020}
1021
Douglas Gregorf9578432010-07-28 21:50:18 +00001022bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
1023 if (!IsOrdinaryNonTypeName(ND))
1024 return 0;
1025
1026 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1027 if (VD->getType()->isIntegralOrEnumerationType())
1028 return true;
1029
1030 return false;
1031}
1032
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001033/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +00001034/// ordinary name lookup.
1035bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001036 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1037
Douglas Gregor01dfea02010-01-10 23:08:15 +00001038 unsigned IDNS = Decl::IDNS_Ordinary;
1039 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +00001040 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001041
1042 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001043 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1044 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001045}
1046
Douglas Gregor86d9a522009-09-21 16:56:56 +00001047/// \brief Determines whether the given declaration is suitable as the
1048/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1049bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1050 // Allow us to find class templates, too.
1051 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1052 ND = ClassTemplate->getTemplatedDecl();
1053
1054 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1055}
1056
1057/// \brief Determines whether the given declaration is an enumeration.
1058bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1059 return isa<EnumDecl>(ND);
1060}
1061
1062/// \brief Determines whether the given declaration is a class or struct.
1063bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1064 // Allow us to find class templates, too.
1065 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1066 ND = ClassTemplate->getTemplatedDecl();
1067
1068 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001069 return RD->getTagKind() == TTK_Class ||
1070 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001071
1072 return false;
1073}
1074
1075/// \brief Determines whether the given declaration is a union.
1076bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1077 // Allow us to find class templates, too.
1078 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1079 ND = ClassTemplate->getTemplatedDecl();
1080
1081 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001082 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001083
1084 return false;
1085}
1086
1087/// \brief Determines whether the given declaration is a namespace.
1088bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1089 return isa<NamespaceDecl>(ND);
1090}
1091
1092/// \brief Determines whether the given declaration is a namespace or
1093/// namespace alias.
1094bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1095 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1096}
1097
Douglas Gregor76282942009-12-11 17:31:05 +00001098/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001099bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001100 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1101 ND = Using->getTargetDecl();
1102
1103 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001104}
1105
Douglas Gregor76282942009-12-11 17:31:05 +00001106/// \brief Determines which members of a class should be visible via
1107/// "." or "->". Only value declarations, nested name specifiers, and
1108/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001109bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001110 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1111 ND = Using->getTargetDecl();
1112
Douglas Gregorce821962009-12-11 18:14:22 +00001113 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1114 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001115}
1116
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001117static bool isObjCReceiverType(ASTContext &C, QualType T) {
1118 T = C.getCanonicalType(T);
1119 switch (T->getTypeClass()) {
1120 case Type::ObjCObject:
1121 case Type::ObjCInterface:
1122 case Type::ObjCObjectPointer:
1123 return true;
1124
1125 case Type::Builtin:
1126 switch (cast<BuiltinType>(T)->getKind()) {
1127 case BuiltinType::ObjCId:
1128 case BuiltinType::ObjCClass:
1129 case BuiltinType::ObjCSel:
1130 return true;
1131
1132 default:
1133 break;
1134 }
1135 return false;
1136
1137 default:
1138 break;
1139 }
1140
1141 if (!C.getLangOptions().CPlusPlus)
1142 return false;
1143
1144 // FIXME: We could perform more analysis here to determine whether a
1145 // particular class type has any conversions to Objective-C types. For now,
1146 // just accept all class types.
1147 return T->isDependentType() || T->isRecordType();
1148}
1149
1150bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1151 QualType T = getDeclUsageType(SemaRef.Context, ND);
1152 if (T.isNull())
1153 return false;
1154
1155 T = SemaRef.Context.getBaseElementType(T);
1156 return isObjCReceiverType(SemaRef.Context, T);
1157}
1158
Douglas Gregorfb629412010-08-23 21:17:50 +00001159bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1160 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1161 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1162 return false;
1163
1164 QualType T = getDeclUsageType(SemaRef.Context, ND);
1165 if (T.isNull())
1166 return false;
1167
1168 T = SemaRef.Context.getBaseElementType(T);
1169 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1170 T->isObjCIdType() ||
1171 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1172}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001173
Douglas Gregor52779fb2010-09-23 23:01:17 +00001174bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1175 return false;
1176}
1177
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001178/// \rief Determines whether the given declaration is an Objective-C
1179/// instance variable.
1180bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1181 return isa<ObjCIvarDecl>(ND);
1182}
1183
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001184namespace {
1185 /// \brief Visible declaration consumer that adds a code-completion result
1186 /// for each visible declaration.
1187 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1188 ResultBuilder &Results;
1189 DeclContext *CurContext;
1190
1191 public:
1192 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1193 : Results(Results), CurContext(CurContext) { }
1194
Douglas Gregor0cc84042010-01-14 15:47:35 +00001195 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1196 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001197 }
1198 };
1199}
1200
Douglas Gregor86d9a522009-09-21 16:56:56 +00001201/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001202static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001203 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001204 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001205 Results.AddResult(Result("short", CCP_Type));
1206 Results.AddResult(Result("long", CCP_Type));
1207 Results.AddResult(Result("signed", CCP_Type));
1208 Results.AddResult(Result("unsigned", CCP_Type));
1209 Results.AddResult(Result("void", CCP_Type));
1210 Results.AddResult(Result("char", CCP_Type));
1211 Results.AddResult(Result("int", CCP_Type));
1212 Results.AddResult(Result("float", CCP_Type));
1213 Results.AddResult(Result("double", CCP_Type));
1214 Results.AddResult(Result("enum", CCP_Type));
1215 Results.AddResult(Result("struct", CCP_Type));
1216 Results.AddResult(Result("union", CCP_Type));
1217 Results.AddResult(Result("const", CCP_Type));
1218 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001219
Douglas Gregor86d9a522009-09-21 16:56:56 +00001220 if (LangOpts.C99) {
1221 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001222 Results.AddResult(Result("_Complex", CCP_Type));
1223 Results.AddResult(Result("_Imaginary", CCP_Type));
1224 Results.AddResult(Result("_Bool", CCP_Type));
1225 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001226 }
1227
Douglas Gregor218937c2011-02-01 19:23:04 +00001228 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001229 if (LangOpts.CPlusPlus) {
1230 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001231 Results.AddResult(Result("bool", CCP_Type +
1232 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001233 Results.AddResult(Result("class", CCP_Type));
1234 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001235
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001236 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001237 Builder.AddTypedTextChunk("typename");
1238 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1239 Builder.AddPlaceholderChunk("qualifier");
1240 Builder.AddTextChunk("::");
1241 Builder.AddPlaceholderChunk("name");
1242 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001243
Douglas Gregor86d9a522009-09-21 16:56:56 +00001244 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001245 Results.AddResult(Result("auto", CCP_Type));
1246 Results.AddResult(Result("char16_t", CCP_Type));
1247 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001248
Douglas Gregor218937c2011-02-01 19:23:04 +00001249 Builder.AddTypedTextChunk("decltype");
1250 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1251 Builder.AddPlaceholderChunk("expression");
1252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1253 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001254 }
1255 }
1256
1257 // GNU extensions
1258 if (LangOpts.GNUMode) {
1259 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001260 // Results.AddResult(Result("_Decimal32"));
1261 // Results.AddResult(Result("_Decimal64"));
1262 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001263
Douglas Gregor218937c2011-02-01 19:23:04 +00001264 Builder.AddTypedTextChunk("typeof");
1265 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1266 Builder.AddPlaceholderChunk("expression");
1267 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001268
Douglas Gregor218937c2011-02-01 19:23:04 +00001269 Builder.AddTypedTextChunk("typeof");
1270 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1271 Builder.AddPlaceholderChunk("type");
1272 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1273 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001274 }
1275}
1276
John McCallf312b1e2010-08-26 23:41:50 +00001277static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001278 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001279 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001280 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001281 // Note: we don't suggest either "auto" or "register", because both
1282 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1283 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001284 Results.AddResult(Result("extern"));
1285 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001286}
1287
John McCallf312b1e2010-08-26 23:41:50 +00001288static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001289 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001290 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001291 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001292 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001293 case Sema::PCC_Class:
1294 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001295 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001296 Results.AddResult(Result("explicit"));
1297 Results.AddResult(Result("friend"));
1298 Results.AddResult(Result("mutable"));
1299 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001300 }
1301 // Fall through
1302
John McCallf312b1e2010-08-26 23:41:50 +00001303 case Sema::PCC_ObjCInterface:
1304 case Sema::PCC_ObjCImplementation:
1305 case Sema::PCC_Namespace:
1306 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001307 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001308 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001309 break;
1310
John McCallf312b1e2010-08-26 23:41:50 +00001311 case Sema::PCC_ObjCInstanceVariableList:
1312 case Sema::PCC_Expression:
1313 case Sema::PCC_Statement:
1314 case Sema::PCC_ForInit:
1315 case Sema::PCC_Condition:
1316 case Sema::PCC_RecoveryInFunction:
1317 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001318 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001319 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001320 break;
1321 }
1322}
1323
Douglas Gregorbca403c2010-01-13 23:51:12 +00001324static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1325static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1326static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001327 ResultBuilder &Results,
1328 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001329static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001330 ResultBuilder &Results,
1331 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001332static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001333 ResultBuilder &Results,
1334 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001335static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001336
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001337static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001338 CodeCompletionBuilder Builder(Results.getAllocator());
1339 Builder.AddTypedTextChunk("typedef");
1340 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1341 Builder.AddPlaceholderChunk("type");
1342 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1343 Builder.AddPlaceholderChunk("name");
1344 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001345}
1346
John McCallf312b1e2010-08-26 23:41:50 +00001347static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001348 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001349 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001350 case Sema::PCC_Namespace:
1351 case Sema::PCC_Class:
1352 case Sema::PCC_ObjCInstanceVariableList:
1353 case Sema::PCC_Template:
1354 case Sema::PCC_MemberTemplate:
1355 case Sema::PCC_Statement:
1356 case Sema::PCC_RecoveryInFunction:
1357 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001358 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001359 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001360 return true;
1361
John McCallf312b1e2010-08-26 23:41:50 +00001362 case Sema::PCC_Expression:
1363 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001364 return LangOpts.CPlusPlus;
1365
1366 case Sema::PCC_ObjCInterface:
1367 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001368 return false;
1369
John McCallf312b1e2010-08-26 23:41:50 +00001370 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001371 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001372 }
1373
1374 return false;
1375}
1376
Douglas Gregor01dfea02010-01-10 23:08:15 +00001377/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001378static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001379 Scope *S,
1380 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001381 ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001382 CodeCompletionBuilder Builder(Results.getAllocator());
1383
John McCall0a2c5e22010-08-25 06:19:51 +00001384 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001385 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001386 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001387 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001388 if (Results.includeCodePatterns()) {
1389 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001390 Builder.AddTypedTextChunk("namespace");
1391 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1392 Builder.AddPlaceholderChunk("identifier");
1393 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1394 Builder.AddPlaceholderChunk("declarations");
1395 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1396 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1397 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001398 }
1399
Douglas Gregor01dfea02010-01-10 23:08:15 +00001400 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001401 Builder.AddTypedTextChunk("namespace");
1402 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1403 Builder.AddPlaceholderChunk("name");
1404 Builder.AddChunk(CodeCompletionString::CK_Equal);
1405 Builder.AddPlaceholderChunk("namespace");
1406 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001407
1408 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001409 Builder.AddTypedTextChunk("using");
1410 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1411 Builder.AddTextChunk("namespace");
1412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1413 Builder.AddPlaceholderChunk("identifier");
1414 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001415
1416 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001417 Builder.AddTypedTextChunk("asm");
1418 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1419 Builder.AddPlaceholderChunk("string-literal");
1420 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1421 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001422
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001423 if (Results.includeCodePatterns()) {
1424 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001425 Builder.AddTypedTextChunk("template");
1426 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1427 Builder.AddPlaceholderChunk("declaration");
1428 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001429 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001430 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001431
1432 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001433 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001434
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001435 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001436 // Fall through
1437
John McCallf312b1e2010-08-26 23:41:50 +00001438 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001439 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001440 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001441 Builder.AddTypedTextChunk("using");
1442 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1443 Builder.AddPlaceholderChunk("qualifier");
1444 Builder.AddTextChunk("::");
1445 Builder.AddPlaceholderChunk("name");
1446 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001447
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001448 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001449 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001450 Builder.AddTypedTextChunk("using");
1451 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1452 Builder.AddTextChunk("typename");
1453 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1454 Builder.AddPlaceholderChunk("qualifier");
1455 Builder.AddTextChunk("::");
1456 Builder.AddPlaceholderChunk("name");
1457 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001458 }
1459
John McCallf312b1e2010-08-26 23:41:50 +00001460 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001461 AddTypedefResult(Results);
1462
Douglas Gregor01dfea02010-01-10 23:08:15 +00001463 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001464 Builder.AddTypedTextChunk("public");
1465 Builder.AddChunk(CodeCompletionString::CK_Colon);
1466 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001467
1468 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001469 Builder.AddTypedTextChunk("protected");
1470 Builder.AddChunk(CodeCompletionString::CK_Colon);
1471 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001472
1473 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001474 Builder.AddTypedTextChunk("private");
1475 Builder.AddChunk(CodeCompletionString::CK_Colon);
1476 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001477 }
1478 }
1479 // Fall through
1480
John McCallf312b1e2010-08-26 23:41:50 +00001481 case Sema::PCC_Template:
1482 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001483 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001484 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001485 Builder.AddTypedTextChunk("template");
1486 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1487 Builder.AddPlaceholderChunk("parameters");
1488 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1489 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001490 }
1491
Douglas Gregorbca403c2010-01-13 23:51:12 +00001492 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1493 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001494 break;
1495
John McCallf312b1e2010-08-26 23:41:50 +00001496 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001497 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1498 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1499 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001500 break;
1501
John McCallf312b1e2010-08-26 23:41:50 +00001502 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001503 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1504 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1505 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001506 break;
1507
John McCallf312b1e2010-08-26 23:41:50 +00001508 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001509 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001510 break;
1511
John McCallf312b1e2010-08-26 23:41:50 +00001512 case Sema::PCC_RecoveryInFunction:
1513 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001514 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001515
Douglas Gregorec3310a2011-04-12 02:47:21 +00001516 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1517 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001518 Builder.AddTypedTextChunk("try");
1519 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1520 Builder.AddPlaceholderChunk("statements");
1521 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1522 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1523 Builder.AddTextChunk("catch");
1524 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1525 Builder.AddPlaceholderChunk("declaration");
1526 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1527 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1528 Builder.AddPlaceholderChunk("statements");
1529 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1530 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1531 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001532 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001533 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001534 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001535
Douglas Gregord8e8a582010-05-25 21:41:55 +00001536 if (Results.includeCodePatterns()) {
1537 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001538 Builder.AddTypedTextChunk("if");
1539 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001540 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001541 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001542 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001543 Builder.AddPlaceholderChunk("expression");
1544 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1545 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1546 Builder.AddPlaceholderChunk("statements");
1547 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1548 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1549 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001550
Douglas Gregord8e8a582010-05-25 21:41:55 +00001551 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001552 Builder.AddTypedTextChunk("switch");
1553 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001554 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001555 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001556 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001557 Builder.AddPlaceholderChunk("expression");
1558 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1559 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1560 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1561 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1562 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001563 }
1564
Douglas Gregor01dfea02010-01-10 23:08:15 +00001565 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001566 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001567 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001568 Builder.AddTypedTextChunk("case");
1569 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1570 Builder.AddPlaceholderChunk("expression");
1571 Builder.AddChunk(CodeCompletionString::CK_Colon);
1572 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001573
1574 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001575 Builder.AddTypedTextChunk("default");
1576 Builder.AddChunk(CodeCompletionString::CK_Colon);
1577 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001578 }
1579
Douglas Gregord8e8a582010-05-25 21:41:55 +00001580 if (Results.includeCodePatterns()) {
1581 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001582 Builder.AddTypedTextChunk("while");
1583 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001584 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001585 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001586 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001587 Builder.AddPlaceholderChunk("expression");
1588 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1589 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1590 Builder.AddPlaceholderChunk("statements");
1591 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1592 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1593 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001594
1595 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001596 Builder.AddTypedTextChunk("do");
1597 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1598 Builder.AddPlaceholderChunk("statements");
1599 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1600 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1601 Builder.AddTextChunk("while");
1602 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1603 Builder.AddPlaceholderChunk("expression");
1604 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1605 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001606
Douglas Gregord8e8a582010-05-25 21:41:55 +00001607 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001608 Builder.AddTypedTextChunk("for");
1609 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001610 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001611 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001612 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001613 Builder.AddPlaceholderChunk("init-expression");
1614 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1615 Builder.AddPlaceholderChunk("condition");
1616 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1617 Builder.AddPlaceholderChunk("inc-expression");
1618 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1619 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1620 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1621 Builder.AddPlaceholderChunk("statements");
1622 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1623 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1624 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001625 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001626
1627 if (S->getContinueParent()) {
1628 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001629 Builder.AddTypedTextChunk("continue");
1630 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001631 }
1632
1633 if (S->getBreakParent()) {
1634 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001635 Builder.AddTypedTextChunk("break");
1636 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001637 }
1638
1639 // "return expression ;" or "return ;", depending on whether we
1640 // know the function is void or not.
1641 bool isVoid = false;
1642 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1643 isVoid = Function->getResultType()->isVoidType();
1644 else if (ObjCMethodDecl *Method
1645 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1646 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001647 else if (SemaRef.getCurBlock() &&
1648 !SemaRef.getCurBlock()->ReturnType.isNull())
1649 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001650 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001651 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001652 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1653 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001654 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001655 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001656
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001657 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001658 Builder.AddTypedTextChunk("goto");
1659 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1660 Builder.AddPlaceholderChunk("label");
1661 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001662
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001663 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001664 Builder.AddTypedTextChunk("using");
1665 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1666 Builder.AddTextChunk("namespace");
1667 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1668 Builder.AddPlaceholderChunk("identifier");
1669 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001670 }
1671
1672 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001673 case Sema::PCC_ForInit:
1674 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001675 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001676 // Fall through: conditions and statements can have expressions.
1677
Douglas Gregor02688102010-09-14 23:59:36 +00001678 case Sema::PCC_ParenthesizedExpression:
John McCallf85e1932011-06-15 23:02:42 +00001679 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1680 CCC == Sema::PCC_ParenthesizedExpression) {
1681 // (__bridge <type>)<expression>
1682 Builder.AddTypedTextChunk("__bridge");
1683 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1684 Builder.AddPlaceholderChunk("type");
1685 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1686 Builder.AddPlaceholderChunk("expression");
1687 Results.AddResult(Result(Builder.TakeString()));
1688
1689 // (__bridge_transfer <Objective-C type>)<expression>
1690 Builder.AddTypedTextChunk("__bridge_transfer");
1691 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1692 Builder.AddPlaceholderChunk("Objective-C type");
1693 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1694 Builder.AddPlaceholderChunk("expression");
1695 Results.AddResult(Result(Builder.TakeString()));
1696
1697 // (__bridge_retained <CF type>)<expression>
1698 Builder.AddTypedTextChunk("__bridge_retained");
1699 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1700 Builder.AddPlaceholderChunk("CF type");
1701 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1702 Builder.AddPlaceholderChunk("expression");
1703 Results.AddResult(Result(Builder.TakeString()));
1704 }
1705 // Fall through
1706
John McCallf312b1e2010-08-26 23:41:50 +00001707 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001708 if (SemaRef.getLangOptions().CPlusPlus) {
1709 // 'this', if we're in a non-static member function.
1710 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1711 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001712 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001713
1714 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001715 Results.AddResult(Result("true"));
1716 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001717
Douglas Gregorec3310a2011-04-12 02:47:21 +00001718 if (SemaRef.getLangOptions().RTTI) {
1719 // dynamic_cast < type-id > ( expression )
1720 Builder.AddTypedTextChunk("dynamic_cast");
1721 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1722 Builder.AddPlaceholderChunk("type");
1723 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1724 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1725 Builder.AddPlaceholderChunk("expression");
1726 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1727 Results.AddResult(Result(Builder.TakeString()));
1728 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001729
1730 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001731 Builder.AddTypedTextChunk("static_cast");
1732 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1733 Builder.AddPlaceholderChunk("type");
1734 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1735 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1736 Builder.AddPlaceholderChunk("expression");
1737 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1738 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001739
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001740 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001741 Builder.AddTypedTextChunk("reinterpret_cast");
1742 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1743 Builder.AddPlaceholderChunk("type");
1744 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1745 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1746 Builder.AddPlaceholderChunk("expression");
1747 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1748 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001749
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001750 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001751 Builder.AddTypedTextChunk("const_cast");
1752 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1753 Builder.AddPlaceholderChunk("type");
1754 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1755 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1756 Builder.AddPlaceholderChunk("expression");
1757 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1758 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001759
Douglas Gregorec3310a2011-04-12 02:47:21 +00001760 if (SemaRef.getLangOptions().RTTI) {
1761 // typeid ( expression-or-type )
1762 Builder.AddTypedTextChunk("typeid");
1763 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1764 Builder.AddPlaceholderChunk("expression-or-type");
1765 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1766 Results.AddResult(Result(Builder.TakeString()));
1767 }
1768
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001769 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001770 Builder.AddTypedTextChunk("new");
1771 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1772 Builder.AddPlaceholderChunk("type");
1773 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1774 Builder.AddPlaceholderChunk("expressions");
1775 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1776 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001777
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001778 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001779 Builder.AddTypedTextChunk("new");
1780 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1781 Builder.AddPlaceholderChunk("type");
1782 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1783 Builder.AddPlaceholderChunk("size");
1784 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1785 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1786 Builder.AddPlaceholderChunk("expressions");
1787 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1788 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001789
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001790 // delete expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001791 Builder.AddTypedTextChunk("delete");
1792 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1793 Builder.AddPlaceholderChunk("expression");
1794 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001795
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001796 // delete [] expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001797 Builder.AddTypedTextChunk("delete");
1798 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1799 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1800 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1801 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1802 Builder.AddPlaceholderChunk("expression");
1803 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001804
Douglas Gregorec3310a2011-04-12 02:47:21 +00001805 if (SemaRef.getLangOptions().CXXExceptions) {
1806 // throw expression
1807 Builder.AddTypedTextChunk("throw");
1808 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1809 Builder.AddPlaceholderChunk("expression");
1810 Results.AddResult(Result(Builder.TakeString()));
1811 }
Douglas Gregor12e13132010-05-26 22:00:08 +00001812
1813 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001814 }
1815
1816 if (SemaRef.getLangOptions().ObjC1) {
1817 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001818 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1819 // The interface can be NULL.
1820 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1821 if (ID->getSuperClass())
1822 Results.AddResult(Result("super"));
1823 }
1824
Douglas Gregorbca403c2010-01-13 23:51:12 +00001825 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001826 }
1827
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001828 // sizeof expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001829 Builder.AddTypedTextChunk("sizeof");
1830 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1831 Builder.AddPlaceholderChunk("expression-or-type");
1832 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1833 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001834 break;
1835 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001836
John McCallf312b1e2010-08-26 23:41:50 +00001837 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001838 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001839 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001840 }
1841
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001842 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1843 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001844
John McCallf312b1e2010-08-26 23:41:50 +00001845 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001846 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001847}
1848
Douglas Gregora63f6de2011-02-01 21:15:40 +00001849/// \brief Retrieve the string representation of the given type as a string
1850/// that has the appropriate lifetime for code completion.
1851///
1852/// This routine provides a fast path where we provide constant strings for
1853/// common type names.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001854static const char *GetCompletionTypeString(QualType T,
1855 ASTContext &Context,
1856 CodeCompletionAllocator &Allocator) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001857 PrintingPolicy Policy(Context.PrintingPolicy);
1858 Policy.AnonymousTagLocations = false;
John McCallf85e1932011-06-15 23:02:42 +00001859 Policy.SuppressStrongLifetime = true;
1860
Douglas Gregora63f6de2011-02-01 21:15:40 +00001861 if (!T.getLocalQualifiers()) {
1862 // Built-in type names are constant strings.
1863 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1864 return BT->getName(Context.getLangOptions());
1865
1866 // Anonymous tag types are constant strings.
1867 if (const TagType *TagT = dyn_cast<TagType>(T))
1868 if (TagDecl *Tag = TagT->getDecl())
Richard Smith162e1c12011-04-15 14:24:37 +00001869 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001870 switch (Tag->getTagKind()) {
1871 case TTK_Struct: return "struct <anonymous>";
1872 case TTK_Class: return "class <anonymous>";
1873 case TTK_Union: return "union <anonymous>";
1874 case TTK_Enum: return "enum <anonymous>";
1875 }
1876 }
1877 }
1878
1879 // Slow path: format the type as a string.
1880 std::string Result;
1881 T.getAsStringInternal(Result, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00001882 return Allocator.CopyString(Result);
Douglas Gregora63f6de2011-02-01 21:15:40 +00001883}
1884
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001885/// \brief If the given declaration has an associated type, add it as a result
1886/// type chunk.
1887static void AddResultTypeChunk(ASTContext &Context,
1888 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001889 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001890 if (!ND)
1891 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001892
1893 // Skip constructors and conversion functions, which have their return types
1894 // built into their names.
1895 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1896 return;
1897
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001898 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001899 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001900 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1901 T = Function->getResultType();
1902 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1903 T = Method->getResultType();
1904 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1905 T = FunTmpl->getTemplatedDecl()->getResultType();
1906 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1907 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1908 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1909 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00001910 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001911 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001912 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001913 T = Property->getType();
1914
1915 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1916 return;
1917
Douglas Gregora63f6de2011-02-01 21:15:40 +00001918 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context,
1919 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001920}
1921
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001922static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001923 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001924 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1925 if (Sentinel->getSentinel() == 0) {
1926 if (Context.getLangOptions().ObjC1 &&
1927 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001928 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001929 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001930 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001931 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001932 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001933 }
1934}
1935
Douglas Gregor83482d12010-08-24 16:15:59 +00001936static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregoraba48082010-08-29 19:47:46 +00001937 ParmVarDecl *Param,
1938 bool SuppressName = false) {
John McCallf85e1932011-06-15 23:02:42 +00001939 PrintingPolicy Policy(Context.PrintingPolicy);
1940 Policy.AnonymousTagLocations = false;
1941 Policy.SuppressStrongLifetime = true;
1942
Douglas Gregor83482d12010-08-24 16:15:59 +00001943 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1944 if (Param->getType()->isDependentType() ||
1945 !Param->getType()->isBlockPointerType()) {
1946 // The argument for a dependent or non-block parameter is a placeholder
1947 // containing that parameter's type.
1948 std::string Result;
1949
Douglas Gregoraba48082010-08-29 19:47:46 +00001950 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001951 Result = Param->getIdentifier()->getName();
1952
John McCallf85e1932011-06-15 23:02:42 +00001953 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00001954
1955 if (ObjCMethodParam) {
1956 Result = "(" + Result;
1957 Result += ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001958 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001959 Result += Param->getIdentifier()->getName();
1960 }
1961 return Result;
1962 }
1963
1964 // The argument for a block pointer parameter is a block literal with
1965 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00001966 FunctionTypeLoc *Block = 0;
1967 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00001968 TypeLoc TL;
1969 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1970 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1971 while (true) {
1972 // Look through typedefs.
1973 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1974 if (TypeSourceInfo *InnerTSInfo
Richard Smith162e1c12011-04-15 14:24:37 +00001975 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001976 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1977 continue;
1978 }
1979 }
1980
1981 // Look through qualified types
1982 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1983 TL = QualifiedTL->getUnqualifiedLoc();
1984 continue;
1985 }
1986
1987 // Try to get the function prototype behind the block pointer type,
1988 // then we're done.
1989 if (BlockPointerTypeLoc *BlockPtr
1990 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00001991 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00001992 Block = dyn_cast<FunctionTypeLoc>(&TL);
1993 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00001994 }
1995 break;
1996 }
1997 }
1998
1999 if (!Block) {
2000 // We were unable to find a FunctionProtoTypeLoc with parameter names
2001 // for the block; just use the parameter type as a placeholder.
2002 std::string Result;
John McCallf85e1932011-06-15 23:02:42 +00002003 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002004
2005 if (ObjCMethodParam) {
2006 Result = "(" + Result;
2007 Result += ")";
2008 if (Param->getIdentifier())
2009 Result += Param->getIdentifier()->getName();
2010 }
2011
2012 return Result;
2013 }
2014
2015 // We have the function prototype behind the block pointer type, as it was
2016 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002017 std::string Result;
2018 QualType ResultType = Block->getTypePtr()->getResultType();
2019 if (!ResultType->isVoidType())
John McCallf85e1932011-06-15 23:02:42 +00002020 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregor38276252010-09-08 22:47:51 +00002021
2022 Result = '^' + Result;
Douglas Gregor830072c2011-02-15 22:37:09 +00002023 if (!BlockProto || Block->getNumArgs() == 0) {
2024 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002025 Result += "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002026 else
2027 Result += "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002028 } else {
2029 Result += "(";
2030 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2031 if (I)
2032 Result += ", ";
2033 Result += FormatFunctionParameter(Context, Block->getArg(I));
2034
Douglas Gregor830072c2011-02-15 22:37:09 +00002035 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002036 Result += ", ...";
2037 }
2038 Result += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002039 }
Douglas Gregor38276252010-09-08 22:47:51 +00002040
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002041 if (Param->getIdentifier())
2042 Result += Param->getIdentifier()->getName();
2043
Douglas Gregor83482d12010-08-24 16:15:59 +00002044 return Result;
2045}
2046
Douglas Gregor86d9a522009-09-21 16:56:56 +00002047/// \brief Add function parameter chunks to the given code completion string.
2048static void AddFunctionParameterChunks(ASTContext &Context,
2049 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002050 CodeCompletionBuilder &Result,
2051 unsigned Start = 0,
2052 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002053 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002054 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002055
Douglas Gregor218937c2011-02-01 19:23:04 +00002056 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002057 ParmVarDecl *Param = Function->getParamDecl(P);
2058
Douglas Gregor218937c2011-02-01 19:23:04 +00002059 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002060 // When we see an optional default argument, put that argument and
2061 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002062 CodeCompletionBuilder Opt(Result.getAllocator());
2063 if (!FirstParameter)
2064 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2065 AddFunctionParameterChunks(Context, Function, Opt, P, true);
2066 Result.AddOptionalChunk(Opt.TakeString());
2067 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002068 }
2069
Douglas Gregor218937c2011-02-01 19:23:04 +00002070 if (FirstParameter)
2071 FirstParameter = false;
2072 else
2073 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2074
2075 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002076
2077 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00002078 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
2079
Douglas Gregore17794f2010-08-31 05:13:43 +00002080 if (Function->isVariadic() && P == N - 1)
2081 PlaceholderStr += ", ...";
2082
Douglas Gregor86d9a522009-09-21 16:56:56 +00002083 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002084 Result.AddPlaceholderChunk(
2085 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002086 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002087
2088 if (const FunctionProtoType *Proto
2089 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002090 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002091 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002092 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002093
Douglas Gregor218937c2011-02-01 19:23:04 +00002094 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002095 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002096}
2097
2098/// \brief Add template parameter chunks to the given code completion string.
2099static void AddTemplateParameterChunks(ASTContext &Context,
2100 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002101 CodeCompletionBuilder &Result,
2102 unsigned MaxParameters = 0,
2103 unsigned Start = 0,
2104 bool InDefaultArg = false) {
John McCallf85e1932011-06-15 23:02:42 +00002105 PrintingPolicy Policy(Context.PrintingPolicy);
2106 Policy.AnonymousTagLocations = false;
2107
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002108 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002109 bool FirstParameter = true;
2110
2111 TemplateParameterList *Params = Template->getTemplateParameters();
2112 TemplateParameterList::iterator PEnd = Params->end();
2113 if (MaxParameters)
2114 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002115 for (TemplateParameterList::iterator P = Params->begin() + Start;
2116 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002117 bool HasDefaultArg = false;
2118 std::string PlaceholderStr;
2119 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2120 if (TTP->wasDeclaredWithTypename())
2121 PlaceholderStr = "typename";
2122 else
2123 PlaceholderStr = "class";
2124
2125 if (TTP->getIdentifier()) {
2126 PlaceholderStr += ' ';
2127 PlaceholderStr += TTP->getIdentifier()->getName();
2128 }
2129
2130 HasDefaultArg = TTP->hasDefaultArgument();
2131 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002132 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002133 if (NTTP->getIdentifier())
2134 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002135 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002136 HasDefaultArg = NTTP->hasDefaultArgument();
2137 } else {
2138 assert(isa<TemplateTemplateParmDecl>(*P));
2139 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2140
2141 // Since putting the template argument list into the placeholder would
2142 // be very, very long, we just use an abbreviation.
2143 PlaceholderStr = "template<...> class";
2144 if (TTP->getIdentifier()) {
2145 PlaceholderStr += ' ';
2146 PlaceholderStr += TTP->getIdentifier()->getName();
2147 }
2148
2149 HasDefaultArg = TTP->hasDefaultArgument();
2150 }
2151
Douglas Gregor218937c2011-02-01 19:23:04 +00002152 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002153 // When we see an optional default argument, put that argument and
2154 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002155 CodeCompletionBuilder Opt(Result.getAllocator());
2156 if (!FirstParameter)
2157 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2158 AddTemplateParameterChunks(Context, Template, Opt, MaxParameters,
2159 P - Params->begin(), true);
2160 Result.AddOptionalChunk(Opt.TakeString());
2161 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002162 }
2163
Douglas Gregor218937c2011-02-01 19:23:04 +00002164 InDefaultArg = false;
2165
Douglas Gregor86d9a522009-09-21 16:56:56 +00002166 if (FirstParameter)
2167 FirstParameter = false;
2168 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002169 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002170
2171 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002172 Result.AddPlaceholderChunk(
2173 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002174 }
2175}
2176
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002177/// \brief Add a qualifier to the given code-completion string, if the
2178/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002179static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002180AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002181 NestedNameSpecifier *Qualifier,
2182 bool QualifierIsInformative,
2183 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002184 if (!Qualifier)
2185 return;
2186
2187 std::string PrintedNNS;
2188 {
2189 llvm::raw_string_ostream OS(PrintedNNS);
2190 Qualifier->print(OS, Context.PrintingPolicy);
2191 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002192 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002193 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002194 else
Douglas Gregordae68752011-02-01 22:57:45 +00002195 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002196}
2197
Douglas Gregor218937c2011-02-01 19:23:04 +00002198static void
2199AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2200 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002201 const FunctionProtoType *Proto
2202 = Function->getType()->getAs<FunctionProtoType>();
2203 if (!Proto || !Proto->getTypeQuals())
2204 return;
2205
Douglas Gregora63f6de2011-02-01 21:15:40 +00002206 // FIXME: Add ref-qualifier!
2207
2208 // Handle single qualifiers without copying
2209 if (Proto->getTypeQuals() == Qualifiers::Const) {
2210 Result.AddInformativeChunk(" const");
2211 return;
2212 }
2213
2214 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2215 Result.AddInformativeChunk(" volatile");
2216 return;
2217 }
2218
2219 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2220 Result.AddInformativeChunk(" restrict");
2221 return;
2222 }
2223
2224 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002225 std::string QualsStr;
2226 if (Proto->getTypeQuals() & Qualifiers::Const)
2227 QualsStr += " const";
2228 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2229 QualsStr += " volatile";
2230 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2231 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002232 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002233}
2234
Douglas Gregor6f942b22010-09-21 16:06:22 +00002235/// \brief Add the name of the given declaration
2236static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00002237 CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002238 typedef CodeCompletionString::Chunk Chunk;
2239
2240 DeclarationName Name = ND->getDeclName();
2241 if (!Name)
2242 return;
2243
2244 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002245 case DeclarationName::CXXOperatorName: {
2246 const char *OperatorName = 0;
2247 switch (Name.getCXXOverloadedOperator()) {
2248 case OO_None:
2249 case OO_Conditional:
2250 case NUM_OVERLOADED_OPERATORS:
2251 OperatorName = "operator";
2252 break;
2253
2254#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2255 case OO_##Name: OperatorName = "operator" Spelling; break;
2256#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2257#include "clang/Basic/OperatorKinds.def"
2258
2259 case OO_New: OperatorName = "operator new"; break;
2260 case OO_Delete: OperatorName = "operator delete"; break;
2261 case OO_Array_New: OperatorName = "operator new[]"; break;
2262 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2263 case OO_Call: OperatorName = "operator()"; break;
2264 case OO_Subscript: OperatorName = "operator[]"; break;
2265 }
2266 Result.AddTypedTextChunk(OperatorName);
2267 break;
2268 }
2269
Douglas Gregor6f942b22010-09-21 16:06:22 +00002270 case DeclarationName::Identifier:
2271 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002272 case DeclarationName::CXXDestructorName:
2273 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002274 Result.AddTypedTextChunk(
2275 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002276 break;
2277
2278 case DeclarationName::CXXUsingDirective:
2279 case DeclarationName::ObjCZeroArgSelector:
2280 case DeclarationName::ObjCOneArgSelector:
2281 case DeclarationName::ObjCMultiArgSelector:
2282 break;
2283
2284 case DeclarationName::CXXConstructorName: {
2285 CXXRecordDecl *Record = 0;
2286 QualType Ty = Name.getCXXNameType();
2287 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2288 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2289 else if (const InjectedClassNameType *InjectedTy
2290 = Ty->getAs<InjectedClassNameType>())
2291 Record = InjectedTy->getDecl();
2292 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002293 Result.AddTypedTextChunk(
2294 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002295 break;
2296 }
2297
Douglas Gregordae68752011-02-01 22:57:45 +00002298 Result.AddTypedTextChunk(
2299 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002300 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002301 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002302 AddTemplateParameterChunks(Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002303 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002304 }
2305 break;
2306 }
2307 }
2308}
2309
Douglas Gregor86d9a522009-09-21 16:56:56 +00002310/// \brief If possible, create a new code completion string for the given
2311/// result.
2312///
2313/// \returns Either a new, heap-allocated code completion string describing
2314/// how to use this result, or NULL to indicate that the string or name of the
2315/// result is all that is needed.
2316CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002317CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002318 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002319 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002320 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002321
John McCallf85e1932011-06-15 23:02:42 +00002322 PrintingPolicy Policy(S.Context.PrintingPolicy);
2323 Policy.AnonymousTagLocations = false;
2324 Policy.SuppressStrongLifetime = true;
2325
Douglas Gregor218937c2011-02-01 19:23:04 +00002326 if (Kind == RK_Pattern) {
2327 Pattern->Priority = Priority;
2328 Pattern->Availability = Availability;
2329 return Pattern;
2330 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002331
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002332 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002333 Result.AddTypedTextChunk(Keyword);
2334 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002335 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002336
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002337 if (Kind == RK_Macro) {
2338 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002339 assert(MI && "Not a macro?");
2340
Douglas Gregordae68752011-02-01 22:57:45 +00002341 Result.AddTypedTextChunk(
2342 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002343
2344 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002345 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002346
2347 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002348 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002349 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2350 A != AEnd; ++A) {
2351 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002352 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002353
2354 if (!MI->isVariadic() || A != AEnd - 1) {
2355 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002356 Result.AddPlaceholderChunk(
2357 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002358 continue;
2359 }
2360
2361 // Variadic argument; cope with the different between GNU and C99
2362 // variadic macros, providing a single placeholder for the rest of the
2363 // arguments.
2364 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002365 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002366 else {
2367 std::string Arg = (*A)->getName();
2368 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002369 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002370 }
2371 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002372 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2373 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002374 }
2375
Douglas Gregord8e8a582010-05-25 21:41:55 +00002376 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002377 NamedDecl *ND = Declaration;
2378
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002379 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002380 Result.AddTypedTextChunk(
2381 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002382 Result.AddTextChunk("::");
2383 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002384 }
2385
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002386 AddResultTypeChunk(S.Context, ND, Result);
2387
Douglas Gregor86d9a522009-09-21 16:56:56 +00002388 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002389 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2390 S.Context);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002391 AddTypedNameChunk(S.Context, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002392 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002393 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002394 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002395 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002396 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002397 }
2398
2399 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002400 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2401 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002402 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor6f942b22010-09-21 16:06:22 +00002403 AddTypedNameChunk(S.Context, Function, Result);
2404
Douglas Gregor86d9a522009-09-21 16:56:56 +00002405 // Figure out which template parameters are deduced (or have default
2406 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002407 SmallVector<bool, 16> Deduced;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002408 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2409 unsigned LastDeducibleArgument;
2410 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2411 --LastDeducibleArgument) {
2412 if (!Deduced[LastDeducibleArgument - 1]) {
2413 // C++0x: Figure out if the template argument has a default. If so,
2414 // the user doesn't need to type this argument.
2415 // FIXME: We need to abstract template parameters better!
2416 bool HasDefaultArg = false;
2417 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002418 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002419 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2420 HasDefaultArg = TTP->hasDefaultArgument();
2421 else if (NonTypeTemplateParmDecl *NTTP
2422 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2423 HasDefaultArg = NTTP->hasDefaultArgument();
2424 else {
2425 assert(isa<TemplateTemplateParmDecl>(Param));
2426 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002427 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002428 }
2429
2430 if (!HasDefaultArg)
2431 break;
2432 }
2433 }
2434
2435 if (LastDeducibleArgument) {
2436 // Some of the function template arguments cannot be deduced from a
2437 // function call, so we introduce an explicit template argument list
2438 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002439 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002440 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2441 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002442 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002443 }
2444
2445 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002446 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002447 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002448 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002449 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002450 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002451 }
2452
2453 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002454 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2455 S.Context);
Douglas Gregordae68752011-02-01 22:57:45 +00002456 Result.AddTypedTextChunk(
2457 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002458 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002459 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002460 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2461 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002462 }
2463
Douglas Gregor9630eb62009-11-17 16:44:22 +00002464 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002465 Selector Sel = Method->getSelector();
2466 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002467 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002468 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002469 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002470 }
2471
Douglas Gregor813d8342011-02-18 22:29:55 +00002472 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002473 SelName += ':';
2474 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002475 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002476 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002477 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002478
2479 // If there is only one parameter, and we're past it, add an empty
2480 // typed-text chunk since there is nothing to type.
2481 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002482 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002483 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002484 unsigned Idx = 0;
2485 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2486 PEnd = Method->param_end();
2487 P != PEnd; (void)++P, ++Idx) {
2488 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002489 std::string Keyword;
2490 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002491 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002492 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2493 Keyword += II->getName().str();
2494 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002495 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002496 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002497 else
Douglas Gregordae68752011-02-01 22:57:45 +00002498 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002499 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002500
2501 // If we're before the starting parameter, skip the placeholder.
2502 if (Idx < StartParameter)
2503 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002504
2505 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002506
2507 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregoraba48082010-08-29 19:47:46 +00002508 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002509 else {
John McCallf85e1932011-06-15 23:02:42 +00002510 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002511 Arg = "(" + Arg + ")";
2512 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002513 if (DeclaringEntity || AllParametersAreInformative)
2514 Arg += II->getName().str();
Douglas Gregor83482d12010-08-24 16:15:59 +00002515 }
2516
Douglas Gregore17794f2010-08-31 05:13:43 +00002517 if (Method->isVariadic() && (P + 1) == PEnd)
2518 Arg += ", ...";
2519
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002520 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002521 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002522 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002523 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002524 else
Douglas Gregordae68752011-02-01 22:57:45 +00002525 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002526 }
2527
Douglas Gregor2a17af02009-12-23 00:21:46 +00002528 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002529 if (Method->param_size() == 0) {
2530 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002531 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002532 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002533 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002534 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002535 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002536 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002537
2538 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002539 }
2540
Douglas Gregor218937c2011-02-01 19:23:04 +00002541 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002542 }
2543
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002544 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002545 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2546 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002547
Douglas Gregordae68752011-02-01 22:57:45 +00002548 Result.AddTypedTextChunk(
2549 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002550 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002551}
2552
Douglas Gregor86d802e2009-09-23 00:34:09 +00002553CodeCompletionString *
2554CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2555 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002556 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002557 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002558 typedef CodeCompletionString::Chunk Chunk;
John McCallf85e1932011-06-15 23:02:42 +00002559 PrintingPolicy Policy(S.Context.PrintingPolicy);
2560 Policy.AnonymousTagLocations = false;
2561 Policy.SuppressStrongLifetime = true;
2562
Douglas Gregor218937c2011-02-01 19:23:04 +00002563 // FIXME: Set priority, availability appropriately.
2564 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002565 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002566 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002567 const FunctionProtoType *Proto
2568 = dyn_cast<FunctionProtoType>(getFunctionType());
2569 if (!FDecl && !Proto) {
2570 // Function without a prototype. Just give the return type and a
2571 // highlighted ellipsis.
2572 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002573 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
2574 S.Context,
2575 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002576 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2577 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2578 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2579 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002580 }
2581
2582 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002583 Result.AddTextChunk(
2584 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002585 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002586 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002587 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002588 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002589
Douglas Gregor218937c2011-02-01 19:23:04 +00002590 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002591 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2592 for (unsigned I = 0; I != NumParams; ++I) {
2593 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002594 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002595
2596 std::string ArgString;
2597 QualType ArgType;
2598
2599 if (FDecl) {
2600 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2601 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2602 } else {
2603 ArgType = Proto->getArgType(I);
2604 }
2605
John McCallf85e1932011-06-15 23:02:42 +00002606 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002607
2608 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002609 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002610 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002611 else
Douglas Gregordae68752011-02-01 22:57:45 +00002612 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002613 }
2614
2615 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002616 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002617 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002618 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002619 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002620 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002621 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002622 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002623
Douglas Gregor218937c2011-02-01 19:23:04 +00002624 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002625}
2626
Chris Lattner5f9e2722011-07-23 10:55:15 +00002627unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002628 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002629 bool PreferredTypeIsPointer) {
2630 unsigned Priority = CCP_Macro;
2631
Douglas Gregorb05496d2010-09-20 21:11:48 +00002632 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2633 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2634 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002635 Priority = CCP_Constant;
2636 if (PreferredTypeIsPointer)
2637 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002638 }
2639 // Treat "YES", "NO", "true", and "false" as constants.
2640 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2641 MacroName.equals("true") || MacroName.equals("false"))
2642 Priority = CCP_Constant;
2643 // Treat "bool" as a type.
2644 else if (MacroName.equals("bool"))
2645 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2646
Douglas Gregor1827e102010-08-16 16:18:59 +00002647
2648 return Priority;
2649}
2650
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002651CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2652 if (!D)
2653 return CXCursor_UnexposedDecl;
2654
2655 switch (D->getKind()) {
2656 case Decl::Enum: return CXCursor_EnumDecl;
2657 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2658 case Decl::Field: return CXCursor_FieldDecl;
2659 case Decl::Function:
2660 return CXCursor_FunctionDecl;
2661 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2662 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2663 case Decl::ObjCClass:
2664 // FIXME
2665 return CXCursor_UnexposedDecl;
2666 case Decl::ObjCForwardProtocol:
2667 // FIXME
2668 return CXCursor_UnexposedDecl;
2669 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2670 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2671 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2672 case Decl::ObjCMethod:
2673 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2674 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2675 case Decl::CXXMethod: return CXCursor_CXXMethod;
2676 case Decl::CXXConstructor: return CXCursor_Constructor;
2677 case Decl::CXXDestructor: return CXCursor_Destructor;
2678 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2679 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2680 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2681 case Decl::ParmVar: return CXCursor_ParmDecl;
2682 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002683 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002684 case Decl::Var: return CXCursor_VarDecl;
2685 case Decl::Namespace: return CXCursor_Namespace;
2686 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2687 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2688 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2689 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2690 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2691 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2692 case Decl::ClassTemplatePartialSpecialization:
2693 return CXCursor_ClassTemplatePartialSpecialization;
2694 case Decl::UsingDirective: return CXCursor_UsingDirective;
2695
2696 case Decl::Using:
2697 case Decl::UnresolvedUsingValue:
2698 case Decl::UnresolvedUsingTypename:
2699 return CXCursor_UsingDeclaration;
2700
Douglas Gregor352697a2011-06-03 23:08:58 +00002701 case Decl::ObjCPropertyImpl:
2702 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2703 case ObjCPropertyImplDecl::Dynamic:
2704 return CXCursor_ObjCDynamicDecl;
2705
2706 case ObjCPropertyImplDecl::Synthesize:
2707 return CXCursor_ObjCSynthesizeDecl;
2708 }
2709 break;
2710
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002711 default:
2712 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2713 switch (TD->getTagKind()) {
2714 case TTK_Struct: return CXCursor_StructDecl;
2715 case TTK_Class: return CXCursor_ClassDecl;
2716 case TTK_Union: return CXCursor_UnionDecl;
2717 case TTK_Enum: return CXCursor_EnumDecl;
2718 }
2719 }
2720 }
2721
2722 return CXCursor_UnexposedDecl;
2723}
2724
Douglas Gregor590c7d52010-07-08 20:55:51 +00002725static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2726 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002727 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002728
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002729 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002730
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002731 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2732 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002733 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002734 Results.AddResult(Result(M->first,
2735 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002736 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002737 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002738 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002739
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002740 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002741
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002742}
2743
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002744static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2745 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002746 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002747
2748 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002749
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002750 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2751 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2752 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2753 Results.AddResult(Result("__func__", CCP_Constant));
2754 Results.ExitScope();
2755}
2756
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002757static void HandleCodeCompleteResults(Sema *S,
2758 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002759 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002760 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002761 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002762 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002763 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002764}
2765
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002766static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2767 Sema::ParserCompletionContext PCC) {
2768 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002769 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002770 return CodeCompletionContext::CCC_TopLevel;
2771
John McCallf312b1e2010-08-26 23:41:50 +00002772 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002773 return CodeCompletionContext::CCC_ClassStructUnion;
2774
John McCallf312b1e2010-08-26 23:41:50 +00002775 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002776 return CodeCompletionContext::CCC_ObjCInterface;
2777
John McCallf312b1e2010-08-26 23:41:50 +00002778 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002779 return CodeCompletionContext::CCC_ObjCImplementation;
2780
John McCallf312b1e2010-08-26 23:41:50 +00002781 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002782 return CodeCompletionContext::CCC_ObjCIvarList;
2783
John McCallf312b1e2010-08-26 23:41:50 +00002784 case Sema::PCC_Template:
2785 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002786 if (S.CurContext->isFileContext())
2787 return CodeCompletionContext::CCC_TopLevel;
2788 else if (S.CurContext->isRecord())
2789 return CodeCompletionContext::CCC_ClassStructUnion;
2790 else
2791 return CodeCompletionContext::CCC_Other;
2792
John McCallf312b1e2010-08-26 23:41:50 +00002793 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002794 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002795
John McCallf312b1e2010-08-26 23:41:50 +00002796 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002797 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2798 S.getLangOptions().ObjC1)
2799 return CodeCompletionContext::CCC_ParenthesizedExpression;
2800 else
2801 return CodeCompletionContext::CCC_Expression;
2802
2803 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002804 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002805 return CodeCompletionContext::CCC_Expression;
2806
John McCallf312b1e2010-08-26 23:41:50 +00002807 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002808 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002809
John McCallf312b1e2010-08-26 23:41:50 +00002810 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002811 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002812
2813 case Sema::PCC_ParenthesizedExpression:
2814 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002815
2816 case Sema::PCC_LocalDeclarationSpecifiers:
2817 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002818 }
2819
2820 return CodeCompletionContext::CCC_Other;
2821}
2822
Douglas Gregorf6961522010-08-27 21:18:54 +00002823/// \brief If we're in a C++ virtual member function, add completion results
2824/// that invoke the functions we override, since it's common to invoke the
2825/// overridden function as well as adding new functionality.
2826///
2827/// \param S The semantic analysis object for which we are generating results.
2828///
2829/// \param InContext This context in which the nested-name-specifier preceding
2830/// the code-completion point
2831static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2832 ResultBuilder &Results) {
2833 // Look through blocks.
2834 DeclContext *CurContext = S.CurContext;
2835 while (isa<BlockDecl>(CurContext))
2836 CurContext = CurContext->getParent();
2837
2838
2839 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2840 if (!Method || !Method->isVirtual())
2841 return;
2842
2843 // We need to have names for all of the parameters, if we're going to
2844 // generate a forwarding call.
2845 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2846 PEnd = Method->param_end();
2847 P != PEnd;
2848 ++P) {
2849 if (!(*P)->getDeclName())
2850 return;
2851 }
2852
2853 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2854 MEnd = Method->end_overridden_methods();
2855 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002856 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002857 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2858 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2859 continue;
2860
2861 // If we need a nested-name-specifier, add one now.
2862 if (!InContext) {
2863 NestedNameSpecifier *NNS
2864 = getRequiredQualification(S.Context, CurContext,
2865 Overridden->getDeclContext());
2866 if (NNS) {
2867 std::string Str;
2868 llvm::raw_string_ostream OS(Str);
2869 NNS->print(OS, S.Context.PrintingPolicy);
Douglas Gregordae68752011-02-01 22:57:45 +00002870 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002871 }
2872 } else if (!InContext->Equals(Overridden->getDeclContext()))
2873 continue;
2874
Douglas Gregordae68752011-02-01 22:57:45 +00002875 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002876 Overridden->getNameAsString()));
2877 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00002878 bool FirstParam = true;
2879 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2880 PEnd = Method->param_end();
2881 P != PEnd; ++P) {
2882 if (FirstParam)
2883 FirstParam = false;
2884 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002885 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00002886
Douglas Gregordae68752011-02-01 22:57:45 +00002887 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002888 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002889 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002890 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2891 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00002892 CCP_SuperCompletion,
2893 CXCursor_CXXMethod));
2894 Results.Ignore(Overridden);
2895 }
2896}
2897
Douglas Gregor01dfea02010-01-10 23:08:15 +00002898void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002899 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002900 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002901 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002902 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002903 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002904
Douglas Gregor01dfea02010-01-10 23:08:15 +00002905 // Determine how to filter results, e.g., so that the names of
2906 // values (functions, enumerators, function templates, etc.) are
2907 // only allowed where we can have an expression.
2908 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002909 case PCC_Namespace:
2910 case PCC_Class:
2911 case PCC_ObjCInterface:
2912 case PCC_ObjCImplementation:
2913 case PCC_ObjCInstanceVariableList:
2914 case PCC_Template:
2915 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002916 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002917 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002918 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2919 break;
2920
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002921 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002922 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002923 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002924 case PCC_ForInit:
2925 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002926 if (WantTypesInContext(CompletionContext, getLangOptions()))
2927 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2928 else
2929 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002930
2931 if (getLangOptions().CPlusPlus)
2932 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002933 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002934
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002935 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002936 // Unfiltered
2937 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002938 }
2939
Douglas Gregor3cdee122010-08-26 16:36:48 +00002940 // If we are in a C++ non-static member function, check the qualifiers on
2941 // the member function to filter/prioritize the results list.
2942 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2943 if (CurMethod->isInstance())
2944 Results.setObjectTypeQualifiers(
2945 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2946
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002947 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002948 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2949 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002950
Douglas Gregorbca403c2010-01-13 23:51:12 +00002951 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002952 Results.ExitScope();
2953
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002954 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00002955 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00002956 case PCC_Expression:
2957 case PCC_Statement:
2958 case PCC_RecoveryInFunction:
2959 if (S->getFnParent())
2960 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2961 break;
2962
2963 case PCC_Namespace:
2964 case PCC_Class:
2965 case PCC_ObjCInterface:
2966 case PCC_ObjCImplementation:
2967 case PCC_ObjCInstanceVariableList:
2968 case PCC_Template:
2969 case PCC_MemberTemplate:
2970 case PCC_ForInit:
2971 case PCC_Condition:
2972 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002973 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00002974 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002975 }
2976
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002977 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002978 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002979
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002980 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002981 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002982}
2983
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002984static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
2985 ParsedType Receiver,
2986 IdentifierInfo **SelIdents,
2987 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00002988 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002989 bool IsSuper,
2990 ResultBuilder &Results);
2991
2992void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
2993 bool AllowNonIdentifiers,
2994 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00002995 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002996 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002997 AllowNestedNameSpecifiers
2998 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2999 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003000 Results.EnterNewScope();
3001
3002 // Type qualifiers can come after names.
3003 Results.AddResult(Result("const"));
3004 Results.AddResult(Result("volatile"));
3005 if (getLangOptions().C99)
3006 Results.AddResult(Result("restrict"));
3007
3008 if (getLangOptions().CPlusPlus) {
3009 if (AllowNonIdentifiers) {
3010 Results.AddResult(Result("operator"));
3011 }
3012
3013 // Add nested-name-specifiers.
3014 if (AllowNestedNameSpecifiers) {
3015 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003016 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003017 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3018 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3019 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003020 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003021 }
3022 }
3023 Results.ExitScope();
3024
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003025 // If we're in a context where we might have an expression (rather than a
3026 // declaration), and what we've seen so far is an Objective-C type that could
3027 // be a receiver of a class message, this may be a class message send with
3028 // the initial opening bracket '[' missing. Add appropriate completions.
3029 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3030 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3031 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3032 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3033 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3034 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3035 DS.getTypeQualifiers() == 0 &&
3036 S &&
3037 (S->getFlags() & Scope::DeclScope) != 0 &&
3038 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3039 Scope::FunctionPrototypeScope |
3040 Scope::AtCatchScope)) == 0) {
3041 ParsedType T = DS.getRepAsType();
3042 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003043 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003044 }
3045
Douglas Gregor4497dd42010-08-24 04:59:56 +00003046 // Note that we intentionally suppress macro results here, since we do not
3047 // encourage using macros to produce the names of entities.
3048
Douglas Gregor52779fb2010-09-23 23:01:17 +00003049 HandleCodeCompleteResults(this, CodeCompleter,
3050 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003051 Results.data(), Results.size());
3052}
3053
Douglas Gregorfb629412010-08-23 21:17:50 +00003054struct Sema::CodeCompleteExpressionData {
3055 CodeCompleteExpressionData(QualType PreferredType = QualType())
3056 : PreferredType(PreferredType), IntegralConstantExpression(false),
3057 ObjCCollection(false) { }
3058
3059 QualType PreferredType;
3060 bool IntegralConstantExpression;
3061 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003062 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003063};
3064
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003065/// \brief Perform code-completion in an expression context when we know what
3066/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003067///
3068/// \param IntegralConstantExpression Only permit integral constant
3069/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003070void Sema::CodeCompleteExpression(Scope *S,
3071 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003072 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003073 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3074 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003075 if (Data.ObjCCollection)
3076 Results.setFilter(&ResultBuilder::IsObjCCollection);
3077 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003078 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003079 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003080 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3081 else
3082 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003083
3084 if (!Data.PreferredType.isNull())
3085 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3086
3087 // Ignore any declarations that we were told that we don't care about.
3088 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3089 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003090
3091 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003092 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3093 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003094
3095 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003096 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003097 Results.ExitScope();
3098
Douglas Gregor590c7d52010-07-08 20:55:51 +00003099 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003100 if (!Data.PreferredType.isNull())
3101 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3102 || Data.PreferredType->isMemberPointerType()
3103 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003104
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003105 if (S->getFnParent() &&
3106 !Data.ObjCCollection &&
3107 !Data.IntegralConstantExpression)
3108 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3109
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003110 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003111 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003112 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003113 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3114 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003115 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003116}
3117
Douglas Gregorac5fd842010-09-18 01:28:11 +00003118void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3119 if (E.isInvalid())
3120 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3121 else if (getLangOptions().ObjC1)
3122 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003123}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003124
Douglas Gregor73449212010-12-09 23:01:55 +00003125/// \brief The set of properties that have already been added, referenced by
3126/// property name.
3127typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3128
Douglas Gregor95ac6552009-11-18 01:29:26 +00003129static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003130 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003131 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003132 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003133 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003134 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003135 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003136
3137 // Add properties in this container.
3138 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3139 PEnd = Container->prop_end();
3140 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003141 ++P) {
3142 if (AddedProperties.insert(P->getIdentifier()))
3143 Results.MaybeAddResult(Result(*P, 0), CurContext);
3144 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003145
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003146 // Add nullary methods
3147 if (AllowNullaryMethods) {
3148 ASTContext &Context = Container->getASTContext();
3149 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3150 MEnd = Container->meth_end();
3151 M != MEnd; ++M) {
3152 if (M->getSelector().isUnarySelector())
3153 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3154 if (AddedProperties.insert(Name)) {
3155 CodeCompletionBuilder Builder(Results.getAllocator());
3156 AddResultTypeChunk(Context, *M, Builder);
3157 Builder.AddTypedTextChunk(
3158 Results.getAllocator().CopyString(Name->getName()));
3159
3160 CXAvailabilityKind Availability = CXAvailability_Available;
3161 switch (M->getAvailability()) {
3162 case AR_Available:
3163 case AR_NotYetIntroduced:
3164 Availability = CXAvailability_Available;
3165 break;
3166
3167 case AR_Deprecated:
3168 Availability = CXAvailability_Deprecated;
3169 break;
3170
3171 case AR_Unavailable:
3172 Availability = CXAvailability_NotAvailable;
3173 break;
3174 }
3175
3176 Results.MaybeAddResult(Result(Builder.TakeString(),
3177 CCP_MemberDeclaration + CCD_MethodAsProperty,
3178 M->isInstanceMethod()
3179 ? CXCursor_ObjCInstanceMethodDecl
3180 : CXCursor_ObjCClassMethodDecl,
3181 Availability),
3182 CurContext);
3183 }
3184 }
3185 }
3186
3187
Douglas Gregor95ac6552009-11-18 01:29:26 +00003188 // Add properties in referenced protocols.
3189 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3190 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3191 PEnd = Protocol->protocol_end();
3192 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003193 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3194 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003195 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003196 if (AllowCategories) {
3197 // Look through categories.
3198 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3199 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003200 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3201 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003202 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003203
3204 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003205 for (ObjCInterfaceDecl::all_protocol_iterator
3206 I = IFace->all_referenced_protocol_begin(),
3207 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003208 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3209 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003210
3211 // Look in the superclass.
3212 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003213 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3214 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003215 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003216 } else if (const ObjCCategoryDecl *Category
3217 = dyn_cast<ObjCCategoryDecl>(Container)) {
3218 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003219 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3220 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003221 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003222 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3223 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003224 }
3225}
3226
Douglas Gregor81b747b2009-09-17 21:32:03 +00003227void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
3228 SourceLocation OpLoc,
3229 bool IsArrow) {
3230 if (!BaseE || !CodeCompleter)
3231 return;
3232
John McCall0a2c5e22010-08-25 06:19:51 +00003233 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003234
Douglas Gregor81b747b2009-09-17 21:32:03 +00003235 Expr *Base = static_cast<Expr *>(BaseE);
3236 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003237
3238 if (IsArrow) {
3239 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3240 BaseType = Ptr->getPointeeType();
3241 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003242 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003243 else
3244 return;
3245 }
3246
Douglas Gregor3da626b2011-07-07 16:03:39 +00003247 enum CodeCompletionContext::Kind contextKind;
3248
3249 if (IsArrow) {
3250 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3251 }
3252 else {
3253 if (BaseType->isObjCObjectPointerType() ||
3254 BaseType->isObjCObjectOrInterfaceType()) {
3255 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3256 }
3257 else {
3258 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3259 }
3260 }
3261
Douglas Gregor218937c2011-02-01 19:23:04 +00003262 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003263 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003264 BaseType),
3265 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003266 Results.EnterNewScope();
3267 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003268 // Indicate that we are performing a member access, and the cv-qualifiers
3269 // for the base object type.
3270 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3271
Douglas Gregor95ac6552009-11-18 01:29:26 +00003272 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003273 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003274 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003275 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3276 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003277
Douglas Gregor95ac6552009-11-18 01:29:26 +00003278 if (getLangOptions().CPlusPlus) {
3279 if (!Results.empty()) {
3280 // The "template" keyword can follow "->" or "." in the grammar.
3281 // However, we only want to suggest the template keyword if something
3282 // is dependent.
3283 bool IsDependent = BaseType->isDependentType();
3284 if (!IsDependent) {
3285 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3286 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3287 IsDependent = Ctx->isDependentContext();
3288 break;
3289 }
3290 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003291
Douglas Gregor95ac6552009-11-18 01:29:26 +00003292 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003293 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003294 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003295 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003296 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3297 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003298 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003299
3300 // Add property results based on our interface.
3301 const ObjCObjectPointerType *ObjCPtr
3302 = BaseType->getAsObjCInterfacePointerType();
3303 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003304 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3305 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003306 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003307
3308 // Add properties from the protocols in a qualified interface.
3309 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3310 E = ObjCPtr->qual_end();
3311 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003312 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3313 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003314 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003315 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003316 // Objective-C instance variable access.
3317 ObjCInterfaceDecl *Class = 0;
3318 if (const ObjCObjectPointerType *ObjCPtr
3319 = BaseType->getAs<ObjCObjectPointerType>())
3320 Class = ObjCPtr->getInterfaceDecl();
3321 else
John McCallc12c5bb2010-05-15 11:32:37 +00003322 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003323
3324 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003325 if (Class) {
3326 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3327 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003328 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3329 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003330 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003331 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003332
3333 // FIXME: How do we cope with isa?
3334
3335 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003336
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003337 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003338 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003339 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003340 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003341}
3342
Douglas Gregor374929f2009-09-18 15:37:17 +00003343void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3344 if (!CodeCompleter)
3345 return;
3346
John McCall0a2c5e22010-08-25 06:19:51 +00003347 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003348 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003349 enum CodeCompletionContext::Kind ContextKind
3350 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003351 switch ((DeclSpec::TST)TagSpec) {
3352 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003353 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003354 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003355 break;
3356
3357 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003358 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003359 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003360 break;
3361
3362 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003363 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003364 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003365 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003366 break;
3367
3368 default:
3369 assert(false && "Unknown type specifier kind in CodeCompleteTag");
3370 return;
3371 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003372
Douglas Gregor218937c2011-02-01 19:23:04 +00003373 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003374 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003375
3376 // First pass: look for tags.
3377 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003378 LookupVisibleDecls(S, LookupTagName, Consumer,
3379 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003380
Douglas Gregor8071e422010-08-15 06:18:01 +00003381 if (CodeCompleter->includeGlobals()) {
3382 // Second pass: look for nested name specifiers.
3383 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3384 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3385 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003386
Douglas Gregor52779fb2010-09-23 23:01:17 +00003387 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003388 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003389}
3390
Douglas Gregor1a480c42010-08-27 17:35:51 +00003391void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003392 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3393 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003394 Results.EnterNewScope();
3395 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3396 Results.AddResult("const");
3397 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3398 Results.AddResult("volatile");
3399 if (getLangOptions().C99 &&
3400 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3401 Results.AddResult("restrict");
3402 Results.ExitScope();
3403 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003404 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003405 Results.data(), Results.size());
3406}
3407
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003408void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003409 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003410 return;
3411
John McCall781472f2010-08-25 08:40:02 +00003412 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregorf9578432010-07-28 21:50:18 +00003413 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregorfb629412010-08-23 21:17:50 +00003414 CodeCompleteExpressionData Data(Switch->getCond()->getType());
3415 Data.IntegralConstantExpression = true;
3416 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003417 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003418 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003419
3420 // Code-complete the cases of a switch statement over an enumeration type
3421 // by providing the list of
3422 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
3423
3424 // Determine which enumerators we have already seen in the switch statement.
3425 // FIXME: Ideally, we would also be able to look *past* the code-completion
3426 // token, in case we are code-completing in the middle of the switch and not
3427 // at the end. However, we aren't able to do so at the moment.
3428 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003429 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003430 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3431 SC = SC->getNextSwitchCase()) {
3432 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3433 if (!Case)
3434 continue;
3435
3436 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3437 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3438 if (EnumConstantDecl *Enumerator
3439 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3440 // We look into the AST of the case statement to determine which
3441 // enumerator was named. Alternatively, we could compute the value of
3442 // the integral constant expression, then compare it against the
3443 // values of each enumerator. However, value-based approach would not
3444 // work as well with C++ templates where enumerators declared within a
3445 // template are type- and value-dependent.
3446 EnumeratorsSeen.insert(Enumerator);
3447
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003448 // If this is a qualified-id, keep track of the nested-name-specifier
3449 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003450 //
3451 // switch (TagD.getKind()) {
3452 // case TagDecl::TK_enum:
3453 // break;
3454 // case XXX
3455 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003456 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003457 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3458 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003459 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003460 }
3461 }
3462
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003463 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3464 // If there are no prior enumerators in C++, check whether we have to
3465 // qualify the names of the enumerators that we suggest, because they
3466 // may not be visible in this scope.
3467 Qualifier = getRequiredQualification(Context, CurContext,
3468 Enum->getDeclContext());
3469
3470 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3471 }
3472
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003473 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003474 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3475 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003476 Results.EnterNewScope();
3477 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3478 EEnd = Enum->enumerator_end();
3479 E != EEnd; ++E) {
3480 if (EnumeratorsSeen.count(*E))
3481 continue;
3482
Douglas Gregor5c722c702011-02-18 23:30:37 +00003483 CodeCompletionResult R(*E, Qualifier);
3484 R.Priority = CCP_EnumInCase;
3485 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003486 }
3487 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003488
Douglas Gregor3da626b2011-07-07 16:03:39 +00003489 //We need to make sure we're setting the right context,
3490 //so only say we include macros if the code completer says we do
3491 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3492 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003493 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003494 kind = CodeCompletionContext::CCC_OtherWithMacros;
3495 }
3496
3497
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003498 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003499 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003500 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003501}
3502
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003503namespace {
3504 struct IsBetterOverloadCandidate {
3505 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003506 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003507
3508 public:
John McCall5769d612010-02-08 23:07:23 +00003509 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3510 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003511
3512 bool
3513 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003514 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003515 }
3516 };
3517}
3518
Douglas Gregord28dcd72010-05-30 06:10:08 +00003519static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3520 if (NumArgs && !Args)
3521 return true;
3522
3523 for (unsigned I = 0; I != NumArgs; ++I)
3524 if (!Args[I])
3525 return true;
3526
3527 return false;
3528}
3529
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003530void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
3531 ExprTy **ArgsIn, unsigned NumArgs) {
3532 if (!CodeCompleter)
3533 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003534
3535 // When we're code-completing for a call, we fall back to ordinary
3536 // name code-completion whenever we can't produce specific
3537 // results. We may want to revisit this strategy in the future,
3538 // e.g., by merging the two kinds of results.
3539
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003540 Expr *Fn = (Expr *)FnIn;
3541 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003542
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003543 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003544 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003545 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003546 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003547 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003548 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003549
John McCall3b4294e2009-12-16 12:17:52 +00003550 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003551 SourceLocation Loc = Fn->getExprLoc();
3552 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003553
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003554 // FIXME: What if we're calling something that isn't a function declaration?
3555 // FIXME: What if we're calling a pseudo-destructor?
3556 // FIXME: What if we're calling a member function?
3557
Douglas Gregorc0265402010-01-21 15:46:19 +00003558 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003559 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003560
John McCall3b4294e2009-12-16 12:17:52 +00003561 Expr *NakedFn = Fn->IgnoreParenCasts();
3562 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3563 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3564 /*PartialOverloading=*/ true);
3565 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3566 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003567 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003568 if (!getLangOptions().CPlusPlus ||
3569 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003570 Results.push_back(ResultCandidate(FDecl));
3571 else
John McCall86820f52010-01-26 01:37:31 +00003572 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003573 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3574 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003575 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003576 }
John McCall3b4294e2009-12-16 12:17:52 +00003577 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003578
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003579 QualType ParamType;
3580
Douglas Gregorc0265402010-01-21 15:46:19 +00003581 if (!CandidateSet.empty()) {
3582 // Sort the overload candidate set by placing the best overloads first.
3583 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003584 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003585
Douglas Gregorc0265402010-01-21 15:46:19 +00003586 // Add the remaining viable overload candidates as code-completion reslults.
3587 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3588 CandEnd = CandidateSet.end();
3589 Cand != CandEnd; ++Cand) {
3590 if (Cand->Viable)
3591 Results.push_back(ResultCandidate(Cand->Function));
3592 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003593
3594 // From the viable candidates, try to determine the type of this parameter.
3595 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3596 if (const FunctionType *FType = Results[I].getFunctionType())
3597 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3598 if (NumArgs < Proto->getNumArgs()) {
3599 if (ParamType.isNull())
3600 ParamType = Proto->getArgType(NumArgs);
3601 else if (!Context.hasSameUnqualifiedType(
3602 ParamType.getNonReferenceType(),
3603 Proto->getArgType(NumArgs).getNonReferenceType())) {
3604 ParamType = QualType();
3605 break;
3606 }
3607 }
3608 }
3609 } else {
3610 // Try to determine the parameter type from the type of the expression
3611 // being called.
3612 QualType FunctionType = Fn->getType();
3613 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3614 FunctionType = Ptr->getPointeeType();
3615 else if (const BlockPointerType *BlockPtr
3616 = FunctionType->getAs<BlockPointerType>())
3617 FunctionType = BlockPtr->getPointeeType();
3618 else if (const MemberPointerType *MemPtr
3619 = FunctionType->getAs<MemberPointerType>())
3620 FunctionType = MemPtr->getPointeeType();
3621
3622 if (const FunctionProtoType *Proto
3623 = FunctionType->getAs<FunctionProtoType>()) {
3624 if (NumArgs < Proto->getNumArgs())
3625 ParamType = Proto->getArgType(NumArgs);
3626 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003627 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003628
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003629 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003630 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003631 else
3632 CodeCompleteExpression(S, ParamType);
3633
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003634 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003635 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3636 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003637}
3638
John McCalld226f652010-08-21 09:40:31 +00003639void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3640 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003641 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003642 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003643 return;
3644 }
3645
3646 CodeCompleteExpression(S, VD->getType());
3647}
3648
3649void Sema::CodeCompleteReturn(Scope *S) {
3650 QualType ResultType;
3651 if (isa<BlockDecl>(CurContext)) {
3652 if (BlockScopeInfo *BSI = getCurBlock())
3653 ResultType = BSI->ReturnType;
3654 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3655 ResultType = Function->getResultType();
3656 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3657 ResultType = Method->getResultType();
3658
3659 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003660 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003661 else
3662 CodeCompleteExpression(S, ResultType);
3663}
3664
3665void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3666 if (LHS)
3667 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3668 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003669 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003670}
3671
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003672void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003673 bool EnteringContext) {
3674 if (!SS.getScopeRep() || !CodeCompleter)
3675 return;
3676
Douglas Gregor86d9a522009-09-21 16:56:56 +00003677 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3678 if (!Ctx)
3679 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003680
3681 // Try to instantiate any non-dependent declaration contexts before
3682 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003683 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003684 return;
3685
Douglas Gregor218937c2011-02-01 19:23:04 +00003686 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3687 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003688 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003689
Douglas Gregor86d9a522009-09-21 16:56:56 +00003690 // The "template" keyword can follow "::" in the grammar, but only
3691 // put it into the grammar if the nested-name-specifier is dependent.
3692 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3693 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003694 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003695
3696 // Add calls to overridden virtual functions, if there are any.
3697 //
3698 // FIXME: This isn't wonderful, because we don't know whether we're actually
3699 // in a context that permits expressions. This is a general issue with
3700 // qualified-id completions.
3701 if (!EnteringContext)
3702 MaybeAddOverrideCalls(*this, Ctx, Results);
3703 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003704
Douglas Gregorf6961522010-08-27 21:18:54 +00003705 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3706 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3707
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003708 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003709 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003710 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003711}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003712
3713void Sema::CodeCompleteUsing(Scope *S) {
3714 if (!CodeCompleter)
3715 return;
3716
Douglas Gregor218937c2011-02-01 19:23:04 +00003717 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003718 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3719 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003720 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003721
3722 // If we aren't in class scope, we could see the "namespace" keyword.
3723 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003724 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003725
3726 // After "using", we can see anything that would start a
3727 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003728 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003729 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3730 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003731 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003732
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003733 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003734 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003735 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003736}
3737
3738void Sema::CodeCompleteUsingDirective(Scope *S) {
3739 if (!CodeCompleter)
3740 return;
3741
Douglas Gregor86d9a522009-09-21 16:56:56 +00003742 // After "using namespace", we expect to see a namespace name or namespace
3743 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003744 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3745 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003746 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003747 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003748 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003749 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3750 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003751 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003752 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003753 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003754 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003755}
3756
3757void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3758 if (!CodeCompleter)
3759 return;
3760
Douglas Gregor86d9a522009-09-21 16:56:56 +00003761 DeclContext *Ctx = (DeclContext *)S->getEntity();
3762 if (!S->getParent())
3763 Ctx = Context.getTranslationUnitDecl();
3764
Douglas Gregor52779fb2010-09-23 23:01:17 +00003765 bool SuppressedGlobalResults
3766 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3767
Douglas Gregor218937c2011-02-01 19:23:04 +00003768 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003769 SuppressedGlobalResults
3770 ? CodeCompletionContext::CCC_Namespace
3771 : CodeCompletionContext::CCC_Other,
3772 &ResultBuilder::IsNamespace);
3773
3774 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003775 // We only want to see those namespaces that have already been defined
3776 // within this scope, because its likely that the user is creating an
3777 // extended namespace declaration. Keep track of the most recent
3778 // definition of each namespace.
3779 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3780 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3781 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3782 NS != NSEnd; ++NS)
3783 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3784
3785 // Add the most recent definition (or extended definition) of each
3786 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003787 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003788 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3789 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3790 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003791 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003792 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003793 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003794 }
3795
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003796 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003797 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003798 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003799}
3800
3801void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3802 if (!CodeCompleter)
3803 return;
3804
Douglas Gregor86d9a522009-09-21 16:56:56 +00003805 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003806 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3807 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003808 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003809 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003810 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3811 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003812 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003813 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003814 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003815}
3816
Douglas Gregored8d3222009-09-18 20:05:18 +00003817void Sema::CodeCompleteOperatorName(Scope *S) {
3818 if (!CodeCompleter)
3819 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003820
John McCall0a2c5e22010-08-25 06:19:51 +00003821 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003822 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3823 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003824 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003825 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003826
Douglas Gregor86d9a522009-09-21 16:56:56 +00003827 // Add the names of overloadable operators.
3828#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3829 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003830 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003831#include "clang/Basic/OperatorKinds.def"
3832
3833 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003834 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003835 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003836 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3837 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003838
3839 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003840 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003841 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003842
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003843 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003844 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003845 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003846}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003847
Douglas Gregor0133f522010-08-28 00:00:50 +00003848void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00003849 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00003850 unsigned NumInitializers) {
John McCallf85e1932011-06-15 23:02:42 +00003851 PrintingPolicy Policy(Context.PrintingPolicy);
3852 Policy.AnonymousTagLocations = false;
3853 Policy.SuppressStrongLifetime = true;
3854
Douglas Gregor0133f522010-08-28 00:00:50 +00003855 CXXConstructorDecl *Constructor
3856 = static_cast<CXXConstructorDecl *>(ConstructorD);
3857 if (!Constructor)
3858 return;
3859
Douglas Gregor218937c2011-02-01 19:23:04 +00003860 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003861 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003862 Results.EnterNewScope();
3863
3864 // Fill in any already-initialized fields or base classes.
3865 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3866 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3867 for (unsigned I = 0; I != NumInitializers; ++I) {
3868 if (Initializers[I]->isBaseInitializer())
3869 InitializedBases.insert(
3870 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3871 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003872 InitializedFields.insert(cast<FieldDecl>(
3873 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00003874 }
3875
3876 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00003877 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00003878 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003879 CXXRecordDecl *ClassDecl = Constructor->getParent();
3880 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3881 BaseEnd = ClassDecl->bases_end();
3882 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003883 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3884 SawLastInitializer
3885 = NumInitializers > 0 &&
3886 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3887 Context.hasSameUnqualifiedType(Base->getType(),
3888 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003889 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003890 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003891
Douglas Gregor218937c2011-02-01 19:23:04 +00003892 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003893 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00003894 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00003895 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3896 Builder.AddPlaceholderChunk("args");
3897 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3898 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003899 SawLastInitializer? CCP_NextInitializer
3900 : CCP_MemberDeclaration));
3901 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003902 }
3903
3904 // Add completions for virtual base classes.
3905 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3906 BaseEnd = ClassDecl->vbases_end();
3907 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003908 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3909 SawLastInitializer
3910 = NumInitializers > 0 &&
3911 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3912 Context.hasSameUnqualifiedType(Base->getType(),
3913 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003914 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003915 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003916
Douglas Gregor218937c2011-02-01 19:23:04 +00003917 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003918 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00003919 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00003920 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3921 Builder.AddPlaceholderChunk("args");
3922 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3923 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003924 SawLastInitializer? CCP_NextInitializer
3925 : CCP_MemberDeclaration));
3926 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003927 }
3928
3929 // Add completions for members.
3930 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3931 FieldEnd = ClassDecl->field_end();
3932 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003933 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
3934 SawLastInitializer
3935 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00003936 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
3937 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00003938 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003939 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003940
3941 if (!Field->getDeclName())
3942 continue;
3943
Douglas Gregordae68752011-02-01 22:57:45 +00003944 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003945 Field->getIdentifier()->getName()));
3946 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3947 Builder.AddPlaceholderChunk("args");
3948 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3949 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003950 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00003951 : CCP_MemberDeclaration,
3952 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00003953 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003954 }
3955 Results.ExitScope();
3956
Douglas Gregor52779fb2010-09-23 23:01:17 +00003957 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00003958 Results.data(), Results.size());
3959}
3960
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003961// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3962// true or false.
3963#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00003964static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003965 ResultBuilder &Results,
3966 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003967 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003968 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003969 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003970
Douglas Gregor218937c2011-02-01 19:23:04 +00003971 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003972 if (LangOpts.ObjC2) {
3973 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00003974 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3975 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3976 Builder.AddPlaceholderChunk("property");
3977 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003978
3979 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00003980 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3981 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3982 Builder.AddPlaceholderChunk("property");
3983 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003984 }
3985}
3986
Douglas Gregorbca403c2010-01-13 23:51:12 +00003987static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003988 ResultBuilder &Results,
3989 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003990 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003991
3992 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003993 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003994
3995 if (LangOpts.ObjC2) {
3996 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00003997 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003998
3999 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004000 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004001
4002 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004003 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004004 }
4005}
4006
Douglas Gregorbca403c2010-01-13 23:51:12 +00004007static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004008 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004009 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004010
4011 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004012 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4013 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4014 Builder.AddPlaceholderChunk("name");
4015 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004016
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004017 if (Results.includeCodePatterns()) {
4018 // @interface name
4019 // FIXME: Could introduce the whole pattern, including superclasses and
4020 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004021 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4022 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4023 Builder.AddPlaceholderChunk("class");
4024 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004025
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004026 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004027 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4028 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4029 Builder.AddPlaceholderChunk("protocol");
4030 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004031
4032 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004033 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4034 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4035 Builder.AddPlaceholderChunk("class");
4036 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004037 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004038
4039 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004040 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4041 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4042 Builder.AddPlaceholderChunk("alias");
4043 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4044 Builder.AddPlaceholderChunk("class");
4045 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004046}
4047
John McCalld226f652010-08-21 09:40:31 +00004048void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorc464ae82009-12-07 09:27:33 +00004049 bool InInterface) {
John McCall0a2c5e22010-08-25 06:19:51 +00004050 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004051 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4052 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004053 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004054 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00004055 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004056 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00004057 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004058 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004059 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004060 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004061 HandleCodeCompleteResults(this, CodeCompleter,
4062 CodeCompletionContext::CCC_Other,
4063 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004064}
4065
Douglas Gregorbca403c2010-01-13 23:51:12 +00004066static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004067 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004068 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004069
4070 // @encode ( type-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004071 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4072 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4073 Builder.AddPlaceholderChunk("type-name");
4074 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4075 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004076
4077 // @protocol ( protocol-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004078 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4079 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4080 Builder.AddPlaceholderChunk("protocol-name");
4081 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4082 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004083
4084 // @selector ( selector )
Douglas Gregor218937c2011-02-01 19:23:04 +00004085 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4086 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4087 Builder.AddPlaceholderChunk("selector");
4088 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4089 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004090}
4091
Douglas Gregorbca403c2010-01-13 23:51:12 +00004092static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004093 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004094 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004095
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004096 if (Results.includeCodePatterns()) {
4097 // @try { statements } @catch ( declaration ) { statements } @finally
4098 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004099 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4100 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4101 Builder.AddPlaceholderChunk("statements");
4102 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4103 Builder.AddTextChunk("@catch");
4104 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4105 Builder.AddPlaceholderChunk("parameter");
4106 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4107 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4108 Builder.AddPlaceholderChunk("statements");
4109 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4110 Builder.AddTextChunk("@finally");
4111 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4112 Builder.AddPlaceholderChunk("statements");
4113 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4114 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004115 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004116
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004117 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004118 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4119 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4120 Builder.AddPlaceholderChunk("expression");
4121 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004122
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004123 if (Results.includeCodePatterns()) {
4124 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004125 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4126 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4127 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4128 Builder.AddPlaceholderChunk("expression");
4129 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4130 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4131 Builder.AddPlaceholderChunk("statements");
4132 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4133 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004134 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004135}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004136
Douglas Gregorbca403c2010-01-13 23:51:12 +00004137static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004138 ResultBuilder &Results,
4139 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004140 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004141 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4142 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4143 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004144 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004145 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004146}
4147
4148void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004149 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4150 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004151 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004152 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004153 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004154 HandleCodeCompleteResults(this, CodeCompleter,
4155 CodeCompletionContext::CCC_Other,
4156 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004157}
4158
4159void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004160 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4161 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004162 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004163 AddObjCStatementResults(Results, false);
4164 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004165 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004166 HandleCodeCompleteResults(this, CodeCompleter,
4167 CodeCompletionContext::CCC_Other,
4168 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004169}
4170
4171void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004172 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4173 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004174 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004175 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004176 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004177 HandleCodeCompleteResults(this, CodeCompleter,
4178 CodeCompletionContext::CCC_Other,
4179 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004180}
4181
Douglas Gregor988358f2009-11-19 00:14:45 +00004182/// \brief Determine whether the addition of the given flag to an Objective-C
4183/// property's attributes will cause a conflict.
4184static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4185 // Check if we've already added this flag.
4186 if (Attributes & NewFlag)
4187 return true;
4188
4189 Attributes |= NewFlag;
4190
4191 // Check for collisions with "readonly".
4192 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4193 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4194 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004195 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004196 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004197 ObjCDeclSpec::DQ_PR_retain |
4198 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004199 return true;
4200
John McCallf85e1932011-06-15 23:02:42 +00004201 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004202 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004203 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004204 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004205 ObjCDeclSpec::DQ_PR_retain|
4206 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004207 if (AssignCopyRetMask &&
4208 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004209 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004210 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004211 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4212 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004213 return true;
4214
4215 return false;
4216}
4217
Douglas Gregora93b1082009-11-18 23:08:07 +00004218void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004219 if (!CodeCompleter)
4220 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004221
Steve Naroffece8e712009-10-08 21:55:05 +00004222 unsigned Attributes = ODS.getPropertyAttributes();
4223
John McCall0a2c5e22010-08-25 06:19:51 +00004224 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004225 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4226 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004227 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004228 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004229 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004230 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004231 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004232 if (!ObjCPropertyFlagConflicts(Attributes,
4233 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4234 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004235 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004236 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004237 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004238 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004239 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4240 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004241 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004242 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004243 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004244 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004245 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4246 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004247 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004248 CodeCompletionBuilder Setter(Results.getAllocator());
4249 Setter.AddTypedTextChunk("setter");
4250 Setter.AddTextChunk(" = ");
4251 Setter.AddPlaceholderChunk("method");
4252 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004253 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004254 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004255 CodeCompletionBuilder Getter(Results.getAllocator());
4256 Getter.AddTypedTextChunk("getter");
4257 Getter.AddTextChunk(" = ");
4258 Getter.AddPlaceholderChunk("method");
4259 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004260 }
Steve Naroffece8e712009-10-08 21:55:05 +00004261 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004262 HandleCodeCompleteResults(this, CodeCompleter,
4263 CodeCompletionContext::CCC_Other,
4264 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004265}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004266
Douglas Gregor4ad96852009-11-19 07:41:15 +00004267/// \brief Descripts the kind of Objective-C method that we want to find
4268/// via code completion.
4269enum ObjCMethodKind {
4270 MK_Any, //< Any kind of method, provided it means other specified criteria.
4271 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4272 MK_OneArgSelector //< One-argument selector.
4273};
4274
Douglas Gregor458433d2010-08-26 15:07:07 +00004275static bool isAcceptableObjCSelector(Selector Sel,
4276 ObjCMethodKind WantKind,
4277 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004278 unsigned NumSelIdents,
4279 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004280 if (NumSelIdents > Sel.getNumArgs())
4281 return false;
4282
4283 switch (WantKind) {
4284 case MK_Any: break;
4285 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4286 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4287 }
4288
Douglas Gregorcf544262010-11-17 21:36:08 +00004289 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4290 return false;
4291
Douglas Gregor458433d2010-08-26 15:07:07 +00004292 for (unsigned I = 0; I != NumSelIdents; ++I)
4293 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4294 return false;
4295
4296 return true;
4297}
4298
Douglas Gregor4ad96852009-11-19 07:41:15 +00004299static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4300 ObjCMethodKind WantKind,
4301 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004302 unsigned NumSelIdents,
4303 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004304 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004305 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004306}
Douglas Gregord36adf52010-09-16 16:06:31 +00004307
4308namespace {
4309 /// \brief A set of selectors, which is used to avoid introducing multiple
4310 /// completions with the same selector into the result set.
4311 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4312}
4313
Douglas Gregor36ecb042009-11-17 23:22:23 +00004314/// \brief Add all of the Objective-C methods in the given Objective-C
4315/// container to the set of results.
4316///
4317/// The container will be a class, protocol, category, or implementation of
4318/// any of the above. This mether will recurse to include methods from
4319/// the superclasses of classes along with their categories, protocols, and
4320/// implementations.
4321///
4322/// \param Container the container in which we'll look to find methods.
4323///
4324/// \param WantInstance whether to add instance methods (only); if false, this
4325/// routine will add factory methods (only).
4326///
4327/// \param CurContext the context in which we're performing the lookup that
4328/// finds methods.
4329///
Douglas Gregorcf544262010-11-17 21:36:08 +00004330/// \param AllowSameLength Whether we allow a method to be added to the list
4331/// when it has the same number of parameters as we have selector identifiers.
4332///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004333/// \param Results the structure into which we'll add results.
4334static void AddObjCMethods(ObjCContainerDecl *Container,
4335 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004336 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004337 IdentifierInfo **SelIdents,
4338 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004339 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004340 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004341 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004342 ResultBuilder &Results,
4343 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004344 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004345 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4346 MEnd = Container->meth_end();
4347 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004348 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4349 // Check whether the selector identifiers we've been given are a
4350 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004351 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4352 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004353 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004354
Douglas Gregord36adf52010-09-16 16:06:31 +00004355 if (!Selectors.insert((*M)->getSelector()))
4356 continue;
4357
Douglas Gregord3c68542009-11-19 01:08:35 +00004358 Result R = Result(*M, 0);
4359 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004360 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004361 if (!InOriginalClass)
4362 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004363 Results.MaybeAddResult(R, CurContext);
4364 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004365 }
4366
Douglas Gregore396c7b2010-09-16 15:34:59 +00004367 // Visit the protocols of protocols.
4368 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4369 const ObjCList<ObjCProtocolDecl> &Protocols
4370 = Protocol->getReferencedProtocols();
4371 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4372 E = Protocols.end();
4373 I != E; ++I)
4374 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004375 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004376 }
4377
Douglas Gregor36ecb042009-11-17 23:22:23 +00004378 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4379 if (!IFace)
4380 return;
4381
4382 // Add methods in protocols.
4383 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4384 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4385 E = Protocols.end();
4386 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004387 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004388 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004389
4390 // Add methods in categories.
4391 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4392 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004393 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004394 NumSelIdents, CurContext, Selectors, AllowSameLength,
4395 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004396
4397 // Add a categories protocol methods.
4398 const ObjCList<ObjCProtocolDecl> &Protocols
4399 = CatDecl->getReferencedProtocols();
4400 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4401 E = Protocols.end();
4402 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004403 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004404 NumSelIdents, CurContext, Selectors, AllowSameLength,
4405 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004406
4407 // Add methods in category implementations.
4408 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004409 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004410 NumSelIdents, CurContext, Selectors, AllowSameLength,
4411 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004412 }
4413
4414 // Add methods in superclass.
4415 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004416 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004417 SelIdents, NumSelIdents, CurContext, Selectors,
4418 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004419
4420 // Add methods in our implementation, if any.
4421 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004422 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004423 NumSelIdents, CurContext, Selectors, AllowSameLength,
4424 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004425}
4426
4427
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004428void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004429 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004430
4431 // Try to find the interface where getters might live.
John McCalld226f652010-08-21 09:40:31 +00004432 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004433 if (!Class) {
4434 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004435 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004436 Class = Category->getClassInterface();
4437
4438 if (!Class)
4439 return;
4440 }
4441
4442 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004443 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4444 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004445 Results.EnterNewScope();
4446
Douglas Gregord36adf52010-09-16 16:06:31 +00004447 VisitedSelectorSet Selectors;
4448 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004449 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004450 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004451 HandleCodeCompleteResults(this, CodeCompleter,
4452 CodeCompletionContext::CCC_Other,
4453 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004454}
4455
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004456void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004457 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004458
4459 // Try to find the interface where setters might live.
4460 ObjCInterfaceDecl *Class
John McCalld226f652010-08-21 09:40:31 +00004461 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004462 if (!Class) {
4463 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004464 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004465 Class = Category->getClassInterface();
4466
4467 if (!Class)
4468 return;
4469 }
4470
4471 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004472 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4473 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004474 Results.EnterNewScope();
4475
Douglas Gregord36adf52010-09-16 16:06:31 +00004476 VisitedSelectorSet Selectors;
4477 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004478 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004479
4480 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004481 HandleCodeCompleteResults(this, CodeCompleter,
4482 CodeCompletionContext::CCC_Other,
4483 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004484}
4485
Douglas Gregorafc45782011-02-15 22:19:42 +00004486void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4487 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004488 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004489 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4490 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004491 Results.EnterNewScope();
4492
4493 // Add context-sensitive, Objective-C parameter-passing keywords.
4494 bool AddedInOut = false;
4495 if ((DS.getObjCDeclQualifier() &
4496 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4497 Results.AddResult("in");
4498 Results.AddResult("inout");
4499 AddedInOut = true;
4500 }
4501 if ((DS.getObjCDeclQualifier() &
4502 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4503 Results.AddResult("out");
4504 if (!AddedInOut)
4505 Results.AddResult("inout");
4506 }
4507 if ((DS.getObjCDeclQualifier() &
4508 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4509 ObjCDeclSpec::DQ_Oneway)) == 0) {
4510 Results.AddResult("bycopy");
4511 Results.AddResult("byref");
4512 Results.AddResult("oneway");
4513 }
4514
Douglas Gregorafc45782011-02-15 22:19:42 +00004515 // If we're completing the return type of an Objective-C method and the
4516 // identifier IBAction refers to a macro, provide a completion item for
4517 // an action, e.g.,
4518 // IBAction)<#selector#>:(id)sender
4519 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4520 Context.Idents.get("IBAction").hasMacroDefinition()) {
4521 typedef CodeCompletionString::Chunk Chunk;
4522 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4523 CXAvailability_Available);
4524 Builder.AddTypedTextChunk("IBAction");
4525 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4526 Builder.AddPlaceholderChunk("selector");
4527 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4528 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4529 Builder.AddTextChunk("id");
4530 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4531 Builder.AddTextChunk("sender");
4532 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4533 }
4534
Douglas Gregord32b0222010-08-24 01:06:58 +00004535 // Add various builtin type names and specifiers.
4536 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4537 Results.ExitScope();
4538
4539 // Add the various type names
4540 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4541 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4542 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4543 CodeCompleter->includeGlobals());
4544
4545 if (CodeCompleter->includeMacros())
4546 AddMacroResults(PP, Results);
4547
4548 HandleCodeCompleteResults(this, CodeCompleter,
4549 CodeCompletionContext::CCC_Type,
4550 Results.data(), Results.size());
4551}
4552
Douglas Gregor22f56992010-04-06 19:22:33 +00004553/// \brief When we have an expression with type "id", we may assume
4554/// that it has some more-specific class type based on knowledge of
4555/// common uses of Objective-C. This routine returns that class type,
4556/// or NULL if no better result could be determined.
4557static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004558 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004559 if (!Msg)
4560 return 0;
4561
4562 Selector Sel = Msg->getSelector();
4563 if (Sel.isNull())
4564 return 0;
4565
4566 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4567 if (!Id)
4568 return 0;
4569
4570 ObjCMethodDecl *Method = Msg->getMethodDecl();
4571 if (!Method)
4572 return 0;
4573
4574 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004575 ObjCInterfaceDecl *IFace = 0;
4576 switch (Msg->getReceiverKind()) {
4577 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004578 if (const ObjCObjectType *ObjType
4579 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4580 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004581 break;
4582
4583 case ObjCMessageExpr::Instance: {
4584 QualType T = Msg->getInstanceReceiver()->getType();
4585 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4586 IFace = Ptr->getInterfaceDecl();
4587 break;
4588 }
4589
4590 case ObjCMessageExpr::SuperInstance:
4591 case ObjCMessageExpr::SuperClass:
4592 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004593 }
4594
4595 if (!IFace)
4596 return 0;
4597
4598 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4599 if (Method->isInstanceMethod())
4600 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4601 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004602 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004603 .Case("autorelease", IFace)
4604 .Case("copy", IFace)
4605 .Case("copyWithZone", IFace)
4606 .Case("mutableCopy", IFace)
4607 .Case("mutableCopyWithZone", IFace)
4608 .Case("awakeFromCoder", IFace)
4609 .Case("replacementObjectFromCoder", IFace)
4610 .Case("class", IFace)
4611 .Case("classForCoder", IFace)
4612 .Case("superclass", Super)
4613 .Default(0);
4614
4615 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4616 .Case("new", IFace)
4617 .Case("alloc", IFace)
4618 .Case("allocWithZone", IFace)
4619 .Case("class", IFace)
4620 .Case("superclass", Super)
4621 .Default(0);
4622}
4623
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004624// Add a special completion for a message send to "super", which fills in the
4625// most likely case of forwarding all of our arguments to the superclass
4626// function.
4627///
4628/// \param S The semantic analysis object.
4629///
4630/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4631/// the "super" keyword. Otherwise, we just need to provide the arguments.
4632///
4633/// \param SelIdents The identifiers in the selector that have already been
4634/// provided as arguments for a send to "super".
4635///
4636/// \param NumSelIdents The number of identifiers in \p SelIdents.
4637///
4638/// \param Results The set of results to augment.
4639///
4640/// \returns the Objective-C method declaration that would be invoked by
4641/// this "super" completion. If NULL, no completion was added.
4642static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4643 IdentifierInfo **SelIdents,
4644 unsigned NumSelIdents,
4645 ResultBuilder &Results) {
4646 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4647 if (!CurMethod)
4648 return 0;
4649
4650 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4651 if (!Class)
4652 return 0;
4653
4654 // Try to find a superclass method with the same selector.
4655 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004656 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4657 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004658 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4659 CurMethod->isInstanceMethod());
4660
Douglas Gregor78bcd912011-02-16 00:51:18 +00004661 // Check in categories or class extensions.
4662 if (!SuperMethod) {
4663 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4664 Category = Category->getNextClassCategory())
4665 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4666 CurMethod->isInstanceMethod())))
4667 break;
4668 }
4669 }
4670
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004671 if (!SuperMethod)
4672 return 0;
4673
4674 // Check whether the superclass method has the same signature.
4675 if (CurMethod->param_size() != SuperMethod->param_size() ||
4676 CurMethod->isVariadic() != SuperMethod->isVariadic())
4677 return 0;
4678
4679 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4680 CurPEnd = CurMethod->param_end(),
4681 SuperP = SuperMethod->param_begin();
4682 CurP != CurPEnd; ++CurP, ++SuperP) {
4683 // Make sure the parameter types are compatible.
4684 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4685 (*SuperP)->getType()))
4686 return 0;
4687
4688 // Make sure we have a parameter name to forward!
4689 if (!(*CurP)->getIdentifier())
4690 return 0;
4691 }
4692
4693 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004694 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004695
4696 // Give this completion a return type.
Douglas Gregor218937c2011-02-01 19:23:04 +00004697 AddResultTypeChunk(S.Context, SuperMethod, Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004698
4699 // If we need the "super" keyword, add it (plus some spacing).
4700 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004701 Builder.AddTypedTextChunk("super");
4702 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004703 }
4704
4705 Selector Sel = CurMethod->getSelector();
4706 if (Sel.isUnarySelector()) {
4707 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004708 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004709 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004710 else
Douglas Gregordae68752011-02-01 22:57:45 +00004711 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004712 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004713 } else {
4714 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4715 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4716 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004717 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004718
4719 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004720 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004721 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004722 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004723 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004724 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004725 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004726 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004727 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004728 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004729 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004730 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004731 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004732 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004733 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004734 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004735 }
4736 }
4737 }
4738
Douglas Gregor218937c2011-02-01 19:23:04 +00004739 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004740 SuperMethod->isInstanceMethod()
4741 ? CXCursor_ObjCInstanceMethodDecl
4742 : CXCursor_ObjCClassMethodDecl));
4743 return SuperMethod;
4744}
4745
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004746void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004747 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004748 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4749 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004750 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004751
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004752 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4753 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004754 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4755 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004756
4757 // If we are in an Objective-C method inside a class that has a superclass,
4758 // add "super" as an option.
4759 if (ObjCMethodDecl *Method = getCurMethodDecl())
4760 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004761 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004762 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004763
4764 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4765 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004766
4767 Results.ExitScope();
4768
4769 if (CodeCompleter->includeMacros())
4770 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004771 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004772 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004773
4774}
4775
Douglas Gregor2725ca82010-04-21 19:57:20 +00004776void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4777 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004778 unsigned NumSelIdents,
4779 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004780 ObjCInterfaceDecl *CDecl = 0;
4781 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4782 // Figure out which interface we're in.
4783 CDecl = CurMethod->getClassInterface();
4784 if (!CDecl)
4785 return;
4786
4787 // Find the superclass of this class.
4788 CDecl = CDecl->getSuperClass();
4789 if (!CDecl)
4790 return;
4791
4792 if (CurMethod->isInstanceMethod()) {
4793 // We are inside an instance method, which means that the message
4794 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004795 // current object.
4796 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004797 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004798 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004799 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004800 }
4801
4802 // Fall through to send to the superclass in CDecl.
4803 } else {
4804 // "super" may be the name of a type or variable. Figure out which
4805 // it is.
4806 IdentifierInfo *Super = &Context.Idents.get("super");
4807 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4808 LookupOrdinaryName);
4809 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4810 // "super" names an interface. Use it.
4811 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004812 if (const ObjCObjectType *Iface
4813 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4814 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004815 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4816 // "super" names an unresolved type; we can't be more specific.
4817 } else {
4818 // Assume that "super" names some kind of value and parse that way.
4819 CXXScopeSpec SS;
4820 UnqualifiedId id;
4821 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004822 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004823 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004824 SelIdents, NumSelIdents,
4825 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004826 }
4827
4828 // Fall through
4829 }
4830
John McCallb3d87482010-08-24 05:47:05 +00004831 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004832 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004833 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004834 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004835 NumSelIdents, AtArgumentExpression,
4836 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004837}
4838
Douglas Gregorb9d77572010-09-21 00:03:25 +00004839/// \brief Given a set of code-completion results for the argument of a message
4840/// send, determine the preferred type (if any) for that argument expression.
4841static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4842 unsigned NumSelIdents) {
4843 typedef CodeCompletionResult Result;
4844 ASTContext &Context = Results.getSema().Context;
4845
4846 QualType PreferredType;
4847 unsigned BestPriority = CCP_Unlikely * 2;
4848 Result *ResultsData = Results.data();
4849 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4850 Result &R = ResultsData[I];
4851 if (R.Kind == Result::RK_Declaration &&
4852 isa<ObjCMethodDecl>(R.Declaration)) {
4853 if (R.Priority <= BestPriority) {
4854 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4855 if (NumSelIdents <= Method->param_size()) {
4856 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4857 ->getType();
4858 if (R.Priority < BestPriority || PreferredType.isNull()) {
4859 BestPriority = R.Priority;
4860 PreferredType = MyPreferredType;
4861 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4862 MyPreferredType)) {
4863 PreferredType = QualType();
4864 }
4865 }
4866 }
4867 }
4868 }
4869
4870 return PreferredType;
4871}
4872
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004873static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4874 ParsedType Receiver,
4875 IdentifierInfo **SelIdents,
4876 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004877 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004878 bool IsSuper,
4879 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004880 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004881 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004882
Douglas Gregor24a069f2009-11-17 17:59:40 +00004883 // If the given name refers to an interface type, retrieve the
4884 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004885 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004886 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004887 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004888 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4889 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004890 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004891
Douglas Gregor36ecb042009-11-17 23:22:23 +00004892 // Add all of the factory methods in this Objective-C class, its protocols,
4893 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004894 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004895
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004896 // If this is a send-to-super, try to add the special "super" send
4897 // completion.
4898 if (IsSuper) {
4899 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004900 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4901 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004902 Results.Ignore(SuperMethod);
4903 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004904
Douglas Gregor265f7492010-08-27 15:29:55 +00004905 // If we're inside an Objective-C method definition, prefer its selector to
4906 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004907 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00004908 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004909
Douglas Gregord36adf52010-09-16 16:06:31 +00004910 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00004911 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004912 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004913 SemaRef.CurContext, Selectors, AtArgumentExpression,
4914 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004915 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00004916 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004917
Douglas Gregor719770d2010-04-06 17:30:22 +00004918 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004919 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004920 if (SemaRef.ExternalSource) {
4921 for (uint32_t I = 0,
4922 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00004923 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004924 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
4925 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004926 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004927
4928 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004929 }
4930 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004931
4932 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
4933 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00004934 M != MEnd; ++M) {
4935 for (ObjCMethodList *MethList = &M->second.second;
4936 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004937 MethList = MethList->Next) {
4938 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4939 NumSelIdents))
4940 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004941
Douglas Gregor13438f92010-04-06 16:40:00 +00004942 Result R(MethList->Method, 0);
4943 R.StartParameter = NumSelIdents;
4944 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004945 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00004946 }
4947 }
4948 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004949
4950 Results.ExitScope();
4951}
Douglas Gregor13438f92010-04-06 16:40:00 +00004952
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004953void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4954 IdentifierInfo **SelIdents,
4955 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004956 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004957 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00004958
4959 QualType T = this->GetTypeFromParser(Receiver);
4960
Douglas Gregor218937c2011-02-01 19:23:04 +00004961 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00004962 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00004963 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00004964
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004965 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
4966 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00004967
4968 // If we're actually at the argument expression (rather than prior to the
4969 // selector), we're actually performing code completion for an expression.
4970 // Determine whether we have a single, best method. If so, we can
4971 // code-complete the expression using the corresponding parameter type as
4972 // our preferred type, improving completion results.
4973 if (AtArgumentExpression) {
4974 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00004975 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00004976 if (PreferredType.isNull())
4977 CodeCompleteOrdinaryName(S, PCC_Expression);
4978 else
4979 CodeCompleteExpression(S, PreferredType);
4980 return;
4981 }
4982
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004983 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00004984 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004985 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004986}
4987
Douglas Gregord3c68542009-11-19 01:08:35 +00004988void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4989 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004990 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004991 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004992 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00004993 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00004994
4995 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00004996
Douglas Gregor36ecb042009-11-17 23:22:23 +00004997 // If necessary, apply function/array conversion to the receiver.
4998 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00004999 if (RecExpr) {
5000 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5001 if (Conv.isInvalid()) // conversion failed. bail.
5002 return;
5003 RecExpr = Conv.take();
5004 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005005 QualType ReceiverType = RecExpr? RecExpr->getType()
5006 : Super? Context.getObjCObjectPointerType(
5007 Context.getObjCInterfaceType(Super))
5008 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005009
Douglas Gregorda892642010-11-08 21:12:30 +00005010 // If we're messaging an expression with type "id" or "Class", check
5011 // whether we know something special about the receiver that allows
5012 // us to assume a more-specific receiver type.
5013 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5014 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5015 if (ReceiverType->isObjCClassType())
5016 return CodeCompleteObjCClassMessage(S,
5017 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5018 SelIdents, NumSelIdents,
5019 AtArgumentExpression, Super);
5020
5021 ReceiverType = Context.getObjCObjectPointerType(
5022 Context.getObjCInterfaceType(IFace));
5023 }
5024
Douglas Gregor36ecb042009-11-17 23:22:23 +00005025 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005026 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005027 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005028 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005029
Douglas Gregor36ecb042009-11-17 23:22:23 +00005030 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005031
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005032 // If this is a send-to-super, try to add the special "super" send
5033 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005034 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005035 if (ObjCMethodDecl *SuperMethod
5036 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5037 Results))
5038 Results.Ignore(SuperMethod);
5039 }
5040
Douglas Gregor265f7492010-08-27 15:29:55 +00005041 // If we're inside an Objective-C method definition, prefer its selector to
5042 // others.
5043 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5044 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005045
Douglas Gregord36adf52010-09-16 16:06:31 +00005046 // Keep track of the selectors we've already added.
5047 VisitedSelectorSet Selectors;
5048
Douglas Gregorf74a4192009-11-18 00:06:18 +00005049 // Handle messages to Class. This really isn't a message to an instance
5050 // method, so we treat it the same way we would treat a message send to a
5051 // class method.
5052 if (ReceiverType->isObjCClassType() ||
5053 ReceiverType->isObjCQualifiedClassType()) {
5054 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5055 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005056 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005057 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005058 }
5059 }
5060 // Handle messages to a qualified ID ("id<foo>").
5061 else if (const ObjCObjectPointerType *QualID
5062 = ReceiverType->getAsObjCQualifiedIdType()) {
5063 // Search protocols for instance methods.
5064 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5065 E = QualID->qual_end();
5066 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005067 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005068 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005069 }
5070 // Handle messages to a pointer to interface type.
5071 else if (const ObjCObjectPointerType *IFacePtr
5072 = ReceiverType->getAsObjCInterfacePointerType()) {
5073 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005074 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005075 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5076 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005077
5078 // Search protocols for instance methods.
5079 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5080 E = IFacePtr->qual_end();
5081 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005082 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005083 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005084 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005085 // Handle messages to "id".
5086 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005087 // We're messaging "id", so provide all instance methods we know
5088 // about as code-completion results.
5089
5090 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005091 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005092 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005093 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5094 I != N; ++I) {
5095 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005096 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005097 continue;
5098
Sebastian Redldb9d2142010-08-02 23:18:59 +00005099 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005100 }
5101 }
5102
Sebastian Redldb9d2142010-08-02 23:18:59 +00005103 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5104 MEnd = MethodPool.end();
5105 M != MEnd; ++M) {
5106 for (ObjCMethodList *MethList = &M->second.first;
5107 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005108 MethList = MethList->Next) {
5109 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5110 NumSelIdents))
5111 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005112
5113 if (!Selectors.insert(MethList->Method->getSelector()))
5114 continue;
5115
Douglas Gregor13438f92010-04-06 16:40:00 +00005116 Result R(MethList->Method, 0);
5117 R.StartParameter = NumSelIdents;
5118 R.AllParametersAreInformative = false;
5119 Results.MaybeAddResult(R, CurContext);
5120 }
5121 }
5122 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005123 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005124
5125
5126 // If we're actually at the argument expression (rather than prior to the
5127 // selector), we're actually performing code completion for an expression.
5128 // Determine whether we have a single, best method. If so, we can
5129 // code-complete the expression using the corresponding parameter type as
5130 // our preferred type, improving completion results.
5131 if (AtArgumentExpression) {
5132 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5133 NumSelIdents);
5134 if (PreferredType.isNull())
5135 CodeCompleteOrdinaryName(S, PCC_Expression);
5136 else
5137 CodeCompleteExpression(S, PreferredType);
5138 return;
5139 }
5140
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005141 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005142 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005143 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005144}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005145
Douglas Gregorfb629412010-08-23 21:17:50 +00005146void Sema::CodeCompleteObjCForCollection(Scope *S,
5147 DeclGroupPtrTy IterationVar) {
5148 CodeCompleteExpressionData Data;
5149 Data.ObjCCollection = true;
5150
5151 if (IterationVar.getAsOpaquePtr()) {
5152 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5153 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5154 if (*I)
5155 Data.IgnoreDecls.push_back(*I);
5156 }
5157 }
5158
5159 CodeCompleteExpression(S, Data);
5160}
5161
Douglas Gregor458433d2010-08-26 15:07:07 +00005162void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5163 unsigned NumSelIdents) {
5164 // If we have an external source, load the entire class method
5165 // pool from the AST file.
5166 if (ExternalSource) {
5167 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5168 I != N; ++I) {
5169 Selector Sel = ExternalSource->GetExternalSelector(I);
5170 if (Sel.isNull() || MethodPool.count(Sel))
5171 continue;
5172
5173 ReadMethodPool(Sel);
5174 }
5175 }
5176
Douglas Gregor218937c2011-02-01 19:23:04 +00005177 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5178 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005179 Results.EnterNewScope();
5180 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5181 MEnd = MethodPool.end();
5182 M != MEnd; ++M) {
5183
5184 Selector Sel = M->first;
5185 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5186 continue;
5187
Douglas Gregor218937c2011-02-01 19:23:04 +00005188 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005189 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005190 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005191 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005192 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005193 continue;
5194 }
5195
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005196 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005197 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005198 if (I == NumSelIdents) {
5199 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005200 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005201 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005202 Accumulator.clear();
5203 }
5204 }
5205
Douglas Gregor813d8342011-02-18 22:29:55 +00005206 Accumulator += Sel.getNameForSlot(I).str();
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005207 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005208 }
Douglas Gregordae68752011-02-01 22:57:45 +00005209 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005210 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005211 }
5212 Results.ExitScope();
5213
5214 HandleCodeCompleteResults(this, CodeCompleter,
5215 CodeCompletionContext::CCC_SelectorName,
5216 Results.data(), Results.size());
5217}
5218
Douglas Gregor55385fe2009-11-18 04:19:12 +00005219/// \brief Add all of the protocol declarations that we find in the given
5220/// (translation unit) context.
5221static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005222 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005223 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005224 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005225
5226 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5227 DEnd = Ctx->decls_end();
5228 D != DEnd; ++D) {
5229 // Record any protocols we find.
5230 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005231 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005232 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005233
5234 // Record any forward-declared protocols we find.
5235 if (ObjCForwardProtocolDecl *Forward
5236 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5237 for (ObjCForwardProtocolDecl::protocol_iterator
5238 P = Forward->protocol_begin(),
5239 PEnd = Forward->protocol_end();
5240 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005241 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005242 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005243 }
5244 }
5245}
5246
5247void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5248 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005249 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5250 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005251
Douglas Gregor70c23352010-12-09 21:44:02 +00005252 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5253 Results.EnterNewScope();
5254
5255 // Tell the result set to ignore all of the protocols we have
5256 // already seen.
5257 // FIXME: This doesn't work when caching code-completion results.
5258 for (unsigned I = 0; I != NumProtocols; ++I)
5259 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5260 Protocols[I].second))
5261 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005262
Douglas Gregor70c23352010-12-09 21:44:02 +00005263 // Add all protocols.
5264 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5265 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005266
Douglas Gregor70c23352010-12-09 21:44:02 +00005267 Results.ExitScope();
5268 }
5269
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005270 HandleCodeCompleteResults(this, CodeCompleter,
5271 CodeCompletionContext::CCC_ObjCProtocolName,
5272 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005273}
5274
5275void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005276 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5277 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005278
Douglas Gregor70c23352010-12-09 21:44:02 +00005279 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5280 Results.EnterNewScope();
5281
5282 // Add all protocols.
5283 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5284 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005285
Douglas Gregor70c23352010-12-09 21:44:02 +00005286 Results.ExitScope();
5287 }
5288
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005289 HandleCodeCompleteResults(this, CodeCompleter,
5290 CodeCompletionContext::CCC_ObjCProtocolName,
5291 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005292}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005293
5294/// \brief Add all of the Objective-C interface declarations that we find in
5295/// the given (translation unit) context.
5296static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5297 bool OnlyForwardDeclarations,
5298 bool OnlyUnimplemented,
5299 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005300 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005301
5302 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5303 DEnd = Ctx->decls_end();
5304 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005305 // Record any interfaces we find.
5306 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5307 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5308 (!OnlyUnimplemented || !Class->getImplementation()))
5309 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005310
5311 // Record any forward-declared interfaces we find.
5312 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
5313 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005314 C != CEnd; ++C)
5315 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
5316 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
5317 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00005318 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005319 }
5320 }
5321}
5322
5323void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005324 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5325 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005326 Results.EnterNewScope();
5327
5328 // Add all classes.
5329 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
5330 false, Results);
5331
5332 Results.ExitScope();
Douglas Gregor3da626b2011-07-07 16:03:39 +00005333 // FIXME: Use cached global completion results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005334 HandleCodeCompleteResults(this, CodeCompleter,
5335 CodeCompletionContext::CCC_Other,
5336 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005337}
5338
Douglas Gregorc83c6872010-04-15 22:33:43 +00005339void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5340 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005341 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005342 CodeCompletionContext::CCC_ObjCSuperclass);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005343 Results.EnterNewScope();
5344
5345 // Make sure that we ignore the class we're currently defining.
5346 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005347 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005348 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005349 Results.Ignore(CurClass);
5350
5351 // Add all classes.
5352 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5353 false, Results);
5354
5355 Results.ExitScope();
Douglas Gregor3da626b2011-07-07 16:03:39 +00005356 // FIXME: Use cached global completion results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005357 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005358 CodeCompletionContext::CCC_ObjCSuperclass,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005359 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005360}
5361
5362void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005363 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5364 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005365 Results.EnterNewScope();
5366
5367 // Add all unimplemented classes.
5368 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5369 true, Results);
5370
5371 Results.ExitScope();
Douglas Gregor3da626b2011-07-07 16:03:39 +00005372 // FIXME: Use cached global completion results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005373 HandleCodeCompleteResults(this, CodeCompleter,
5374 CodeCompletionContext::CCC_Other,
5375 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005376}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005377
5378void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005379 IdentifierInfo *ClassName,
5380 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005381 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005382
Douglas Gregor218937c2011-02-01 19:23:04 +00005383 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005384 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005385
5386 // Ignore any categories we find that have already been implemented by this
5387 // interface.
5388 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5389 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005390 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005391 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5392 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5393 Category = Category->getNextClassCategory())
5394 CategoryNames.insert(Category->getIdentifier());
5395
5396 // Add all of the categories we know about.
5397 Results.EnterNewScope();
5398 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5399 for (DeclContext::decl_iterator D = TU->decls_begin(),
5400 DEnd = TU->decls_end();
5401 D != DEnd; ++D)
5402 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5403 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005404 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005405 Results.ExitScope();
5406
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005407 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005408 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005409 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005410}
5411
5412void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005413 IdentifierInfo *ClassName,
5414 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005415 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005416
5417 // Find the corresponding interface. If we couldn't find the interface, the
5418 // program itself is ill-formed. However, we'll try to be helpful still by
5419 // providing the list of all of the categories we know about.
5420 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005421 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005422 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5423 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005424 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005425
Douglas Gregor218937c2011-02-01 19:23:04 +00005426 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005427 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005428
5429 // Add all of the categories that have have corresponding interface
5430 // declarations in this class and any of its superclasses, except for
5431 // already-implemented categories in the class itself.
5432 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5433 Results.EnterNewScope();
5434 bool IgnoreImplemented = true;
5435 while (Class) {
5436 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5437 Category = Category->getNextClassCategory())
5438 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5439 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005440 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005441
5442 Class = Class->getSuperClass();
5443 IgnoreImplemented = false;
5444 }
5445 Results.ExitScope();
5446
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005447 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005448 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005449 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005450}
Douglas Gregor322328b2009-11-18 22:32:06 +00005451
John McCalld226f652010-08-21 09:40:31 +00005452void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005453 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005454 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5455 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005456
5457 // Figure out where this @synthesize lives.
5458 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005459 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005460 if (!Container ||
5461 (!isa<ObjCImplementationDecl>(Container) &&
5462 !isa<ObjCCategoryImplDecl>(Container)))
5463 return;
5464
5465 // Ignore any properties that have already been implemented.
5466 for (DeclContext::decl_iterator D = Container->decls_begin(),
5467 DEnd = Container->decls_end();
5468 D != DEnd; ++D)
5469 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5470 Results.Ignore(PropertyImpl->getPropertyDecl());
5471
5472 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005473 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005474 Results.EnterNewScope();
5475 if (ObjCImplementationDecl *ClassImpl
5476 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005477 AddObjCProperties(ClassImpl->getClassInterface(), false,
5478 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005479 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005480 else
5481 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005482 false, /*AllowNullaryMethods=*/false, CurContext,
5483 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005484 Results.ExitScope();
5485
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005486 HandleCodeCompleteResults(this, CodeCompleter,
5487 CodeCompletionContext::CCC_Other,
5488 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005489}
5490
5491void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5492 IdentifierInfo *PropertyName,
John McCalld226f652010-08-21 09:40:31 +00005493 Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005494 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005495 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5496 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005497
5498 // Figure out where this @synthesize lives.
5499 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005500 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005501 if (!Container ||
5502 (!isa<ObjCImplementationDecl>(Container) &&
5503 !isa<ObjCCategoryImplDecl>(Container)))
5504 return;
5505
5506 // Figure out which interface we're looking into.
5507 ObjCInterfaceDecl *Class = 0;
5508 if (ObjCImplementationDecl *ClassImpl
5509 = dyn_cast<ObjCImplementationDecl>(Container))
5510 Class = ClassImpl->getClassInterface();
5511 else
5512 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5513 ->getClassInterface();
5514
Douglas Gregore8426052011-04-18 14:40:46 +00005515 // Determine the type of the property we're synthesizing.
5516 QualType PropertyType = Context.getObjCIdType();
5517 if (Class) {
5518 if (ObjCPropertyDecl *Property
5519 = Class->FindPropertyDeclaration(PropertyName)) {
5520 PropertyType
5521 = Property->getType().getNonReferenceType().getUnqualifiedType();
5522
5523 // Give preference to ivars
5524 Results.setPreferredType(PropertyType);
5525 }
5526 }
5527
Douglas Gregor322328b2009-11-18 22:32:06 +00005528 // Add all of the instance variables in this class and its superclasses.
5529 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005530 bool SawSimilarlyNamedIvar = false;
5531 std::string NameWithPrefix;
5532 NameWithPrefix += '_';
5533 NameWithPrefix += PropertyName->getName().str();
5534 std::string NameWithSuffix = PropertyName->getName().str();
5535 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005536 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005537 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5538 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005539 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5540
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005541 // Determine whether we've seen an ivar with a name similar to the
5542 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005543 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005544 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005545 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005546 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005547
5548 // Reduce the priority of this result by one, to give it a slight
5549 // advantage over other results whose names don't match so closely.
5550 if (Results.size() &&
5551 Results.data()[Results.size() - 1].Kind
5552 == CodeCompletionResult::RK_Declaration &&
5553 Results.data()[Results.size() - 1].Declaration == Ivar)
5554 Results.data()[Results.size() - 1].Priority--;
5555 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005556 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005557 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005558
5559 if (!SawSimilarlyNamedIvar) {
5560 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005561 // an ivar of the appropriate type.
5562 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005563 typedef CodeCompletionResult Result;
5564 CodeCompletionAllocator &Allocator = Results.getAllocator();
5565 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5566
Douglas Gregore8426052011-04-18 14:40:46 +00005567 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
5568 Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005569 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5570 Results.AddResult(Result(Builder.TakeString(), Priority,
5571 CXCursor_ObjCIvarDecl));
5572 }
5573
Douglas Gregor322328b2009-11-18 22:32:06 +00005574 Results.ExitScope();
5575
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005576 HandleCodeCompleteResults(this, CodeCompleter,
5577 CodeCompletionContext::CCC_Other,
5578 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005579}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005580
Douglas Gregor408be5a2010-08-25 01:08:01 +00005581// Mapping from selectors to the methods that implement that selector, along
5582// with the "in original class" flag.
5583typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5584 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005585
5586/// \brief Find all of the methods that reside in the given container
5587/// (and its superclasses, protocols, etc.) that meet the given
5588/// criteria. Insert those methods into the map of known methods,
5589/// indexed by selector so they can be easily found.
5590static void FindImplementableMethods(ASTContext &Context,
5591 ObjCContainerDecl *Container,
5592 bool WantInstanceMethods,
5593 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005594 KnownMethodsMap &KnownMethods,
5595 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005596 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5597 // Recurse into protocols.
5598 const ObjCList<ObjCProtocolDecl> &Protocols
5599 = IFace->getReferencedProtocols();
5600 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005601 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005602 I != E; ++I)
5603 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005604 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005605
Douglas Gregorea766182010-10-18 18:21:28 +00005606 // Add methods from any class extensions and categories.
5607 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5608 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005609 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5610 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005611 KnownMethods, false);
5612
5613 // Visit the superclass.
5614 if (IFace->getSuperClass())
5615 FindImplementableMethods(Context, IFace->getSuperClass(),
5616 WantInstanceMethods, ReturnType,
5617 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005618 }
5619
5620 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5621 // Recurse into protocols.
5622 const ObjCList<ObjCProtocolDecl> &Protocols
5623 = Category->getReferencedProtocols();
5624 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005625 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005626 I != E; ++I)
5627 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005628 KnownMethods, InOriginalClass);
5629
5630 // If this category is the original class, jump to the interface.
5631 if (InOriginalClass && Category->getClassInterface())
5632 FindImplementableMethods(Context, Category->getClassInterface(),
5633 WantInstanceMethods, ReturnType, KnownMethods,
5634 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005635 }
5636
5637 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5638 // Recurse into protocols.
5639 const ObjCList<ObjCProtocolDecl> &Protocols
5640 = Protocol->getReferencedProtocols();
5641 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5642 E = Protocols.end();
5643 I != E; ++I)
5644 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005645 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005646 }
5647
5648 // Add methods in this container. This operation occurs last because
5649 // we want the methods from this container to override any methods
5650 // we've previously seen with the same selector.
5651 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5652 MEnd = Container->meth_end();
5653 M != MEnd; ++M) {
5654 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5655 if (!ReturnType.isNull() &&
5656 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5657 continue;
5658
Douglas Gregor408be5a2010-08-25 01:08:01 +00005659 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005660 }
5661 }
5662}
5663
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005664/// \brief Add the parenthesized return or parameter type chunk to a code
5665/// completion string.
5666static void AddObjCPassingTypeChunk(QualType Type,
5667 ASTContext &Context,
5668 CodeCompletionBuilder &Builder) {
5669 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5670 Builder.AddTextChunk(GetCompletionTypeString(Type, Context,
5671 Builder.getAllocator()));
5672 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5673}
5674
5675/// \brief Determine whether the given class is or inherits from a class by
5676/// the given name.
5677static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005678 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005679 if (!Class)
5680 return false;
5681
5682 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5683 return true;
5684
5685 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5686}
5687
5688/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5689/// Key-Value Observing (KVO).
5690static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5691 bool IsInstanceMethod,
5692 QualType ReturnType,
5693 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005694 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005695 ResultBuilder &Results) {
5696 IdentifierInfo *PropName = Property->getIdentifier();
5697 if (!PropName || PropName->getLength() == 0)
5698 return;
5699
5700
5701 // Builder that will create each code completion.
5702 typedef CodeCompletionResult Result;
5703 CodeCompletionAllocator &Allocator = Results.getAllocator();
5704 CodeCompletionBuilder Builder(Allocator);
5705
5706 // The selector table.
5707 SelectorTable &Selectors = Context.Selectors;
5708
5709 // The property name, copied into the code completion allocation region
5710 // on demand.
5711 struct KeyHolder {
5712 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005713 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005714 const char *CopiedKey;
5715
Chris Lattner5f9e2722011-07-23 10:55:15 +00005716 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005717 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5718
5719 operator const char *() {
5720 if (CopiedKey)
5721 return CopiedKey;
5722
5723 return CopiedKey = Allocator.CopyString(Key);
5724 }
5725 } Key(Allocator, PropName->getName());
5726
5727 // The uppercased name of the property name.
5728 std::string UpperKey = PropName->getName();
5729 if (!UpperKey.empty())
5730 UpperKey[0] = toupper(UpperKey[0]);
5731
5732 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5733 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5734 Property->getType());
5735 bool ReturnTypeMatchesVoid
5736 = ReturnType.isNull() || ReturnType->isVoidType();
5737
5738 // Add the normal accessor -(type)key.
5739 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005740 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005741 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5742 if (ReturnType.isNull())
5743 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5744
5745 Builder.AddTypedTextChunk(Key);
5746 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5747 CXCursor_ObjCInstanceMethodDecl));
5748 }
5749
5750 // If we have an integral or boolean property (or the user has provided
5751 // an integral or boolean return type), add the accessor -(type)isKey.
5752 if (IsInstanceMethod &&
5753 ((!ReturnType.isNull() &&
5754 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5755 (ReturnType.isNull() &&
5756 (Property->getType()->isIntegerType() ||
5757 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005758 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005759 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005760 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005761 if (ReturnType.isNull()) {
5762 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5763 Builder.AddTextChunk("BOOL");
5764 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5765 }
5766
5767 Builder.AddTypedTextChunk(
5768 Allocator.CopyString(SelectorId->getName()));
5769 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5770 CXCursor_ObjCInstanceMethodDecl));
5771 }
5772 }
5773
5774 // Add the normal mutator.
5775 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5776 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005777 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005778 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005779 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005780 if (ReturnType.isNull()) {
5781 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5782 Builder.AddTextChunk("void");
5783 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5784 }
5785
5786 Builder.AddTypedTextChunk(
5787 Allocator.CopyString(SelectorId->getName()));
5788 Builder.AddTypedTextChunk(":");
5789 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5790 Builder.AddTextChunk(Key);
5791 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5792 CXCursor_ObjCInstanceMethodDecl));
5793 }
5794 }
5795
5796 // Indexed and unordered accessors
5797 unsigned IndexedGetterPriority = CCP_CodePattern;
5798 unsigned IndexedSetterPriority = CCP_CodePattern;
5799 unsigned UnorderedGetterPriority = CCP_CodePattern;
5800 unsigned UnorderedSetterPriority = CCP_CodePattern;
5801 if (const ObjCObjectPointerType *ObjCPointer
5802 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5803 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5804 // If this interface type is not provably derived from a known
5805 // collection, penalize the corresponding completions.
5806 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5807 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5808 if (!InheritsFromClassNamed(IFace, "NSArray"))
5809 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5810 }
5811
5812 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5813 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5814 if (!InheritsFromClassNamed(IFace, "NSSet"))
5815 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5816 }
5817 }
5818 } else {
5819 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5820 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5821 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5822 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5823 }
5824
5825 // Add -(NSUInteger)countOf<key>
5826 if (IsInstanceMethod &&
5827 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005828 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005829 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005830 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005831 if (ReturnType.isNull()) {
5832 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5833 Builder.AddTextChunk("NSUInteger");
5834 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5835 }
5836
5837 Builder.AddTypedTextChunk(
5838 Allocator.CopyString(SelectorId->getName()));
5839 Results.AddResult(Result(Builder.TakeString(),
5840 std::min(IndexedGetterPriority,
5841 UnorderedGetterPriority),
5842 CXCursor_ObjCInstanceMethodDecl));
5843 }
5844 }
5845
5846 // Indexed getters
5847 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
5848 if (IsInstanceMethod &&
5849 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005850 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005851 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005852 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005853 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005854 if (ReturnType.isNull()) {
5855 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5856 Builder.AddTextChunk("id");
5857 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5858 }
5859
5860 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5861 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5862 Builder.AddTextChunk("NSUInteger");
5863 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5864 Builder.AddTextChunk("index");
5865 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5866 CXCursor_ObjCInstanceMethodDecl));
5867 }
5868 }
5869
5870 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
5871 if (IsInstanceMethod &&
5872 (ReturnType.isNull() ||
5873 (ReturnType->isObjCObjectPointerType() &&
5874 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
5875 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
5876 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005877 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005878 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005879 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005880 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005881 if (ReturnType.isNull()) {
5882 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5883 Builder.AddTextChunk("NSArray *");
5884 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5885 }
5886
5887 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5888 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5889 Builder.AddTextChunk("NSIndexSet *");
5890 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5891 Builder.AddTextChunk("indexes");
5892 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5893 CXCursor_ObjCInstanceMethodDecl));
5894 }
5895 }
5896
5897 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
5898 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005899 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005900 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005901 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005902 &Context.Idents.get("range")
5903 };
5904
Douglas Gregore74c25c2011-05-04 23:50:46 +00005905 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005906 if (ReturnType.isNull()) {
5907 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5908 Builder.AddTextChunk("void");
5909 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5910 }
5911
5912 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5913 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5914 Builder.AddPlaceholderChunk("object-type");
5915 Builder.AddTextChunk(" **");
5916 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5917 Builder.AddTextChunk("buffer");
5918 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5919 Builder.AddTypedTextChunk("range:");
5920 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5921 Builder.AddTextChunk("NSRange");
5922 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5923 Builder.AddTextChunk("inRange");
5924 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5925 CXCursor_ObjCInstanceMethodDecl));
5926 }
5927 }
5928
5929 // Mutable indexed accessors
5930
5931 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
5932 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005933 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005934 IdentifierInfo *SelectorIds[2] = {
5935 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00005936 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005937 };
5938
Douglas Gregore74c25c2011-05-04 23:50:46 +00005939 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005940 if (ReturnType.isNull()) {
5941 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5942 Builder.AddTextChunk("void");
5943 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5944 }
5945
5946 Builder.AddTypedTextChunk("insertObject:");
5947 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5948 Builder.AddPlaceholderChunk("object-type");
5949 Builder.AddTextChunk(" *");
5950 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5951 Builder.AddTextChunk("object");
5952 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5953 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5954 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5955 Builder.AddPlaceholderChunk("NSUInteger");
5956 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5957 Builder.AddTextChunk("index");
5958 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5959 CXCursor_ObjCInstanceMethodDecl));
5960 }
5961 }
5962
5963 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
5964 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005965 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005966 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005967 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005968 &Context.Idents.get("atIndexes")
5969 };
5970
Douglas Gregore74c25c2011-05-04 23:50:46 +00005971 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005972 if (ReturnType.isNull()) {
5973 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5974 Builder.AddTextChunk("void");
5975 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5976 }
5977
5978 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5979 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5980 Builder.AddTextChunk("NSArray *");
5981 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5982 Builder.AddTextChunk("array");
5983 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5984 Builder.AddTypedTextChunk("atIndexes:");
5985 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5986 Builder.AddPlaceholderChunk("NSIndexSet *");
5987 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5988 Builder.AddTextChunk("indexes");
5989 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5990 CXCursor_ObjCInstanceMethodDecl));
5991 }
5992 }
5993
5994 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
5995 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005996 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005997 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005998 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005999 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006000 if (ReturnType.isNull()) {
6001 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6002 Builder.AddTextChunk("void");
6003 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6004 }
6005
6006 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6007 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6008 Builder.AddTextChunk("NSUInteger");
6009 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6010 Builder.AddTextChunk("index");
6011 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6012 CXCursor_ObjCInstanceMethodDecl));
6013 }
6014 }
6015
6016 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6017 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006018 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006019 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006020 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006021 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006022 if (ReturnType.isNull()) {
6023 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6024 Builder.AddTextChunk("void");
6025 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6026 }
6027
6028 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6029 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6030 Builder.AddTextChunk("NSIndexSet *");
6031 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6032 Builder.AddTextChunk("indexes");
6033 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6034 CXCursor_ObjCInstanceMethodDecl));
6035 }
6036 }
6037
6038 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6039 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006040 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006041 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006042 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006043 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006044 &Context.Idents.get("withObject")
6045 };
6046
Douglas Gregore74c25c2011-05-04 23:50:46 +00006047 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006048 if (ReturnType.isNull()) {
6049 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6050 Builder.AddTextChunk("void");
6051 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6052 }
6053
6054 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6055 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6056 Builder.AddPlaceholderChunk("NSUInteger");
6057 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6058 Builder.AddTextChunk("index");
6059 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6060 Builder.AddTypedTextChunk("withObject:");
6061 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6062 Builder.AddTextChunk("id");
6063 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6064 Builder.AddTextChunk("object");
6065 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6066 CXCursor_ObjCInstanceMethodDecl));
6067 }
6068 }
6069
6070 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6071 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006072 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006073 = (Twine("replace") + UpperKey + "AtIndexes").str();
6074 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006075 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006076 &Context.Idents.get(SelectorName1),
6077 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006078 };
6079
Douglas Gregore74c25c2011-05-04 23:50:46 +00006080 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006081 if (ReturnType.isNull()) {
6082 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6083 Builder.AddTextChunk("void");
6084 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6085 }
6086
6087 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6088 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6089 Builder.AddPlaceholderChunk("NSIndexSet *");
6090 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6091 Builder.AddTextChunk("indexes");
6092 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6093 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6094 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6095 Builder.AddTextChunk("NSArray *");
6096 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6097 Builder.AddTextChunk("array");
6098 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6099 CXCursor_ObjCInstanceMethodDecl));
6100 }
6101 }
6102
6103 // Unordered getters
6104 // - (NSEnumerator *)enumeratorOfKey
6105 if (IsInstanceMethod &&
6106 (ReturnType.isNull() ||
6107 (ReturnType->isObjCObjectPointerType() &&
6108 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6109 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6110 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006111 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).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.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006114 if (ReturnType.isNull()) {
6115 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6116 Builder.AddTextChunk("NSEnumerator *");
6117 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6118 }
6119
6120 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6121 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6122 CXCursor_ObjCInstanceMethodDecl));
6123 }
6124 }
6125
6126 // - (type *)memberOfKey:(type *)object
6127 if (IsInstanceMethod &&
6128 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006129 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006130 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006131 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006132 if (ReturnType.isNull()) {
6133 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6134 Builder.AddPlaceholderChunk("object-type");
6135 Builder.AddTextChunk(" *");
6136 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6137 }
6138
6139 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6140 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6141 if (ReturnType.isNull()) {
6142 Builder.AddPlaceholderChunk("object-type");
6143 Builder.AddTextChunk(" *");
6144 } else {
6145 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
6146 Builder.getAllocator()));
6147 }
6148 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6149 Builder.AddTextChunk("object");
6150 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6151 CXCursor_ObjCInstanceMethodDecl));
6152 }
6153 }
6154
6155 // Mutable unordered accessors
6156 // - (void)addKeyObject:(type *)object
6157 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006158 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006159 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006160 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006161 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006162 if (ReturnType.isNull()) {
6163 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6164 Builder.AddTextChunk("void");
6165 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6166 }
6167
6168 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6169 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6170 Builder.AddPlaceholderChunk("object-type");
6171 Builder.AddTextChunk(" *");
6172 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6173 Builder.AddTextChunk("object");
6174 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6175 CXCursor_ObjCInstanceMethodDecl));
6176 }
6177 }
6178
6179 // - (void)addKey:(NSSet *)objects
6180 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006181 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006182 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006183 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006184 if (ReturnType.isNull()) {
6185 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6186 Builder.AddTextChunk("void");
6187 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6188 }
6189
6190 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6191 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6192 Builder.AddTextChunk("NSSet *");
6193 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6194 Builder.AddTextChunk("objects");
6195 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6196 CXCursor_ObjCInstanceMethodDecl));
6197 }
6198 }
6199
6200 // - (void)removeKeyObject:(type *)object
6201 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006202 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006203 = (Twine("remove") + UpperKey + Twine("Object")).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.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006206 if (ReturnType.isNull()) {
6207 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6208 Builder.AddTextChunk("void");
6209 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6210 }
6211
6212 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6213 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6214 Builder.AddPlaceholderChunk("object-type");
6215 Builder.AddTextChunk(" *");
6216 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6217 Builder.AddTextChunk("object");
6218 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6219 CXCursor_ObjCInstanceMethodDecl));
6220 }
6221 }
6222
6223 // - (void)removeKey:(NSSet *)objects
6224 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006225 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006226 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006227 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006228 if (ReturnType.isNull()) {
6229 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6230 Builder.AddTextChunk("void");
6231 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6232 }
6233
6234 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6235 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6236 Builder.AddTextChunk("NSSet *");
6237 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6238 Builder.AddTextChunk("objects");
6239 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6240 CXCursor_ObjCInstanceMethodDecl));
6241 }
6242 }
6243
6244 // - (void)intersectKey:(NSSet *)objects
6245 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006246 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006247 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006248 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006249 if (ReturnType.isNull()) {
6250 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6251 Builder.AddTextChunk("void");
6252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6253 }
6254
6255 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6256 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6257 Builder.AddTextChunk("NSSet *");
6258 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6259 Builder.AddTextChunk("objects");
6260 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6261 CXCursor_ObjCInstanceMethodDecl));
6262 }
6263 }
6264
6265 // Key-Value Observing
6266 // + (NSSet *)keyPathsForValuesAffectingKey
6267 if (!IsInstanceMethod &&
6268 (ReturnType.isNull() ||
6269 (ReturnType->isObjCObjectPointerType() &&
6270 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6271 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6272 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006273 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006274 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006275 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006276 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006277 if (ReturnType.isNull()) {
6278 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6279 Builder.AddTextChunk("NSSet *");
6280 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6281 }
6282
6283 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6284 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006285 CXCursor_ObjCClassMethodDecl));
6286 }
6287 }
6288
6289 // + (BOOL)automaticallyNotifiesObserversForKey
6290 if (!IsInstanceMethod &&
6291 (ReturnType.isNull() ||
6292 ReturnType->isIntegerType() ||
6293 ReturnType->isBooleanType())) {
6294 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006295 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006296 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6297 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6298 if (ReturnType.isNull()) {
6299 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6300 Builder.AddTextChunk("BOOL");
6301 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6302 }
6303
6304 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6305 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6306 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006307 }
6308 }
6309}
6310
Douglas Gregore8f5a172010-04-07 00:21:17 +00006311void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6312 bool IsInstanceMethod,
John McCallb3d87482010-08-24 05:47:05 +00006313 ParsedType ReturnTy,
John McCalld226f652010-08-21 09:40:31 +00006314 Decl *IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006315 // Determine the return type of the method we're declaring, if
6316 // provided.
6317 QualType ReturnType = GetTypeFromParser(ReturnTy);
6318
Douglas Gregorea766182010-10-18 18:21:28 +00006319 // Determine where we should start searching for methods.
6320 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006321 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006322 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006323 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6324 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006325 IsInImplementation = true;
6326 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006327 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006328 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006329 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006330 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006331 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006332 }
6333
6334 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006335 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006336 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006337 }
6338
Douglas Gregorea766182010-10-18 18:21:28 +00006339 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006340 HandleCodeCompleteResults(this, CodeCompleter,
6341 CodeCompletionContext::CCC_Other,
6342 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006343 return;
6344 }
6345
6346 // Find all of the methods that we could declare/implement here.
6347 KnownMethodsMap KnownMethods;
6348 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006349 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006350
Douglas Gregore8f5a172010-04-07 00:21:17 +00006351 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006352 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006353 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6354 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006355 Results.EnterNewScope();
6356 PrintingPolicy Policy(Context.PrintingPolicy);
6357 Policy.AnonymousTagLocations = false;
John McCallf85e1932011-06-15 23:02:42 +00006358 Policy.SuppressStrongLifetime = true;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006359 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6360 MEnd = KnownMethods.end();
6361 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006362 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006363 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006364
6365 // If the result type was not already provided, add it to the
6366 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006367 if (ReturnType.isNull())
6368 AddObjCPassingTypeChunk(Method->getResultType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006369
6370 Selector Sel = Method->getSelector();
6371
6372 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006373 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006374 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006375
6376 // Add parameters to the pattern.
6377 unsigned I = 0;
6378 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6379 PEnd = Method->param_end();
6380 P != PEnd; (void)++P, ++I) {
6381 // Add the part of the selector name.
6382 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006383 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006384 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006385 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6386 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006387 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006388 } else
6389 break;
6390
6391 // Add the parameter type.
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006392 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006393
6394 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006395 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006396 }
6397
6398 if (Method->isVariadic()) {
6399 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006400 Builder.AddChunk(CodeCompletionString::CK_Comma);
6401 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006402 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006403
Douglas Gregor447107d2010-05-28 00:57:46 +00006404 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006405 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006406 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6407 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6408 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006409 if (!Method->getResultType()->isVoidType()) {
6410 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006411 Builder.AddTextChunk("return");
6412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6413 Builder.AddPlaceholderChunk("expression");
6414 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006415 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006416 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006417
Douglas Gregor218937c2011-02-01 19:23:04 +00006418 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6419 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006420 }
6421
Douglas Gregor408be5a2010-08-25 01:08:01 +00006422 unsigned Priority = CCP_CodePattern;
6423 if (!M->second.second)
6424 Priority += CCD_InBaseClass;
6425
Douglas Gregor218937c2011-02-01 19:23:04 +00006426 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006427 Method->isInstanceMethod()
6428 ? CXCursor_ObjCInstanceMethodDecl
6429 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006430 }
6431
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006432 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6433 // the properties in this class and its categories.
6434 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006435 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006436 Containers.push_back(SearchDecl);
6437
Douglas Gregore74c25c2011-05-04 23:50:46 +00006438 VisitedSelectorSet KnownSelectors;
6439 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6440 MEnd = KnownMethods.end();
6441 M != MEnd; ++M)
6442 KnownSelectors.insert(M->first);
6443
6444
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006445 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6446 if (!IFace)
6447 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6448 IFace = Category->getClassInterface();
6449
6450 if (IFace) {
6451 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6452 Category = Category->getNextClassCategory())
6453 Containers.push_back(Category);
6454 }
6455
6456 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6457 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6458 PEnd = Containers[I]->prop_end();
6459 P != PEnd; ++P) {
6460 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006461 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006462 }
6463 }
6464 }
6465
Douglas Gregore8f5a172010-04-07 00:21:17 +00006466 Results.ExitScope();
6467
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006468 HandleCodeCompleteResults(this, CodeCompleter,
6469 CodeCompletionContext::CCC_Other,
6470 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006471}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006472
6473void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6474 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006475 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006476 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006477 IdentifierInfo **SelIdents,
6478 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006479 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006480 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006481 if (ExternalSource) {
6482 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6483 I != N; ++I) {
6484 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006485 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006486 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006487
6488 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006489 }
6490 }
6491
6492 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006493 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006494 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6495 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006496
6497 if (ReturnTy)
6498 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006499
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006500 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006501 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6502 MEnd = MethodPool.end();
6503 M != MEnd; ++M) {
6504 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6505 &M->second.second;
6506 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006507 MethList = MethList->Next) {
6508 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6509 NumSelIdents))
6510 continue;
6511
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006512 if (AtParameterName) {
6513 // Suggest parameter names we've seen before.
6514 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6515 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6516 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006517 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006518 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006519 Param->getIdentifier()->getName()));
6520 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006521 }
6522 }
6523
6524 continue;
6525 }
6526
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006527 Result R(MethList->Method, 0);
6528 R.StartParameter = NumSelIdents;
6529 R.AllParametersAreInformative = false;
6530 R.DeclaringEntity = true;
6531 Results.MaybeAddResult(R, CurContext);
6532 }
6533 }
6534
6535 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006536 HandleCodeCompleteResults(this, CodeCompleter,
6537 CodeCompletionContext::CCC_Other,
6538 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006539}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006540
Douglas Gregorf29c5232010-08-24 22:20:20 +00006541void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006542 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006543 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006544 Results.EnterNewScope();
6545
6546 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006547 CodeCompletionBuilder Builder(Results.getAllocator());
6548 Builder.AddTypedTextChunk("if");
6549 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6550 Builder.AddPlaceholderChunk("condition");
6551 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006552
6553 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006554 Builder.AddTypedTextChunk("ifdef");
6555 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6556 Builder.AddPlaceholderChunk("macro");
6557 Results.AddResult(Builder.TakeString());
6558
Douglas Gregorf44e8542010-08-24 19:08:16 +00006559 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006560 Builder.AddTypedTextChunk("ifndef");
6561 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6562 Builder.AddPlaceholderChunk("macro");
6563 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006564
6565 if (InConditional) {
6566 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006567 Builder.AddTypedTextChunk("elif");
6568 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6569 Builder.AddPlaceholderChunk("condition");
6570 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006571
6572 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006573 Builder.AddTypedTextChunk("else");
6574 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006575
6576 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006577 Builder.AddTypedTextChunk("endif");
6578 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006579 }
6580
6581 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006582 Builder.AddTypedTextChunk("include");
6583 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6584 Builder.AddTextChunk("\"");
6585 Builder.AddPlaceholderChunk("header");
6586 Builder.AddTextChunk("\"");
6587 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006588
6589 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006590 Builder.AddTypedTextChunk("include");
6591 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6592 Builder.AddTextChunk("<");
6593 Builder.AddPlaceholderChunk("header");
6594 Builder.AddTextChunk(">");
6595 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006596
6597 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006598 Builder.AddTypedTextChunk("define");
6599 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6600 Builder.AddPlaceholderChunk("macro");
6601 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006602
6603 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006604 Builder.AddTypedTextChunk("define");
6605 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6606 Builder.AddPlaceholderChunk("macro");
6607 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6608 Builder.AddPlaceholderChunk("args");
6609 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6610 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006611
6612 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006613 Builder.AddTypedTextChunk("undef");
6614 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6615 Builder.AddPlaceholderChunk("macro");
6616 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006617
6618 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006619 Builder.AddTypedTextChunk("line");
6620 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6621 Builder.AddPlaceholderChunk("number");
6622 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006623
6624 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006625 Builder.AddTypedTextChunk("line");
6626 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6627 Builder.AddPlaceholderChunk("number");
6628 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6629 Builder.AddTextChunk("\"");
6630 Builder.AddPlaceholderChunk("filename");
6631 Builder.AddTextChunk("\"");
6632 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006633
6634 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006635 Builder.AddTypedTextChunk("error");
6636 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6637 Builder.AddPlaceholderChunk("message");
6638 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006639
6640 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006641 Builder.AddTypedTextChunk("pragma");
6642 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6643 Builder.AddPlaceholderChunk("arguments");
6644 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006645
6646 if (getLangOptions().ObjC1) {
6647 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006648 Builder.AddTypedTextChunk("import");
6649 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6650 Builder.AddTextChunk("\"");
6651 Builder.AddPlaceholderChunk("header");
6652 Builder.AddTextChunk("\"");
6653 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006654
6655 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006656 Builder.AddTypedTextChunk("import");
6657 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6658 Builder.AddTextChunk("<");
6659 Builder.AddPlaceholderChunk("header");
6660 Builder.AddTextChunk(">");
6661 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006662 }
6663
6664 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006665 Builder.AddTypedTextChunk("include_next");
6666 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6667 Builder.AddTextChunk("\"");
6668 Builder.AddPlaceholderChunk("header");
6669 Builder.AddTextChunk("\"");
6670 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006671
6672 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006673 Builder.AddTypedTextChunk("include_next");
6674 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6675 Builder.AddTextChunk("<");
6676 Builder.AddPlaceholderChunk("header");
6677 Builder.AddTextChunk(">");
6678 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006679
6680 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006681 Builder.AddTypedTextChunk("warning");
6682 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6683 Builder.AddPlaceholderChunk("message");
6684 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006685
6686 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6687 // completions for them. And __include_macros is a Clang-internal extension
6688 // that we don't want to encourage anyone to use.
6689
6690 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6691 Results.ExitScope();
6692
Douglas Gregorf44e8542010-08-24 19:08:16 +00006693 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006694 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006695 Results.data(), Results.size());
6696}
6697
6698void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006699 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006700 S->getFnParent()? Sema::PCC_RecoveryInFunction
6701 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006702}
6703
Douglas Gregorf29c5232010-08-24 22:20:20 +00006704void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006705 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006706 IsDefinition? CodeCompletionContext::CCC_MacroName
6707 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006708 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6709 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006710 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006711 Results.EnterNewScope();
6712 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6713 MEnd = PP.macro_end();
6714 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006715 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006716 M->first->getName()));
6717 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006718 }
6719 Results.ExitScope();
6720 } else if (IsDefinition) {
6721 // FIXME: Can we detect when the user just wrote an include guard above?
6722 }
6723
Douglas Gregor52779fb2010-09-23 23:01:17 +00006724 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006725 Results.data(), Results.size());
6726}
6727
Douglas Gregorf29c5232010-08-24 22:20:20 +00006728void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006729 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006730 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006731
6732 if (!CodeCompleter || CodeCompleter->includeMacros())
6733 AddMacroResults(PP, Results);
6734
6735 // defined (<macro>)
6736 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006737 CodeCompletionBuilder Builder(Results.getAllocator());
6738 Builder.AddTypedTextChunk("defined");
6739 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6740 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6741 Builder.AddPlaceholderChunk("macro");
6742 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6743 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006744 Results.ExitScope();
6745
6746 HandleCodeCompleteResults(this, CodeCompleter,
6747 CodeCompletionContext::CCC_PreprocessorExpression,
6748 Results.data(), Results.size());
6749}
6750
6751void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6752 IdentifierInfo *Macro,
6753 MacroInfo *MacroInfo,
6754 unsigned Argument) {
6755 // FIXME: In the future, we could provide "overload" results, much like we
6756 // do for function calls.
6757
6758 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006759 S->getFnParent()? Sema::PCC_RecoveryInFunction
6760 : Sema::PCC_Namespace);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006761}
6762
Douglas Gregor55817af2010-08-25 17:04:25 +00006763void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006764 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006765 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006766 0, 0);
6767}
6768
Douglas Gregordae68752011-02-01 22:57:45 +00006769void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006770 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006771 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006772 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6773 CodeCompletionDeclConsumer Consumer(Builder,
6774 Context.getTranslationUnitDecl());
6775 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6776 Consumer);
6777 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006778
6779 if (!CodeCompleter || CodeCompleter->includeMacros())
6780 AddMacroResults(PP, Builder);
6781
6782 Results.clear();
6783 Results.insert(Results.end(),
6784 Builder.data(), Builder.data() + Builder.size());
6785}