blob: e328eeb0aa2bd840c3c2db26490eb12dfd880fbd [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 {
64 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
65
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) {
437 llvm::SmallVector<DeclContext *, 4> TargetParents;
438
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 McCallf312b1e2010-08-26 23:41:50 +00001679 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001680 if (SemaRef.getLangOptions().CPlusPlus) {
1681 // 'this', if we're in a non-static member function.
1682 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1683 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001684 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001685
1686 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001687 Results.AddResult(Result("true"));
1688 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001689
Douglas Gregorec3310a2011-04-12 02:47:21 +00001690 if (SemaRef.getLangOptions().RTTI) {
1691 // dynamic_cast < type-id > ( expression )
1692 Builder.AddTypedTextChunk("dynamic_cast");
1693 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1694 Builder.AddPlaceholderChunk("type");
1695 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1696 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1697 Builder.AddPlaceholderChunk("expression");
1698 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1699 Results.AddResult(Result(Builder.TakeString()));
1700 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001701
1702 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001703 Builder.AddTypedTextChunk("static_cast");
1704 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1705 Builder.AddPlaceholderChunk("type");
1706 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1707 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1708 Builder.AddPlaceholderChunk("expression");
1709 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1710 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001711
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001712 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001713 Builder.AddTypedTextChunk("reinterpret_cast");
1714 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1715 Builder.AddPlaceholderChunk("type");
1716 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1717 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1718 Builder.AddPlaceholderChunk("expression");
1719 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1720 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001721
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001722 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001723 Builder.AddTypedTextChunk("const_cast");
1724 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1725 Builder.AddPlaceholderChunk("type");
1726 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1727 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1728 Builder.AddPlaceholderChunk("expression");
1729 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1730 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001731
Douglas Gregorec3310a2011-04-12 02:47:21 +00001732 if (SemaRef.getLangOptions().RTTI) {
1733 // typeid ( expression-or-type )
1734 Builder.AddTypedTextChunk("typeid");
1735 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1736 Builder.AddPlaceholderChunk("expression-or-type");
1737 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1738 Results.AddResult(Result(Builder.TakeString()));
1739 }
1740
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001741 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001742 Builder.AddTypedTextChunk("new");
1743 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1744 Builder.AddPlaceholderChunk("type");
1745 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1746 Builder.AddPlaceholderChunk("expressions");
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 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001751 Builder.AddTypedTextChunk("new");
1752 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1753 Builder.AddPlaceholderChunk("type");
1754 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1755 Builder.AddPlaceholderChunk("size");
1756 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1757 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1758 Builder.AddPlaceholderChunk("expressions");
1759 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1760 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001761
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001762 // delete expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001763 Builder.AddTypedTextChunk("delete");
1764 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1765 Builder.AddPlaceholderChunk("expression");
1766 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001767
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001768 // delete [] expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001769 Builder.AddTypedTextChunk("delete");
1770 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1771 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1772 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1773 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1774 Builder.AddPlaceholderChunk("expression");
1775 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001776
Douglas Gregorec3310a2011-04-12 02:47:21 +00001777 if (SemaRef.getLangOptions().CXXExceptions) {
1778 // throw expression
1779 Builder.AddTypedTextChunk("throw");
1780 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1781 Builder.AddPlaceholderChunk("expression");
1782 Results.AddResult(Result(Builder.TakeString()));
1783 }
Douglas Gregor12e13132010-05-26 22:00:08 +00001784
1785 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001786 }
1787
1788 if (SemaRef.getLangOptions().ObjC1) {
1789 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001790 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1791 // The interface can be NULL.
1792 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1793 if (ID->getSuperClass())
1794 Results.AddResult(Result("super"));
1795 }
1796
Douglas Gregorbca403c2010-01-13 23:51:12 +00001797 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001798 }
1799
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001800 // sizeof expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001801 Builder.AddTypedTextChunk("sizeof");
1802 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1803 Builder.AddPlaceholderChunk("expression-or-type");
1804 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1805 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001806 break;
1807 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001808
John McCallf312b1e2010-08-26 23:41:50 +00001809 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001810 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001811 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001812 }
1813
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001814 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1815 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001816
John McCallf312b1e2010-08-26 23:41:50 +00001817 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001818 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001819}
1820
Douglas Gregora63f6de2011-02-01 21:15:40 +00001821/// \brief Retrieve the string representation of the given type as a string
1822/// that has the appropriate lifetime for code completion.
1823///
1824/// This routine provides a fast path where we provide constant strings for
1825/// common type names.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001826static const char *GetCompletionTypeString(QualType T,
1827 ASTContext &Context,
1828 CodeCompletionAllocator &Allocator) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001829 PrintingPolicy Policy(Context.PrintingPolicy);
1830 Policy.AnonymousTagLocations = false;
1831
1832 if (!T.getLocalQualifiers()) {
1833 // Built-in type names are constant strings.
1834 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1835 return BT->getName(Context.getLangOptions());
1836
1837 // Anonymous tag types are constant strings.
1838 if (const TagType *TagT = dyn_cast<TagType>(T))
1839 if (TagDecl *Tag = TagT->getDecl())
Richard Smith162e1c12011-04-15 14:24:37 +00001840 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001841 switch (Tag->getTagKind()) {
1842 case TTK_Struct: return "struct <anonymous>";
1843 case TTK_Class: return "class <anonymous>";
1844 case TTK_Union: return "union <anonymous>";
1845 case TTK_Enum: return "enum <anonymous>";
1846 }
1847 }
1848 }
1849
1850 // Slow path: format the type as a string.
1851 std::string Result;
1852 T.getAsStringInternal(Result, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00001853 return Allocator.CopyString(Result);
Douglas Gregora63f6de2011-02-01 21:15:40 +00001854}
1855
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001856/// \brief If the given declaration has an associated type, add it as a result
1857/// type chunk.
1858static void AddResultTypeChunk(ASTContext &Context,
1859 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001860 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001861 if (!ND)
1862 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001863
1864 // Skip constructors and conversion functions, which have their return types
1865 // built into their names.
1866 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1867 return;
1868
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001869 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001870 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001871 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1872 T = Function->getResultType();
1873 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1874 T = Method->getResultType();
1875 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1876 T = FunTmpl->getTemplatedDecl()->getResultType();
1877 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1878 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1879 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1880 /* Do nothing: ignore unresolved using declarations*/
1881 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1882 T = Value->getType();
1883 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1884 T = Property->getType();
1885
1886 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1887 return;
1888
Douglas Gregora63f6de2011-02-01 21:15:40 +00001889 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context,
1890 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001891}
1892
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001893static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001894 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001895 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1896 if (Sentinel->getSentinel() == 0) {
1897 if (Context.getLangOptions().ObjC1 &&
1898 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001899 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001900 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001901 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001902 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001903 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001904 }
1905}
1906
Douglas Gregor83482d12010-08-24 16:15:59 +00001907static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregoraba48082010-08-29 19:47:46 +00001908 ParmVarDecl *Param,
1909 bool SuppressName = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001910 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1911 if (Param->getType()->isDependentType() ||
1912 !Param->getType()->isBlockPointerType()) {
1913 // The argument for a dependent or non-block parameter is a placeholder
1914 // containing that parameter's type.
1915 std::string Result;
1916
Douglas Gregoraba48082010-08-29 19:47:46 +00001917 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001918 Result = Param->getIdentifier()->getName();
1919
1920 Param->getType().getAsStringInternal(Result,
1921 Context.PrintingPolicy);
1922
1923 if (ObjCMethodParam) {
1924 Result = "(" + Result;
1925 Result += ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001926 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001927 Result += Param->getIdentifier()->getName();
1928 }
1929 return Result;
1930 }
1931
1932 // The argument for a block pointer parameter is a block literal with
1933 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00001934 FunctionTypeLoc *Block = 0;
1935 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00001936 TypeLoc TL;
1937 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1938 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1939 while (true) {
1940 // Look through typedefs.
1941 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1942 if (TypeSourceInfo *InnerTSInfo
Richard Smith162e1c12011-04-15 14:24:37 +00001943 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001944 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1945 continue;
1946 }
1947 }
1948
1949 // Look through qualified types
1950 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1951 TL = QualifiedTL->getUnqualifiedLoc();
1952 continue;
1953 }
1954
1955 // Try to get the function prototype behind the block pointer type,
1956 // then we're done.
1957 if (BlockPointerTypeLoc *BlockPtr
1958 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00001959 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00001960 Block = dyn_cast<FunctionTypeLoc>(&TL);
1961 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00001962 }
1963 break;
1964 }
1965 }
1966
1967 if (!Block) {
1968 // We were unable to find a FunctionProtoTypeLoc with parameter names
1969 // for the block; just use the parameter type as a placeholder.
1970 std::string Result;
1971 Param->getType().getUnqualifiedType().
1972 getAsStringInternal(Result, Context.PrintingPolicy);
1973
1974 if (ObjCMethodParam) {
1975 Result = "(" + Result;
1976 Result += ")";
1977 if (Param->getIdentifier())
1978 Result += Param->getIdentifier()->getName();
1979 }
1980
1981 return Result;
1982 }
1983
1984 // We have the function prototype behind the block pointer type, as it was
1985 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00001986 std::string Result;
1987 QualType ResultType = Block->getTypePtr()->getResultType();
1988 if (!ResultType->isVoidType())
1989 ResultType.getAsStringInternal(Result, Context.PrintingPolicy);
1990
1991 Result = '^' + Result;
Douglas Gregor830072c2011-02-15 22:37:09 +00001992 if (!BlockProto || Block->getNumArgs() == 0) {
1993 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00001994 Result += "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00001995 else
1996 Result += "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00001997 } else {
1998 Result += "(";
1999 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2000 if (I)
2001 Result += ", ";
2002 Result += FormatFunctionParameter(Context, Block->getArg(I));
2003
Douglas Gregor830072c2011-02-15 22:37:09 +00002004 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002005 Result += ", ...";
2006 }
2007 Result += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002008 }
Douglas Gregor38276252010-09-08 22:47:51 +00002009
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002010 if (Param->getIdentifier())
2011 Result += Param->getIdentifier()->getName();
2012
Douglas Gregor83482d12010-08-24 16:15:59 +00002013 return Result;
2014}
2015
Douglas Gregor86d9a522009-09-21 16:56:56 +00002016/// \brief Add function parameter chunks to the given code completion string.
2017static void AddFunctionParameterChunks(ASTContext &Context,
2018 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002019 CodeCompletionBuilder &Result,
2020 unsigned Start = 0,
2021 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002022 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002023 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002024
Douglas Gregor218937c2011-02-01 19:23:04 +00002025 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002026 ParmVarDecl *Param = Function->getParamDecl(P);
2027
Douglas Gregor218937c2011-02-01 19:23:04 +00002028 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002029 // When we see an optional default argument, put that argument and
2030 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002031 CodeCompletionBuilder Opt(Result.getAllocator());
2032 if (!FirstParameter)
2033 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2034 AddFunctionParameterChunks(Context, Function, Opt, P, true);
2035 Result.AddOptionalChunk(Opt.TakeString());
2036 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002037 }
2038
Douglas Gregor218937c2011-02-01 19:23:04 +00002039 if (FirstParameter)
2040 FirstParameter = false;
2041 else
2042 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2043
2044 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002045
2046 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00002047 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
2048
Douglas Gregore17794f2010-08-31 05:13:43 +00002049 if (Function->isVariadic() && P == N - 1)
2050 PlaceholderStr += ", ...";
2051
Douglas Gregor86d9a522009-09-21 16:56:56 +00002052 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002053 Result.AddPlaceholderChunk(
2054 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002055 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002056
2057 if (const FunctionProtoType *Proto
2058 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002059 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002060 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002061 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002062
Douglas Gregor218937c2011-02-01 19:23:04 +00002063 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002064 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002065}
2066
2067/// \brief Add template parameter chunks to the given code completion string.
2068static void AddTemplateParameterChunks(ASTContext &Context,
2069 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002070 CodeCompletionBuilder &Result,
2071 unsigned MaxParameters = 0,
2072 unsigned Start = 0,
2073 bool InDefaultArg = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002074 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002075 bool FirstParameter = true;
2076
2077 TemplateParameterList *Params = Template->getTemplateParameters();
2078 TemplateParameterList::iterator PEnd = Params->end();
2079 if (MaxParameters)
2080 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002081 for (TemplateParameterList::iterator P = Params->begin() + Start;
2082 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002083 bool HasDefaultArg = false;
2084 std::string PlaceholderStr;
2085 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2086 if (TTP->wasDeclaredWithTypename())
2087 PlaceholderStr = "typename";
2088 else
2089 PlaceholderStr = "class";
2090
2091 if (TTP->getIdentifier()) {
2092 PlaceholderStr += ' ';
2093 PlaceholderStr += TTP->getIdentifier()->getName();
2094 }
2095
2096 HasDefaultArg = TTP->hasDefaultArgument();
2097 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002098 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002099 if (NTTP->getIdentifier())
2100 PlaceholderStr = NTTP->getIdentifier()->getName();
2101 NTTP->getType().getAsStringInternal(PlaceholderStr,
2102 Context.PrintingPolicy);
2103 HasDefaultArg = NTTP->hasDefaultArgument();
2104 } else {
2105 assert(isa<TemplateTemplateParmDecl>(*P));
2106 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2107
2108 // Since putting the template argument list into the placeholder would
2109 // be very, very long, we just use an abbreviation.
2110 PlaceholderStr = "template<...> class";
2111 if (TTP->getIdentifier()) {
2112 PlaceholderStr += ' ';
2113 PlaceholderStr += TTP->getIdentifier()->getName();
2114 }
2115
2116 HasDefaultArg = TTP->hasDefaultArgument();
2117 }
2118
Douglas Gregor218937c2011-02-01 19:23:04 +00002119 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002120 // When we see an optional default argument, put that argument and
2121 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002122 CodeCompletionBuilder Opt(Result.getAllocator());
2123 if (!FirstParameter)
2124 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2125 AddTemplateParameterChunks(Context, Template, Opt, MaxParameters,
2126 P - Params->begin(), true);
2127 Result.AddOptionalChunk(Opt.TakeString());
2128 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002129 }
2130
Douglas Gregor218937c2011-02-01 19:23:04 +00002131 InDefaultArg = false;
2132
Douglas Gregor86d9a522009-09-21 16:56:56 +00002133 if (FirstParameter)
2134 FirstParameter = false;
2135 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002136 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002137
2138 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002139 Result.AddPlaceholderChunk(
2140 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002141 }
2142}
2143
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002144/// \brief Add a qualifier to the given code-completion string, if the
2145/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002146static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002147AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002148 NestedNameSpecifier *Qualifier,
2149 bool QualifierIsInformative,
2150 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002151 if (!Qualifier)
2152 return;
2153
2154 std::string PrintedNNS;
2155 {
2156 llvm::raw_string_ostream OS(PrintedNNS);
2157 Qualifier->print(OS, Context.PrintingPolicy);
2158 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002159 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002160 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002161 else
Douglas Gregordae68752011-02-01 22:57:45 +00002162 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002163}
2164
Douglas Gregor218937c2011-02-01 19:23:04 +00002165static void
2166AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2167 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002168 const FunctionProtoType *Proto
2169 = Function->getType()->getAs<FunctionProtoType>();
2170 if (!Proto || !Proto->getTypeQuals())
2171 return;
2172
Douglas Gregora63f6de2011-02-01 21:15:40 +00002173 // FIXME: Add ref-qualifier!
2174
2175 // Handle single qualifiers without copying
2176 if (Proto->getTypeQuals() == Qualifiers::Const) {
2177 Result.AddInformativeChunk(" const");
2178 return;
2179 }
2180
2181 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2182 Result.AddInformativeChunk(" volatile");
2183 return;
2184 }
2185
2186 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2187 Result.AddInformativeChunk(" restrict");
2188 return;
2189 }
2190
2191 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002192 std::string QualsStr;
2193 if (Proto->getTypeQuals() & Qualifiers::Const)
2194 QualsStr += " const";
2195 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2196 QualsStr += " volatile";
2197 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2198 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002199 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002200}
2201
Douglas Gregor6f942b22010-09-21 16:06:22 +00002202/// \brief Add the name of the given declaration
2203static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00002204 CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002205 typedef CodeCompletionString::Chunk Chunk;
2206
2207 DeclarationName Name = ND->getDeclName();
2208 if (!Name)
2209 return;
2210
2211 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002212 case DeclarationName::CXXOperatorName: {
2213 const char *OperatorName = 0;
2214 switch (Name.getCXXOverloadedOperator()) {
2215 case OO_None:
2216 case OO_Conditional:
2217 case NUM_OVERLOADED_OPERATORS:
2218 OperatorName = "operator";
2219 break;
2220
2221#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2222 case OO_##Name: OperatorName = "operator" Spelling; break;
2223#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2224#include "clang/Basic/OperatorKinds.def"
2225
2226 case OO_New: OperatorName = "operator new"; break;
2227 case OO_Delete: OperatorName = "operator delete"; break;
2228 case OO_Array_New: OperatorName = "operator new[]"; break;
2229 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2230 case OO_Call: OperatorName = "operator()"; break;
2231 case OO_Subscript: OperatorName = "operator[]"; break;
2232 }
2233 Result.AddTypedTextChunk(OperatorName);
2234 break;
2235 }
2236
Douglas Gregor6f942b22010-09-21 16:06:22 +00002237 case DeclarationName::Identifier:
2238 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002239 case DeclarationName::CXXDestructorName:
2240 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002241 Result.AddTypedTextChunk(
2242 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002243 break;
2244
2245 case DeclarationName::CXXUsingDirective:
2246 case DeclarationName::ObjCZeroArgSelector:
2247 case DeclarationName::ObjCOneArgSelector:
2248 case DeclarationName::ObjCMultiArgSelector:
2249 break;
2250
2251 case DeclarationName::CXXConstructorName: {
2252 CXXRecordDecl *Record = 0;
2253 QualType Ty = Name.getCXXNameType();
2254 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2255 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2256 else if (const InjectedClassNameType *InjectedTy
2257 = Ty->getAs<InjectedClassNameType>())
2258 Record = InjectedTy->getDecl();
2259 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002260 Result.AddTypedTextChunk(
2261 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002262 break;
2263 }
2264
Douglas Gregordae68752011-02-01 22:57:45 +00002265 Result.AddTypedTextChunk(
2266 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002267 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002268 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002269 AddTemplateParameterChunks(Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002270 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002271 }
2272 break;
2273 }
2274 }
2275}
2276
Douglas Gregor86d9a522009-09-21 16:56:56 +00002277/// \brief If possible, create a new code completion string for the given
2278/// result.
2279///
2280/// \returns Either a new, heap-allocated code completion string describing
2281/// how to use this result, or NULL to indicate that the string or name of the
2282/// result is all that is needed.
2283CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002284CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002285 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002286 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002287 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002288
Douglas Gregor218937c2011-02-01 19:23:04 +00002289 if (Kind == RK_Pattern) {
2290 Pattern->Priority = Priority;
2291 Pattern->Availability = Availability;
2292 return Pattern;
2293 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002294
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002295 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002296 Result.AddTypedTextChunk(Keyword);
2297 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002298 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002299
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002300 if (Kind == RK_Macro) {
2301 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002302 assert(MI && "Not a macro?");
2303
Douglas Gregordae68752011-02-01 22:57:45 +00002304 Result.AddTypedTextChunk(
2305 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002306
2307 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002308 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002309
2310 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002311 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002312 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2313 A != AEnd; ++A) {
2314 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002315 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002316
2317 if (!MI->isVariadic() || A != AEnd - 1) {
2318 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002319 Result.AddPlaceholderChunk(
2320 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002321 continue;
2322 }
2323
2324 // Variadic argument; cope with the different between GNU and C99
2325 // variadic macros, providing a single placeholder for the rest of the
2326 // arguments.
2327 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002328 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002329 else {
2330 std::string Arg = (*A)->getName();
2331 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002332 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002333 }
2334 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002335 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2336 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002337 }
2338
Douglas Gregord8e8a582010-05-25 21:41:55 +00002339 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002340 NamedDecl *ND = Declaration;
2341
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002342 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002343 Result.AddTypedTextChunk(
2344 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002345 Result.AddTextChunk("::");
2346 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002347 }
2348
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002349 AddResultTypeChunk(S.Context, ND, Result);
2350
Douglas Gregor86d9a522009-09-21 16:56:56 +00002351 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002352 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2353 S.Context);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002354 AddTypedNameChunk(S.Context, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002355 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002356 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002357 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002358 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002359 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002360 }
2361
2362 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002363 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2364 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002365 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor6f942b22010-09-21 16:06:22 +00002366 AddTypedNameChunk(S.Context, Function, Result);
2367
Douglas Gregor86d9a522009-09-21 16:56:56 +00002368 // Figure out which template parameters are deduced (or have default
2369 // arguments).
2370 llvm::SmallVector<bool, 16> Deduced;
2371 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2372 unsigned LastDeducibleArgument;
2373 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2374 --LastDeducibleArgument) {
2375 if (!Deduced[LastDeducibleArgument - 1]) {
2376 // C++0x: Figure out if the template argument has a default. If so,
2377 // the user doesn't need to type this argument.
2378 // FIXME: We need to abstract template parameters better!
2379 bool HasDefaultArg = false;
2380 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002381 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002382 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2383 HasDefaultArg = TTP->hasDefaultArgument();
2384 else if (NonTypeTemplateParmDecl *NTTP
2385 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2386 HasDefaultArg = NTTP->hasDefaultArgument();
2387 else {
2388 assert(isa<TemplateTemplateParmDecl>(Param));
2389 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002390 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002391 }
2392
2393 if (!HasDefaultArg)
2394 break;
2395 }
2396 }
2397
2398 if (LastDeducibleArgument) {
2399 // Some of the function template arguments cannot be deduced from a
2400 // function call, so we introduce an explicit template argument list
2401 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002402 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002403 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2404 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002405 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002406 }
2407
2408 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002409 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002410 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002411 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002412 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002413 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002414 }
2415
2416 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002417 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2418 S.Context);
Douglas Gregordae68752011-02-01 22:57:45 +00002419 Result.AddTypedTextChunk(
2420 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002421 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002422 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002423 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2424 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002425 }
2426
Douglas Gregor9630eb62009-11-17 16:44:22 +00002427 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002428 Selector Sel = Method->getSelector();
2429 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002430 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002431 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002432 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002433 }
2434
Douglas Gregor813d8342011-02-18 22:29:55 +00002435 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002436 SelName += ':';
2437 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002438 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002439 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002440 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002441
2442 // If there is only one parameter, and we're past it, add an empty
2443 // typed-text chunk since there is nothing to type.
2444 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002445 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002446 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002447 unsigned Idx = 0;
2448 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2449 PEnd = Method->param_end();
2450 P != PEnd; (void)++P, ++Idx) {
2451 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002452 std::string Keyword;
2453 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002454 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002455 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2456 Keyword += II->getName().str();
2457 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002458 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002459 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002460 else
Douglas Gregordae68752011-02-01 22:57:45 +00002461 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002462 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002463
2464 // If we're before the starting parameter, skip the placeholder.
2465 if (Idx < StartParameter)
2466 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002467
2468 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002469
2470 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregoraba48082010-08-29 19:47:46 +00002471 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002472 else {
2473 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
2474 Arg = "(" + Arg + ")";
2475 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002476 if (DeclaringEntity || AllParametersAreInformative)
2477 Arg += II->getName().str();
Douglas Gregor83482d12010-08-24 16:15:59 +00002478 }
2479
Douglas Gregore17794f2010-08-31 05:13:43 +00002480 if (Method->isVariadic() && (P + 1) == PEnd)
2481 Arg += ", ...";
2482
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002483 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002484 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002485 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002486 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002487 else
Douglas Gregordae68752011-02-01 22:57:45 +00002488 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002489 }
2490
Douglas Gregor2a17af02009-12-23 00:21:46 +00002491 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002492 if (Method->param_size() == 0) {
2493 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002494 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002495 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002496 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002497 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002498 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002499 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002500
2501 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002502 }
2503
Douglas Gregor218937c2011-02-01 19:23:04 +00002504 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002505 }
2506
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002507 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002508 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2509 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002510
Douglas Gregordae68752011-02-01 22:57:45 +00002511 Result.AddTypedTextChunk(
2512 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002513 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002514}
2515
Douglas Gregor86d802e2009-09-23 00:34:09 +00002516CodeCompletionString *
2517CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2518 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002519 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002520 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002521 typedef CodeCompletionString::Chunk Chunk;
2522
Douglas Gregor218937c2011-02-01 19:23:04 +00002523 // FIXME: Set priority, availability appropriately.
2524 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002525 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002526 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002527 const FunctionProtoType *Proto
2528 = dyn_cast<FunctionProtoType>(getFunctionType());
2529 if (!FDecl && !Proto) {
2530 // Function without a prototype. Just give the return type and a
2531 // highlighted ellipsis.
2532 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002533 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
2534 S.Context,
2535 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002536 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2537 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2538 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2539 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002540 }
2541
2542 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002543 Result.AddTextChunk(
2544 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002545 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002546 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002547 Result.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002548 Proto->getResultType().getAsString(S.Context.PrintingPolicy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002549
Douglas Gregor218937c2011-02-01 19:23:04 +00002550 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002551 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2552 for (unsigned I = 0; I != NumParams; ++I) {
2553 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002554 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002555
2556 std::string ArgString;
2557 QualType ArgType;
2558
2559 if (FDecl) {
2560 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2561 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2562 } else {
2563 ArgType = Proto->getArgType(I);
2564 }
2565
2566 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2567
2568 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002569 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002570 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002571 else
Douglas Gregordae68752011-02-01 22:57:45 +00002572 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002573 }
2574
2575 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002576 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002577 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002578 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002579 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002580 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002581 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002582 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002583
Douglas Gregor218937c2011-02-01 19:23:04 +00002584 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002585}
2586
Douglas Gregor1827e102010-08-16 16:18:59 +00002587unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002588 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002589 bool PreferredTypeIsPointer) {
2590 unsigned Priority = CCP_Macro;
2591
Douglas Gregorb05496d2010-09-20 21:11:48 +00002592 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2593 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2594 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002595 Priority = CCP_Constant;
2596 if (PreferredTypeIsPointer)
2597 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002598 }
2599 // Treat "YES", "NO", "true", and "false" as constants.
2600 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2601 MacroName.equals("true") || MacroName.equals("false"))
2602 Priority = CCP_Constant;
2603 // Treat "bool" as a type.
2604 else if (MacroName.equals("bool"))
2605 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2606
Douglas Gregor1827e102010-08-16 16:18:59 +00002607
2608 return Priority;
2609}
2610
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002611CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2612 if (!D)
2613 return CXCursor_UnexposedDecl;
2614
2615 switch (D->getKind()) {
2616 case Decl::Enum: return CXCursor_EnumDecl;
2617 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2618 case Decl::Field: return CXCursor_FieldDecl;
2619 case Decl::Function:
2620 return CXCursor_FunctionDecl;
2621 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2622 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2623 case Decl::ObjCClass:
2624 // FIXME
2625 return CXCursor_UnexposedDecl;
2626 case Decl::ObjCForwardProtocol:
2627 // FIXME
2628 return CXCursor_UnexposedDecl;
2629 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2630 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2631 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2632 case Decl::ObjCMethod:
2633 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2634 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2635 case Decl::CXXMethod: return CXCursor_CXXMethod;
2636 case Decl::CXXConstructor: return CXCursor_Constructor;
2637 case Decl::CXXDestructor: return CXCursor_Destructor;
2638 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2639 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2640 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2641 case Decl::ParmVar: return CXCursor_ParmDecl;
2642 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002643 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002644 case Decl::Var: return CXCursor_VarDecl;
2645 case Decl::Namespace: return CXCursor_Namespace;
2646 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2647 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2648 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2649 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2650 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2651 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2652 case Decl::ClassTemplatePartialSpecialization:
2653 return CXCursor_ClassTemplatePartialSpecialization;
2654 case Decl::UsingDirective: return CXCursor_UsingDirective;
2655
2656 case Decl::Using:
2657 case Decl::UnresolvedUsingValue:
2658 case Decl::UnresolvedUsingTypename:
2659 return CXCursor_UsingDeclaration;
2660
Douglas Gregor352697a2011-06-03 23:08:58 +00002661 case Decl::ObjCPropertyImpl:
2662 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2663 case ObjCPropertyImplDecl::Dynamic:
2664 return CXCursor_ObjCDynamicDecl;
2665
2666 case ObjCPropertyImplDecl::Synthesize:
2667 return CXCursor_ObjCSynthesizeDecl;
2668 }
2669 break;
2670
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002671 default:
2672 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2673 switch (TD->getTagKind()) {
2674 case TTK_Struct: return CXCursor_StructDecl;
2675 case TTK_Class: return CXCursor_ClassDecl;
2676 case TTK_Union: return CXCursor_UnionDecl;
2677 case TTK_Enum: return CXCursor_EnumDecl;
2678 }
2679 }
2680 }
2681
2682 return CXCursor_UnexposedDecl;
2683}
2684
Douglas Gregor590c7d52010-07-08 20:55:51 +00002685static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2686 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002687 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002688
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002689 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002690
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002691 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2692 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002693 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002694 Results.AddResult(Result(M->first,
2695 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002696 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002697 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002698 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002699
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002700 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002701
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002702}
2703
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002704static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2705 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002706 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002707
2708 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002709
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002710 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2711 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2712 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2713 Results.AddResult(Result("__func__", CCP_Constant));
2714 Results.ExitScope();
2715}
2716
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002717static void HandleCodeCompleteResults(Sema *S,
2718 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002719 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002720 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002721 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002722 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002723 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002724}
2725
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002726static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2727 Sema::ParserCompletionContext PCC) {
2728 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002729 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002730 return CodeCompletionContext::CCC_TopLevel;
2731
John McCallf312b1e2010-08-26 23:41:50 +00002732 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002733 return CodeCompletionContext::CCC_ClassStructUnion;
2734
John McCallf312b1e2010-08-26 23:41:50 +00002735 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002736 return CodeCompletionContext::CCC_ObjCInterface;
2737
John McCallf312b1e2010-08-26 23:41:50 +00002738 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002739 return CodeCompletionContext::CCC_ObjCImplementation;
2740
John McCallf312b1e2010-08-26 23:41:50 +00002741 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002742 return CodeCompletionContext::CCC_ObjCIvarList;
2743
John McCallf312b1e2010-08-26 23:41:50 +00002744 case Sema::PCC_Template:
2745 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002746 if (S.CurContext->isFileContext())
2747 return CodeCompletionContext::CCC_TopLevel;
2748 else if (S.CurContext->isRecord())
2749 return CodeCompletionContext::CCC_ClassStructUnion;
2750 else
2751 return CodeCompletionContext::CCC_Other;
2752
John McCallf312b1e2010-08-26 23:41:50 +00002753 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002754 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002755
John McCallf312b1e2010-08-26 23:41:50 +00002756 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002757 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2758 S.getLangOptions().ObjC1)
2759 return CodeCompletionContext::CCC_ParenthesizedExpression;
2760 else
2761 return CodeCompletionContext::CCC_Expression;
2762
2763 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002764 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002765 return CodeCompletionContext::CCC_Expression;
2766
John McCallf312b1e2010-08-26 23:41:50 +00002767 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002768 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002769
John McCallf312b1e2010-08-26 23:41:50 +00002770 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002771 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002772
2773 case Sema::PCC_ParenthesizedExpression:
2774 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002775
2776 case Sema::PCC_LocalDeclarationSpecifiers:
2777 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002778 }
2779
2780 return CodeCompletionContext::CCC_Other;
2781}
2782
Douglas Gregorf6961522010-08-27 21:18:54 +00002783/// \brief If we're in a C++ virtual member function, add completion results
2784/// that invoke the functions we override, since it's common to invoke the
2785/// overridden function as well as adding new functionality.
2786///
2787/// \param S The semantic analysis object for which we are generating results.
2788///
2789/// \param InContext This context in which the nested-name-specifier preceding
2790/// the code-completion point
2791static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2792 ResultBuilder &Results) {
2793 // Look through blocks.
2794 DeclContext *CurContext = S.CurContext;
2795 while (isa<BlockDecl>(CurContext))
2796 CurContext = CurContext->getParent();
2797
2798
2799 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2800 if (!Method || !Method->isVirtual())
2801 return;
2802
2803 // We need to have names for all of the parameters, if we're going to
2804 // generate a forwarding call.
2805 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2806 PEnd = Method->param_end();
2807 P != PEnd;
2808 ++P) {
2809 if (!(*P)->getDeclName())
2810 return;
2811 }
2812
2813 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2814 MEnd = Method->end_overridden_methods();
2815 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002816 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002817 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2818 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2819 continue;
2820
2821 // If we need a nested-name-specifier, add one now.
2822 if (!InContext) {
2823 NestedNameSpecifier *NNS
2824 = getRequiredQualification(S.Context, CurContext,
2825 Overridden->getDeclContext());
2826 if (NNS) {
2827 std::string Str;
2828 llvm::raw_string_ostream OS(Str);
2829 NNS->print(OS, S.Context.PrintingPolicy);
Douglas Gregordae68752011-02-01 22:57:45 +00002830 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002831 }
2832 } else if (!InContext->Equals(Overridden->getDeclContext()))
2833 continue;
2834
Douglas Gregordae68752011-02-01 22:57:45 +00002835 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002836 Overridden->getNameAsString()));
2837 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00002838 bool FirstParam = true;
2839 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2840 PEnd = Method->param_end();
2841 P != PEnd; ++P) {
2842 if (FirstParam)
2843 FirstParam = false;
2844 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002845 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00002846
Douglas Gregordae68752011-02-01 22:57:45 +00002847 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002848 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002849 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002850 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2851 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00002852 CCP_SuperCompletion,
2853 CXCursor_CXXMethod));
2854 Results.Ignore(Overridden);
2855 }
2856}
2857
Douglas Gregor01dfea02010-01-10 23:08:15 +00002858void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002859 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002860 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002861 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002862 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002863 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002864
Douglas Gregor01dfea02010-01-10 23:08:15 +00002865 // Determine how to filter results, e.g., so that the names of
2866 // values (functions, enumerators, function templates, etc.) are
2867 // only allowed where we can have an expression.
2868 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002869 case PCC_Namespace:
2870 case PCC_Class:
2871 case PCC_ObjCInterface:
2872 case PCC_ObjCImplementation:
2873 case PCC_ObjCInstanceVariableList:
2874 case PCC_Template:
2875 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002876 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002877 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002878 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2879 break;
2880
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002881 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002882 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002883 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002884 case PCC_ForInit:
2885 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002886 if (WantTypesInContext(CompletionContext, getLangOptions()))
2887 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2888 else
2889 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002890
2891 if (getLangOptions().CPlusPlus)
2892 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002893 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002894
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002895 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002896 // Unfiltered
2897 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002898 }
2899
Douglas Gregor3cdee122010-08-26 16:36:48 +00002900 // If we are in a C++ non-static member function, check the qualifiers on
2901 // the member function to filter/prioritize the results list.
2902 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2903 if (CurMethod->isInstance())
2904 Results.setObjectTypeQualifiers(
2905 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2906
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002907 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002908 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2909 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002910
Douglas Gregorbca403c2010-01-13 23:51:12 +00002911 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002912 Results.ExitScope();
2913
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002914 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00002915 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00002916 case PCC_Expression:
2917 case PCC_Statement:
2918 case PCC_RecoveryInFunction:
2919 if (S->getFnParent())
2920 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2921 break;
2922
2923 case PCC_Namespace:
2924 case PCC_Class:
2925 case PCC_ObjCInterface:
2926 case PCC_ObjCImplementation:
2927 case PCC_ObjCInstanceVariableList:
2928 case PCC_Template:
2929 case PCC_MemberTemplate:
2930 case PCC_ForInit:
2931 case PCC_Condition:
2932 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002933 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00002934 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002935 }
2936
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002937 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002938 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002939
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002940 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002941 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002942}
2943
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002944static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
2945 ParsedType Receiver,
2946 IdentifierInfo **SelIdents,
2947 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00002948 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002949 bool IsSuper,
2950 ResultBuilder &Results);
2951
2952void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
2953 bool AllowNonIdentifiers,
2954 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00002955 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002956 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002957 AllowNestedNameSpecifiers
2958 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2959 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002960 Results.EnterNewScope();
2961
2962 // Type qualifiers can come after names.
2963 Results.AddResult(Result("const"));
2964 Results.AddResult(Result("volatile"));
2965 if (getLangOptions().C99)
2966 Results.AddResult(Result("restrict"));
2967
2968 if (getLangOptions().CPlusPlus) {
2969 if (AllowNonIdentifiers) {
2970 Results.AddResult(Result("operator"));
2971 }
2972
2973 // Add nested-name-specifiers.
2974 if (AllowNestedNameSpecifiers) {
2975 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00002976 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002977 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2978 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
2979 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00002980 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002981 }
2982 }
2983 Results.ExitScope();
2984
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002985 // If we're in a context where we might have an expression (rather than a
2986 // declaration), and what we've seen so far is an Objective-C type that could
2987 // be a receiver of a class message, this may be a class message send with
2988 // the initial opening bracket '[' missing. Add appropriate completions.
2989 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
2990 DS.getTypeSpecType() == DeclSpec::TST_typename &&
2991 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
2992 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
2993 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
2994 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
2995 DS.getTypeQualifiers() == 0 &&
2996 S &&
2997 (S->getFlags() & Scope::DeclScope) != 0 &&
2998 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
2999 Scope::FunctionPrototypeScope |
3000 Scope::AtCatchScope)) == 0) {
3001 ParsedType T = DS.getRepAsType();
3002 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003003 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003004 }
3005
Douglas Gregor4497dd42010-08-24 04:59:56 +00003006 // Note that we intentionally suppress macro results here, since we do not
3007 // encourage using macros to produce the names of entities.
3008
Douglas Gregor52779fb2010-09-23 23:01:17 +00003009 HandleCodeCompleteResults(this, CodeCompleter,
3010 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003011 Results.data(), Results.size());
3012}
3013
Douglas Gregorfb629412010-08-23 21:17:50 +00003014struct Sema::CodeCompleteExpressionData {
3015 CodeCompleteExpressionData(QualType PreferredType = QualType())
3016 : PreferredType(PreferredType), IntegralConstantExpression(false),
3017 ObjCCollection(false) { }
3018
3019 QualType PreferredType;
3020 bool IntegralConstantExpression;
3021 bool ObjCCollection;
3022 llvm::SmallVector<Decl *, 4> IgnoreDecls;
3023};
3024
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003025/// \brief Perform code-completion in an expression context when we know what
3026/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003027///
3028/// \param IntegralConstantExpression Only permit integral constant
3029/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003030void Sema::CodeCompleteExpression(Scope *S,
3031 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003032 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003033 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3034 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003035 if (Data.ObjCCollection)
3036 Results.setFilter(&ResultBuilder::IsObjCCollection);
3037 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003038 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003039 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003040 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3041 else
3042 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003043
3044 if (!Data.PreferredType.isNull())
3045 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3046
3047 // Ignore any declarations that we were told that we don't care about.
3048 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3049 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003050
3051 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003052 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3053 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003054
3055 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003056 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003057 Results.ExitScope();
3058
Douglas Gregor590c7d52010-07-08 20:55:51 +00003059 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003060 if (!Data.PreferredType.isNull())
3061 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3062 || Data.PreferredType->isMemberPointerType()
3063 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003064
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003065 if (S->getFnParent() &&
3066 !Data.ObjCCollection &&
3067 !Data.IntegralConstantExpression)
3068 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3069
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003070 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003071 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003072 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003073 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3074 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003075 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003076}
3077
Douglas Gregorac5fd842010-09-18 01:28:11 +00003078void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3079 if (E.isInvalid())
3080 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3081 else if (getLangOptions().ObjC1)
3082 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003083}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003084
Douglas Gregor73449212010-12-09 23:01:55 +00003085/// \brief The set of properties that have already been added, referenced by
3086/// property name.
3087typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3088
Douglas Gregor95ac6552009-11-18 01:29:26 +00003089static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003090 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003091 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003092 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003093 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003094 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003095 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003096
3097 // Add properties in this container.
3098 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3099 PEnd = Container->prop_end();
3100 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003101 ++P) {
3102 if (AddedProperties.insert(P->getIdentifier()))
3103 Results.MaybeAddResult(Result(*P, 0), CurContext);
3104 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003105
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003106 // Add nullary methods
3107 if (AllowNullaryMethods) {
3108 ASTContext &Context = Container->getASTContext();
3109 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3110 MEnd = Container->meth_end();
3111 M != MEnd; ++M) {
3112 if (M->getSelector().isUnarySelector())
3113 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3114 if (AddedProperties.insert(Name)) {
3115 CodeCompletionBuilder Builder(Results.getAllocator());
3116 AddResultTypeChunk(Context, *M, Builder);
3117 Builder.AddTypedTextChunk(
3118 Results.getAllocator().CopyString(Name->getName()));
3119
3120 CXAvailabilityKind Availability = CXAvailability_Available;
3121 switch (M->getAvailability()) {
3122 case AR_Available:
3123 case AR_NotYetIntroduced:
3124 Availability = CXAvailability_Available;
3125 break;
3126
3127 case AR_Deprecated:
3128 Availability = CXAvailability_Deprecated;
3129 break;
3130
3131 case AR_Unavailable:
3132 Availability = CXAvailability_NotAvailable;
3133 break;
3134 }
3135
3136 Results.MaybeAddResult(Result(Builder.TakeString(),
3137 CCP_MemberDeclaration + CCD_MethodAsProperty,
3138 M->isInstanceMethod()
3139 ? CXCursor_ObjCInstanceMethodDecl
3140 : CXCursor_ObjCClassMethodDecl,
3141 Availability),
3142 CurContext);
3143 }
3144 }
3145 }
3146
3147
Douglas Gregor95ac6552009-11-18 01:29:26 +00003148 // Add properties in referenced protocols.
3149 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3150 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3151 PEnd = Protocol->protocol_end();
3152 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003153 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3154 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003155 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003156 if (AllowCategories) {
3157 // Look through categories.
3158 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3159 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003160 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3161 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003162 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003163
3164 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003165 for (ObjCInterfaceDecl::all_protocol_iterator
3166 I = IFace->all_referenced_protocol_begin(),
3167 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003168 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3169 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003170
3171 // Look in the superclass.
3172 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003173 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3174 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003175 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003176 } else if (const ObjCCategoryDecl *Category
3177 = dyn_cast<ObjCCategoryDecl>(Container)) {
3178 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003179 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3180 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003181 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003182 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3183 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003184 }
3185}
3186
Douglas Gregor81b747b2009-09-17 21:32:03 +00003187void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
3188 SourceLocation OpLoc,
3189 bool IsArrow) {
3190 if (!BaseE || !CodeCompleter)
3191 return;
3192
John McCall0a2c5e22010-08-25 06:19:51 +00003193 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003194
Douglas Gregor81b747b2009-09-17 21:32:03 +00003195 Expr *Base = static_cast<Expr *>(BaseE);
3196 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003197
3198 if (IsArrow) {
3199 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3200 BaseType = Ptr->getPointeeType();
3201 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003202 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003203 else
3204 return;
3205 }
3206
Douglas Gregor218937c2011-02-01 19:23:04 +00003207 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003208 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
3209 BaseType),
3210 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003211 Results.EnterNewScope();
3212 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003213 // Indicate that we are performing a member access, and the cv-qualifiers
3214 // for the base object type.
3215 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3216
Douglas Gregor95ac6552009-11-18 01:29:26 +00003217 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003218 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003219 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003220 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3221 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003222
Douglas Gregor95ac6552009-11-18 01:29:26 +00003223 if (getLangOptions().CPlusPlus) {
3224 if (!Results.empty()) {
3225 // The "template" keyword can follow "->" or "." in the grammar.
3226 // However, we only want to suggest the template keyword if something
3227 // is dependent.
3228 bool IsDependent = BaseType->isDependentType();
3229 if (!IsDependent) {
3230 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3231 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3232 IsDependent = Ctx->isDependentContext();
3233 break;
3234 }
3235 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003236
Douglas Gregor95ac6552009-11-18 01:29:26 +00003237 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003238 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003239 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003240 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003241 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3242 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003243 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003244
3245 // Add property results based on our interface.
3246 const ObjCObjectPointerType *ObjCPtr
3247 = BaseType->getAsObjCInterfacePointerType();
3248 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003249 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3250 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003251 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003252
3253 // Add properties from the protocols in a qualified interface.
3254 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3255 E = ObjCPtr->qual_end();
3256 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003257 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3258 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003259 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003260 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003261 // Objective-C instance variable access.
3262 ObjCInterfaceDecl *Class = 0;
3263 if (const ObjCObjectPointerType *ObjCPtr
3264 = BaseType->getAs<ObjCObjectPointerType>())
3265 Class = ObjCPtr->getInterfaceDecl();
3266 else
John McCallc12c5bb2010-05-15 11:32:37 +00003267 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003268
3269 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003270 if (Class) {
3271 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3272 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003273 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3274 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003275 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003276 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003277
3278 // FIXME: How do we cope with isa?
3279
3280 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003281
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003282 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003283 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003284 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003285 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003286}
3287
Douglas Gregor374929f2009-09-18 15:37:17 +00003288void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3289 if (!CodeCompleter)
3290 return;
3291
John McCall0a2c5e22010-08-25 06:19:51 +00003292 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003293 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003294 enum CodeCompletionContext::Kind ContextKind
3295 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003296 switch ((DeclSpec::TST)TagSpec) {
3297 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003298 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003299 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003300 break;
3301
3302 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003303 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003304 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003305 break;
3306
3307 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003308 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003309 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003310 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003311 break;
3312
3313 default:
3314 assert(false && "Unknown type specifier kind in CodeCompleteTag");
3315 return;
3316 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003317
Douglas Gregor218937c2011-02-01 19:23:04 +00003318 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003319 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003320
3321 // First pass: look for tags.
3322 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003323 LookupVisibleDecls(S, LookupTagName, Consumer,
3324 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003325
Douglas Gregor8071e422010-08-15 06:18:01 +00003326 if (CodeCompleter->includeGlobals()) {
3327 // Second pass: look for nested name specifiers.
3328 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3329 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3330 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003331
Douglas Gregor52779fb2010-09-23 23:01:17 +00003332 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003333 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003334}
3335
Douglas Gregor1a480c42010-08-27 17:35:51 +00003336void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003337 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3338 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003339 Results.EnterNewScope();
3340 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3341 Results.AddResult("const");
3342 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3343 Results.AddResult("volatile");
3344 if (getLangOptions().C99 &&
3345 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3346 Results.AddResult("restrict");
3347 Results.ExitScope();
3348 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003349 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003350 Results.data(), Results.size());
3351}
3352
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003353void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003354 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003355 return;
3356
John McCall781472f2010-08-25 08:40:02 +00003357 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregorf9578432010-07-28 21:50:18 +00003358 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregorfb629412010-08-23 21:17:50 +00003359 CodeCompleteExpressionData Data(Switch->getCond()->getType());
3360 Data.IntegralConstantExpression = true;
3361 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003362 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003363 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003364
3365 // Code-complete the cases of a switch statement over an enumeration type
3366 // by providing the list of
3367 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
3368
3369 // Determine which enumerators we have already seen in the switch statement.
3370 // FIXME: Ideally, we would also be able to look *past* the code-completion
3371 // token, in case we are code-completing in the middle of the switch and not
3372 // at the end. However, we aren't able to do so at the moment.
3373 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003374 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003375 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3376 SC = SC->getNextSwitchCase()) {
3377 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3378 if (!Case)
3379 continue;
3380
3381 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3382 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3383 if (EnumConstantDecl *Enumerator
3384 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3385 // We look into the AST of the case statement to determine which
3386 // enumerator was named. Alternatively, we could compute the value of
3387 // the integral constant expression, then compare it against the
3388 // values of each enumerator. However, value-based approach would not
3389 // work as well with C++ templates where enumerators declared within a
3390 // template are type- and value-dependent.
3391 EnumeratorsSeen.insert(Enumerator);
3392
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003393 // If this is a qualified-id, keep track of the nested-name-specifier
3394 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003395 //
3396 // switch (TagD.getKind()) {
3397 // case TagDecl::TK_enum:
3398 // break;
3399 // case XXX
3400 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003401 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003402 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3403 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003404 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003405 }
3406 }
3407
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003408 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3409 // If there are no prior enumerators in C++, check whether we have to
3410 // qualify the names of the enumerators that we suggest, because they
3411 // may not be visible in this scope.
3412 Qualifier = getRequiredQualification(Context, CurContext,
3413 Enum->getDeclContext());
3414
3415 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3416 }
3417
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003418 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003419 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3420 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003421 Results.EnterNewScope();
3422 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3423 EEnd = Enum->enumerator_end();
3424 E != EEnd; ++E) {
3425 if (EnumeratorsSeen.count(*E))
3426 continue;
3427
Douglas Gregor5c722c702011-02-18 23:30:37 +00003428 CodeCompletionResult R(*E, Qualifier);
3429 R.Priority = CCP_EnumInCase;
3430 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003431 }
3432 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003433
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003434 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003435 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003436 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor5c722c702011-02-18 23:30:37 +00003437 CodeCompletionContext::CCC_OtherWithMacros,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003438 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003439}
3440
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003441namespace {
3442 struct IsBetterOverloadCandidate {
3443 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003444 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003445
3446 public:
John McCall5769d612010-02-08 23:07:23 +00003447 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3448 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003449
3450 bool
3451 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003452 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003453 }
3454 };
3455}
3456
Douglas Gregord28dcd72010-05-30 06:10:08 +00003457static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3458 if (NumArgs && !Args)
3459 return true;
3460
3461 for (unsigned I = 0; I != NumArgs; ++I)
3462 if (!Args[I])
3463 return true;
3464
3465 return false;
3466}
3467
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003468void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
3469 ExprTy **ArgsIn, unsigned NumArgs) {
3470 if (!CodeCompleter)
3471 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003472
3473 // When we're code-completing for a call, we fall back to ordinary
3474 // name code-completion whenever we can't produce specific
3475 // results. We may want to revisit this strategy in the future,
3476 // e.g., by merging the two kinds of results.
3477
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003478 Expr *Fn = (Expr *)FnIn;
3479 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003480
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003481 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003482 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003483 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003484 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003485 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003486 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003487
John McCall3b4294e2009-12-16 12:17:52 +00003488 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003489 SourceLocation Loc = Fn->getExprLoc();
3490 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003491
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003492 // FIXME: What if we're calling something that isn't a function declaration?
3493 // FIXME: What if we're calling a pseudo-destructor?
3494 // FIXME: What if we're calling a member function?
3495
Douglas Gregorc0265402010-01-21 15:46:19 +00003496 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3497 llvm::SmallVector<ResultCandidate, 8> Results;
3498
John McCall3b4294e2009-12-16 12:17:52 +00003499 Expr *NakedFn = Fn->IgnoreParenCasts();
3500 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3501 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3502 /*PartialOverloading=*/ true);
3503 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3504 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003505 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003506 if (!getLangOptions().CPlusPlus ||
3507 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003508 Results.push_back(ResultCandidate(FDecl));
3509 else
John McCall86820f52010-01-26 01:37:31 +00003510 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003511 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3512 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003513 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003514 }
John McCall3b4294e2009-12-16 12:17:52 +00003515 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003516
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003517 QualType ParamType;
3518
Douglas Gregorc0265402010-01-21 15:46:19 +00003519 if (!CandidateSet.empty()) {
3520 // Sort the overload candidate set by placing the best overloads first.
3521 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003522 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003523
Douglas Gregorc0265402010-01-21 15:46:19 +00003524 // Add the remaining viable overload candidates as code-completion reslults.
3525 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3526 CandEnd = CandidateSet.end();
3527 Cand != CandEnd; ++Cand) {
3528 if (Cand->Viable)
3529 Results.push_back(ResultCandidate(Cand->Function));
3530 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003531
3532 // From the viable candidates, try to determine the type of this parameter.
3533 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3534 if (const FunctionType *FType = Results[I].getFunctionType())
3535 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3536 if (NumArgs < Proto->getNumArgs()) {
3537 if (ParamType.isNull())
3538 ParamType = Proto->getArgType(NumArgs);
3539 else if (!Context.hasSameUnqualifiedType(
3540 ParamType.getNonReferenceType(),
3541 Proto->getArgType(NumArgs).getNonReferenceType())) {
3542 ParamType = QualType();
3543 break;
3544 }
3545 }
3546 }
3547 } else {
3548 // Try to determine the parameter type from the type of the expression
3549 // being called.
3550 QualType FunctionType = Fn->getType();
3551 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3552 FunctionType = Ptr->getPointeeType();
3553 else if (const BlockPointerType *BlockPtr
3554 = FunctionType->getAs<BlockPointerType>())
3555 FunctionType = BlockPtr->getPointeeType();
3556 else if (const MemberPointerType *MemPtr
3557 = FunctionType->getAs<MemberPointerType>())
3558 FunctionType = MemPtr->getPointeeType();
3559
3560 if (const FunctionProtoType *Proto
3561 = FunctionType->getAs<FunctionProtoType>()) {
3562 if (NumArgs < Proto->getNumArgs())
3563 ParamType = Proto->getArgType(NumArgs);
3564 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003565 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003566
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003567 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003568 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003569 else
3570 CodeCompleteExpression(S, ParamType);
3571
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003572 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003573 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3574 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003575}
3576
John McCalld226f652010-08-21 09:40:31 +00003577void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3578 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003579 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003580 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003581 return;
3582 }
3583
3584 CodeCompleteExpression(S, VD->getType());
3585}
3586
3587void Sema::CodeCompleteReturn(Scope *S) {
3588 QualType ResultType;
3589 if (isa<BlockDecl>(CurContext)) {
3590 if (BlockScopeInfo *BSI = getCurBlock())
3591 ResultType = BSI->ReturnType;
3592 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3593 ResultType = Function->getResultType();
3594 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3595 ResultType = Method->getResultType();
3596
3597 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003598 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003599 else
3600 CodeCompleteExpression(S, ResultType);
3601}
3602
3603void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3604 if (LHS)
3605 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3606 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003607 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003608}
3609
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003610void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003611 bool EnteringContext) {
3612 if (!SS.getScopeRep() || !CodeCompleter)
3613 return;
3614
Douglas Gregor86d9a522009-09-21 16:56:56 +00003615 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3616 if (!Ctx)
3617 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003618
3619 // Try to instantiate any non-dependent declaration contexts before
3620 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003621 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003622 return;
3623
Douglas Gregor218937c2011-02-01 19:23:04 +00003624 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3625 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003626 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003627
Douglas Gregor86d9a522009-09-21 16:56:56 +00003628 // The "template" keyword can follow "::" in the grammar, but only
3629 // put it into the grammar if the nested-name-specifier is dependent.
3630 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3631 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003632 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003633
3634 // Add calls to overridden virtual functions, if there are any.
3635 //
3636 // FIXME: This isn't wonderful, because we don't know whether we're actually
3637 // in a context that permits expressions. This is a general issue with
3638 // qualified-id completions.
3639 if (!EnteringContext)
3640 MaybeAddOverrideCalls(*this, Ctx, Results);
3641 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003642
Douglas Gregorf6961522010-08-27 21:18:54 +00003643 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3644 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3645
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003646 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorf6961522010-08-27 21:18:54 +00003647 CodeCompletionContext::CCC_Name,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003648 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003649}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003650
3651void Sema::CodeCompleteUsing(Scope *S) {
3652 if (!CodeCompleter)
3653 return;
3654
Douglas Gregor218937c2011-02-01 19:23:04 +00003655 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003656 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3657 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003658 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003659
3660 // If we aren't in class scope, we could see the "namespace" keyword.
3661 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003662 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003663
3664 // After "using", we can see anything that would start a
3665 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003666 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003667 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3668 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003669 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003670
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003671 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003672 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003673 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003674}
3675
3676void Sema::CodeCompleteUsingDirective(Scope *S) {
3677 if (!CodeCompleter)
3678 return;
3679
Douglas Gregor86d9a522009-09-21 16:56:56 +00003680 // After "using namespace", we expect to see a namespace name or namespace
3681 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003682 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3683 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003684 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003685 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003686 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003687 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3688 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003689 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003690 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003691 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003692 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003693}
3694
3695void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3696 if (!CodeCompleter)
3697 return;
3698
Douglas Gregor86d9a522009-09-21 16:56:56 +00003699 DeclContext *Ctx = (DeclContext *)S->getEntity();
3700 if (!S->getParent())
3701 Ctx = Context.getTranslationUnitDecl();
3702
Douglas Gregor52779fb2010-09-23 23:01:17 +00003703 bool SuppressedGlobalResults
3704 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3705
Douglas Gregor218937c2011-02-01 19:23:04 +00003706 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003707 SuppressedGlobalResults
3708 ? CodeCompletionContext::CCC_Namespace
3709 : CodeCompletionContext::CCC_Other,
3710 &ResultBuilder::IsNamespace);
3711
3712 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003713 // We only want to see those namespaces that have already been defined
3714 // within this scope, because its likely that the user is creating an
3715 // extended namespace declaration. Keep track of the most recent
3716 // definition of each namespace.
3717 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3718 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3719 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3720 NS != NSEnd; ++NS)
3721 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3722
3723 // Add the most recent definition (or extended definition) of each
3724 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003725 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003726 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3727 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3728 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003729 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003730 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003731 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003732 }
3733
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003734 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003735 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003736 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003737}
3738
3739void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3740 if (!CodeCompleter)
3741 return;
3742
Douglas Gregor86d9a522009-09-21 16:56:56 +00003743 // After "namespace", we expect to see a namespace or 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 Gregor5d2fc402010-01-14 03:27:13 +00003747 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003748 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3749 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003750 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003751 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003752 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003753}
3754
Douglas Gregored8d3222009-09-18 20:05:18 +00003755void Sema::CodeCompleteOperatorName(Scope *S) {
3756 if (!CodeCompleter)
3757 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003758
John McCall0a2c5e22010-08-25 06:19:51 +00003759 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003760 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3761 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003762 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003763 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003764
Douglas Gregor86d9a522009-09-21 16:56:56 +00003765 // Add the names of overloadable operators.
3766#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3767 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003768 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003769#include "clang/Basic/OperatorKinds.def"
3770
3771 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003772 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003773 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003774 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3775 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003776
3777 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003778 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003779 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003780
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003781 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003782 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003783 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003784}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003785
Douglas Gregor0133f522010-08-28 00:00:50 +00003786void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00003787 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00003788 unsigned NumInitializers) {
3789 CXXConstructorDecl *Constructor
3790 = static_cast<CXXConstructorDecl *>(ConstructorD);
3791 if (!Constructor)
3792 return;
3793
Douglas Gregor218937c2011-02-01 19:23:04 +00003794 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003795 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003796 Results.EnterNewScope();
3797
3798 // Fill in any already-initialized fields or base classes.
3799 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3800 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3801 for (unsigned I = 0; I != NumInitializers; ++I) {
3802 if (Initializers[I]->isBaseInitializer())
3803 InitializedBases.insert(
3804 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3805 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003806 InitializedFields.insert(cast<FieldDecl>(
3807 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00003808 }
3809
3810 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00003811 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00003812 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003813 CXXRecordDecl *ClassDecl = Constructor->getParent();
3814 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3815 BaseEnd = ClassDecl->bases_end();
3816 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003817 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3818 SawLastInitializer
3819 = NumInitializers > 0 &&
3820 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3821 Context.hasSameUnqualifiedType(Base->getType(),
3822 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003823 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003824 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003825
Douglas Gregor218937c2011-02-01 19:23:04 +00003826 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003827 Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003828 Base->getType().getAsString(Context.PrintingPolicy)));
3829 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3830 Builder.AddPlaceholderChunk("args");
3831 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3832 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003833 SawLastInitializer? CCP_NextInitializer
3834 : CCP_MemberDeclaration));
3835 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003836 }
3837
3838 // Add completions for virtual base classes.
3839 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3840 BaseEnd = ClassDecl->vbases_end();
3841 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003842 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3843 SawLastInitializer
3844 = NumInitializers > 0 &&
3845 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3846 Context.hasSameUnqualifiedType(Base->getType(),
3847 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003848 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003849 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003850
Douglas Gregor218937c2011-02-01 19:23:04 +00003851 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003852 Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003853 Base->getType().getAsString(Context.PrintingPolicy)));
3854 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3855 Builder.AddPlaceholderChunk("args");
3856 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3857 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003858 SawLastInitializer? CCP_NextInitializer
3859 : CCP_MemberDeclaration));
3860 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003861 }
3862
3863 // Add completions for members.
3864 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3865 FieldEnd = ClassDecl->field_end();
3866 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003867 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
3868 SawLastInitializer
3869 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00003870 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
3871 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00003872 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003873 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003874
3875 if (!Field->getDeclName())
3876 continue;
3877
Douglas Gregordae68752011-02-01 22:57:45 +00003878 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003879 Field->getIdentifier()->getName()));
3880 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3881 Builder.AddPlaceholderChunk("args");
3882 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3883 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003884 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00003885 : CCP_MemberDeclaration,
3886 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00003887 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003888 }
3889 Results.ExitScope();
3890
Douglas Gregor52779fb2010-09-23 23:01:17 +00003891 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00003892 Results.data(), Results.size());
3893}
3894
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003895// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3896// true or false.
3897#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00003898static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003899 ResultBuilder &Results,
3900 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003901 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003902 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003903 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003904
Douglas Gregor218937c2011-02-01 19:23:04 +00003905 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003906 if (LangOpts.ObjC2) {
3907 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00003908 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3909 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3910 Builder.AddPlaceholderChunk("property");
3911 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003912
3913 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00003914 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3915 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3916 Builder.AddPlaceholderChunk("property");
3917 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003918 }
3919}
3920
Douglas Gregorbca403c2010-01-13 23:51:12 +00003921static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003922 ResultBuilder &Results,
3923 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003924 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003925
3926 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003927 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003928
3929 if (LangOpts.ObjC2) {
3930 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00003931 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003932
3933 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00003934 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003935
3936 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00003937 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003938 }
3939}
3940
Douglas Gregorbca403c2010-01-13 23:51:12 +00003941static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003942 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003943 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003944
3945 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00003946 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3947 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3948 Builder.AddPlaceholderChunk("name");
3949 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003950
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003951 if (Results.includeCodePatterns()) {
3952 // @interface name
3953 // FIXME: Could introduce the whole pattern, including superclasses and
3954 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00003955 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
3956 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3957 Builder.AddPlaceholderChunk("class");
3958 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003959
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003960 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00003961 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3962 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3963 Builder.AddPlaceholderChunk("protocol");
3964 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003965
3966 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00003967 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
3968 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3969 Builder.AddPlaceholderChunk("class");
3970 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003971 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003972
3973 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00003974 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
3975 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3976 Builder.AddPlaceholderChunk("alias");
3977 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3978 Builder.AddPlaceholderChunk("class");
3979 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003980}
3981
John McCalld226f652010-08-21 09:40:31 +00003982void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorc464ae82009-12-07 09:27:33 +00003983 bool InInterface) {
John McCall0a2c5e22010-08-25 06:19:51 +00003984 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003985 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3986 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003987 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003988 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003989 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003990 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003991 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003992 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00003993 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003994 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003995 HandleCodeCompleteResults(this, CodeCompleter,
3996 CodeCompletionContext::CCC_Other,
3997 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00003998}
3999
Douglas Gregorbca403c2010-01-13 23:51:12 +00004000static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004001 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004002 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004003
4004 // @encode ( type-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004005 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4006 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4007 Builder.AddPlaceholderChunk("type-name");
4008 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4009 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004010
4011 // @protocol ( protocol-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004012 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4013 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4014 Builder.AddPlaceholderChunk("protocol-name");
4015 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4016 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004017
4018 // @selector ( selector )
Douglas Gregor218937c2011-02-01 19:23:04 +00004019 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4020 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4021 Builder.AddPlaceholderChunk("selector");
4022 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4023 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004024}
4025
Douglas Gregorbca403c2010-01-13 23:51:12 +00004026static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004027 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004028 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004029
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004030 if (Results.includeCodePatterns()) {
4031 // @try { statements } @catch ( declaration ) { statements } @finally
4032 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004033 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4034 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4035 Builder.AddPlaceholderChunk("statements");
4036 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4037 Builder.AddTextChunk("@catch");
4038 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4039 Builder.AddPlaceholderChunk("parameter");
4040 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4041 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4042 Builder.AddPlaceholderChunk("statements");
4043 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4044 Builder.AddTextChunk("@finally");
4045 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4046 Builder.AddPlaceholderChunk("statements");
4047 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4048 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004049 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004050
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004051 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004052 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4053 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4054 Builder.AddPlaceholderChunk("expression");
4055 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004056
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004057 if (Results.includeCodePatterns()) {
4058 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004059 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4060 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4061 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4062 Builder.AddPlaceholderChunk("expression");
4063 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4064 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4065 Builder.AddPlaceholderChunk("statements");
4066 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4067 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004068 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004069}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004070
Douglas Gregorbca403c2010-01-13 23:51:12 +00004071static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004072 ResultBuilder &Results,
4073 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004074 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004075 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4076 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4077 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004078 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004079 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004080}
4081
4082void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004083 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4084 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004085 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004086 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004087 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004088 HandleCodeCompleteResults(this, CodeCompleter,
4089 CodeCompletionContext::CCC_Other,
4090 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004091}
4092
4093void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004094 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4095 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004096 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004097 AddObjCStatementResults(Results, false);
4098 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004099 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004100 HandleCodeCompleteResults(this, CodeCompleter,
4101 CodeCompletionContext::CCC_Other,
4102 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004103}
4104
4105void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004106 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4107 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004108 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004109 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004110 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004111 HandleCodeCompleteResults(this, CodeCompleter,
4112 CodeCompletionContext::CCC_Other,
4113 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004114}
4115
Douglas Gregor988358f2009-11-19 00:14:45 +00004116/// \brief Determine whether the addition of the given flag to an Objective-C
4117/// property's attributes will cause a conflict.
4118static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4119 // Check if we've already added this flag.
4120 if (Attributes & NewFlag)
4121 return true;
4122
4123 Attributes |= NewFlag;
4124
4125 // Check for collisions with "readonly".
4126 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4127 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4128 ObjCDeclSpec::DQ_PR_assign |
4129 ObjCDeclSpec::DQ_PR_copy |
4130 ObjCDeclSpec::DQ_PR_retain)))
4131 return true;
4132
4133 // Check for more than one of { assign, copy, retain }.
4134 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
4135 ObjCDeclSpec::DQ_PR_copy |
4136 ObjCDeclSpec::DQ_PR_retain);
4137 if (AssignCopyRetMask &&
4138 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
4139 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
4140 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
4141 return true;
4142
4143 return false;
4144}
4145
Douglas Gregora93b1082009-11-18 23:08:07 +00004146void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004147 if (!CodeCompleter)
4148 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004149
Steve Naroffece8e712009-10-08 21:55:05 +00004150 unsigned Attributes = ODS.getPropertyAttributes();
4151
John McCall0a2c5e22010-08-25 06:19:51 +00004152 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004153 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4154 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004155 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004156 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004157 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004158 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004159 Results.AddResult(CodeCompletionResult("assign"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004160 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004161 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004162 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004163 Results.AddResult(CodeCompletionResult("retain"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004164 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004165 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004166 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004167 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004168 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4169 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004170 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004171 CodeCompletionBuilder Setter(Results.getAllocator());
4172 Setter.AddTypedTextChunk("setter");
4173 Setter.AddTextChunk(" = ");
4174 Setter.AddPlaceholderChunk("method");
4175 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004176 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004177 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004178 CodeCompletionBuilder Getter(Results.getAllocator());
4179 Getter.AddTypedTextChunk("getter");
4180 Getter.AddTextChunk(" = ");
4181 Getter.AddPlaceholderChunk("method");
4182 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004183 }
Steve Naroffece8e712009-10-08 21:55:05 +00004184 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004185 HandleCodeCompleteResults(this, CodeCompleter,
4186 CodeCompletionContext::CCC_Other,
4187 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004188}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004189
Douglas Gregor4ad96852009-11-19 07:41:15 +00004190/// \brief Descripts the kind of Objective-C method that we want to find
4191/// via code completion.
4192enum ObjCMethodKind {
4193 MK_Any, //< Any kind of method, provided it means other specified criteria.
4194 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4195 MK_OneArgSelector //< One-argument selector.
4196};
4197
Douglas Gregor458433d2010-08-26 15:07:07 +00004198static bool isAcceptableObjCSelector(Selector Sel,
4199 ObjCMethodKind WantKind,
4200 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004201 unsigned NumSelIdents,
4202 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004203 if (NumSelIdents > Sel.getNumArgs())
4204 return false;
4205
4206 switch (WantKind) {
4207 case MK_Any: break;
4208 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4209 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4210 }
4211
Douglas Gregorcf544262010-11-17 21:36:08 +00004212 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4213 return false;
4214
Douglas Gregor458433d2010-08-26 15:07:07 +00004215 for (unsigned I = 0; I != NumSelIdents; ++I)
4216 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4217 return false;
4218
4219 return true;
4220}
4221
Douglas Gregor4ad96852009-11-19 07:41:15 +00004222static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4223 ObjCMethodKind WantKind,
4224 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004225 unsigned NumSelIdents,
4226 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004227 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004228 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004229}
Douglas Gregord36adf52010-09-16 16:06:31 +00004230
4231namespace {
4232 /// \brief A set of selectors, which is used to avoid introducing multiple
4233 /// completions with the same selector into the result set.
4234 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4235}
4236
Douglas Gregor36ecb042009-11-17 23:22:23 +00004237/// \brief Add all of the Objective-C methods in the given Objective-C
4238/// container to the set of results.
4239///
4240/// The container will be a class, protocol, category, or implementation of
4241/// any of the above. This mether will recurse to include methods from
4242/// the superclasses of classes along with their categories, protocols, and
4243/// implementations.
4244///
4245/// \param Container the container in which we'll look to find methods.
4246///
4247/// \param WantInstance whether to add instance methods (only); if false, this
4248/// routine will add factory methods (only).
4249///
4250/// \param CurContext the context in which we're performing the lookup that
4251/// finds methods.
4252///
Douglas Gregorcf544262010-11-17 21:36:08 +00004253/// \param AllowSameLength Whether we allow a method to be added to the list
4254/// when it has the same number of parameters as we have selector identifiers.
4255///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004256/// \param Results the structure into which we'll add results.
4257static void AddObjCMethods(ObjCContainerDecl *Container,
4258 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004259 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004260 IdentifierInfo **SelIdents,
4261 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004262 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004263 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004264 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004265 ResultBuilder &Results,
4266 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004267 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004268 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4269 MEnd = Container->meth_end();
4270 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004271 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4272 // Check whether the selector identifiers we've been given are a
4273 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004274 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4275 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004276 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004277
Douglas Gregord36adf52010-09-16 16:06:31 +00004278 if (!Selectors.insert((*M)->getSelector()))
4279 continue;
4280
Douglas Gregord3c68542009-11-19 01:08:35 +00004281 Result R = Result(*M, 0);
4282 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004283 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004284 if (!InOriginalClass)
4285 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004286 Results.MaybeAddResult(R, CurContext);
4287 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004288 }
4289
Douglas Gregore396c7b2010-09-16 15:34:59 +00004290 // Visit the protocols of protocols.
4291 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4292 const ObjCList<ObjCProtocolDecl> &Protocols
4293 = Protocol->getReferencedProtocols();
4294 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4295 E = Protocols.end();
4296 I != E; ++I)
4297 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004298 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004299 }
4300
Douglas Gregor36ecb042009-11-17 23:22:23 +00004301 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4302 if (!IFace)
4303 return;
4304
4305 // Add methods in protocols.
4306 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4307 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4308 E = Protocols.end();
4309 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004310 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004311 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004312
4313 // Add methods in categories.
4314 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4315 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004316 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004317 NumSelIdents, CurContext, Selectors, AllowSameLength,
4318 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004319
4320 // Add a categories protocol methods.
4321 const ObjCList<ObjCProtocolDecl> &Protocols
4322 = CatDecl->getReferencedProtocols();
4323 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4324 E = Protocols.end();
4325 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004326 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004327 NumSelIdents, CurContext, Selectors, AllowSameLength,
4328 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004329
4330 // Add methods in category implementations.
4331 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004332 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004333 NumSelIdents, CurContext, Selectors, AllowSameLength,
4334 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004335 }
4336
4337 // Add methods in superclass.
4338 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004339 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004340 SelIdents, NumSelIdents, CurContext, Selectors,
4341 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004342
4343 // Add methods in our implementation, if any.
4344 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004345 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004346 NumSelIdents, CurContext, Selectors, AllowSameLength,
4347 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004348}
4349
4350
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004351void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004352 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004353
4354 // Try to find the interface where getters might live.
John McCalld226f652010-08-21 09:40:31 +00004355 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004356 if (!Class) {
4357 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004358 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004359 Class = Category->getClassInterface();
4360
4361 if (!Class)
4362 return;
4363 }
4364
4365 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004366 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4367 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004368 Results.EnterNewScope();
4369
Douglas Gregord36adf52010-09-16 16:06:31 +00004370 VisitedSelectorSet Selectors;
4371 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004372 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004373 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004374 HandleCodeCompleteResults(this, CodeCompleter,
4375 CodeCompletionContext::CCC_Other,
4376 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004377}
4378
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004379void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004380 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004381
4382 // Try to find the interface where setters might live.
4383 ObjCInterfaceDecl *Class
John McCalld226f652010-08-21 09:40:31 +00004384 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004385 if (!Class) {
4386 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004387 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004388 Class = Category->getClassInterface();
4389
4390 if (!Class)
4391 return;
4392 }
4393
4394 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004395 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4396 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004397 Results.EnterNewScope();
4398
Douglas Gregord36adf52010-09-16 16:06:31 +00004399 VisitedSelectorSet Selectors;
4400 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004401 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004402
4403 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004404 HandleCodeCompleteResults(this, CodeCompleter,
4405 CodeCompletionContext::CCC_Other,
4406 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004407}
4408
Douglas Gregorafc45782011-02-15 22:19:42 +00004409void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4410 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004411 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004412 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4413 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004414 Results.EnterNewScope();
4415
4416 // Add context-sensitive, Objective-C parameter-passing keywords.
4417 bool AddedInOut = false;
4418 if ((DS.getObjCDeclQualifier() &
4419 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4420 Results.AddResult("in");
4421 Results.AddResult("inout");
4422 AddedInOut = true;
4423 }
4424 if ((DS.getObjCDeclQualifier() &
4425 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4426 Results.AddResult("out");
4427 if (!AddedInOut)
4428 Results.AddResult("inout");
4429 }
4430 if ((DS.getObjCDeclQualifier() &
4431 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4432 ObjCDeclSpec::DQ_Oneway)) == 0) {
4433 Results.AddResult("bycopy");
4434 Results.AddResult("byref");
4435 Results.AddResult("oneway");
4436 }
4437
Douglas Gregorafc45782011-02-15 22:19:42 +00004438 // If we're completing the return type of an Objective-C method and the
4439 // identifier IBAction refers to a macro, provide a completion item for
4440 // an action, e.g.,
4441 // IBAction)<#selector#>:(id)sender
4442 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4443 Context.Idents.get("IBAction").hasMacroDefinition()) {
4444 typedef CodeCompletionString::Chunk Chunk;
4445 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4446 CXAvailability_Available);
4447 Builder.AddTypedTextChunk("IBAction");
4448 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4449 Builder.AddPlaceholderChunk("selector");
4450 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4451 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4452 Builder.AddTextChunk("id");
4453 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4454 Builder.AddTextChunk("sender");
4455 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4456 }
4457
Douglas Gregord32b0222010-08-24 01:06:58 +00004458 // Add various builtin type names and specifiers.
4459 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4460 Results.ExitScope();
4461
4462 // Add the various type names
4463 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4464 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4465 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4466 CodeCompleter->includeGlobals());
4467
4468 if (CodeCompleter->includeMacros())
4469 AddMacroResults(PP, Results);
4470
4471 HandleCodeCompleteResults(this, CodeCompleter,
4472 CodeCompletionContext::CCC_Type,
4473 Results.data(), Results.size());
4474}
4475
Douglas Gregor22f56992010-04-06 19:22:33 +00004476/// \brief When we have an expression with type "id", we may assume
4477/// that it has some more-specific class type based on knowledge of
4478/// common uses of Objective-C. This routine returns that class type,
4479/// or NULL if no better result could be determined.
4480static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004481 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004482 if (!Msg)
4483 return 0;
4484
4485 Selector Sel = Msg->getSelector();
4486 if (Sel.isNull())
4487 return 0;
4488
4489 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4490 if (!Id)
4491 return 0;
4492
4493 ObjCMethodDecl *Method = Msg->getMethodDecl();
4494 if (!Method)
4495 return 0;
4496
4497 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004498 ObjCInterfaceDecl *IFace = 0;
4499 switch (Msg->getReceiverKind()) {
4500 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004501 if (const ObjCObjectType *ObjType
4502 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4503 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004504 break;
4505
4506 case ObjCMessageExpr::Instance: {
4507 QualType T = Msg->getInstanceReceiver()->getType();
4508 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4509 IFace = Ptr->getInterfaceDecl();
4510 break;
4511 }
4512
4513 case ObjCMessageExpr::SuperInstance:
4514 case ObjCMessageExpr::SuperClass:
4515 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004516 }
4517
4518 if (!IFace)
4519 return 0;
4520
4521 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4522 if (Method->isInstanceMethod())
4523 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4524 .Case("retain", IFace)
4525 .Case("autorelease", IFace)
4526 .Case("copy", IFace)
4527 .Case("copyWithZone", IFace)
4528 .Case("mutableCopy", IFace)
4529 .Case("mutableCopyWithZone", IFace)
4530 .Case("awakeFromCoder", IFace)
4531 .Case("replacementObjectFromCoder", IFace)
4532 .Case("class", IFace)
4533 .Case("classForCoder", IFace)
4534 .Case("superclass", Super)
4535 .Default(0);
4536
4537 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4538 .Case("new", IFace)
4539 .Case("alloc", IFace)
4540 .Case("allocWithZone", IFace)
4541 .Case("class", IFace)
4542 .Case("superclass", Super)
4543 .Default(0);
4544}
4545
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004546// Add a special completion for a message send to "super", which fills in the
4547// most likely case of forwarding all of our arguments to the superclass
4548// function.
4549///
4550/// \param S The semantic analysis object.
4551///
4552/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4553/// the "super" keyword. Otherwise, we just need to provide the arguments.
4554///
4555/// \param SelIdents The identifiers in the selector that have already been
4556/// provided as arguments for a send to "super".
4557///
4558/// \param NumSelIdents The number of identifiers in \p SelIdents.
4559///
4560/// \param Results The set of results to augment.
4561///
4562/// \returns the Objective-C method declaration that would be invoked by
4563/// this "super" completion. If NULL, no completion was added.
4564static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4565 IdentifierInfo **SelIdents,
4566 unsigned NumSelIdents,
4567 ResultBuilder &Results) {
4568 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4569 if (!CurMethod)
4570 return 0;
4571
4572 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4573 if (!Class)
4574 return 0;
4575
4576 // Try to find a superclass method with the same selector.
4577 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004578 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4579 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004580 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4581 CurMethod->isInstanceMethod());
4582
Douglas Gregor78bcd912011-02-16 00:51:18 +00004583 // Check in categories or class extensions.
4584 if (!SuperMethod) {
4585 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4586 Category = Category->getNextClassCategory())
4587 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4588 CurMethod->isInstanceMethod())))
4589 break;
4590 }
4591 }
4592
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004593 if (!SuperMethod)
4594 return 0;
4595
4596 // Check whether the superclass method has the same signature.
4597 if (CurMethod->param_size() != SuperMethod->param_size() ||
4598 CurMethod->isVariadic() != SuperMethod->isVariadic())
4599 return 0;
4600
4601 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4602 CurPEnd = CurMethod->param_end(),
4603 SuperP = SuperMethod->param_begin();
4604 CurP != CurPEnd; ++CurP, ++SuperP) {
4605 // Make sure the parameter types are compatible.
4606 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4607 (*SuperP)->getType()))
4608 return 0;
4609
4610 // Make sure we have a parameter name to forward!
4611 if (!(*CurP)->getIdentifier())
4612 return 0;
4613 }
4614
4615 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004616 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004617
4618 // Give this completion a return type.
Douglas Gregor218937c2011-02-01 19:23:04 +00004619 AddResultTypeChunk(S.Context, SuperMethod, Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004620
4621 // If we need the "super" keyword, add it (plus some spacing).
4622 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004623 Builder.AddTypedTextChunk("super");
4624 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004625 }
4626
4627 Selector Sel = CurMethod->getSelector();
4628 if (Sel.isUnarySelector()) {
4629 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004630 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004631 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004632 else
Douglas Gregordae68752011-02-01 22:57:45 +00004633 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004634 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004635 } else {
4636 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4637 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4638 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004639 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004640
4641 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004642 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004643 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004644 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004645 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004646 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004647 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004648 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004649 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004650 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004651 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004652 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004653 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004654 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004655 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004656 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004657 }
4658 }
4659 }
4660
Douglas Gregor218937c2011-02-01 19:23:04 +00004661 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004662 SuperMethod->isInstanceMethod()
4663 ? CXCursor_ObjCInstanceMethodDecl
4664 : CXCursor_ObjCClassMethodDecl));
4665 return SuperMethod;
4666}
4667
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004668void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004669 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004670 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4671 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004672 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004673
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004674 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4675 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004676 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4677 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004678
4679 // If we are in an Objective-C method inside a class that has a superclass,
4680 // add "super" as an option.
4681 if (ObjCMethodDecl *Method = getCurMethodDecl())
4682 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004683 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004684 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004685
4686 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4687 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004688
4689 Results.ExitScope();
4690
4691 if (CodeCompleter->includeMacros())
4692 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004693 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004694 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004695
4696}
4697
Douglas Gregor2725ca82010-04-21 19:57:20 +00004698void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4699 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004700 unsigned NumSelIdents,
4701 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004702 ObjCInterfaceDecl *CDecl = 0;
4703 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4704 // Figure out which interface we're in.
4705 CDecl = CurMethod->getClassInterface();
4706 if (!CDecl)
4707 return;
4708
4709 // Find the superclass of this class.
4710 CDecl = CDecl->getSuperClass();
4711 if (!CDecl)
4712 return;
4713
4714 if (CurMethod->isInstanceMethod()) {
4715 // We are inside an instance method, which means that the message
4716 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004717 // current object.
4718 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004719 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004720 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004721 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004722 }
4723
4724 // Fall through to send to the superclass in CDecl.
4725 } else {
4726 // "super" may be the name of a type or variable. Figure out which
4727 // it is.
4728 IdentifierInfo *Super = &Context.Idents.get("super");
4729 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4730 LookupOrdinaryName);
4731 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4732 // "super" names an interface. Use it.
4733 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004734 if (const ObjCObjectType *Iface
4735 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4736 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004737 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4738 // "super" names an unresolved type; we can't be more specific.
4739 } else {
4740 // Assume that "super" names some kind of value and parse that way.
4741 CXXScopeSpec SS;
4742 UnqualifiedId id;
4743 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004744 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004745 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004746 SelIdents, NumSelIdents,
4747 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004748 }
4749
4750 // Fall through
4751 }
4752
John McCallb3d87482010-08-24 05:47:05 +00004753 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004754 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004755 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004756 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004757 NumSelIdents, AtArgumentExpression,
4758 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004759}
4760
Douglas Gregorb9d77572010-09-21 00:03:25 +00004761/// \brief Given a set of code-completion results for the argument of a message
4762/// send, determine the preferred type (if any) for that argument expression.
4763static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4764 unsigned NumSelIdents) {
4765 typedef CodeCompletionResult Result;
4766 ASTContext &Context = Results.getSema().Context;
4767
4768 QualType PreferredType;
4769 unsigned BestPriority = CCP_Unlikely * 2;
4770 Result *ResultsData = Results.data();
4771 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4772 Result &R = ResultsData[I];
4773 if (R.Kind == Result::RK_Declaration &&
4774 isa<ObjCMethodDecl>(R.Declaration)) {
4775 if (R.Priority <= BestPriority) {
4776 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4777 if (NumSelIdents <= Method->param_size()) {
4778 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4779 ->getType();
4780 if (R.Priority < BestPriority || PreferredType.isNull()) {
4781 BestPriority = R.Priority;
4782 PreferredType = MyPreferredType;
4783 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4784 MyPreferredType)) {
4785 PreferredType = QualType();
4786 }
4787 }
4788 }
4789 }
4790 }
4791
4792 return PreferredType;
4793}
4794
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004795static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4796 ParsedType Receiver,
4797 IdentifierInfo **SelIdents,
4798 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004799 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004800 bool IsSuper,
4801 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004802 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004803 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004804
Douglas Gregor24a069f2009-11-17 17:59:40 +00004805 // If the given name refers to an interface type, retrieve the
4806 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004807 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004808 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004809 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004810 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4811 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004812 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004813
Douglas Gregor36ecb042009-11-17 23:22:23 +00004814 // Add all of the factory methods in this Objective-C class, its protocols,
4815 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004816 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004817
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004818 // If this is a send-to-super, try to add the special "super" send
4819 // completion.
4820 if (IsSuper) {
4821 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004822 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4823 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004824 Results.Ignore(SuperMethod);
4825 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004826
Douglas Gregor265f7492010-08-27 15:29:55 +00004827 // If we're inside an Objective-C method definition, prefer its selector to
4828 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004829 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00004830 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004831
Douglas Gregord36adf52010-09-16 16:06:31 +00004832 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00004833 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004834 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004835 SemaRef.CurContext, Selectors, AtArgumentExpression,
4836 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004837 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00004838 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004839
Douglas Gregor719770d2010-04-06 17:30:22 +00004840 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004841 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004842 if (SemaRef.ExternalSource) {
4843 for (uint32_t I = 0,
4844 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00004845 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004846 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
4847 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004848 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004849
4850 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004851 }
4852 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004853
4854 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
4855 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00004856 M != MEnd; ++M) {
4857 for (ObjCMethodList *MethList = &M->second.second;
4858 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004859 MethList = MethList->Next) {
4860 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4861 NumSelIdents))
4862 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004863
Douglas Gregor13438f92010-04-06 16:40:00 +00004864 Result R(MethList->Method, 0);
4865 R.StartParameter = NumSelIdents;
4866 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004867 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00004868 }
4869 }
4870 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004871
4872 Results.ExitScope();
4873}
Douglas Gregor13438f92010-04-06 16:40:00 +00004874
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004875void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4876 IdentifierInfo **SelIdents,
4877 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004878 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004879 bool IsSuper) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004880 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4881 CodeCompletionContext::CCC_Other);
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004882 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
4883 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00004884
4885 // If we're actually at the argument expression (rather than prior to the
4886 // selector), we're actually performing code completion for an expression.
4887 // Determine whether we have a single, best method. If so, we can
4888 // code-complete the expression using the corresponding parameter type as
4889 // our preferred type, improving completion results.
4890 if (AtArgumentExpression) {
4891 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4892 NumSelIdents);
4893 if (PreferredType.isNull())
4894 CodeCompleteOrdinaryName(S, PCC_Expression);
4895 else
4896 CodeCompleteExpression(S, PreferredType);
4897 return;
4898 }
4899
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004900 HandleCodeCompleteResults(this, CodeCompleter,
4901 CodeCompletionContext::CCC_Other,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004902 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004903}
4904
Douglas Gregord3c68542009-11-19 01:08:35 +00004905void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4906 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004907 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004908 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004909 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00004910 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00004911
4912 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00004913
Douglas Gregor36ecb042009-11-17 23:22:23 +00004914 // If necessary, apply function/array conversion to the receiver.
4915 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00004916 if (RecExpr) {
4917 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
4918 if (Conv.isInvalid()) // conversion failed. bail.
4919 return;
4920 RecExpr = Conv.take();
4921 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004922 QualType ReceiverType = RecExpr? RecExpr->getType()
4923 : Super? Context.getObjCObjectPointerType(
4924 Context.getObjCInterfaceType(Super))
4925 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00004926
Douglas Gregorda892642010-11-08 21:12:30 +00004927 // If we're messaging an expression with type "id" or "Class", check
4928 // whether we know something special about the receiver that allows
4929 // us to assume a more-specific receiver type.
4930 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
4931 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
4932 if (ReceiverType->isObjCClassType())
4933 return CodeCompleteObjCClassMessage(S,
4934 ParsedType::make(Context.getObjCInterfaceType(IFace)),
4935 SelIdents, NumSelIdents,
4936 AtArgumentExpression, Super);
4937
4938 ReceiverType = Context.getObjCObjectPointerType(
4939 Context.getObjCInterfaceType(IFace));
4940 }
4941
Douglas Gregor36ecb042009-11-17 23:22:23 +00004942 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00004943 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4944 CodeCompletionContext::CCC_Other);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004945 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00004946
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004947 // If this is a send-to-super, try to add the special "super" send
4948 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004949 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004950 if (ObjCMethodDecl *SuperMethod
4951 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
4952 Results))
4953 Results.Ignore(SuperMethod);
4954 }
4955
Douglas Gregor265f7492010-08-27 15:29:55 +00004956 // If we're inside an Objective-C method definition, prefer its selector to
4957 // others.
4958 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
4959 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004960
Douglas Gregord36adf52010-09-16 16:06:31 +00004961 // Keep track of the selectors we've already added.
4962 VisitedSelectorSet Selectors;
4963
Douglas Gregorf74a4192009-11-18 00:06:18 +00004964 // Handle messages to Class. This really isn't a message to an instance
4965 // method, so we treat it the same way we would treat a message send to a
4966 // class method.
4967 if (ReceiverType->isObjCClassType() ||
4968 ReceiverType->isObjCQualifiedClassType()) {
4969 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4970 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004971 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004972 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004973 }
4974 }
4975 // Handle messages to a qualified ID ("id<foo>").
4976 else if (const ObjCObjectPointerType *QualID
4977 = ReceiverType->getAsObjCQualifiedIdType()) {
4978 // Search protocols for instance methods.
4979 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
4980 E = QualID->qual_end();
4981 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004982 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004983 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004984 }
4985 // Handle messages to a pointer to interface type.
4986 else if (const ObjCObjectPointerType *IFacePtr
4987 = ReceiverType->getAsObjCInterfacePointerType()) {
4988 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00004989 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004990 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
4991 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004992
4993 // Search protocols for instance methods.
4994 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
4995 E = IFacePtr->qual_end();
4996 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004997 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004998 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004999 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005000 // Handle messages to "id".
5001 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005002 // We're messaging "id", so provide all instance methods we know
5003 // about as code-completion results.
5004
5005 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005006 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005007 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005008 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5009 I != N; ++I) {
5010 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005011 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005012 continue;
5013
Sebastian Redldb9d2142010-08-02 23:18:59 +00005014 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005015 }
5016 }
5017
Sebastian Redldb9d2142010-08-02 23:18:59 +00005018 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5019 MEnd = MethodPool.end();
5020 M != MEnd; ++M) {
5021 for (ObjCMethodList *MethList = &M->second.first;
5022 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005023 MethList = MethList->Next) {
5024 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5025 NumSelIdents))
5026 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005027
5028 if (!Selectors.insert(MethList->Method->getSelector()))
5029 continue;
5030
Douglas Gregor13438f92010-04-06 16:40:00 +00005031 Result R(MethList->Method, 0);
5032 R.StartParameter = NumSelIdents;
5033 R.AllParametersAreInformative = false;
5034 Results.MaybeAddResult(R, CurContext);
5035 }
5036 }
5037 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005038 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005039
5040
5041 // If we're actually at the argument expression (rather than prior to the
5042 // selector), we're actually performing code completion for an expression.
5043 // Determine whether we have a single, best method. If so, we can
5044 // code-complete the expression using the corresponding parameter type as
5045 // our preferred type, improving completion results.
5046 if (AtArgumentExpression) {
5047 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5048 NumSelIdents);
5049 if (PreferredType.isNull())
5050 CodeCompleteOrdinaryName(S, PCC_Expression);
5051 else
5052 CodeCompleteExpression(S, PreferredType);
5053 return;
5054 }
5055
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005056 HandleCodeCompleteResults(this, CodeCompleter,
5057 CodeCompletionContext::CCC_Other,
5058 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005059}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005060
Douglas Gregorfb629412010-08-23 21:17:50 +00005061void Sema::CodeCompleteObjCForCollection(Scope *S,
5062 DeclGroupPtrTy IterationVar) {
5063 CodeCompleteExpressionData Data;
5064 Data.ObjCCollection = true;
5065
5066 if (IterationVar.getAsOpaquePtr()) {
5067 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5068 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5069 if (*I)
5070 Data.IgnoreDecls.push_back(*I);
5071 }
5072 }
5073
5074 CodeCompleteExpression(S, Data);
5075}
5076
Douglas Gregor458433d2010-08-26 15:07:07 +00005077void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5078 unsigned NumSelIdents) {
5079 // If we have an external source, load the entire class method
5080 // pool from the AST file.
5081 if (ExternalSource) {
5082 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5083 I != N; ++I) {
5084 Selector Sel = ExternalSource->GetExternalSelector(I);
5085 if (Sel.isNull() || MethodPool.count(Sel))
5086 continue;
5087
5088 ReadMethodPool(Sel);
5089 }
5090 }
5091
Douglas Gregor218937c2011-02-01 19:23:04 +00005092 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5093 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005094 Results.EnterNewScope();
5095 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5096 MEnd = MethodPool.end();
5097 M != MEnd; ++M) {
5098
5099 Selector Sel = M->first;
5100 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5101 continue;
5102
Douglas Gregor218937c2011-02-01 19:23:04 +00005103 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005104 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005105 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005106 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005107 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005108 continue;
5109 }
5110
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005111 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005112 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005113 if (I == NumSelIdents) {
5114 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005115 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005116 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005117 Accumulator.clear();
5118 }
5119 }
5120
Douglas Gregor813d8342011-02-18 22:29:55 +00005121 Accumulator += Sel.getNameForSlot(I).str();
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005122 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005123 }
Douglas Gregordae68752011-02-01 22:57:45 +00005124 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005125 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005126 }
5127 Results.ExitScope();
5128
5129 HandleCodeCompleteResults(this, CodeCompleter,
5130 CodeCompletionContext::CCC_SelectorName,
5131 Results.data(), Results.size());
5132}
5133
Douglas Gregor55385fe2009-11-18 04:19:12 +00005134/// \brief Add all of the protocol declarations that we find in the given
5135/// (translation unit) context.
5136static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005137 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005138 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005139 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005140
5141 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5142 DEnd = Ctx->decls_end();
5143 D != DEnd; ++D) {
5144 // Record any protocols we find.
5145 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005146 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005147 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005148
5149 // Record any forward-declared protocols we find.
5150 if (ObjCForwardProtocolDecl *Forward
5151 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5152 for (ObjCForwardProtocolDecl::protocol_iterator
5153 P = Forward->protocol_begin(),
5154 PEnd = Forward->protocol_end();
5155 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005156 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005157 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005158 }
5159 }
5160}
5161
5162void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5163 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005164 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5165 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005166
Douglas Gregor70c23352010-12-09 21:44:02 +00005167 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5168 Results.EnterNewScope();
5169
5170 // Tell the result set to ignore all of the protocols we have
5171 // already seen.
5172 // FIXME: This doesn't work when caching code-completion results.
5173 for (unsigned I = 0; I != NumProtocols; ++I)
5174 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5175 Protocols[I].second))
5176 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005177
Douglas Gregor70c23352010-12-09 21:44:02 +00005178 // Add all protocols.
5179 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5180 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005181
Douglas Gregor70c23352010-12-09 21:44:02 +00005182 Results.ExitScope();
5183 }
5184
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005185 HandleCodeCompleteResults(this, CodeCompleter,
5186 CodeCompletionContext::CCC_ObjCProtocolName,
5187 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005188}
5189
5190void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005191 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5192 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005193
Douglas Gregor70c23352010-12-09 21:44:02 +00005194 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5195 Results.EnterNewScope();
5196
5197 // Add all protocols.
5198 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5199 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005200
Douglas Gregor70c23352010-12-09 21:44:02 +00005201 Results.ExitScope();
5202 }
5203
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005204 HandleCodeCompleteResults(this, CodeCompleter,
5205 CodeCompletionContext::CCC_ObjCProtocolName,
5206 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005207}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005208
5209/// \brief Add all of the Objective-C interface declarations that we find in
5210/// the given (translation unit) context.
5211static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5212 bool OnlyForwardDeclarations,
5213 bool OnlyUnimplemented,
5214 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005215 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005216
5217 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5218 DEnd = Ctx->decls_end();
5219 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005220 // Record any interfaces we find.
5221 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5222 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5223 (!OnlyUnimplemented || !Class->getImplementation()))
5224 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005225
5226 // Record any forward-declared interfaces we find.
5227 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
5228 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005229 C != CEnd; ++C)
5230 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
5231 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
5232 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00005233 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005234 }
5235 }
5236}
5237
5238void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005239 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5240 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005241 Results.EnterNewScope();
5242
5243 // Add all classes.
5244 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
5245 false, Results);
5246
5247 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005248 // FIXME: Add a special context for this, use cached global completion
5249 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005250 HandleCodeCompleteResults(this, CodeCompleter,
5251 CodeCompletionContext::CCC_Other,
5252 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005253}
5254
Douglas Gregorc83c6872010-04-15 22:33:43 +00005255void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5256 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005257 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5258 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005259 Results.EnterNewScope();
5260
5261 // Make sure that we ignore the class we're currently defining.
5262 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005263 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005264 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005265 Results.Ignore(CurClass);
5266
5267 // Add all classes.
5268 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5269 false, Results);
5270
5271 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005272 // FIXME: Add a special context for this, use cached global completion
5273 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005274 HandleCodeCompleteResults(this, CodeCompleter,
5275 CodeCompletionContext::CCC_Other,
5276 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005277}
5278
5279void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005280 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5281 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005282 Results.EnterNewScope();
5283
5284 // Add all unimplemented classes.
5285 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5286 true, Results);
5287
5288 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005289 // FIXME: Add a special context for this, use cached global completion
5290 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005291 HandleCodeCompleteResults(this, CodeCompleter,
5292 CodeCompletionContext::CCC_Other,
5293 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005294}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005295
5296void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005297 IdentifierInfo *ClassName,
5298 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005299 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005300
Douglas Gregor218937c2011-02-01 19:23:04 +00005301 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5302 CodeCompletionContext::CCC_Other);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005303
5304 // Ignore any categories we find that have already been implemented by this
5305 // interface.
5306 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5307 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005308 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005309 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5310 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5311 Category = Category->getNextClassCategory())
5312 CategoryNames.insert(Category->getIdentifier());
5313
5314 // Add all of the categories we know about.
5315 Results.EnterNewScope();
5316 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5317 for (DeclContext::decl_iterator D = TU->decls_begin(),
5318 DEnd = TU->decls_end();
5319 D != DEnd; ++D)
5320 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5321 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005322 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005323 Results.ExitScope();
5324
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005325 HandleCodeCompleteResults(this, CodeCompleter,
5326 CodeCompletionContext::CCC_Other,
5327 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005328}
5329
5330void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005331 IdentifierInfo *ClassName,
5332 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005333 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005334
5335 // Find the corresponding interface. If we couldn't find the interface, the
5336 // program itself is ill-formed. However, we'll try to be helpful still by
5337 // providing the list of all of the categories we know about.
5338 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005339 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005340 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5341 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005342 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005343
Douglas Gregor218937c2011-02-01 19:23:04 +00005344 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5345 CodeCompletionContext::CCC_Other);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005346
5347 // Add all of the categories that have have corresponding interface
5348 // declarations in this class and any of its superclasses, except for
5349 // already-implemented categories in the class itself.
5350 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5351 Results.EnterNewScope();
5352 bool IgnoreImplemented = true;
5353 while (Class) {
5354 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5355 Category = Category->getNextClassCategory())
5356 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5357 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005358 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005359
5360 Class = Class->getSuperClass();
5361 IgnoreImplemented = false;
5362 }
5363 Results.ExitScope();
5364
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005365 HandleCodeCompleteResults(this, CodeCompleter,
5366 CodeCompletionContext::CCC_Other,
5367 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005368}
Douglas Gregor322328b2009-11-18 22:32:06 +00005369
John McCalld226f652010-08-21 09:40:31 +00005370void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005371 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005372 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5373 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005374
5375 // Figure out where this @synthesize lives.
5376 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005377 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005378 if (!Container ||
5379 (!isa<ObjCImplementationDecl>(Container) &&
5380 !isa<ObjCCategoryImplDecl>(Container)))
5381 return;
5382
5383 // Ignore any properties that have already been implemented.
5384 for (DeclContext::decl_iterator D = Container->decls_begin(),
5385 DEnd = Container->decls_end();
5386 D != DEnd; ++D)
5387 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5388 Results.Ignore(PropertyImpl->getPropertyDecl());
5389
5390 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005391 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005392 Results.EnterNewScope();
5393 if (ObjCImplementationDecl *ClassImpl
5394 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005395 AddObjCProperties(ClassImpl->getClassInterface(), false,
5396 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005397 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005398 else
5399 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005400 false, /*AllowNullaryMethods=*/false, CurContext,
5401 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005402 Results.ExitScope();
5403
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005404 HandleCodeCompleteResults(this, CodeCompleter,
5405 CodeCompletionContext::CCC_Other,
5406 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005407}
5408
5409void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5410 IdentifierInfo *PropertyName,
John McCalld226f652010-08-21 09:40:31 +00005411 Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005412 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005413 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5414 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005415
5416 // Figure out where this @synthesize lives.
5417 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005418 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005419 if (!Container ||
5420 (!isa<ObjCImplementationDecl>(Container) &&
5421 !isa<ObjCCategoryImplDecl>(Container)))
5422 return;
5423
5424 // Figure out which interface we're looking into.
5425 ObjCInterfaceDecl *Class = 0;
5426 if (ObjCImplementationDecl *ClassImpl
5427 = dyn_cast<ObjCImplementationDecl>(Container))
5428 Class = ClassImpl->getClassInterface();
5429 else
5430 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5431 ->getClassInterface();
5432
Douglas Gregore8426052011-04-18 14:40:46 +00005433 // Determine the type of the property we're synthesizing.
5434 QualType PropertyType = Context.getObjCIdType();
5435 if (Class) {
5436 if (ObjCPropertyDecl *Property
5437 = Class->FindPropertyDeclaration(PropertyName)) {
5438 PropertyType
5439 = Property->getType().getNonReferenceType().getUnqualifiedType();
5440
5441 // Give preference to ivars
5442 Results.setPreferredType(PropertyType);
5443 }
5444 }
5445
Douglas Gregor322328b2009-11-18 22:32:06 +00005446 // Add all of the instance variables in this class and its superclasses.
5447 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005448 bool SawSimilarlyNamedIvar = false;
5449 std::string NameWithPrefix;
5450 NameWithPrefix += '_';
5451 NameWithPrefix += PropertyName->getName().str();
5452 std::string NameWithSuffix = PropertyName->getName().str();
5453 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005454 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005455 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5456 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005457 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5458
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005459 // Determine whether we've seen an ivar with a name similar to the
5460 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005461 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005462 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005463 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005464 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005465
5466 // Reduce the priority of this result by one, to give it a slight
5467 // advantage over other results whose names don't match so closely.
5468 if (Results.size() &&
5469 Results.data()[Results.size() - 1].Kind
5470 == CodeCompletionResult::RK_Declaration &&
5471 Results.data()[Results.size() - 1].Declaration == Ivar)
5472 Results.data()[Results.size() - 1].Priority--;
5473 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005474 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005475 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005476
5477 if (!SawSimilarlyNamedIvar) {
5478 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005479 // an ivar of the appropriate type.
5480 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005481 typedef CodeCompletionResult Result;
5482 CodeCompletionAllocator &Allocator = Results.getAllocator();
5483 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5484
Douglas Gregore8426052011-04-18 14:40:46 +00005485 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
5486 Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005487 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5488 Results.AddResult(Result(Builder.TakeString(), Priority,
5489 CXCursor_ObjCIvarDecl));
5490 }
5491
Douglas Gregor322328b2009-11-18 22:32:06 +00005492 Results.ExitScope();
5493
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005494 HandleCodeCompleteResults(this, CodeCompleter,
5495 CodeCompletionContext::CCC_Other,
5496 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005497}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005498
Douglas Gregor408be5a2010-08-25 01:08:01 +00005499// Mapping from selectors to the methods that implement that selector, along
5500// with the "in original class" flag.
5501typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5502 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005503
5504/// \brief Find all of the methods that reside in the given container
5505/// (and its superclasses, protocols, etc.) that meet the given
5506/// criteria. Insert those methods into the map of known methods,
5507/// indexed by selector so they can be easily found.
5508static void FindImplementableMethods(ASTContext &Context,
5509 ObjCContainerDecl *Container,
5510 bool WantInstanceMethods,
5511 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005512 KnownMethodsMap &KnownMethods,
5513 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005514 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5515 // Recurse into protocols.
5516 const ObjCList<ObjCProtocolDecl> &Protocols
5517 = IFace->getReferencedProtocols();
5518 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005519 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005520 I != E; ++I)
5521 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005522 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005523
Douglas Gregorea766182010-10-18 18:21:28 +00005524 // Add methods from any class extensions and categories.
5525 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5526 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005527 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5528 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005529 KnownMethods, false);
5530
5531 // Visit the superclass.
5532 if (IFace->getSuperClass())
5533 FindImplementableMethods(Context, IFace->getSuperClass(),
5534 WantInstanceMethods, ReturnType,
5535 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005536 }
5537
5538 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5539 // Recurse into protocols.
5540 const ObjCList<ObjCProtocolDecl> &Protocols
5541 = Category->getReferencedProtocols();
5542 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005543 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005544 I != E; ++I)
5545 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005546 KnownMethods, InOriginalClass);
5547
5548 // If this category is the original class, jump to the interface.
5549 if (InOriginalClass && Category->getClassInterface())
5550 FindImplementableMethods(Context, Category->getClassInterface(),
5551 WantInstanceMethods, ReturnType, KnownMethods,
5552 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005553 }
5554
5555 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5556 // Recurse into protocols.
5557 const ObjCList<ObjCProtocolDecl> &Protocols
5558 = Protocol->getReferencedProtocols();
5559 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5560 E = Protocols.end();
5561 I != E; ++I)
5562 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005563 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005564 }
5565
5566 // Add methods in this container. This operation occurs last because
5567 // we want the methods from this container to override any methods
5568 // we've previously seen with the same selector.
5569 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5570 MEnd = Container->meth_end();
5571 M != MEnd; ++M) {
5572 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5573 if (!ReturnType.isNull() &&
5574 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5575 continue;
5576
Douglas Gregor408be5a2010-08-25 01:08:01 +00005577 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005578 }
5579 }
5580}
5581
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005582/// \brief Add the parenthesized return or parameter type chunk to a code
5583/// completion string.
5584static void AddObjCPassingTypeChunk(QualType Type,
5585 ASTContext &Context,
5586 CodeCompletionBuilder &Builder) {
5587 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5588 Builder.AddTextChunk(GetCompletionTypeString(Type, Context,
5589 Builder.getAllocator()));
5590 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5591}
5592
5593/// \brief Determine whether the given class is or inherits from a class by
5594/// the given name.
5595static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
5596 llvm::StringRef Name) {
5597 if (!Class)
5598 return false;
5599
5600 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5601 return true;
5602
5603 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5604}
5605
5606/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5607/// Key-Value Observing (KVO).
5608static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5609 bool IsInstanceMethod,
5610 QualType ReturnType,
5611 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005612 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005613 ResultBuilder &Results) {
5614 IdentifierInfo *PropName = Property->getIdentifier();
5615 if (!PropName || PropName->getLength() == 0)
5616 return;
5617
5618
5619 // Builder that will create each code completion.
5620 typedef CodeCompletionResult Result;
5621 CodeCompletionAllocator &Allocator = Results.getAllocator();
5622 CodeCompletionBuilder Builder(Allocator);
5623
5624 // The selector table.
5625 SelectorTable &Selectors = Context.Selectors;
5626
5627 // The property name, copied into the code completion allocation region
5628 // on demand.
5629 struct KeyHolder {
5630 CodeCompletionAllocator &Allocator;
5631 llvm::StringRef Key;
5632 const char *CopiedKey;
5633
5634 KeyHolder(CodeCompletionAllocator &Allocator, llvm::StringRef Key)
5635 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5636
5637 operator const char *() {
5638 if (CopiedKey)
5639 return CopiedKey;
5640
5641 return CopiedKey = Allocator.CopyString(Key);
5642 }
5643 } Key(Allocator, PropName->getName());
5644
5645 // The uppercased name of the property name.
5646 std::string UpperKey = PropName->getName();
5647 if (!UpperKey.empty())
5648 UpperKey[0] = toupper(UpperKey[0]);
5649
5650 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5651 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5652 Property->getType());
5653 bool ReturnTypeMatchesVoid
5654 = ReturnType.isNull() || ReturnType->isVoidType();
5655
5656 // Add the normal accessor -(type)key.
5657 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005658 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005659 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5660 if (ReturnType.isNull())
5661 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5662
5663 Builder.AddTypedTextChunk(Key);
5664 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5665 CXCursor_ObjCInstanceMethodDecl));
5666 }
5667
5668 // If we have an integral or boolean property (or the user has provided
5669 // an integral or boolean return type), add the accessor -(type)isKey.
5670 if (IsInstanceMethod &&
5671 ((!ReturnType.isNull() &&
5672 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5673 (ReturnType.isNull() &&
5674 (Property->getType()->isIntegerType() ||
5675 Property->getType()->isBooleanType())))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005676 std::string SelectorName = (llvm::Twine("is") + UpperKey).str();
5677 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005678 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005679 if (ReturnType.isNull()) {
5680 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5681 Builder.AddTextChunk("BOOL");
5682 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5683 }
5684
5685 Builder.AddTypedTextChunk(
5686 Allocator.CopyString(SelectorId->getName()));
5687 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5688 CXCursor_ObjCInstanceMethodDecl));
5689 }
5690 }
5691
5692 // Add the normal mutator.
5693 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5694 !Property->getSetterMethodDecl()) {
Douglas Gregor62041592011-02-17 03:19:26 +00005695 std::string SelectorName = (llvm::Twine("set") + UpperKey).str();
5696 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005697 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005698 if (ReturnType.isNull()) {
5699 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5700 Builder.AddTextChunk("void");
5701 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5702 }
5703
5704 Builder.AddTypedTextChunk(
5705 Allocator.CopyString(SelectorId->getName()));
5706 Builder.AddTypedTextChunk(":");
5707 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5708 Builder.AddTextChunk(Key);
5709 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5710 CXCursor_ObjCInstanceMethodDecl));
5711 }
5712 }
5713
5714 // Indexed and unordered accessors
5715 unsigned IndexedGetterPriority = CCP_CodePattern;
5716 unsigned IndexedSetterPriority = CCP_CodePattern;
5717 unsigned UnorderedGetterPriority = CCP_CodePattern;
5718 unsigned UnorderedSetterPriority = CCP_CodePattern;
5719 if (const ObjCObjectPointerType *ObjCPointer
5720 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5721 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5722 // If this interface type is not provably derived from a known
5723 // collection, penalize the corresponding completions.
5724 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5725 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5726 if (!InheritsFromClassNamed(IFace, "NSArray"))
5727 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5728 }
5729
5730 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5731 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5732 if (!InheritsFromClassNamed(IFace, "NSSet"))
5733 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5734 }
5735 }
5736 } else {
5737 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5738 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5739 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5740 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5741 }
5742
5743 // Add -(NSUInteger)countOf<key>
5744 if (IsInstanceMethod &&
5745 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005746 std::string SelectorName = (llvm::Twine("countOf") + UpperKey).str();
5747 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005748 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005749 if (ReturnType.isNull()) {
5750 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5751 Builder.AddTextChunk("NSUInteger");
5752 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5753 }
5754
5755 Builder.AddTypedTextChunk(
5756 Allocator.CopyString(SelectorId->getName()));
5757 Results.AddResult(Result(Builder.TakeString(),
5758 std::min(IndexedGetterPriority,
5759 UnorderedGetterPriority),
5760 CXCursor_ObjCInstanceMethodDecl));
5761 }
5762 }
5763
5764 // Indexed getters
5765 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
5766 if (IsInstanceMethod &&
5767 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005768 std::string SelectorName
5769 = (llvm::Twine("objectIn") + UpperKey + "AtIndex").str();
5770 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005771 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005772 if (ReturnType.isNull()) {
5773 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5774 Builder.AddTextChunk("id");
5775 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5776 }
5777
5778 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5779 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5780 Builder.AddTextChunk("NSUInteger");
5781 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5782 Builder.AddTextChunk("index");
5783 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5784 CXCursor_ObjCInstanceMethodDecl));
5785 }
5786 }
5787
5788 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
5789 if (IsInstanceMethod &&
5790 (ReturnType.isNull() ||
5791 (ReturnType->isObjCObjectPointerType() &&
5792 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
5793 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
5794 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005795 std::string SelectorName
5796 = (llvm::Twine(Property->getName()) + "AtIndexes").str();
5797 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005798 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005799 if (ReturnType.isNull()) {
5800 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5801 Builder.AddTextChunk("NSArray *");
5802 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5803 }
5804
5805 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5806 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5807 Builder.AddTextChunk("NSIndexSet *");
5808 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5809 Builder.AddTextChunk("indexes");
5810 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5811 CXCursor_ObjCInstanceMethodDecl));
5812 }
5813 }
5814
5815 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
5816 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005817 std::string SelectorName = (llvm::Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005818 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005819 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005820 &Context.Idents.get("range")
5821 };
5822
Douglas Gregore74c25c2011-05-04 23:50:46 +00005823 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005824 if (ReturnType.isNull()) {
5825 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5826 Builder.AddTextChunk("void");
5827 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5828 }
5829
5830 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5831 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5832 Builder.AddPlaceholderChunk("object-type");
5833 Builder.AddTextChunk(" **");
5834 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5835 Builder.AddTextChunk("buffer");
5836 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5837 Builder.AddTypedTextChunk("range:");
5838 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5839 Builder.AddTextChunk("NSRange");
5840 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5841 Builder.AddTextChunk("inRange");
5842 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5843 CXCursor_ObjCInstanceMethodDecl));
5844 }
5845 }
5846
5847 // Mutable indexed accessors
5848
5849 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
5850 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005851 std::string SelectorName = (llvm::Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005852 IdentifierInfo *SelectorIds[2] = {
5853 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00005854 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005855 };
5856
Douglas Gregore74c25c2011-05-04 23:50:46 +00005857 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005858 if (ReturnType.isNull()) {
5859 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5860 Builder.AddTextChunk("void");
5861 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5862 }
5863
5864 Builder.AddTypedTextChunk("insertObject:");
5865 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5866 Builder.AddPlaceholderChunk("object-type");
5867 Builder.AddTextChunk(" *");
5868 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5869 Builder.AddTextChunk("object");
5870 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5871 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5872 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5873 Builder.AddPlaceholderChunk("NSUInteger");
5874 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5875 Builder.AddTextChunk("index");
5876 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5877 CXCursor_ObjCInstanceMethodDecl));
5878 }
5879 }
5880
5881 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
5882 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005883 std::string SelectorName = (llvm::Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005884 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005885 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005886 &Context.Idents.get("atIndexes")
5887 };
5888
Douglas Gregore74c25c2011-05-04 23:50:46 +00005889 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005890 if (ReturnType.isNull()) {
5891 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5892 Builder.AddTextChunk("void");
5893 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5894 }
5895
5896 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5897 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5898 Builder.AddTextChunk("NSArray *");
5899 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5900 Builder.AddTextChunk("array");
5901 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5902 Builder.AddTypedTextChunk("atIndexes:");
5903 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5904 Builder.AddPlaceholderChunk("NSIndexSet *");
5905 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5906 Builder.AddTextChunk("indexes");
5907 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5908 CXCursor_ObjCInstanceMethodDecl));
5909 }
5910 }
5911
5912 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
5913 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005914 std::string SelectorName
5915 = (llvm::Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
5916 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005917 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005918 if (ReturnType.isNull()) {
5919 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5920 Builder.AddTextChunk("void");
5921 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5922 }
5923
5924 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5925 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5926 Builder.AddTextChunk("NSUInteger");
5927 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5928 Builder.AddTextChunk("index");
5929 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5930 CXCursor_ObjCInstanceMethodDecl));
5931 }
5932 }
5933
5934 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
5935 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005936 std::string SelectorName
5937 = (llvm::Twine("remove") + UpperKey + "AtIndexes").str();
5938 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005939 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005940 if (ReturnType.isNull()) {
5941 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5942 Builder.AddTextChunk("void");
5943 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5944 }
5945
5946 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5947 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5948 Builder.AddTextChunk("NSIndexSet *");
5949 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5950 Builder.AddTextChunk("indexes");
5951 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5952 CXCursor_ObjCInstanceMethodDecl));
5953 }
5954 }
5955
5956 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
5957 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005958 std::string SelectorName
5959 = (llvm::Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005960 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005961 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005962 &Context.Idents.get("withObject")
5963 };
5964
Douglas Gregore74c25c2011-05-04 23:50:46 +00005965 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005966 if (ReturnType.isNull()) {
5967 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5968 Builder.AddTextChunk("void");
5969 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5970 }
5971
5972 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5973 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5974 Builder.AddPlaceholderChunk("NSUInteger");
5975 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5976 Builder.AddTextChunk("index");
5977 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5978 Builder.AddTypedTextChunk("withObject:");
5979 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5980 Builder.AddTextChunk("id");
5981 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5982 Builder.AddTextChunk("object");
5983 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5984 CXCursor_ObjCInstanceMethodDecl));
5985 }
5986 }
5987
5988 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
5989 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005990 std::string SelectorName1
5991 = (llvm::Twine("replace") + UpperKey + "AtIndexes").str();
5992 std::string SelectorName2 = (llvm::Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005993 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005994 &Context.Idents.get(SelectorName1),
5995 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005996 };
5997
Douglas Gregore74c25c2011-05-04 23:50:46 +00005998 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005999 if (ReturnType.isNull()) {
6000 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6001 Builder.AddTextChunk("void");
6002 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6003 }
6004
6005 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6006 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6007 Builder.AddPlaceholderChunk("NSIndexSet *");
6008 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6009 Builder.AddTextChunk("indexes");
6010 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6011 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6012 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6013 Builder.AddTextChunk("NSArray *");
6014 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6015 Builder.AddTextChunk("array");
6016 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6017 CXCursor_ObjCInstanceMethodDecl));
6018 }
6019 }
6020
6021 // Unordered getters
6022 // - (NSEnumerator *)enumeratorOfKey
6023 if (IsInstanceMethod &&
6024 (ReturnType.isNull() ||
6025 (ReturnType->isObjCObjectPointerType() &&
6026 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6027 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6028 ->getName() == "NSEnumerator"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006029 std::string SelectorName = (llvm::Twine("enumeratorOf") + UpperKey).str();
6030 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006031 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006032 if (ReturnType.isNull()) {
6033 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6034 Builder.AddTextChunk("NSEnumerator *");
6035 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6036 }
6037
6038 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6039 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6040 CXCursor_ObjCInstanceMethodDecl));
6041 }
6042 }
6043
6044 // - (type *)memberOfKey:(type *)object
6045 if (IsInstanceMethod &&
6046 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00006047 std::string SelectorName = (llvm::Twine("memberOf") + UpperKey).str();
6048 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006049 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006050 if (ReturnType.isNull()) {
6051 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6052 Builder.AddPlaceholderChunk("object-type");
6053 Builder.AddTextChunk(" *");
6054 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6055 }
6056
6057 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6058 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6059 if (ReturnType.isNull()) {
6060 Builder.AddPlaceholderChunk("object-type");
6061 Builder.AddTextChunk(" *");
6062 } else {
6063 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
6064 Builder.getAllocator()));
6065 }
6066 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6067 Builder.AddTextChunk("object");
6068 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6069 CXCursor_ObjCInstanceMethodDecl));
6070 }
6071 }
6072
6073 // Mutable unordered accessors
6074 // - (void)addKeyObject:(type *)object
6075 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006076 std::string SelectorName
6077 = (llvm::Twine("add") + UpperKey + llvm::Twine("Object")).str();
6078 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006079 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006080 if (ReturnType.isNull()) {
6081 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6082 Builder.AddTextChunk("void");
6083 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6084 }
6085
6086 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6087 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6088 Builder.AddPlaceholderChunk("object-type");
6089 Builder.AddTextChunk(" *");
6090 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6091 Builder.AddTextChunk("object");
6092 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6093 CXCursor_ObjCInstanceMethodDecl));
6094 }
6095 }
6096
6097 // - (void)addKey:(NSSet *)objects
6098 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006099 std::string SelectorName = (llvm::Twine("add") + UpperKey).str();
6100 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006101 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006102 if (ReturnType.isNull()) {
6103 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6104 Builder.AddTextChunk("void");
6105 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6106 }
6107
6108 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6109 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6110 Builder.AddTextChunk("NSSet *");
6111 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6112 Builder.AddTextChunk("objects");
6113 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6114 CXCursor_ObjCInstanceMethodDecl));
6115 }
6116 }
6117
6118 // - (void)removeKeyObject:(type *)object
6119 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006120 std::string SelectorName
6121 = (llvm::Twine("remove") + UpperKey + llvm::Twine("Object")).str();
6122 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006123 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006124 if (ReturnType.isNull()) {
6125 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6126 Builder.AddTextChunk("void");
6127 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6128 }
6129
6130 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6131 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6132 Builder.AddPlaceholderChunk("object-type");
6133 Builder.AddTextChunk(" *");
6134 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6135 Builder.AddTextChunk("object");
6136 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6137 CXCursor_ObjCInstanceMethodDecl));
6138 }
6139 }
6140
6141 // - (void)removeKey:(NSSet *)objects
6142 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006143 std::string SelectorName = (llvm::Twine("remove") + UpperKey).str();
6144 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006145 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006146 if (ReturnType.isNull()) {
6147 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6148 Builder.AddTextChunk("void");
6149 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6150 }
6151
6152 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6153 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6154 Builder.AddTextChunk("NSSet *");
6155 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6156 Builder.AddTextChunk("objects");
6157 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6158 CXCursor_ObjCInstanceMethodDecl));
6159 }
6160 }
6161
6162 // - (void)intersectKey:(NSSet *)objects
6163 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006164 std::string SelectorName = (llvm::Twine("intersect") + UpperKey).str();
6165 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006166 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006167 if (ReturnType.isNull()) {
6168 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6169 Builder.AddTextChunk("void");
6170 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6171 }
6172
6173 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6174 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6175 Builder.AddTextChunk("NSSet *");
6176 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6177 Builder.AddTextChunk("objects");
6178 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6179 CXCursor_ObjCInstanceMethodDecl));
6180 }
6181 }
6182
6183 // Key-Value Observing
6184 // + (NSSet *)keyPathsForValuesAffectingKey
6185 if (!IsInstanceMethod &&
6186 (ReturnType.isNull() ||
6187 (ReturnType->isObjCObjectPointerType() &&
6188 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6189 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6190 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006191 std::string SelectorName
6192 = (llvm::Twine("keyPathsForValuesAffecting") + UpperKey).str();
6193 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006194 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006195 if (ReturnType.isNull()) {
6196 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6197 Builder.AddTextChunk("NSSet *");
6198 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6199 }
6200
6201 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6202 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006203 CXCursor_ObjCClassMethodDecl));
6204 }
6205 }
6206
6207 // + (BOOL)automaticallyNotifiesObserversForKey
6208 if (!IsInstanceMethod &&
6209 (ReturnType.isNull() ||
6210 ReturnType->isIntegerType() ||
6211 ReturnType->isBooleanType())) {
6212 std::string SelectorName
6213 = (llvm::Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
6214 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6215 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6216 if (ReturnType.isNull()) {
6217 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6218 Builder.AddTextChunk("BOOL");
6219 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6220 }
6221
6222 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6223 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6224 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006225 }
6226 }
6227}
6228
Douglas Gregore8f5a172010-04-07 00:21:17 +00006229void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6230 bool IsInstanceMethod,
John McCallb3d87482010-08-24 05:47:05 +00006231 ParsedType ReturnTy,
John McCalld226f652010-08-21 09:40:31 +00006232 Decl *IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006233 // Determine the return type of the method we're declaring, if
6234 // provided.
6235 QualType ReturnType = GetTypeFromParser(ReturnTy);
6236
Douglas Gregorea766182010-10-18 18:21:28 +00006237 // Determine where we should start searching for methods.
6238 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006239 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006240 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006241 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6242 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006243 IsInImplementation = true;
6244 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006245 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006246 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006247 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006248 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006249 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006250 }
6251
6252 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006253 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006254 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006255 }
6256
Douglas Gregorea766182010-10-18 18:21:28 +00006257 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006258 HandleCodeCompleteResults(this, CodeCompleter,
6259 CodeCompletionContext::CCC_Other,
6260 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006261 return;
6262 }
6263
6264 // Find all of the methods that we could declare/implement here.
6265 KnownMethodsMap KnownMethods;
6266 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006267 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006268
Douglas Gregore8f5a172010-04-07 00:21:17 +00006269 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006270 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006271 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6272 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006273 Results.EnterNewScope();
6274 PrintingPolicy Policy(Context.PrintingPolicy);
6275 Policy.AnonymousTagLocations = false;
6276 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6277 MEnd = KnownMethods.end();
6278 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006279 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006280 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006281
6282 // If the result type was not already provided, add it to the
6283 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006284 if (ReturnType.isNull())
6285 AddObjCPassingTypeChunk(Method->getResultType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006286
6287 Selector Sel = Method->getSelector();
6288
6289 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006290 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006291 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006292
6293 // Add parameters to the pattern.
6294 unsigned I = 0;
6295 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6296 PEnd = Method->param_end();
6297 P != PEnd; (void)++P, ++I) {
6298 // Add the part of the selector name.
6299 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006300 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006301 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006302 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6303 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006304 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006305 } else
6306 break;
6307
6308 // Add the parameter type.
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006309 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006310
6311 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006312 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006313 }
6314
6315 if (Method->isVariadic()) {
6316 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006317 Builder.AddChunk(CodeCompletionString::CK_Comma);
6318 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006319 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006320
Douglas Gregor447107d2010-05-28 00:57:46 +00006321 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006322 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006323 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6324 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6325 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006326 if (!Method->getResultType()->isVoidType()) {
6327 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006328 Builder.AddTextChunk("return");
6329 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6330 Builder.AddPlaceholderChunk("expression");
6331 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006332 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006333 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006334
Douglas Gregor218937c2011-02-01 19:23:04 +00006335 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6336 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006337 }
6338
Douglas Gregor408be5a2010-08-25 01:08:01 +00006339 unsigned Priority = CCP_CodePattern;
6340 if (!M->second.second)
6341 Priority += CCD_InBaseClass;
6342
Douglas Gregor218937c2011-02-01 19:23:04 +00006343 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006344 Method->isInstanceMethod()
6345 ? CXCursor_ObjCInstanceMethodDecl
6346 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006347 }
6348
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006349 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6350 // the properties in this class and its categories.
6351 if (Context.getLangOptions().ObjC2) {
6352 llvm::SmallVector<ObjCContainerDecl *, 4> Containers;
6353 Containers.push_back(SearchDecl);
6354
Douglas Gregore74c25c2011-05-04 23:50:46 +00006355 VisitedSelectorSet KnownSelectors;
6356 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6357 MEnd = KnownMethods.end();
6358 M != MEnd; ++M)
6359 KnownSelectors.insert(M->first);
6360
6361
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006362 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6363 if (!IFace)
6364 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6365 IFace = Category->getClassInterface();
6366
6367 if (IFace) {
6368 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6369 Category = Category->getNextClassCategory())
6370 Containers.push_back(Category);
6371 }
6372
6373 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6374 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6375 PEnd = Containers[I]->prop_end();
6376 P != PEnd; ++P) {
6377 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006378 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006379 }
6380 }
6381 }
6382
Douglas Gregore8f5a172010-04-07 00:21:17 +00006383 Results.ExitScope();
6384
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006385 HandleCodeCompleteResults(this, CodeCompleter,
6386 CodeCompletionContext::CCC_Other,
6387 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006388}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006389
6390void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6391 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006392 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006393 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006394 IdentifierInfo **SelIdents,
6395 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006396 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006397 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006398 if (ExternalSource) {
6399 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6400 I != N; ++I) {
6401 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006402 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006403 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006404
6405 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006406 }
6407 }
6408
6409 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006410 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006411 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6412 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006413
6414 if (ReturnTy)
6415 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006416
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006417 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006418 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6419 MEnd = MethodPool.end();
6420 M != MEnd; ++M) {
6421 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6422 &M->second.second;
6423 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006424 MethList = MethList->Next) {
6425 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6426 NumSelIdents))
6427 continue;
6428
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006429 if (AtParameterName) {
6430 // Suggest parameter names we've seen before.
6431 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6432 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6433 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006434 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006435 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006436 Param->getIdentifier()->getName()));
6437 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006438 }
6439 }
6440
6441 continue;
6442 }
6443
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006444 Result R(MethList->Method, 0);
6445 R.StartParameter = NumSelIdents;
6446 R.AllParametersAreInformative = false;
6447 R.DeclaringEntity = true;
6448 Results.MaybeAddResult(R, CurContext);
6449 }
6450 }
6451
6452 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006453 HandleCodeCompleteResults(this, CodeCompleter,
6454 CodeCompletionContext::CCC_Other,
6455 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006456}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006457
Douglas Gregorf29c5232010-08-24 22:20:20 +00006458void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006459 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006460 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006461 Results.EnterNewScope();
6462
6463 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006464 CodeCompletionBuilder Builder(Results.getAllocator());
6465 Builder.AddTypedTextChunk("if");
6466 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6467 Builder.AddPlaceholderChunk("condition");
6468 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006469
6470 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006471 Builder.AddTypedTextChunk("ifdef");
6472 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6473 Builder.AddPlaceholderChunk("macro");
6474 Results.AddResult(Builder.TakeString());
6475
Douglas Gregorf44e8542010-08-24 19:08:16 +00006476 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006477 Builder.AddTypedTextChunk("ifndef");
6478 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6479 Builder.AddPlaceholderChunk("macro");
6480 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006481
6482 if (InConditional) {
6483 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006484 Builder.AddTypedTextChunk("elif");
6485 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6486 Builder.AddPlaceholderChunk("condition");
6487 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006488
6489 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006490 Builder.AddTypedTextChunk("else");
6491 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006492
6493 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006494 Builder.AddTypedTextChunk("endif");
6495 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006496 }
6497
6498 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006499 Builder.AddTypedTextChunk("include");
6500 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6501 Builder.AddTextChunk("\"");
6502 Builder.AddPlaceholderChunk("header");
6503 Builder.AddTextChunk("\"");
6504 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006505
6506 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006507 Builder.AddTypedTextChunk("include");
6508 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6509 Builder.AddTextChunk("<");
6510 Builder.AddPlaceholderChunk("header");
6511 Builder.AddTextChunk(">");
6512 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006513
6514 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006515 Builder.AddTypedTextChunk("define");
6516 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6517 Builder.AddPlaceholderChunk("macro");
6518 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006519
6520 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006521 Builder.AddTypedTextChunk("define");
6522 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6523 Builder.AddPlaceholderChunk("macro");
6524 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6525 Builder.AddPlaceholderChunk("args");
6526 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6527 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006528
6529 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006530 Builder.AddTypedTextChunk("undef");
6531 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6532 Builder.AddPlaceholderChunk("macro");
6533 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006534
6535 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006536 Builder.AddTypedTextChunk("line");
6537 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6538 Builder.AddPlaceholderChunk("number");
6539 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006540
6541 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006542 Builder.AddTypedTextChunk("line");
6543 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6544 Builder.AddPlaceholderChunk("number");
6545 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6546 Builder.AddTextChunk("\"");
6547 Builder.AddPlaceholderChunk("filename");
6548 Builder.AddTextChunk("\"");
6549 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006550
6551 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006552 Builder.AddTypedTextChunk("error");
6553 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6554 Builder.AddPlaceholderChunk("message");
6555 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006556
6557 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006558 Builder.AddTypedTextChunk("pragma");
6559 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6560 Builder.AddPlaceholderChunk("arguments");
6561 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006562
6563 if (getLangOptions().ObjC1) {
6564 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006565 Builder.AddTypedTextChunk("import");
6566 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6567 Builder.AddTextChunk("\"");
6568 Builder.AddPlaceholderChunk("header");
6569 Builder.AddTextChunk("\"");
6570 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006571
6572 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006573 Builder.AddTypedTextChunk("import");
6574 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6575 Builder.AddTextChunk("<");
6576 Builder.AddPlaceholderChunk("header");
6577 Builder.AddTextChunk(">");
6578 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006579 }
6580
6581 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006582 Builder.AddTypedTextChunk("include_next");
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_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006590 Builder.AddTypedTextChunk("include_next");
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 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006598 Builder.AddTypedTextChunk("warning");
6599 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6600 Builder.AddPlaceholderChunk("message");
6601 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006602
6603 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6604 // completions for them. And __include_macros is a Clang-internal extension
6605 // that we don't want to encourage anyone to use.
6606
6607 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6608 Results.ExitScope();
6609
Douglas Gregorf44e8542010-08-24 19:08:16 +00006610 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006611 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006612 Results.data(), Results.size());
6613}
6614
6615void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006616 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006617 S->getFnParent()? Sema::PCC_RecoveryInFunction
6618 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006619}
6620
Douglas Gregorf29c5232010-08-24 22:20:20 +00006621void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006622 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006623 IsDefinition? CodeCompletionContext::CCC_MacroName
6624 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006625 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6626 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006627 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006628 Results.EnterNewScope();
6629 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6630 MEnd = PP.macro_end();
6631 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006632 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006633 M->first->getName()));
6634 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006635 }
6636 Results.ExitScope();
6637 } else if (IsDefinition) {
6638 // FIXME: Can we detect when the user just wrote an include guard above?
6639 }
6640
Douglas Gregor52779fb2010-09-23 23:01:17 +00006641 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006642 Results.data(), Results.size());
6643}
6644
Douglas Gregorf29c5232010-08-24 22:20:20 +00006645void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006646 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006647 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006648
6649 if (!CodeCompleter || CodeCompleter->includeMacros())
6650 AddMacroResults(PP, Results);
6651
6652 // defined (<macro>)
6653 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006654 CodeCompletionBuilder Builder(Results.getAllocator());
6655 Builder.AddTypedTextChunk("defined");
6656 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6657 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6658 Builder.AddPlaceholderChunk("macro");
6659 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6660 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006661 Results.ExitScope();
6662
6663 HandleCodeCompleteResults(this, CodeCompleter,
6664 CodeCompletionContext::CCC_PreprocessorExpression,
6665 Results.data(), Results.size());
6666}
6667
6668void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6669 IdentifierInfo *Macro,
6670 MacroInfo *MacroInfo,
6671 unsigned Argument) {
6672 // FIXME: In the future, we could provide "overload" results, much like we
6673 // do for function calls.
6674
6675 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006676 S->getFnParent()? Sema::PCC_RecoveryInFunction
6677 : Sema::PCC_Namespace);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006678}
6679
Douglas Gregor55817af2010-08-25 17:04:25 +00006680void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006681 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006682 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006683 0, 0);
6684}
6685
Douglas Gregordae68752011-02-01 22:57:45 +00006686void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
John McCall0a2c5e22010-08-25 06:19:51 +00006687 llvm::SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006688 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006689 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6690 CodeCompletionDeclConsumer Consumer(Builder,
6691 Context.getTranslationUnitDecl());
6692 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6693 Consumer);
6694 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006695
6696 if (!CodeCompleter || CodeCompleter->includeMacros())
6697 AddMacroResults(PP, Builder);
6698
6699 Results.clear();
6700 Results.insert(Results.end(),
6701 Builder.data(), Builder.data() + Builder.size());
6702}