blob: 5803a76600b953a45c0ee7873f9a36cab4b0712b [file] [log] [blame]
Douglas Gregor81b747b2009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
John McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
John McCall120d63c2010-08-24 20:38:10 +000015#include "clang/Sema/Overload.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000016#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregor719770d2010-04-06 17:30:22 +000017#include "clang/Sema/ExternalSemaSource.h"
John McCall5f1e0942010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000023#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
Douglas Gregord36adf52010-09-16 16:06:31 +000025#include "llvm/ADT/DenseSet.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000026#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000027#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000028#include "llvm/ADT/StringSwitch.h"
Douglas Gregor458433d2010-08-26 15:07:07 +000029#include "llvm/ADT/Twine.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000030#include <list>
31#include <map>
32#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000033
34using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000035using namespace sema;
Douglas Gregor81b747b2009-09-17 21:32:03 +000036
Douglas Gregor86d9a522009-09-21 16:56:56 +000037namespace {
38 /// \brief A container of code-completion results.
39 class ResultBuilder {
40 public:
41 /// \brief The type of a name-lookup filter, which can be provided to the
42 /// name-lookup routines to specify which declarations should be included in
43 /// the result set (when it returns true) and which declarations should be
44 /// filtered out (returns false).
45 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
46
John McCall0a2c5e22010-08-25 06:19:51 +000047 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +000048
49 private:
50 /// \brief The actual results we have found.
51 std::vector<Result> Results;
52
53 /// \brief A record of all of the declarations we have found and placed
54 /// into the result set, used to ensure that no declaration ever gets into
55 /// the result set twice.
56 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
57
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000058 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
59
60 /// \brief An entry in the shadow map, which is optimized to store
61 /// a single (declaration, index) mapping (the common case) but
62 /// can also store a list of (declaration, index) mappings.
63 class ShadowMapEntry {
Chris Lattner5f9e2722011-07-23 10:55:15 +000064 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000065
66 /// \brief Contains either the solitary NamedDecl * or a vector
67 /// of (declaration, index) pairs.
68 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
69
70 /// \brief When the entry contains a single declaration, this is
71 /// the index associated with that entry.
72 unsigned SingleDeclIndex;
73
74 public:
75 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
76
77 void Add(NamedDecl *ND, unsigned Index) {
78 if (DeclOrVector.isNull()) {
79 // 0 - > 1 elements: just set the single element information.
80 DeclOrVector = ND;
81 SingleDeclIndex = Index;
82 return;
83 }
84
85 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
86 // 1 -> 2 elements: create the vector of results and push in the
87 // existing declaration.
88 DeclIndexPairVector *Vec = new DeclIndexPairVector;
89 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
90 DeclOrVector = Vec;
91 }
92
93 // Add the new element to the end of the vector.
94 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
95 DeclIndexPair(ND, Index));
96 }
97
98 void Destroy() {
99 if (DeclIndexPairVector *Vec
100 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
101 delete Vec;
102 DeclOrVector = ((NamedDecl *)0);
103 }
104 }
105
106 // Iteration.
107 class iterator;
108 iterator begin() const;
109 iterator end() const;
110 };
111
Douglas Gregor86d9a522009-09-21 16:56:56 +0000112 /// \brief A mapping from declaration names to the declarations that have
113 /// this name within a particular scope and their index within the list of
114 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000115 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000116
117 /// \brief The semantic analysis object for which results are being
118 /// produced.
119 Sema &SemaRef;
Douglas Gregor218937c2011-02-01 19:23:04 +0000120
121 /// \brief The allocator used to allocate new code-completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000122 CodeCompletionAllocator &Allocator;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000123
124 /// \brief If non-NULL, a filter function used to remove any code-completion
125 /// results that are not desirable.
126 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000127
128 /// \brief Whether we should allow declarations as
129 /// nested-name-specifiers that would otherwise be filtered out.
130 bool AllowNestedNameSpecifiers;
131
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000132 /// \brief If set, the type that we would prefer our resulting value
133 /// declarations to have.
134 ///
135 /// Closely matching the preferred type gives a boost to a result's
136 /// priority.
137 CanQualType PreferredType;
138
Douglas Gregor86d9a522009-09-21 16:56:56 +0000139 /// \brief A list of shadow maps, which is used to model name hiding at
140 /// different levels of, e.g., the inheritance hierarchy.
141 std::list<ShadowMap> ShadowMaps;
142
Douglas Gregor3cdee122010-08-26 16:36:48 +0000143 /// \brief If we're potentially referring to a C++ member function, the set
144 /// of qualifiers applied to the object type.
145 Qualifiers ObjectTypeQualifiers;
146
147 /// \brief Whether the \p ObjectTypeQualifiers field is active.
148 bool HasObjectTypeQualifiers;
149
Douglas Gregor265f7492010-08-27 15:29:55 +0000150 /// \brief The selector that we prefer.
151 Selector PreferredSelector;
152
Douglas Gregorca45da02010-11-02 20:36:02 +0000153 /// \brief The completion context in which we are gathering results.
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000154 CodeCompletionContext CompletionContext;
155
Douglas Gregorca45da02010-11-02 20:36:02 +0000156 /// \brief If we are in an instance method definition, the @implementation
157 /// object.
158 ObjCImplementationDecl *ObjCImplementation;
159
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000160 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000161
Douglas Gregor6f942b22010-09-21 16:06:22 +0000162 void MaybeAddConstructorResults(Result R);
163
Douglas Gregor86d9a522009-09-21 16:56:56 +0000164 public:
Douglas Gregordae68752011-02-01 22:57:45 +0000165 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Douglas Gregor52779fb2010-09-23 23:01:17 +0000166 const CodeCompletionContext &CompletionContext,
167 LookupFilter Filter = 0)
Douglas Gregor218937c2011-02-01 19:23:04 +0000168 : SemaRef(SemaRef), Allocator(Allocator), Filter(Filter),
169 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregorca45da02010-11-02 20:36:02 +0000170 CompletionContext(CompletionContext),
171 ObjCImplementation(0)
172 {
173 // If this is an Objective-C instance method definition, dig out the
174 // corresponding implementation.
175 switch (CompletionContext.getKind()) {
176 case CodeCompletionContext::CCC_Expression:
177 case CodeCompletionContext::CCC_ObjCMessageReceiver:
178 case CodeCompletionContext::CCC_ParenthesizedExpression:
179 case CodeCompletionContext::CCC_Statement:
180 case CodeCompletionContext::CCC_Recovery:
181 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
182 if (Method->isInstanceMethod())
183 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
184 ObjCImplementation = Interface->getImplementation();
185 break;
186
187 default:
188 break;
189 }
190 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000191
Douglas Gregord8e8a582010-05-25 21:41:55 +0000192 /// \brief Whether we should include code patterns in the completion
193 /// results.
194 bool includeCodePatterns() const {
195 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000196 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000197 }
198
Douglas Gregor86d9a522009-09-21 16:56:56 +0000199 /// \brief Set the filter used for code-completion results.
200 void setFilter(LookupFilter Filter) {
201 this->Filter = Filter;
202 }
203
Douglas Gregor86d9a522009-09-21 16:56:56 +0000204 Result *data() { return Results.empty()? 0 : &Results.front(); }
205 unsigned size() const { return Results.size(); }
206 bool empty() const { return Results.empty(); }
207
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000208 /// \brief Specify the preferred type.
209 void setPreferredType(QualType T) {
210 PreferredType = SemaRef.Context.getCanonicalType(T);
211 }
212
Douglas Gregor3cdee122010-08-26 16:36:48 +0000213 /// \brief Set the cv-qualifiers on the object type, for us in filtering
214 /// calls to member functions.
215 ///
216 /// When there are qualifiers in this set, they will be used to filter
217 /// out member functions that aren't available (because there will be a
218 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
219 /// match.
220 void setObjectTypeQualifiers(Qualifiers Quals) {
221 ObjectTypeQualifiers = Quals;
222 HasObjectTypeQualifiers = true;
223 }
224
Douglas Gregor265f7492010-08-27 15:29:55 +0000225 /// \brief Set the preferred selector.
226 ///
227 /// When an Objective-C method declaration result is added, and that
228 /// method's selector matches this preferred selector, we give that method
229 /// a slight priority boost.
230 void setPreferredSelector(Selector Sel) {
231 PreferredSelector = Sel;
232 }
Douglas Gregorca45da02010-11-02 20:36:02 +0000233
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000234 /// \brief Retrieve the code-completion context for which results are
235 /// being collected.
236 const CodeCompletionContext &getCompletionContext() const {
237 return CompletionContext;
238 }
239
Douglas Gregor45bcd432010-01-14 03:21:49 +0000240 /// \brief Specify whether nested-name-specifiers are allowed.
241 void allowNestedNameSpecifiers(bool Allow = true) {
242 AllowNestedNameSpecifiers = Allow;
243 }
244
Douglas Gregorb9d77572010-09-21 00:03:25 +0000245 /// \brief Return the semantic analysis object for which we are collecting
246 /// code completion results.
247 Sema &getSema() const { return SemaRef; }
248
Douglas Gregor218937c2011-02-01 19:23:04 +0000249 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000250 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Douglas Gregor218937c2011-02-01 19:23:04 +0000251
Douglas Gregore495b7f2010-01-14 00:20:49 +0000252 /// \brief Determine whether the given declaration is at all interesting
253 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000254 ///
255 /// \param ND the declaration that we are inspecting.
256 ///
257 /// \param AsNestedNameSpecifier will be set true if this declaration is
258 /// only interesting when it is a nested-name-specifier.
259 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000260
261 /// \brief Check whether the result is hidden by the Hiding declaration.
262 ///
263 /// \returns true if the result is hidden and cannot be found, false if
264 /// the hidden result could still be found. When false, \p R may be
265 /// modified to describe how the result can be found (e.g., via extra
266 /// qualification).
267 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
268 NamedDecl *Hiding);
269
Douglas Gregor86d9a522009-09-21 16:56:56 +0000270 /// \brief Add a new result to this result set (if it isn't already in one
271 /// of the shadow maps), or replace an existing result (for, e.g., a
272 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000273 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000274 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000275 ///
276 /// \param R the context in which this result will be named.
277 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000278
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000279 /// \brief Add a new result to this result set, where we already know
280 /// the hiding declation (if any).
281 ///
282 /// \param R the result to add (if it is unique).
283 ///
284 /// \param CurContext the context in which this result will be named.
285 ///
286 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000287 ///
288 /// \param InBaseClass whether the result was found in a base
289 /// class of the searched context.
290 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
291 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000292
Douglas Gregora4477812010-01-14 16:01:26 +0000293 /// \brief Add a new non-declaration result to this result set.
294 void AddResult(Result R);
295
Douglas Gregor86d9a522009-09-21 16:56:56 +0000296 /// \brief Enter into a new scope.
297 void EnterNewScope();
298
299 /// \brief Exit from the current scope.
300 void ExitScope();
301
Douglas Gregor55385fe2009-11-18 04:19:12 +0000302 /// \brief Ignore this declaration, if it is seen again.
303 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
304
Douglas Gregor86d9a522009-09-21 16:56:56 +0000305 /// \name Name lookup predicates
306 ///
307 /// These predicates can be passed to the name lookup functions to filter the
308 /// results of name lookup. All of the predicates have the same type, so that
309 ///
310 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000311 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000312 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000313 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000314 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000315 bool IsNestedNameSpecifier(NamedDecl *ND) const;
316 bool IsEnum(NamedDecl *ND) const;
317 bool IsClassOrStruct(NamedDecl *ND) const;
318 bool IsUnion(NamedDecl *ND) const;
319 bool IsNamespace(NamedDecl *ND) const;
320 bool IsNamespaceOrAlias(NamedDecl *ND) const;
321 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000322 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000323 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000324 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000325 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000326 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000327 //@}
328 };
329}
330
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000331class ResultBuilder::ShadowMapEntry::iterator {
332 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
333 unsigned SingleDeclIndex;
334
335public:
336 typedef DeclIndexPair value_type;
337 typedef value_type reference;
338 typedef std::ptrdiff_t difference_type;
339 typedef std::input_iterator_tag iterator_category;
340
341 class pointer {
342 DeclIndexPair Value;
343
344 public:
345 pointer(const DeclIndexPair &Value) : Value(Value) { }
346
347 const DeclIndexPair *operator->() const {
348 return &Value;
349 }
350 };
351
352 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
353
354 iterator(NamedDecl *SingleDecl, unsigned Index)
355 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
356
357 iterator(const DeclIndexPair *Iterator)
358 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
359
360 iterator &operator++() {
361 if (DeclOrIterator.is<NamedDecl *>()) {
362 DeclOrIterator = (NamedDecl *)0;
363 SingleDeclIndex = 0;
364 return *this;
365 }
366
367 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
368 ++I;
369 DeclOrIterator = I;
370 return *this;
371 }
372
Chris Lattner66392d42010-09-04 18:12:20 +0000373 /*iterator operator++(int) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000374 iterator tmp(*this);
375 ++(*this);
376 return tmp;
Chris Lattner66392d42010-09-04 18:12:20 +0000377 }*/
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000378
379 reference operator*() const {
380 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
381 return reference(ND, SingleDeclIndex);
382
Douglas Gregord490f952009-12-06 21:27:58 +0000383 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000384 }
385
386 pointer operator->() const {
387 return pointer(**this);
388 }
389
390 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000391 return X.DeclOrIterator.getOpaqueValue()
392 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000393 X.SingleDeclIndex == Y.SingleDeclIndex;
394 }
395
396 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000397 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000398 }
399};
400
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000401ResultBuilder::ShadowMapEntry::iterator
402ResultBuilder::ShadowMapEntry::begin() const {
403 if (DeclOrVector.isNull())
404 return iterator();
405
406 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
407 return iterator(ND, SingleDeclIndex);
408
409 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
410}
411
412ResultBuilder::ShadowMapEntry::iterator
413ResultBuilder::ShadowMapEntry::end() const {
414 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
415 return iterator();
416
417 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
418}
419
Douglas Gregor456c4a12009-09-21 20:12:40 +0000420/// \brief Compute the qualification required to get from the current context
421/// (\p CurContext) to the target context (\p TargetContext).
422///
423/// \param Context the AST context in which the qualification will be used.
424///
425/// \param CurContext the context where an entity is being named, which is
426/// typically based on the current scope.
427///
428/// \param TargetContext the context in which the named entity actually
429/// resides.
430///
431/// \returns a nested name specifier that refers into the target context, or
432/// NULL if no qualification is needed.
433static NestedNameSpecifier *
434getRequiredQualification(ASTContext &Context,
435 DeclContext *CurContext,
436 DeclContext *TargetContext) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000437 SmallVector<DeclContext *, 4> TargetParents;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000438
439 for (DeclContext *CommonAncestor = TargetContext;
440 CommonAncestor && !CommonAncestor->Encloses(CurContext);
441 CommonAncestor = CommonAncestor->getLookupParent()) {
442 if (CommonAncestor->isTransparentContext() ||
443 CommonAncestor->isFunctionOrMethod())
444 continue;
445
446 TargetParents.push_back(CommonAncestor);
447 }
448
449 NestedNameSpecifier *Result = 0;
450 while (!TargetParents.empty()) {
451 DeclContext *Parent = TargetParents.back();
452 TargetParents.pop_back();
453
Douglas Gregorfb629412010-08-23 21:17:50 +0000454 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
455 if (!Namespace->getIdentifier())
456 continue;
457
Douglas Gregor456c4a12009-09-21 20:12:40 +0000458 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000459 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000460 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
461 Result = NestedNameSpecifier::Create(Context, Result,
462 false,
463 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000464 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000465 return Result;
466}
467
Douglas Gregor45bcd432010-01-14 03:21:49 +0000468bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
469 bool &AsNestedNameSpecifier) const {
470 AsNestedNameSpecifier = false;
471
Douglas Gregore495b7f2010-01-14 00:20:49 +0000472 ND = ND->getUnderlyingDecl();
473 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000474
475 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000476 if (!ND->getDeclName())
477 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000478
479 // Friend declarations and declarations introduced due to friends are never
480 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000481 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000482 return false;
483
Douglas Gregor76282942009-12-11 17:31:05 +0000484 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000485 if (isa<ClassTemplateSpecializationDecl>(ND) ||
486 isa<ClassTemplatePartialSpecializationDecl>(ND))
487 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000488
Douglas Gregor76282942009-12-11 17:31:05 +0000489 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000490 if (isa<UsingDecl>(ND))
491 return false;
492
493 // Some declarations have reserved names that we don't want to ever show.
494 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000495 // __va_list_tag is a freak of nature. Find it and skip it.
496 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000497 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000498
Douglas Gregorf52cede2009-10-09 22:16:47 +0000499 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000500 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000501 //
502 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000503 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000504 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000505 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000506 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
507 (ND->getLocation().isInvalid() ||
508 SemaRef.SourceMgr.isInSystemHeader(
509 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000510 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000511 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000512 }
Douglas Gregor6f942b22010-09-21 16:06:22 +0000513
Douglas Gregor9b0ba872010-11-09 03:59:40 +0000514 // Skip out-of-line declarations and definitions.
515 // NOTE: Unless it's an Objective-C property, method, or ivar, where
516 // the contexts can be messy.
517 if (!ND->getDeclContext()->Equals(ND->getLexicalDeclContext()) &&
518 !(isa<ObjCPropertyDecl>(ND) || isa<ObjCIvarDecl>(ND) ||
519 isa<ObjCMethodDecl>(ND)))
520 return false;
521
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000522 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
523 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
524 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor52779fb2010-09-23 23:01:17 +0000525 Filter != &ResultBuilder::IsNamespaceOrAlias &&
526 Filter != 0))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000527 AsNestedNameSpecifier = true;
528
Douglas Gregor86d9a522009-09-21 16:56:56 +0000529 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000530 if (Filter && !(this->*Filter)(ND)) {
531 // Check whether it is interesting as a nested-name-specifier.
532 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
533 IsNestedNameSpecifier(ND) &&
534 (Filter != &ResultBuilder::IsMember ||
535 (isa<CXXRecordDecl>(ND) &&
536 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
537 AsNestedNameSpecifier = true;
538 return true;
539 }
540
Douglas Gregore495b7f2010-01-14 00:20:49 +0000541 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000542 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000543 // ... then it must be interesting!
544 return true;
545}
546
Douglas Gregor6660d842010-01-14 00:41:07 +0000547bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
548 NamedDecl *Hiding) {
549 // In C, there is no way to refer to a hidden name.
550 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
551 // name if we introduce the tag type.
552 if (!SemaRef.getLangOptions().CPlusPlus)
553 return true;
554
Sebastian Redl7a126a42010-08-31 00:36:30 +0000555 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregor6660d842010-01-14 00:41:07 +0000556
557 // There is no way to qualify a name declared in a function or method.
558 if (HiddenCtx->isFunctionOrMethod())
559 return true;
560
Sebastian Redl7a126a42010-08-31 00:36:30 +0000561 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregor6660d842010-01-14 00:41:07 +0000562 return true;
563
564 // We can refer to the result with the appropriate qualification. Do it.
565 R.Hidden = true;
566 R.QualifierIsInformative = false;
567
568 if (!R.Qualifier)
569 R.Qualifier = getRequiredQualification(SemaRef.Context,
570 CurContext,
571 R.Declaration->getDeclContext());
572 return false;
573}
574
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000575/// \brief A simplified classification of types used to determine whether two
576/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000577SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000578 switch (T->getTypeClass()) {
579 case Type::Builtin:
580 switch (cast<BuiltinType>(T)->getKind()) {
581 case BuiltinType::Void:
582 return STC_Void;
583
584 case BuiltinType::NullPtr:
585 return STC_Pointer;
586
587 case BuiltinType::Overload:
588 case BuiltinType::Dependent:
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000589 return STC_Other;
590
591 case BuiltinType::ObjCId:
592 case BuiltinType::ObjCClass:
593 case BuiltinType::ObjCSel:
594 return STC_ObjectiveC;
595
596 default:
597 return STC_Arithmetic;
598 }
599 return STC_Other;
600
601 case Type::Complex:
602 return STC_Arithmetic;
603
604 case Type::Pointer:
605 return STC_Pointer;
606
607 case Type::BlockPointer:
608 return STC_Block;
609
610 case Type::LValueReference:
611 case Type::RValueReference:
612 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
613
614 case Type::ConstantArray:
615 case Type::IncompleteArray:
616 case Type::VariableArray:
617 case Type::DependentSizedArray:
618 return STC_Array;
619
620 case Type::DependentSizedExtVector:
621 case Type::Vector:
622 case Type::ExtVector:
623 return STC_Arithmetic;
624
625 case Type::FunctionProto:
626 case Type::FunctionNoProto:
627 return STC_Function;
628
629 case Type::Record:
630 return STC_Record;
631
632 case Type::Enum:
633 return STC_Arithmetic;
634
635 case Type::ObjCObject:
636 case Type::ObjCInterface:
637 case Type::ObjCObjectPointer:
638 return STC_ObjectiveC;
639
640 default:
641 return STC_Other;
642 }
643}
644
645/// \brief Get the type that a given expression will have if this declaration
646/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000647QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000648 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
649
650 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
651 return C.getTypeDeclType(Type);
652 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
653 return C.getObjCInterfaceType(Iface);
654
655 QualType T;
656 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000657 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000658 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000659 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000660 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000661 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000662 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
663 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
664 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
665 T = Property->getType();
666 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
667 T = Value->getType();
668 else
669 return QualType();
Douglas Gregor3e64d562011-04-14 20:33:34 +0000670
671 // Dig through references, function pointers, and block pointers to
672 // get down to the likely type of an expression when the entity is
673 // used.
674 do {
675 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
676 T = Ref->getPointeeType();
677 continue;
678 }
679
680 if (const PointerType *Pointer = T->getAs<PointerType>()) {
681 if (Pointer->getPointeeType()->isFunctionType()) {
682 T = Pointer->getPointeeType();
683 continue;
684 }
685
686 break;
687 }
688
689 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
690 T = Block->getPointeeType();
691 continue;
692 }
693
694 if (const FunctionType *Function = T->getAs<FunctionType>()) {
695 T = Function->getResultType();
696 continue;
697 }
698
699 break;
700 } while (true);
701
702 return T;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000703}
704
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000705void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
706 // If this is an Objective-C method declaration whose selector matches our
707 // preferred selector, give it a priority boost.
708 if (!PreferredSelector.isNull())
709 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
710 if (PreferredSelector == Method->getSelector())
711 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000712
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000713 // If we have a preferred type, adjust the priority for results with exactly-
714 // matching or nearly-matching types.
715 if (!PreferredType.isNull()) {
716 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
717 if (!T.isNull()) {
718 CanQualType TC = SemaRef.Context.getCanonicalType(T);
719 // Check for exactly-matching types (modulo qualifiers).
720 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
721 R.Priority /= CCF_ExactTypeMatch;
722 // Check for nearly-matching types, based on classification of each.
723 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000724 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000725 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
726 R.Priority /= CCF_SimilarTypeMatch;
727 }
728 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000729}
730
Douglas Gregor6f942b22010-09-21 16:06:22 +0000731void ResultBuilder::MaybeAddConstructorResults(Result R) {
732 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
733 !CompletionContext.wantConstructorResults())
734 return;
735
736 ASTContext &Context = SemaRef.Context;
737 NamedDecl *D = R.Declaration;
738 CXXRecordDecl *Record = 0;
739 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
740 Record = ClassTemplate->getTemplatedDecl();
741 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
742 // Skip specializations and partial specializations.
743 if (isa<ClassTemplateSpecializationDecl>(Record))
744 return;
745 } else {
746 // There are no constructors here.
747 return;
748 }
749
750 Record = Record->getDefinition();
751 if (!Record)
752 return;
753
754
755 QualType RecordTy = Context.getTypeDeclType(Record);
756 DeclarationName ConstructorName
757 = Context.DeclarationNames.getCXXConstructorName(
758 Context.getCanonicalType(RecordTy));
759 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
760 Ctors.first != Ctors.second; ++Ctors.first) {
761 R.Declaration = *Ctors.first;
762 R.CursorKind = getCursorKindForDecl(R.Declaration);
763 Results.push_back(R);
764 }
765}
766
Douglas Gregore495b7f2010-01-14 00:20:49 +0000767void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
768 assert(!ShadowMaps.empty() && "Must enter into a results scope");
769
770 if (R.Kind != Result::RK_Declaration) {
771 // For non-declaration results, just add the result.
772 Results.push_back(R);
773 return;
774 }
775
776 // Look through using declarations.
777 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
778 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
779 return;
780 }
781
782 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
783 unsigned IDNS = CanonDecl->getIdentifierNamespace();
784
Douglas Gregor45bcd432010-01-14 03:21:49 +0000785 bool AsNestedNameSpecifier = false;
786 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000787 return;
788
Douglas Gregor6f942b22010-09-21 16:06:22 +0000789 // C++ constructors are never found by name lookup.
790 if (isa<CXXConstructorDecl>(R.Declaration))
791 return;
792
Douglas Gregor86d9a522009-09-21 16:56:56 +0000793 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000794 ShadowMapEntry::iterator I, IEnd;
795 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
796 if (NamePos != SMap.end()) {
797 I = NamePos->second.begin();
798 IEnd = NamePos->second.end();
799 }
800
801 for (; I != IEnd; ++I) {
802 NamedDecl *ND = I->first;
803 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000804 if (ND->getCanonicalDecl() == CanonDecl) {
805 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000806 Results[Index].Declaration = R.Declaration;
807
Douglas Gregor86d9a522009-09-21 16:56:56 +0000808 // We're done.
809 return;
810 }
811 }
812
813 // This is a new declaration in this scope. However, check whether this
814 // declaration name is hidden by a similarly-named declaration in an outer
815 // scope.
816 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
817 --SMEnd;
818 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000819 ShadowMapEntry::iterator I, IEnd;
820 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
821 if (NamePos != SM->end()) {
822 I = NamePos->second.begin();
823 IEnd = NamePos->second.end();
824 }
825 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000826 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000827 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000828 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
829 Decl::IDNS_ObjCProtocol)))
830 continue;
831
832 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000833 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000834 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000835 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000836 continue;
837
838 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000839 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000840 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000841
842 break;
843 }
844 }
845
846 // Make sure that any given declaration only shows up in the result set once.
847 if (!AllDeclsFound.insert(CanonDecl))
848 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000849
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000850 // If the filter is for nested-name-specifiers, then this result starts a
851 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000852 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000853 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000854 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000855 } else
856 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000857
Douglas Gregor0563c262009-09-22 23:15:58 +0000858 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000859 if (R.QualifierIsInformative && !R.Qualifier &&
860 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000861 DeclContext *Ctx = R.Declaration->getDeclContext();
862 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
863 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
864 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
865 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
866 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
867 else
868 R.QualifierIsInformative = false;
869 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000870
Douglas Gregor86d9a522009-09-21 16:56:56 +0000871 // Insert this result into the set of results and into the current shadow
872 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000873 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000874 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000875
876 if (!AsNestedNameSpecifier)
877 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000878}
879
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000880void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000881 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000882 if (R.Kind != Result::RK_Declaration) {
883 // For non-declaration results, just add the result.
884 Results.push_back(R);
885 return;
886 }
887
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000888 // Look through using declarations.
889 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
890 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
891 return;
892 }
893
Douglas Gregor45bcd432010-01-14 03:21:49 +0000894 bool AsNestedNameSpecifier = false;
895 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000896 return;
897
Douglas Gregor6f942b22010-09-21 16:06:22 +0000898 // C++ constructors are never found by name lookup.
899 if (isa<CXXConstructorDecl>(R.Declaration))
900 return;
901
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000902 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
903 return;
904
905 // Make sure that any given declaration only shows up in the result set once.
906 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
907 return;
908
909 // If the filter is for nested-name-specifiers, then this result starts a
910 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000911 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000912 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000913 R.Priority = CCP_NestedNameSpecifier;
914 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000915 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
916 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000917 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000918 R.QualifierIsInformative = true;
919
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000920 // If this result is supposed to have an informative qualifier, add one.
921 if (R.QualifierIsInformative && !R.Qualifier &&
922 !R.StartsNestedNameSpecifier) {
923 DeclContext *Ctx = R.Declaration->getDeclContext();
924 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
925 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
926 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
927 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000928 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000929 else
930 R.QualifierIsInformative = false;
931 }
932
Douglas Gregor12e13132010-05-26 22:00:08 +0000933 // Adjust the priority if this result comes from a base class.
934 if (InBaseClass)
935 R.Priority += CCD_InBaseClass;
936
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000937 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000938
Douglas Gregor3cdee122010-08-26 16:36:48 +0000939 if (HasObjectTypeQualifiers)
940 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
941 if (Method->isInstance()) {
942 Qualifiers MethodQuals
943 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
944 if (ObjectTypeQualifiers == MethodQuals)
945 R.Priority += CCD_ObjectQualifierMatch;
946 else if (ObjectTypeQualifiers - MethodQuals) {
947 // The method cannot be invoked, because doing so would drop
948 // qualifiers.
949 return;
950 }
951 }
952
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000953 // Insert this result into the set of results.
954 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000955
956 if (!AsNestedNameSpecifier)
957 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000958}
959
Douglas Gregora4477812010-01-14 16:01:26 +0000960void ResultBuilder::AddResult(Result R) {
961 assert(R.Kind != Result::RK_Declaration &&
962 "Declaration results need more context");
963 Results.push_back(R);
964}
965
Douglas Gregor86d9a522009-09-21 16:56:56 +0000966/// \brief Enter into a new scope.
967void ResultBuilder::EnterNewScope() {
968 ShadowMaps.push_back(ShadowMap());
969}
970
971/// \brief Exit from the current scope.
972void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000973 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
974 EEnd = ShadowMaps.back().end();
975 E != EEnd;
976 ++E)
977 E->second.Destroy();
978
Douglas Gregor86d9a522009-09-21 16:56:56 +0000979 ShadowMaps.pop_back();
980}
981
Douglas Gregor791215b2009-09-21 20:51:25 +0000982/// \brief Determines whether this given declaration will be found by
983/// ordinary name lookup.
984bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000985 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
986
Douglas Gregor791215b2009-09-21 20:51:25 +0000987 unsigned IDNS = Decl::IDNS_Ordinary;
988 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000989 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000990 else if (SemaRef.getLangOptions().ObjC1) {
991 if (isa<ObjCIvarDecl>(ND))
992 return true;
993 if (isa<ObjCPropertyDecl>(ND) &&
994 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
995 return true;
996 }
997
Douglas Gregor791215b2009-09-21 20:51:25 +0000998 return ND->getIdentifierNamespace() & IDNS;
999}
1000
Douglas Gregor01dfea02010-01-10 23:08:15 +00001001/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001002/// ordinary name lookup but is not a type name.
1003bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
1004 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1005 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1006 return false;
1007
1008 unsigned IDNS = Decl::IDNS_Ordinary;
1009 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +00001010 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +00001011 else if (SemaRef.getLangOptions().ObjC1) {
1012 if (isa<ObjCIvarDecl>(ND))
1013 return true;
1014 if (isa<ObjCPropertyDecl>(ND) &&
1015 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
1016 return true;
1017 }
1018
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001019 return ND->getIdentifierNamespace() & IDNS;
1020}
1021
Douglas Gregorf9578432010-07-28 21:50:18 +00001022bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
1023 if (!IsOrdinaryNonTypeName(ND))
1024 return 0;
1025
1026 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1027 if (VD->getType()->isIntegralOrEnumerationType())
1028 return true;
1029
1030 return false;
1031}
1032
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001033/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +00001034/// ordinary name lookup.
1035bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001036 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1037
Douglas Gregor01dfea02010-01-10 23:08:15 +00001038 unsigned IDNS = Decl::IDNS_Ordinary;
1039 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +00001040 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001041
1042 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001043 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1044 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001045}
1046
Douglas Gregor86d9a522009-09-21 16:56:56 +00001047/// \brief Determines whether the given declaration is suitable as the
1048/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1049bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1050 // Allow us to find class templates, too.
1051 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1052 ND = ClassTemplate->getTemplatedDecl();
1053
1054 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1055}
1056
1057/// \brief Determines whether the given declaration is an enumeration.
1058bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1059 return isa<EnumDecl>(ND);
1060}
1061
1062/// \brief Determines whether the given declaration is a class or struct.
1063bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1064 // Allow us to find class templates, too.
1065 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1066 ND = ClassTemplate->getTemplatedDecl();
1067
1068 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001069 return RD->getTagKind() == TTK_Class ||
1070 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001071
1072 return false;
1073}
1074
1075/// \brief Determines whether the given declaration is a union.
1076bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1077 // Allow us to find class templates, too.
1078 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1079 ND = ClassTemplate->getTemplatedDecl();
1080
1081 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001082 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001083
1084 return false;
1085}
1086
1087/// \brief Determines whether the given declaration is a namespace.
1088bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1089 return isa<NamespaceDecl>(ND);
1090}
1091
1092/// \brief Determines whether the given declaration is a namespace or
1093/// namespace alias.
1094bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1095 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1096}
1097
Douglas Gregor76282942009-12-11 17:31:05 +00001098/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001099bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001100 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1101 ND = Using->getTargetDecl();
1102
1103 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001104}
1105
Douglas Gregor76282942009-12-11 17:31:05 +00001106/// \brief Determines which members of a class should be visible via
1107/// "." or "->". Only value declarations, nested name specifiers, and
1108/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001109bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001110 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1111 ND = Using->getTargetDecl();
1112
Douglas Gregorce821962009-12-11 18:14:22 +00001113 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1114 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001115}
1116
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001117static bool isObjCReceiverType(ASTContext &C, QualType T) {
1118 T = C.getCanonicalType(T);
1119 switch (T->getTypeClass()) {
1120 case Type::ObjCObject:
1121 case Type::ObjCInterface:
1122 case Type::ObjCObjectPointer:
1123 return true;
1124
1125 case Type::Builtin:
1126 switch (cast<BuiltinType>(T)->getKind()) {
1127 case BuiltinType::ObjCId:
1128 case BuiltinType::ObjCClass:
1129 case BuiltinType::ObjCSel:
1130 return true;
1131
1132 default:
1133 break;
1134 }
1135 return false;
1136
1137 default:
1138 break;
1139 }
1140
1141 if (!C.getLangOptions().CPlusPlus)
1142 return false;
1143
1144 // FIXME: We could perform more analysis here to determine whether a
1145 // particular class type has any conversions to Objective-C types. For now,
1146 // just accept all class types.
1147 return T->isDependentType() || T->isRecordType();
1148}
1149
1150bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1151 QualType T = getDeclUsageType(SemaRef.Context, ND);
1152 if (T.isNull())
1153 return false;
1154
1155 T = SemaRef.Context.getBaseElementType(T);
1156 return isObjCReceiverType(SemaRef.Context, T);
1157}
1158
Douglas Gregorfb629412010-08-23 21:17:50 +00001159bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1160 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1161 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1162 return false;
1163
1164 QualType T = getDeclUsageType(SemaRef.Context, ND);
1165 if (T.isNull())
1166 return false;
1167
1168 T = SemaRef.Context.getBaseElementType(T);
1169 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1170 T->isObjCIdType() ||
1171 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1172}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001173
Douglas Gregor52779fb2010-09-23 23:01:17 +00001174bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1175 return false;
1176}
1177
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001178/// \rief Determines whether the given declaration is an Objective-C
1179/// instance variable.
1180bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1181 return isa<ObjCIvarDecl>(ND);
1182}
1183
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001184namespace {
1185 /// \brief Visible declaration consumer that adds a code-completion result
1186 /// for each visible declaration.
1187 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1188 ResultBuilder &Results;
1189 DeclContext *CurContext;
1190
1191 public:
1192 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1193 : Results(Results), CurContext(CurContext) { }
1194
Douglas Gregor0cc84042010-01-14 15:47:35 +00001195 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1196 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001197 }
1198 };
1199}
1200
Douglas Gregor86d9a522009-09-21 16:56:56 +00001201/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001202static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001203 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001204 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001205 Results.AddResult(Result("short", CCP_Type));
1206 Results.AddResult(Result("long", CCP_Type));
1207 Results.AddResult(Result("signed", CCP_Type));
1208 Results.AddResult(Result("unsigned", CCP_Type));
1209 Results.AddResult(Result("void", CCP_Type));
1210 Results.AddResult(Result("char", CCP_Type));
1211 Results.AddResult(Result("int", CCP_Type));
1212 Results.AddResult(Result("float", CCP_Type));
1213 Results.AddResult(Result("double", CCP_Type));
1214 Results.AddResult(Result("enum", CCP_Type));
1215 Results.AddResult(Result("struct", CCP_Type));
1216 Results.AddResult(Result("union", CCP_Type));
1217 Results.AddResult(Result("const", CCP_Type));
1218 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001219
Douglas Gregor86d9a522009-09-21 16:56:56 +00001220 if (LangOpts.C99) {
1221 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001222 Results.AddResult(Result("_Complex", CCP_Type));
1223 Results.AddResult(Result("_Imaginary", CCP_Type));
1224 Results.AddResult(Result("_Bool", CCP_Type));
1225 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001226 }
1227
Douglas Gregor218937c2011-02-01 19:23:04 +00001228 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001229 if (LangOpts.CPlusPlus) {
1230 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001231 Results.AddResult(Result("bool", CCP_Type +
1232 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001233 Results.AddResult(Result("class", CCP_Type));
1234 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001235
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001236 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001237 Builder.AddTypedTextChunk("typename");
1238 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1239 Builder.AddPlaceholderChunk("qualifier");
1240 Builder.AddTextChunk("::");
1241 Builder.AddPlaceholderChunk("name");
1242 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001243
Douglas Gregor86d9a522009-09-21 16:56:56 +00001244 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001245 Results.AddResult(Result("auto", CCP_Type));
1246 Results.AddResult(Result("char16_t", CCP_Type));
1247 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001248
Douglas Gregor218937c2011-02-01 19:23:04 +00001249 Builder.AddTypedTextChunk("decltype");
1250 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1251 Builder.AddPlaceholderChunk("expression");
1252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1253 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001254 }
1255 }
1256
1257 // GNU extensions
1258 if (LangOpts.GNUMode) {
1259 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001260 // Results.AddResult(Result("_Decimal32"));
1261 // Results.AddResult(Result("_Decimal64"));
1262 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001263
Douglas Gregor218937c2011-02-01 19:23:04 +00001264 Builder.AddTypedTextChunk("typeof");
1265 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1266 Builder.AddPlaceholderChunk("expression");
1267 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001268
Douglas Gregor218937c2011-02-01 19:23:04 +00001269 Builder.AddTypedTextChunk("typeof");
1270 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1271 Builder.AddPlaceholderChunk("type");
1272 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1273 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001274 }
1275}
1276
John McCallf312b1e2010-08-26 23:41:50 +00001277static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001278 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001279 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001280 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001281 // Note: we don't suggest either "auto" or "register", because both
1282 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1283 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001284 Results.AddResult(Result("extern"));
1285 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001286}
1287
John McCallf312b1e2010-08-26 23:41:50 +00001288static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001289 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001290 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001291 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001292 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001293 case Sema::PCC_Class:
1294 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001295 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001296 Results.AddResult(Result("explicit"));
1297 Results.AddResult(Result("friend"));
1298 Results.AddResult(Result("mutable"));
1299 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001300 }
1301 // Fall through
1302
John McCallf312b1e2010-08-26 23:41:50 +00001303 case Sema::PCC_ObjCInterface:
1304 case Sema::PCC_ObjCImplementation:
1305 case Sema::PCC_Namespace:
1306 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001307 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001308 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001309 break;
1310
John McCallf312b1e2010-08-26 23:41:50 +00001311 case Sema::PCC_ObjCInstanceVariableList:
1312 case Sema::PCC_Expression:
1313 case Sema::PCC_Statement:
1314 case Sema::PCC_ForInit:
1315 case Sema::PCC_Condition:
1316 case Sema::PCC_RecoveryInFunction:
1317 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001318 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001319 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001320 break;
1321 }
1322}
1323
Douglas Gregorbca403c2010-01-13 23:51:12 +00001324static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1325static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1326static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001327 ResultBuilder &Results,
1328 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001329static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001330 ResultBuilder &Results,
1331 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001332static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001333 ResultBuilder &Results,
1334 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001335static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001336
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001337static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001338 CodeCompletionBuilder Builder(Results.getAllocator());
1339 Builder.AddTypedTextChunk("typedef");
1340 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1341 Builder.AddPlaceholderChunk("type");
1342 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1343 Builder.AddPlaceholderChunk("name");
1344 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001345}
1346
John McCallf312b1e2010-08-26 23:41:50 +00001347static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001348 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001349 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001350 case Sema::PCC_Namespace:
1351 case Sema::PCC_Class:
1352 case Sema::PCC_ObjCInstanceVariableList:
1353 case Sema::PCC_Template:
1354 case Sema::PCC_MemberTemplate:
1355 case Sema::PCC_Statement:
1356 case Sema::PCC_RecoveryInFunction:
1357 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001358 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001359 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001360 return true;
1361
John McCallf312b1e2010-08-26 23:41:50 +00001362 case Sema::PCC_Expression:
1363 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001364 return LangOpts.CPlusPlus;
1365
1366 case Sema::PCC_ObjCInterface:
1367 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001368 return false;
1369
John McCallf312b1e2010-08-26 23:41:50 +00001370 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001371 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001372 }
1373
1374 return false;
1375}
1376
Douglas Gregor01dfea02010-01-10 23:08:15 +00001377/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001378static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001379 Scope *S,
1380 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001381 ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001382 CodeCompletionBuilder Builder(Results.getAllocator());
1383
John McCall0a2c5e22010-08-25 06:19:51 +00001384 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001385 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001386 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001387 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001388 if (Results.includeCodePatterns()) {
1389 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001390 Builder.AddTypedTextChunk("namespace");
1391 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1392 Builder.AddPlaceholderChunk("identifier");
1393 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1394 Builder.AddPlaceholderChunk("declarations");
1395 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1396 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1397 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001398 }
1399
Douglas Gregor01dfea02010-01-10 23:08:15 +00001400 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001401 Builder.AddTypedTextChunk("namespace");
1402 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1403 Builder.AddPlaceholderChunk("name");
1404 Builder.AddChunk(CodeCompletionString::CK_Equal);
1405 Builder.AddPlaceholderChunk("namespace");
1406 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001407
1408 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001409 Builder.AddTypedTextChunk("using");
1410 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1411 Builder.AddTextChunk("namespace");
1412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1413 Builder.AddPlaceholderChunk("identifier");
1414 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001415
1416 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001417 Builder.AddTypedTextChunk("asm");
1418 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1419 Builder.AddPlaceholderChunk("string-literal");
1420 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1421 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001422
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001423 if (Results.includeCodePatterns()) {
1424 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001425 Builder.AddTypedTextChunk("template");
1426 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1427 Builder.AddPlaceholderChunk("declaration");
1428 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001429 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001430 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001431
1432 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001433 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001434
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001435 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001436 // Fall through
1437
John McCallf312b1e2010-08-26 23:41:50 +00001438 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001439 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001440 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001441 Builder.AddTypedTextChunk("using");
1442 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1443 Builder.AddPlaceholderChunk("qualifier");
1444 Builder.AddTextChunk("::");
1445 Builder.AddPlaceholderChunk("name");
1446 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001447
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001448 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001449 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001450 Builder.AddTypedTextChunk("using");
1451 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1452 Builder.AddTextChunk("typename");
1453 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1454 Builder.AddPlaceholderChunk("qualifier");
1455 Builder.AddTextChunk("::");
1456 Builder.AddPlaceholderChunk("name");
1457 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001458 }
1459
John McCallf312b1e2010-08-26 23:41:50 +00001460 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001461 AddTypedefResult(Results);
1462
Douglas Gregor01dfea02010-01-10 23:08:15 +00001463 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001464 Builder.AddTypedTextChunk("public");
1465 Builder.AddChunk(CodeCompletionString::CK_Colon);
1466 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001467
1468 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001469 Builder.AddTypedTextChunk("protected");
1470 Builder.AddChunk(CodeCompletionString::CK_Colon);
1471 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001472
1473 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001474 Builder.AddTypedTextChunk("private");
1475 Builder.AddChunk(CodeCompletionString::CK_Colon);
1476 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001477 }
1478 }
1479 // Fall through
1480
John McCallf312b1e2010-08-26 23:41:50 +00001481 case Sema::PCC_Template:
1482 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001483 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001484 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001485 Builder.AddTypedTextChunk("template");
1486 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1487 Builder.AddPlaceholderChunk("parameters");
1488 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1489 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001490 }
1491
Douglas Gregorbca403c2010-01-13 23:51:12 +00001492 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1493 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001494 break;
1495
John McCallf312b1e2010-08-26 23:41:50 +00001496 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001497 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1498 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1499 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001500 break;
1501
John McCallf312b1e2010-08-26 23:41:50 +00001502 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001503 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1504 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1505 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001506 break;
1507
John McCallf312b1e2010-08-26 23:41:50 +00001508 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001509 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001510 break;
1511
John McCallf312b1e2010-08-26 23:41:50 +00001512 case Sema::PCC_RecoveryInFunction:
1513 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001514 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001515
Douglas Gregorec3310a2011-04-12 02:47:21 +00001516 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1517 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001518 Builder.AddTypedTextChunk("try");
1519 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1520 Builder.AddPlaceholderChunk("statements");
1521 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1522 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1523 Builder.AddTextChunk("catch");
1524 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1525 Builder.AddPlaceholderChunk("declaration");
1526 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1527 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1528 Builder.AddPlaceholderChunk("statements");
1529 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1530 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1531 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001532 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001533 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001534 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001535
Douglas Gregord8e8a582010-05-25 21:41:55 +00001536 if (Results.includeCodePatterns()) {
1537 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001538 Builder.AddTypedTextChunk("if");
1539 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001540 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001541 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001542 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001543 Builder.AddPlaceholderChunk("expression");
1544 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1545 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1546 Builder.AddPlaceholderChunk("statements");
1547 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1548 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1549 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001550
Douglas Gregord8e8a582010-05-25 21:41:55 +00001551 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001552 Builder.AddTypedTextChunk("switch");
1553 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001554 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001555 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001556 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001557 Builder.AddPlaceholderChunk("expression");
1558 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1559 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1560 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1561 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1562 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001563 }
1564
Douglas Gregor01dfea02010-01-10 23:08:15 +00001565 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001566 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001567 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001568 Builder.AddTypedTextChunk("case");
1569 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1570 Builder.AddPlaceholderChunk("expression");
1571 Builder.AddChunk(CodeCompletionString::CK_Colon);
1572 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001573
1574 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001575 Builder.AddTypedTextChunk("default");
1576 Builder.AddChunk(CodeCompletionString::CK_Colon);
1577 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001578 }
1579
Douglas Gregord8e8a582010-05-25 21:41:55 +00001580 if (Results.includeCodePatterns()) {
1581 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001582 Builder.AddTypedTextChunk("while");
1583 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001584 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001585 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001586 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001587 Builder.AddPlaceholderChunk("expression");
1588 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1589 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1590 Builder.AddPlaceholderChunk("statements");
1591 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1592 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1593 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001594
1595 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001596 Builder.AddTypedTextChunk("do");
1597 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1598 Builder.AddPlaceholderChunk("statements");
1599 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1600 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1601 Builder.AddTextChunk("while");
1602 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1603 Builder.AddPlaceholderChunk("expression");
1604 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1605 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001606
Douglas Gregord8e8a582010-05-25 21:41:55 +00001607 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001608 Builder.AddTypedTextChunk("for");
1609 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001610 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001611 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001612 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001613 Builder.AddPlaceholderChunk("init-expression");
1614 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1615 Builder.AddPlaceholderChunk("condition");
1616 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1617 Builder.AddPlaceholderChunk("inc-expression");
1618 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1619 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1620 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1621 Builder.AddPlaceholderChunk("statements");
1622 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1623 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1624 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001625 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001626
1627 if (S->getContinueParent()) {
1628 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001629 Builder.AddTypedTextChunk("continue");
1630 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001631 }
1632
1633 if (S->getBreakParent()) {
1634 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001635 Builder.AddTypedTextChunk("break");
1636 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001637 }
1638
1639 // "return expression ;" or "return ;", depending on whether we
1640 // know the function is void or not.
1641 bool isVoid = false;
1642 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1643 isVoid = Function->getResultType()->isVoidType();
1644 else if (ObjCMethodDecl *Method
1645 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1646 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001647 else if (SemaRef.getCurBlock() &&
1648 !SemaRef.getCurBlock()->ReturnType.isNull())
1649 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001650 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001651 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001652 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1653 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001654 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001655 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001656
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001657 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001658 Builder.AddTypedTextChunk("goto");
1659 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1660 Builder.AddPlaceholderChunk("label");
1661 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001662
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001663 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001664 Builder.AddTypedTextChunk("using");
1665 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1666 Builder.AddTextChunk("namespace");
1667 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1668 Builder.AddPlaceholderChunk("identifier");
1669 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001670 }
1671
1672 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001673 case Sema::PCC_ForInit:
1674 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001675 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001676 // Fall through: conditions and statements can have expressions.
1677
Douglas Gregor02688102010-09-14 23:59:36 +00001678 case Sema::PCC_ParenthesizedExpression:
John McCallf85e1932011-06-15 23:02:42 +00001679 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1680 CCC == Sema::PCC_ParenthesizedExpression) {
1681 // (__bridge <type>)<expression>
1682 Builder.AddTypedTextChunk("__bridge");
1683 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1684 Builder.AddPlaceholderChunk("type");
1685 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1686 Builder.AddPlaceholderChunk("expression");
1687 Results.AddResult(Result(Builder.TakeString()));
1688
1689 // (__bridge_transfer <Objective-C type>)<expression>
1690 Builder.AddTypedTextChunk("__bridge_transfer");
1691 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1692 Builder.AddPlaceholderChunk("Objective-C type");
1693 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1694 Builder.AddPlaceholderChunk("expression");
1695 Results.AddResult(Result(Builder.TakeString()));
1696
1697 // (__bridge_retained <CF type>)<expression>
1698 Builder.AddTypedTextChunk("__bridge_retained");
1699 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1700 Builder.AddPlaceholderChunk("CF type");
1701 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1702 Builder.AddPlaceholderChunk("expression");
1703 Results.AddResult(Result(Builder.TakeString()));
1704 }
1705 // Fall through
1706
John McCallf312b1e2010-08-26 23:41:50 +00001707 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001708 if (SemaRef.getLangOptions().CPlusPlus) {
1709 // 'this', if we're in a non-static member function.
1710 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1711 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001712 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001713
1714 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001715 Results.AddResult(Result("true"));
1716 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001717
Douglas Gregorec3310a2011-04-12 02:47:21 +00001718 if (SemaRef.getLangOptions().RTTI) {
1719 // dynamic_cast < type-id > ( expression )
1720 Builder.AddTypedTextChunk("dynamic_cast");
1721 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1722 Builder.AddPlaceholderChunk("type");
1723 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1724 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1725 Builder.AddPlaceholderChunk("expression");
1726 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1727 Results.AddResult(Result(Builder.TakeString()));
1728 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001729
1730 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001731 Builder.AddTypedTextChunk("static_cast");
1732 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1733 Builder.AddPlaceholderChunk("type");
1734 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1735 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1736 Builder.AddPlaceholderChunk("expression");
1737 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1738 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001739
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001740 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001741 Builder.AddTypedTextChunk("reinterpret_cast");
1742 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1743 Builder.AddPlaceholderChunk("type");
1744 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1745 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1746 Builder.AddPlaceholderChunk("expression");
1747 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1748 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001749
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001750 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001751 Builder.AddTypedTextChunk("const_cast");
1752 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1753 Builder.AddPlaceholderChunk("type");
1754 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1755 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1756 Builder.AddPlaceholderChunk("expression");
1757 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1758 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001759
Douglas Gregorec3310a2011-04-12 02:47:21 +00001760 if (SemaRef.getLangOptions().RTTI) {
1761 // typeid ( expression-or-type )
1762 Builder.AddTypedTextChunk("typeid");
1763 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1764 Builder.AddPlaceholderChunk("expression-or-type");
1765 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1766 Results.AddResult(Result(Builder.TakeString()));
1767 }
1768
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001769 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001770 Builder.AddTypedTextChunk("new");
1771 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1772 Builder.AddPlaceholderChunk("type");
1773 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1774 Builder.AddPlaceholderChunk("expressions");
1775 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1776 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001777
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001778 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001779 Builder.AddTypedTextChunk("new");
1780 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1781 Builder.AddPlaceholderChunk("type");
1782 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1783 Builder.AddPlaceholderChunk("size");
1784 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1785 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1786 Builder.AddPlaceholderChunk("expressions");
1787 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1788 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001789
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001790 // delete expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001791 Builder.AddTypedTextChunk("delete");
1792 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1793 Builder.AddPlaceholderChunk("expression");
1794 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001795
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001796 // delete [] expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001797 Builder.AddTypedTextChunk("delete");
1798 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1799 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1800 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1801 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1802 Builder.AddPlaceholderChunk("expression");
1803 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001804
Douglas Gregorec3310a2011-04-12 02:47:21 +00001805 if (SemaRef.getLangOptions().CXXExceptions) {
1806 // throw expression
1807 Builder.AddTypedTextChunk("throw");
1808 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1809 Builder.AddPlaceholderChunk("expression");
1810 Results.AddResult(Result(Builder.TakeString()));
1811 }
Douglas Gregor12e13132010-05-26 22:00:08 +00001812
1813 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001814 }
1815
1816 if (SemaRef.getLangOptions().ObjC1) {
1817 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001818 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1819 // The interface can be NULL.
1820 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1821 if (ID->getSuperClass())
1822 Results.AddResult(Result("super"));
1823 }
1824
Douglas Gregorbca403c2010-01-13 23:51:12 +00001825 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001826 }
1827
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001828 // sizeof expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001829 Builder.AddTypedTextChunk("sizeof");
1830 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1831 Builder.AddPlaceholderChunk("expression-or-type");
1832 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1833 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001834 break;
1835 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001836
John McCallf312b1e2010-08-26 23:41:50 +00001837 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001838 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001839 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001840 }
1841
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001842 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1843 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001844
John McCallf312b1e2010-08-26 23:41:50 +00001845 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001846 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001847}
1848
Douglas Gregora63f6de2011-02-01 21:15:40 +00001849/// \brief Retrieve the string representation of the given type as a string
1850/// that has the appropriate lifetime for code completion.
1851///
1852/// This routine provides a fast path where we provide constant strings for
1853/// common type names.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001854static const char *GetCompletionTypeString(QualType T,
1855 ASTContext &Context,
1856 CodeCompletionAllocator &Allocator) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001857 PrintingPolicy Policy(Context.PrintingPolicy);
1858 Policy.AnonymousTagLocations = false;
John McCallf85e1932011-06-15 23:02:42 +00001859 Policy.SuppressStrongLifetime = true;
1860
Douglas Gregora63f6de2011-02-01 21:15:40 +00001861 if (!T.getLocalQualifiers()) {
1862 // Built-in type names are constant strings.
1863 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1864 return BT->getName(Context.getLangOptions());
1865
1866 // Anonymous tag types are constant strings.
1867 if (const TagType *TagT = dyn_cast<TagType>(T))
1868 if (TagDecl *Tag = TagT->getDecl())
Richard Smith162e1c12011-04-15 14:24:37 +00001869 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001870 switch (Tag->getTagKind()) {
1871 case TTK_Struct: return "struct <anonymous>";
1872 case TTK_Class: return "class <anonymous>";
1873 case TTK_Union: return "union <anonymous>";
1874 case TTK_Enum: return "enum <anonymous>";
1875 }
1876 }
1877 }
1878
1879 // Slow path: format the type as a string.
1880 std::string Result;
1881 T.getAsStringInternal(Result, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00001882 return Allocator.CopyString(Result);
Douglas Gregora63f6de2011-02-01 21:15:40 +00001883}
1884
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001885/// \brief If the given declaration has an associated type, add it as a result
1886/// type chunk.
1887static void AddResultTypeChunk(ASTContext &Context,
1888 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001889 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001890 if (!ND)
1891 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001892
1893 // Skip constructors and conversion functions, which have their return types
1894 // built into their names.
1895 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1896 return;
1897
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001898 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001899 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001900 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1901 T = Function->getResultType();
1902 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1903 T = Method->getResultType();
1904 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1905 T = FunTmpl->getTemplatedDecl()->getResultType();
1906 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1907 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1908 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1909 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00001910 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001911 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001912 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001913 T = Property->getType();
1914
1915 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1916 return;
1917
Douglas Gregora63f6de2011-02-01 21:15:40 +00001918 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context,
1919 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001920}
1921
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001922static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001923 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001924 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1925 if (Sentinel->getSentinel() == 0) {
1926 if (Context.getLangOptions().ObjC1 &&
1927 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001928 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001929 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001930 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001931 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001932 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001933 }
1934}
1935
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00001936static void appendWithSpace(std::string &Result, StringRef Text) {
1937 if (!Result.empty())
1938 Result += ' ';
1939 Result += Text.str();
1940}
1941static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
1942 std::string Result;
1943 if (ObjCQuals & Decl::OBJC_TQ_In)
1944 appendWithSpace(Result, "in");
1945 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
1946 appendWithSpace(Result, "inout");
1947 else if (ObjCQuals & Decl::OBJC_TQ_Out)
1948 appendWithSpace(Result, "out");
1949 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
1950 appendWithSpace(Result, "bycopy");
1951 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
1952 appendWithSpace(Result, "byref");
1953 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
1954 appendWithSpace(Result, "oneway");
1955 return Result;
1956}
1957
Douglas Gregor83482d12010-08-24 16:15:59 +00001958static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregoraba48082010-08-29 19:47:46 +00001959 ParmVarDecl *Param,
1960 bool SuppressName = false) {
John McCallf85e1932011-06-15 23:02:42 +00001961 PrintingPolicy Policy(Context.PrintingPolicy);
1962 Policy.AnonymousTagLocations = false;
1963 Policy.SuppressStrongLifetime = true;
1964
Douglas Gregor83482d12010-08-24 16:15:59 +00001965 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1966 if (Param->getType()->isDependentType() ||
1967 !Param->getType()->isBlockPointerType()) {
1968 // The argument for a dependent or non-block parameter is a placeholder
1969 // containing that parameter's type.
1970 std::string Result;
1971
Douglas Gregoraba48082010-08-29 19:47:46 +00001972 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001973 Result = Param->getIdentifier()->getName();
1974
John McCallf85e1932011-06-15 23:02:42 +00001975 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00001976
1977 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00001978 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
1979 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001980 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001981 Result += Param->getIdentifier()->getName();
1982 }
1983 return Result;
1984 }
1985
1986 // The argument for a block pointer parameter is a block literal with
1987 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00001988 FunctionTypeLoc *Block = 0;
1989 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00001990 TypeLoc TL;
1991 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1992 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1993 while (true) {
1994 // Look through typedefs.
1995 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1996 if (TypeSourceInfo *InnerTSInfo
Richard Smith162e1c12011-04-15 14:24:37 +00001997 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001998 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1999 continue;
2000 }
2001 }
2002
2003 // Look through qualified types
2004 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2005 TL = QualifiedTL->getUnqualifiedLoc();
2006 continue;
2007 }
2008
2009 // Try to get the function prototype behind the block pointer type,
2010 // then we're done.
2011 if (BlockPointerTypeLoc *BlockPtr
2012 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002013 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002014 Block = dyn_cast<FunctionTypeLoc>(&TL);
2015 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002016 }
2017 break;
2018 }
2019 }
2020
2021 if (!Block) {
2022 // We were unable to find a FunctionProtoTypeLoc with parameter names
2023 // for the block; just use the parameter type as a placeholder.
2024 std::string Result;
John McCallf85e1932011-06-15 23:02:42 +00002025 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002026
2027 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002028 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2029 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002030 if (Param->getIdentifier())
2031 Result += Param->getIdentifier()->getName();
2032 }
2033
2034 return Result;
2035 }
2036
2037 // We have the function prototype behind the block pointer type, as it was
2038 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002039 std::string Result;
2040 QualType ResultType = Block->getTypePtr()->getResultType();
2041 if (!ResultType->isVoidType())
John McCallf85e1932011-06-15 23:02:42 +00002042 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregor38276252010-09-08 22:47:51 +00002043
2044 Result = '^' + Result;
Douglas Gregor830072c2011-02-15 22:37:09 +00002045 if (!BlockProto || Block->getNumArgs() == 0) {
2046 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002047 Result += "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002048 else
2049 Result += "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002050 } else {
2051 Result += "(";
2052 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2053 if (I)
2054 Result += ", ";
2055 Result += FormatFunctionParameter(Context, Block->getArg(I));
2056
Douglas Gregor830072c2011-02-15 22:37:09 +00002057 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00002058 Result += ", ...";
2059 }
2060 Result += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002061 }
Douglas Gregor38276252010-09-08 22:47:51 +00002062
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002063 if (Param->getIdentifier())
2064 Result += Param->getIdentifier()->getName();
2065
Douglas Gregor83482d12010-08-24 16:15:59 +00002066 return Result;
2067}
2068
Douglas Gregor86d9a522009-09-21 16:56:56 +00002069/// \brief Add function parameter chunks to the given code completion string.
2070static void AddFunctionParameterChunks(ASTContext &Context,
2071 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002072 CodeCompletionBuilder &Result,
2073 unsigned Start = 0,
2074 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002075 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002076 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002077
Douglas Gregor218937c2011-02-01 19:23:04 +00002078 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002079 ParmVarDecl *Param = Function->getParamDecl(P);
2080
Douglas Gregor218937c2011-02-01 19:23:04 +00002081 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002082 // When we see an optional default argument, put that argument and
2083 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002084 CodeCompletionBuilder Opt(Result.getAllocator());
2085 if (!FirstParameter)
2086 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2087 AddFunctionParameterChunks(Context, Function, Opt, P, true);
2088 Result.AddOptionalChunk(Opt.TakeString());
2089 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002090 }
2091
Douglas Gregor218937c2011-02-01 19:23:04 +00002092 if (FirstParameter)
2093 FirstParameter = false;
2094 else
2095 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2096
2097 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002098
2099 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00002100 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
2101
Douglas Gregore17794f2010-08-31 05:13:43 +00002102 if (Function->isVariadic() && P == N - 1)
2103 PlaceholderStr += ", ...";
2104
Douglas Gregor86d9a522009-09-21 16:56:56 +00002105 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002106 Result.AddPlaceholderChunk(
2107 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002108 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002109
2110 if (const FunctionProtoType *Proto
2111 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002112 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002113 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002114 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002115
Douglas Gregor218937c2011-02-01 19:23:04 +00002116 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002117 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002118}
2119
2120/// \brief Add template parameter chunks to the given code completion string.
2121static void AddTemplateParameterChunks(ASTContext &Context,
2122 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002123 CodeCompletionBuilder &Result,
2124 unsigned MaxParameters = 0,
2125 unsigned Start = 0,
2126 bool InDefaultArg = false) {
John McCallf85e1932011-06-15 23:02:42 +00002127 PrintingPolicy Policy(Context.PrintingPolicy);
2128 Policy.AnonymousTagLocations = false;
2129
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002130 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002131 bool FirstParameter = true;
2132
2133 TemplateParameterList *Params = Template->getTemplateParameters();
2134 TemplateParameterList::iterator PEnd = Params->end();
2135 if (MaxParameters)
2136 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002137 for (TemplateParameterList::iterator P = Params->begin() + Start;
2138 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002139 bool HasDefaultArg = false;
2140 std::string PlaceholderStr;
2141 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2142 if (TTP->wasDeclaredWithTypename())
2143 PlaceholderStr = "typename";
2144 else
2145 PlaceholderStr = "class";
2146
2147 if (TTP->getIdentifier()) {
2148 PlaceholderStr += ' ';
2149 PlaceholderStr += TTP->getIdentifier()->getName();
2150 }
2151
2152 HasDefaultArg = TTP->hasDefaultArgument();
2153 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002154 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002155 if (NTTP->getIdentifier())
2156 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002157 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002158 HasDefaultArg = NTTP->hasDefaultArgument();
2159 } else {
2160 assert(isa<TemplateTemplateParmDecl>(*P));
2161 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2162
2163 // Since putting the template argument list into the placeholder would
2164 // be very, very long, we just use an abbreviation.
2165 PlaceholderStr = "template<...> class";
2166 if (TTP->getIdentifier()) {
2167 PlaceholderStr += ' ';
2168 PlaceholderStr += TTP->getIdentifier()->getName();
2169 }
2170
2171 HasDefaultArg = TTP->hasDefaultArgument();
2172 }
2173
Douglas Gregor218937c2011-02-01 19:23:04 +00002174 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002175 // When we see an optional default argument, put that argument and
2176 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002177 CodeCompletionBuilder Opt(Result.getAllocator());
2178 if (!FirstParameter)
2179 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2180 AddTemplateParameterChunks(Context, Template, Opt, MaxParameters,
2181 P - Params->begin(), true);
2182 Result.AddOptionalChunk(Opt.TakeString());
2183 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002184 }
2185
Douglas Gregor218937c2011-02-01 19:23:04 +00002186 InDefaultArg = false;
2187
Douglas Gregor86d9a522009-09-21 16:56:56 +00002188 if (FirstParameter)
2189 FirstParameter = false;
2190 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002191 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002192
2193 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002194 Result.AddPlaceholderChunk(
2195 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002196 }
2197}
2198
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002199/// \brief Add a qualifier to the given code-completion string, if the
2200/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002201static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002202AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002203 NestedNameSpecifier *Qualifier,
2204 bool QualifierIsInformative,
2205 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002206 if (!Qualifier)
2207 return;
2208
2209 std::string PrintedNNS;
2210 {
2211 llvm::raw_string_ostream OS(PrintedNNS);
2212 Qualifier->print(OS, Context.PrintingPolicy);
2213 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002214 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002215 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002216 else
Douglas Gregordae68752011-02-01 22:57:45 +00002217 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002218}
2219
Douglas Gregor218937c2011-02-01 19:23:04 +00002220static void
2221AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2222 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002223 const FunctionProtoType *Proto
2224 = Function->getType()->getAs<FunctionProtoType>();
2225 if (!Proto || !Proto->getTypeQuals())
2226 return;
2227
Douglas Gregora63f6de2011-02-01 21:15:40 +00002228 // FIXME: Add ref-qualifier!
2229
2230 // Handle single qualifiers without copying
2231 if (Proto->getTypeQuals() == Qualifiers::Const) {
2232 Result.AddInformativeChunk(" const");
2233 return;
2234 }
2235
2236 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2237 Result.AddInformativeChunk(" volatile");
2238 return;
2239 }
2240
2241 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2242 Result.AddInformativeChunk(" restrict");
2243 return;
2244 }
2245
2246 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002247 std::string QualsStr;
2248 if (Proto->getTypeQuals() & Qualifiers::Const)
2249 QualsStr += " const";
2250 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2251 QualsStr += " volatile";
2252 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2253 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002254 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002255}
2256
Douglas Gregor6f942b22010-09-21 16:06:22 +00002257/// \brief Add the name of the given declaration
2258static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00002259 CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002260 typedef CodeCompletionString::Chunk Chunk;
2261
2262 DeclarationName Name = ND->getDeclName();
2263 if (!Name)
2264 return;
2265
2266 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002267 case DeclarationName::CXXOperatorName: {
2268 const char *OperatorName = 0;
2269 switch (Name.getCXXOverloadedOperator()) {
2270 case OO_None:
2271 case OO_Conditional:
2272 case NUM_OVERLOADED_OPERATORS:
2273 OperatorName = "operator";
2274 break;
2275
2276#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2277 case OO_##Name: OperatorName = "operator" Spelling; break;
2278#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2279#include "clang/Basic/OperatorKinds.def"
2280
2281 case OO_New: OperatorName = "operator new"; break;
2282 case OO_Delete: OperatorName = "operator delete"; break;
2283 case OO_Array_New: OperatorName = "operator new[]"; break;
2284 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2285 case OO_Call: OperatorName = "operator()"; break;
2286 case OO_Subscript: OperatorName = "operator[]"; break;
2287 }
2288 Result.AddTypedTextChunk(OperatorName);
2289 break;
2290 }
2291
Douglas Gregor6f942b22010-09-21 16:06:22 +00002292 case DeclarationName::Identifier:
2293 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002294 case DeclarationName::CXXDestructorName:
2295 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002296 Result.AddTypedTextChunk(
2297 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002298 break;
2299
2300 case DeclarationName::CXXUsingDirective:
2301 case DeclarationName::ObjCZeroArgSelector:
2302 case DeclarationName::ObjCOneArgSelector:
2303 case DeclarationName::ObjCMultiArgSelector:
2304 break;
2305
2306 case DeclarationName::CXXConstructorName: {
2307 CXXRecordDecl *Record = 0;
2308 QualType Ty = Name.getCXXNameType();
2309 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2310 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2311 else if (const InjectedClassNameType *InjectedTy
2312 = Ty->getAs<InjectedClassNameType>())
2313 Record = InjectedTy->getDecl();
2314 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002315 Result.AddTypedTextChunk(
2316 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002317 break;
2318 }
2319
Douglas Gregordae68752011-02-01 22:57:45 +00002320 Result.AddTypedTextChunk(
2321 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002322 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002323 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002324 AddTemplateParameterChunks(Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002325 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002326 }
2327 break;
2328 }
2329 }
2330}
2331
Douglas Gregor86d9a522009-09-21 16:56:56 +00002332/// \brief If possible, create a new code completion string for the given
2333/// result.
2334///
2335/// \returns Either a new, heap-allocated code completion string describing
2336/// how to use this result, or NULL to indicate that the string or name of the
2337/// result is all that is needed.
2338CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002339CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002340 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002341 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002342 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002343
John McCallf85e1932011-06-15 23:02:42 +00002344 PrintingPolicy Policy(S.Context.PrintingPolicy);
2345 Policy.AnonymousTagLocations = false;
2346 Policy.SuppressStrongLifetime = true;
2347
Douglas Gregor218937c2011-02-01 19:23:04 +00002348 if (Kind == RK_Pattern) {
2349 Pattern->Priority = Priority;
2350 Pattern->Availability = Availability;
2351 return Pattern;
2352 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002353
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002354 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002355 Result.AddTypedTextChunk(Keyword);
2356 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002357 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002358
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002359 if (Kind == RK_Macro) {
2360 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002361 assert(MI && "Not a macro?");
2362
Douglas Gregordae68752011-02-01 22:57:45 +00002363 Result.AddTypedTextChunk(
2364 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002365
2366 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002367 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002368
2369 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002370 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregore4244702011-07-30 08:17:44 +00002371 bool CombineVariadicArgument = false;
2372 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2373 if (MI->isVariadic() && AEnd - A > 1) {
2374 AEnd -= 2;
2375 CombineVariadicArgument = true;
2376 }
2377 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002378 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002379 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002380
Douglas Gregore4244702011-07-30 08:17:44 +00002381 if (!MI->isVariadic() || A + 1 != AEnd) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002382 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002383 Result.AddPlaceholderChunk(
2384 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002385 continue;
2386 }
2387
Douglas Gregore4244702011-07-30 08:17:44 +00002388 // Variadic argument; cope with the difference between GNU and C99
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002389 // variadic macros, providing a single placeholder for the rest of the
2390 // arguments.
2391 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002392 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002393 else {
2394 std::string Arg = (*A)->getName();
2395 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002396 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002397 }
2398 }
Douglas Gregore4244702011-07-30 08:17:44 +00002399
2400 if (CombineVariadicArgument) {
2401 // Handle the next-to-last argument, combining it with the variadic
2402 // argument.
2403 std::string LastArg = (*A)->getName();
2404 ++A;
2405 if ((*A)->isStr("__VA_ARGS__"))
2406 LastArg += ", ...";
2407 else
2408 LastArg += ", " + (*A)->getName().str() + "...";
2409 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(LastArg));
2410 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002411 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2412 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002413 }
2414
Douglas Gregord8e8a582010-05-25 21:41:55 +00002415 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002416 NamedDecl *ND = Declaration;
2417
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002418 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002419 Result.AddTypedTextChunk(
2420 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002421 Result.AddTextChunk("::");
2422 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002423 }
2424
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002425 AddResultTypeChunk(S.Context, ND, Result);
2426
Douglas Gregor86d9a522009-09-21 16:56:56 +00002427 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002428 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2429 S.Context);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002430 AddTypedNameChunk(S.Context, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002431 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002432 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002433 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002434 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002435 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002436 }
2437
2438 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002439 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2440 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002441 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor6f942b22010-09-21 16:06:22 +00002442 AddTypedNameChunk(S.Context, Function, Result);
2443
Douglas Gregor86d9a522009-09-21 16:56:56 +00002444 // Figure out which template parameters are deduced (or have default
2445 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002446 SmallVector<bool, 16> Deduced;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002447 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2448 unsigned LastDeducibleArgument;
2449 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2450 --LastDeducibleArgument) {
2451 if (!Deduced[LastDeducibleArgument - 1]) {
2452 // C++0x: Figure out if the template argument has a default. If so,
2453 // the user doesn't need to type this argument.
2454 // FIXME: We need to abstract template parameters better!
2455 bool HasDefaultArg = false;
2456 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002457 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002458 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2459 HasDefaultArg = TTP->hasDefaultArgument();
2460 else if (NonTypeTemplateParmDecl *NTTP
2461 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2462 HasDefaultArg = NTTP->hasDefaultArgument();
2463 else {
2464 assert(isa<TemplateTemplateParmDecl>(Param));
2465 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002466 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002467 }
2468
2469 if (!HasDefaultArg)
2470 break;
2471 }
2472 }
2473
2474 if (LastDeducibleArgument) {
2475 // Some of the function template arguments cannot be deduced from a
2476 // function call, so we introduce an explicit template argument list
2477 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002478 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002479 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2480 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002481 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002482 }
2483
2484 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002485 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002486 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002487 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002488 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002489 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002490 }
2491
2492 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002493 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2494 S.Context);
Douglas Gregordae68752011-02-01 22:57:45 +00002495 Result.AddTypedTextChunk(
2496 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002497 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002498 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002499 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2500 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002501 }
2502
Douglas Gregor9630eb62009-11-17 16:44:22 +00002503 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002504 Selector Sel = Method->getSelector();
2505 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002506 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002507 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002508 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002509 }
2510
Douglas Gregor813d8342011-02-18 22:29:55 +00002511 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002512 SelName += ':';
2513 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002514 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002515 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002516 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002517
2518 // If there is only one parameter, and we're past it, add an empty
2519 // typed-text chunk since there is nothing to type.
2520 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002521 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002522 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002523 unsigned Idx = 0;
2524 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2525 PEnd = Method->param_end();
2526 P != PEnd; (void)++P, ++Idx) {
2527 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002528 std::string Keyword;
2529 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002530 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002531 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002532 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002533 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002534 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002535 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002536 else
Douglas Gregordae68752011-02-01 22:57:45 +00002537 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002538 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002539
2540 // If we're before the starting parameter, skip the placeholder.
2541 if (Idx < StartParameter)
2542 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002543
2544 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002545
2546 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregoraba48082010-08-29 19:47:46 +00002547 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002548 else {
John McCallf85e1932011-06-15 23:02:42 +00002549 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002550 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2551 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002552 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002553 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002554 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002555 }
2556
Douglas Gregore17794f2010-08-31 05:13:43 +00002557 if (Method->isVariadic() && (P + 1) == PEnd)
2558 Arg += ", ...";
2559
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002560 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002561 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002562 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002563 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002564 else
Douglas Gregordae68752011-02-01 22:57:45 +00002565 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002566 }
2567
Douglas Gregor2a17af02009-12-23 00:21:46 +00002568 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002569 if (Method->param_size() == 0) {
2570 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002571 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002572 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002573 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002574 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002575 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002576 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002577
2578 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002579 }
2580
Douglas Gregor218937c2011-02-01 19:23:04 +00002581 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002582 }
2583
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002584 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002585 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2586 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002587
Douglas Gregordae68752011-02-01 22:57:45 +00002588 Result.AddTypedTextChunk(
2589 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002590 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002591}
2592
Douglas Gregor86d802e2009-09-23 00:34:09 +00002593CodeCompletionString *
2594CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2595 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002596 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002597 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002598 typedef CodeCompletionString::Chunk Chunk;
John McCallf85e1932011-06-15 23:02:42 +00002599 PrintingPolicy Policy(S.Context.PrintingPolicy);
2600 Policy.AnonymousTagLocations = false;
2601 Policy.SuppressStrongLifetime = true;
2602
Douglas Gregor218937c2011-02-01 19:23:04 +00002603 // FIXME: Set priority, availability appropriately.
2604 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002605 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002606 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002607 const FunctionProtoType *Proto
2608 = dyn_cast<FunctionProtoType>(getFunctionType());
2609 if (!FDecl && !Proto) {
2610 // Function without a prototype. Just give the return type and a
2611 // highlighted ellipsis.
2612 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002613 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
2614 S.Context,
2615 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002616 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2617 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2618 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2619 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002620 }
2621
2622 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002623 Result.AddTextChunk(
2624 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002625 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002626 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002627 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002628 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002629
Douglas Gregor218937c2011-02-01 19:23:04 +00002630 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002631 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2632 for (unsigned I = 0; I != NumParams; ++I) {
2633 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002634 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002635
2636 std::string ArgString;
2637 QualType ArgType;
2638
2639 if (FDecl) {
2640 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2641 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2642 } else {
2643 ArgType = Proto->getArgType(I);
2644 }
2645
John McCallf85e1932011-06-15 23:02:42 +00002646 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002647
2648 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002649 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002650 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002651 else
Douglas Gregordae68752011-02-01 22:57:45 +00002652 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002653 }
2654
2655 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002656 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002657 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002658 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002659 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002660 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002661 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002662 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002663
Douglas Gregor218937c2011-02-01 19:23:04 +00002664 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002665}
2666
Chris Lattner5f9e2722011-07-23 10:55:15 +00002667unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002668 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002669 bool PreferredTypeIsPointer) {
2670 unsigned Priority = CCP_Macro;
2671
Douglas Gregorb05496d2010-09-20 21:11:48 +00002672 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2673 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2674 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002675 Priority = CCP_Constant;
2676 if (PreferredTypeIsPointer)
2677 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002678 }
2679 // Treat "YES", "NO", "true", and "false" as constants.
2680 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2681 MacroName.equals("true") || MacroName.equals("false"))
2682 Priority = CCP_Constant;
2683 // Treat "bool" as a type.
2684 else if (MacroName.equals("bool"))
2685 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2686
Douglas Gregor1827e102010-08-16 16:18:59 +00002687
2688 return Priority;
2689}
2690
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002691CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2692 if (!D)
2693 return CXCursor_UnexposedDecl;
2694
2695 switch (D->getKind()) {
2696 case Decl::Enum: return CXCursor_EnumDecl;
2697 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2698 case Decl::Field: return CXCursor_FieldDecl;
2699 case Decl::Function:
2700 return CXCursor_FunctionDecl;
2701 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2702 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2703 case Decl::ObjCClass:
2704 // FIXME
2705 return CXCursor_UnexposedDecl;
2706 case Decl::ObjCForwardProtocol:
2707 // FIXME
2708 return CXCursor_UnexposedDecl;
2709 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2710 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2711 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2712 case Decl::ObjCMethod:
2713 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2714 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2715 case Decl::CXXMethod: return CXCursor_CXXMethod;
2716 case Decl::CXXConstructor: return CXCursor_Constructor;
2717 case Decl::CXXDestructor: return CXCursor_Destructor;
2718 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2719 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2720 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2721 case Decl::ParmVar: return CXCursor_ParmDecl;
2722 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002723 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002724 case Decl::Var: return CXCursor_VarDecl;
2725 case Decl::Namespace: return CXCursor_Namespace;
2726 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2727 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2728 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2729 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2730 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2731 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2732 case Decl::ClassTemplatePartialSpecialization:
2733 return CXCursor_ClassTemplatePartialSpecialization;
2734 case Decl::UsingDirective: return CXCursor_UsingDirective;
2735
2736 case Decl::Using:
2737 case Decl::UnresolvedUsingValue:
2738 case Decl::UnresolvedUsingTypename:
2739 return CXCursor_UsingDeclaration;
2740
Douglas Gregor352697a2011-06-03 23:08:58 +00002741 case Decl::ObjCPropertyImpl:
2742 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2743 case ObjCPropertyImplDecl::Dynamic:
2744 return CXCursor_ObjCDynamicDecl;
2745
2746 case ObjCPropertyImplDecl::Synthesize:
2747 return CXCursor_ObjCSynthesizeDecl;
2748 }
2749 break;
2750
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002751 default:
2752 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2753 switch (TD->getTagKind()) {
2754 case TTK_Struct: return CXCursor_StructDecl;
2755 case TTK_Class: return CXCursor_ClassDecl;
2756 case TTK_Union: return CXCursor_UnionDecl;
2757 case TTK_Enum: return CXCursor_EnumDecl;
2758 }
2759 }
2760 }
2761
2762 return CXCursor_UnexposedDecl;
2763}
2764
Douglas Gregor590c7d52010-07-08 20:55:51 +00002765static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2766 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002767 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002768
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002769 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002770
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002771 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2772 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002773 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002774 Results.AddResult(Result(M->first,
2775 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002776 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002777 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002778 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002779
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002780 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002781
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002782}
2783
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002784static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2785 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002786 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002787
2788 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002789
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002790 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2791 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2792 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2793 Results.AddResult(Result("__func__", CCP_Constant));
2794 Results.ExitScope();
2795}
2796
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002797static void HandleCodeCompleteResults(Sema *S,
2798 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002799 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002800 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002801 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002802 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002803 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002804}
2805
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002806static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2807 Sema::ParserCompletionContext PCC) {
2808 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002809 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002810 return CodeCompletionContext::CCC_TopLevel;
2811
John McCallf312b1e2010-08-26 23:41:50 +00002812 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002813 return CodeCompletionContext::CCC_ClassStructUnion;
2814
John McCallf312b1e2010-08-26 23:41:50 +00002815 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002816 return CodeCompletionContext::CCC_ObjCInterface;
2817
John McCallf312b1e2010-08-26 23:41:50 +00002818 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002819 return CodeCompletionContext::CCC_ObjCImplementation;
2820
John McCallf312b1e2010-08-26 23:41:50 +00002821 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002822 return CodeCompletionContext::CCC_ObjCIvarList;
2823
John McCallf312b1e2010-08-26 23:41:50 +00002824 case Sema::PCC_Template:
2825 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002826 if (S.CurContext->isFileContext())
2827 return CodeCompletionContext::CCC_TopLevel;
2828 else if (S.CurContext->isRecord())
2829 return CodeCompletionContext::CCC_ClassStructUnion;
2830 else
2831 return CodeCompletionContext::CCC_Other;
2832
John McCallf312b1e2010-08-26 23:41:50 +00002833 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002834 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002835
John McCallf312b1e2010-08-26 23:41:50 +00002836 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002837 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2838 S.getLangOptions().ObjC1)
2839 return CodeCompletionContext::CCC_ParenthesizedExpression;
2840 else
2841 return CodeCompletionContext::CCC_Expression;
2842
2843 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002844 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002845 return CodeCompletionContext::CCC_Expression;
2846
John McCallf312b1e2010-08-26 23:41:50 +00002847 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002848 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002849
John McCallf312b1e2010-08-26 23:41:50 +00002850 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002851 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002852
2853 case Sema::PCC_ParenthesizedExpression:
2854 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002855
2856 case Sema::PCC_LocalDeclarationSpecifiers:
2857 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002858 }
2859
2860 return CodeCompletionContext::CCC_Other;
2861}
2862
Douglas Gregorf6961522010-08-27 21:18:54 +00002863/// \brief If we're in a C++ virtual member function, add completion results
2864/// that invoke the functions we override, since it's common to invoke the
2865/// overridden function as well as adding new functionality.
2866///
2867/// \param S The semantic analysis object for which we are generating results.
2868///
2869/// \param InContext This context in which the nested-name-specifier preceding
2870/// the code-completion point
2871static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2872 ResultBuilder &Results) {
2873 // Look through blocks.
2874 DeclContext *CurContext = S.CurContext;
2875 while (isa<BlockDecl>(CurContext))
2876 CurContext = CurContext->getParent();
2877
2878
2879 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2880 if (!Method || !Method->isVirtual())
2881 return;
2882
2883 // We need to have names for all of the parameters, if we're going to
2884 // generate a forwarding call.
2885 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2886 PEnd = Method->param_end();
2887 P != PEnd;
2888 ++P) {
2889 if (!(*P)->getDeclName())
2890 return;
2891 }
2892
2893 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2894 MEnd = Method->end_overridden_methods();
2895 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002896 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002897 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2898 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2899 continue;
2900
2901 // If we need a nested-name-specifier, add one now.
2902 if (!InContext) {
2903 NestedNameSpecifier *NNS
2904 = getRequiredQualification(S.Context, CurContext,
2905 Overridden->getDeclContext());
2906 if (NNS) {
2907 std::string Str;
2908 llvm::raw_string_ostream OS(Str);
2909 NNS->print(OS, S.Context.PrintingPolicy);
Douglas Gregordae68752011-02-01 22:57:45 +00002910 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002911 }
2912 } else if (!InContext->Equals(Overridden->getDeclContext()))
2913 continue;
2914
Douglas Gregordae68752011-02-01 22:57:45 +00002915 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002916 Overridden->getNameAsString()));
2917 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00002918 bool FirstParam = true;
2919 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2920 PEnd = Method->param_end();
2921 P != PEnd; ++P) {
2922 if (FirstParam)
2923 FirstParam = false;
2924 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002925 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00002926
Douglas Gregordae68752011-02-01 22:57:45 +00002927 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002928 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002929 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002930 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2931 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00002932 CCP_SuperCompletion,
2933 CXCursor_CXXMethod));
2934 Results.Ignore(Overridden);
2935 }
2936}
2937
Douglas Gregor01dfea02010-01-10 23:08:15 +00002938void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002939 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002940 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002941 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002942 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002943 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002944
Douglas Gregor01dfea02010-01-10 23:08:15 +00002945 // Determine how to filter results, e.g., so that the names of
2946 // values (functions, enumerators, function templates, etc.) are
2947 // only allowed where we can have an expression.
2948 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002949 case PCC_Namespace:
2950 case PCC_Class:
2951 case PCC_ObjCInterface:
2952 case PCC_ObjCImplementation:
2953 case PCC_ObjCInstanceVariableList:
2954 case PCC_Template:
2955 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002956 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002957 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002958 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2959 break;
2960
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002961 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002962 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002963 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002964 case PCC_ForInit:
2965 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002966 if (WantTypesInContext(CompletionContext, getLangOptions()))
2967 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2968 else
2969 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002970
2971 if (getLangOptions().CPlusPlus)
2972 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002973 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002974
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002975 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002976 // Unfiltered
2977 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002978 }
2979
Douglas Gregor3cdee122010-08-26 16:36:48 +00002980 // If we are in a C++ non-static member function, check the qualifiers on
2981 // the member function to filter/prioritize the results list.
2982 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2983 if (CurMethod->isInstance())
2984 Results.setObjectTypeQualifiers(
2985 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2986
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002987 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002988 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2989 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002990
Douglas Gregorbca403c2010-01-13 23:51:12 +00002991 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002992 Results.ExitScope();
2993
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002994 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00002995 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00002996 case PCC_Expression:
2997 case PCC_Statement:
2998 case PCC_RecoveryInFunction:
2999 if (S->getFnParent())
3000 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3001 break;
3002
3003 case PCC_Namespace:
3004 case PCC_Class:
3005 case PCC_ObjCInterface:
3006 case PCC_ObjCImplementation:
3007 case PCC_ObjCInstanceVariableList:
3008 case PCC_Template:
3009 case PCC_MemberTemplate:
3010 case PCC_ForInit:
3011 case PCC_Condition:
3012 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003013 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003014 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003015 }
3016
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003017 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003018 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003019
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003020 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003021 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003022}
3023
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003024static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3025 ParsedType Receiver,
3026 IdentifierInfo **SelIdents,
3027 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003028 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003029 bool IsSuper,
3030 ResultBuilder &Results);
3031
3032void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3033 bool AllowNonIdentifiers,
3034 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003035 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003036 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003037 AllowNestedNameSpecifiers
3038 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3039 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003040 Results.EnterNewScope();
3041
3042 // Type qualifiers can come after names.
3043 Results.AddResult(Result("const"));
3044 Results.AddResult(Result("volatile"));
3045 if (getLangOptions().C99)
3046 Results.AddResult(Result("restrict"));
3047
3048 if (getLangOptions().CPlusPlus) {
3049 if (AllowNonIdentifiers) {
3050 Results.AddResult(Result("operator"));
3051 }
3052
3053 // Add nested-name-specifiers.
3054 if (AllowNestedNameSpecifiers) {
3055 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003056 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003057 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3058 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3059 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003060 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003061 }
3062 }
3063 Results.ExitScope();
3064
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003065 // If we're in a context where we might have an expression (rather than a
3066 // declaration), and what we've seen so far is an Objective-C type that could
3067 // be a receiver of a class message, this may be a class message send with
3068 // the initial opening bracket '[' missing. Add appropriate completions.
3069 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3070 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3071 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3072 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3073 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3074 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3075 DS.getTypeQualifiers() == 0 &&
3076 S &&
3077 (S->getFlags() & Scope::DeclScope) != 0 &&
3078 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3079 Scope::FunctionPrototypeScope |
3080 Scope::AtCatchScope)) == 0) {
3081 ParsedType T = DS.getRepAsType();
3082 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003083 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003084 }
3085
Douglas Gregor4497dd42010-08-24 04:59:56 +00003086 // Note that we intentionally suppress macro results here, since we do not
3087 // encourage using macros to produce the names of entities.
3088
Douglas Gregor52779fb2010-09-23 23:01:17 +00003089 HandleCodeCompleteResults(this, CodeCompleter,
3090 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003091 Results.data(), Results.size());
3092}
3093
Douglas Gregorfb629412010-08-23 21:17:50 +00003094struct Sema::CodeCompleteExpressionData {
3095 CodeCompleteExpressionData(QualType PreferredType = QualType())
3096 : PreferredType(PreferredType), IntegralConstantExpression(false),
3097 ObjCCollection(false) { }
3098
3099 QualType PreferredType;
3100 bool IntegralConstantExpression;
3101 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003102 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003103};
3104
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003105/// \brief Perform code-completion in an expression context when we know what
3106/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003107///
3108/// \param IntegralConstantExpression Only permit integral constant
3109/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003110void Sema::CodeCompleteExpression(Scope *S,
3111 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003112 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003113 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3114 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003115 if (Data.ObjCCollection)
3116 Results.setFilter(&ResultBuilder::IsObjCCollection);
3117 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003118 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003119 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003120 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3121 else
3122 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003123
3124 if (!Data.PreferredType.isNull())
3125 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3126
3127 // Ignore any declarations that we were told that we don't care about.
3128 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3129 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003130
3131 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003132 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3133 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003134
3135 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003136 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003137 Results.ExitScope();
3138
Douglas Gregor590c7d52010-07-08 20:55:51 +00003139 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003140 if (!Data.PreferredType.isNull())
3141 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3142 || Data.PreferredType->isMemberPointerType()
3143 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003144
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003145 if (S->getFnParent() &&
3146 !Data.ObjCCollection &&
3147 !Data.IntegralConstantExpression)
3148 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3149
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003150 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003151 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003152 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003153 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3154 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003155 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003156}
3157
Douglas Gregorac5fd842010-09-18 01:28:11 +00003158void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3159 if (E.isInvalid())
3160 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3161 else if (getLangOptions().ObjC1)
3162 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003163}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003164
Douglas Gregor73449212010-12-09 23:01:55 +00003165/// \brief The set of properties that have already been added, referenced by
3166/// property name.
3167typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3168
Douglas Gregor95ac6552009-11-18 01:29:26 +00003169static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003170 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003171 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003172 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003173 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003174 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003175 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003176
3177 // Add properties in this container.
3178 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3179 PEnd = Container->prop_end();
3180 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003181 ++P) {
3182 if (AddedProperties.insert(P->getIdentifier()))
3183 Results.MaybeAddResult(Result(*P, 0), CurContext);
3184 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003185
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003186 // Add nullary methods
3187 if (AllowNullaryMethods) {
3188 ASTContext &Context = Container->getASTContext();
3189 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3190 MEnd = Container->meth_end();
3191 M != MEnd; ++M) {
3192 if (M->getSelector().isUnarySelector())
3193 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3194 if (AddedProperties.insert(Name)) {
3195 CodeCompletionBuilder Builder(Results.getAllocator());
3196 AddResultTypeChunk(Context, *M, Builder);
3197 Builder.AddTypedTextChunk(
3198 Results.getAllocator().CopyString(Name->getName()));
3199
3200 CXAvailabilityKind Availability = CXAvailability_Available;
3201 switch (M->getAvailability()) {
3202 case AR_Available:
3203 case AR_NotYetIntroduced:
3204 Availability = CXAvailability_Available;
3205 break;
3206
3207 case AR_Deprecated:
3208 Availability = CXAvailability_Deprecated;
3209 break;
3210
3211 case AR_Unavailable:
3212 Availability = CXAvailability_NotAvailable;
3213 break;
3214 }
3215
3216 Results.MaybeAddResult(Result(Builder.TakeString(),
3217 CCP_MemberDeclaration + CCD_MethodAsProperty,
3218 M->isInstanceMethod()
3219 ? CXCursor_ObjCInstanceMethodDecl
3220 : CXCursor_ObjCClassMethodDecl,
3221 Availability),
3222 CurContext);
3223 }
3224 }
3225 }
3226
3227
Douglas Gregor95ac6552009-11-18 01:29:26 +00003228 // Add properties in referenced protocols.
3229 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3230 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3231 PEnd = Protocol->protocol_end();
3232 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003233 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3234 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003235 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003236 if (AllowCategories) {
3237 // Look through categories.
3238 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3239 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003240 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3241 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003242 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003243
3244 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003245 for (ObjCInterfaceDecl::all_protocol_iterator
3246 I = IFace->all_referenced_protocol_begin(),
3247 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003248 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3249 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003250
3251 // Look in the superclass.
3252 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003253 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3254 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003255 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003256 } else if (const ObjCCategoryDecl *Category
3257 = dyn_cast<ObjCCategoryDecl>(Container)) {
3258 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003259 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3260 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003261 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003262 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3263 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003264 }
3265}
3266
Douglas Gregor81b747b2009-09-17 21:32:03 +00003267void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
3268 SourceLocation OpLoc,
3269 bool IsArrow) {
3270 if (!BaseE || !CodeCompleter)
3271 return;
3272
John McCall0a2c5e22010-08-25 06:19:51 +00003273 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003274
Douglas Gregor81b747b2009-09-17 21:32:03 +00003275 Expr *Base = static_cast<Expr *>(BaseE);
3276 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003277
3278 if (IsArrow) {
3279 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3280 BaseType = Ptr->getPointeeType();
3281 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003282 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003283 else
3284 return;
3285 }
3286
Douglas Gregor3da626b2011-07-07 16:03:39 +00003287 enum CodeCompletionContext::Kind contextKind;
3288
3289 if (IsArrow) {
3290 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3291 }
3292 else {
3293 if (BaseType->isObjCObjectPointerType() ||
3294 BaseType->isObjCObjectOrInterfaceType()) {
3295 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3296 }
3297 else {
3298 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3299 }
3300 }
3301
Douglas Gregor218937c2011-02-01 19:23:04 +00003302 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003303 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003304 BaseType),
3305 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003306 Results.EnterNewScope();
3307 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003308 // Indicate that we are performing a member access, and the cv-qualifiers
3309 // for the base object type.
3310 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3311
Douglas Gregor95ac6552009-11-18 01:29:26 +00003312 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003313 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003314 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003315 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3316 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003317
Douglas Gregor95ac6552009-11-18 01:29:26 +00003318 if (getLangOptions().CPlusPlus) {
3319 if (!Results.empty()) {
3320 // The "template" keyword can follow "->" or "." in the grammar.
3321 // However, we only want to suggest the template keyword if something
3322 // is dependent.
3323 bool IsDependent = BaseType->isDependentType();
3324 if (!IsDependent) {
3325 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3326 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3327 IsDependent = Ctx->isDependentContext();
3328 break;
3329 }
3330 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003331
Douglas Gregor95ac6552009-11-18 01:29:26 +00003332 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003333 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003334 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003335 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003336 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3337 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003338 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003339
3340 // Add property results based on our interface.
3341 const ObjCObjectPointerType *ObjCPtr
3342 = BaseType->getAsObjCInterfacePointerType();
3343 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003344 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3345 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003346 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003347
3348 // Add properties from the protocols in a qualified interface.
3349 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3350 E = ObjCPtr->qual_end();
3351 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003352 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3353 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003354 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003355 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003356 // Objective-C instance variable access.
3357 ObjCInterfaceDecl *Class = 0;
3358 if (const ObjCObjectPointerType *ObjCPtr
3359 = BaseType->getAs<ObjCObjectPointerType>())
3360 Class = ObjCPtr->getInterfaceDecl();
3361 else
John McCallc12c5bb2010-05-15 11:32:37 +00003362 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003363
3364 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003365 if (Class) {
3366 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3367 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003368 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3369 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003370 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003371 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003372
3373 // FIXME: How do we cope with isa?
3374
3375 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003376
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003377 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003378 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003379 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003380 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003381}
3382
Douglas Gregor374929f2009-09-18 15:37:17 +00003383void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3384 if (!CodeCompleter)
3385 return;
3386
John McCall0a2c5e22010-08-25 06:19:51 +00003387 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003388 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003389 enum CodeCompletionContext::Kind ContextKind
3390 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003391 switch ((DeclSpec::TST)TagSpec) {
3392 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003393 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003394 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003395 break;
3396
3397 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003398 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003399 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003400 break;
3401
3402 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003403 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003404 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003405 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003406 break;
3407
3408 default:
3409 assert(false && "Unknown type specifier kind in CodeCompleteTag");
3410 return;
3411 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003412
Douglas Gregor218937c2011-02-01 19:23:04 +00003413 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003414 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003415
3416 // First pass: look for tags.
3417 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003418 LookupVisibleDecls(S, LookupTagName, Consumer,
3419 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003420
Douglas Gregor8071e422010-08-15 06:18:01 +00003421 if (CodeCompleter->includeGlobals()) {
3422 // Second pass: look for nested name specifiers.
3423 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3424 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3425 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003426
Douglas Gregor52779fb2010-09-23 23:01:17 +00003427 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003428 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003429}
3430
Douglas Gregor1a480c42010-08-27 17:35:51 +00003431void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003432 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3433 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003434 Results.EnterNewScope();
3435 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3436 Results.AddResult("const");
3437 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3438 Results.AddResult("volatile");
3439 if (getLangOptions().C99 &&
3440 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3441 Results.AddResult("restrict");
3442 Results.ExitScope();
3443 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003444 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003445 Results.data(), Results.size());
3446}
3447
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003448void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003449 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003450 return;
3451
John McCall781472f2010-08-25 08:40:02 +00003452 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregorf9578432010-07-28 21:50:18 +00003453 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregorfb629412010-08-23 21:17:50 +00003454 CodeCompleteExpressionData Data(Switch->getCond()->getType());
3455 Data.IntegralConstantExpression = true;
3456 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003457 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003458 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003459
3460 // Code-complete the cases of a switch statement over an enumeration type
3461 // by providing the list of
3462 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
3463
3464 // Determine which enumerators we have already seen in the switch statement.
3465 // FIXME: Ideally, we would also be able to look *past* the code-completion
3466 // token, in case we are code-completing in the middle of the switch and not
3467 // at the end. However, we aren't able to do so at the moment.
3468 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003469 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003470 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3471 SC = SC->getNextSwitchCase()) {
3472 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3473 if (!Case)
3474 continue;
3475
3476 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3477 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3478 if (EnumConstantDecl *Enumerator
3479 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3480 // We look into the AST of the case statement to determine which
3481 // enumerator was named. Alternatively, we could compute the value of
3482 // the integral constant expression, then compare it against the
3483 // values of each enumerator. However, value-based approach would not
3484 // work as well with C++ templates where enumerators declared within a
3485 // template are type- and value-dependent.
3486 EnumeratorsSeen.insert(Enumerator);
3487
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003488 // If this is a qualified-id, keep track of the nested-name-specifier
3489 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003490 //
3491 // switch (TagD.getKind()) {
3492 // case TagDecl::TK_enum:
3493 // break;
3494 // case XXX
3495 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003496 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003497 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3498 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003499 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003500 }
3501 }
3502
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003503 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3504 // If there are no prior enumerators in C++, check whether we have to
3505 // qualify the names of the enumerators that we suggest, because they
3506 // may not be visible in this scope.
3507 Qualifier = getRequiredQualification(Context, CurContext,
3508 Enum->getDeclContext());
3509
3510 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3511 }
3512
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003513 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003514 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3515 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003516 Results.EnterNewScope();
3517 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3518 EEnd = Enum->enumerator_end();
3519 E != EEnd; ++E) {
3520 if (EnumeratorsSeen.count(*E))
3521 continue;
3522
Douglas Gregor5c722c702011-02-18 23:30:37 +00003523 CodeCompletionResult R(*E, Qualifier);
3524 R.Priority = CCP_EnumInCase;
3525 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003526 }
3527 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003528
Douglas Gregor3da626b2011-07-07 16:03:39 +00003529 //We need to make sure we're setting the right context,
3530 //so only say we include macros if the code completer says we do
3531 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3532 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003533 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003534 kind = CodeCompletionContext::CCC_OtherWithMacros;
3535 }
3536
3537
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003538 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003539 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003540 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003541}
3542
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003543namespace {
3544 struct IsBetterOverloadCandidate {
3545 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003546 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003547
3548 public:
John McCall5769d612010-02-08 23:07:23 +00003549 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3550 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003551
3552 bool
3553 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003554 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003555 }
3556 };
3557}
3558
Douglas Gregord28dcd72010-05-30 06:10:08 +00003559static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3560 if (NumArgs && !Args)
3561 return true;
3562
3563 for (unsigned I = 0; I != NumArgs; ++I)
3564 if (!Args[I])
3565 return true;
3566
3567 return false;
3568}
3569
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003570void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
3571 ExprTy **ArgsIn, unsigned NumArgs) {
3572 if (!CodeCompleter)
3573 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003574
3575 // When we're code-completing for a call, we fall back to ordinary
3576 // name code-completion whenever we can't produce specific
3577 // results. We may want to revisit this strategy in the future,
3578 // e.g., by merging the two kinds of results.
3579
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003580 Expr *Fn = (Expr *)FnIn;
3581 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003582
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003583 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003584 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003585 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003586 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003587 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003588 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003589
John McCall3b4294e2009-12-16 12:17:52 +00003590 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003591 SourceLocation Loc = Fn->getExprLoc();
3592 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003593
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003594 // FIXME: What if we're calling something that isn't a function declaration?
3595 // FIXME: What if we're calling a pseudo-destructor?
3596 // FIXME: What if we're calling a member function?
3597
Douglas Gregorc0265402010-01-21 15:46:19 +00003598 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003599 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003600
John McCall3b4294e2009-12-16 12:17:52 +00003601 Expr *NakedFn = Fn->IgnoreParenCasts();
3602 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3603 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3604 /*PartialOverloading=*/ true);
3605 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3606 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003607 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003608 if (!getLangOptions().CPlusPlus ||
3609 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003610 Results.push_back(ResultCandidate(FDecl));
3611 else
John McCall86820f52010-01-26 01:37:31 +00003612 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003613 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3614 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003615 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003616 }
John McCall3b4294e2009-12-16 12:17:52 +00003617 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003618
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003619 QualType ParamType;
3620
Douglas Gregorc0265402010-01-21 15:46:19 +00003621 if (!CandidateSet.empty()) {
3622 // Sort the overload candidate set by placing the best overloads first.
3623 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003624 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003625
Douglas Gregorc0265402010-01-21 15:46:19 +00003626 // Add the remaining viable overload candidates as code-completion reslults.
3627 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3628 CandEnd = CandidateSet.end();
3629 Cand != CandEnd; ++Cand) {
3630 if (Cand->Viable)
3631 Results.push_back(ResultCandidate(Cand->Function));
3632 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003633
3634 // From the viable candidates, try to determine the type of this parameter.
3635 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3636 if (const FunctionType *FType = Results[I].getFunctionType())
3637 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3638 if (NumArgs < Proto->getNumArgs()) {
3639 if (ParamType.isNull())
3640 ParamType = Proto->getArgType(NumArgs);
3641 else if (!Context.hasSameUnqualifiedType(
3642 ParamType.getNonReferenceType(),
3643 Proto->getArgType(NumArgs).getNonReferenceType())) {
3644 ParamType = QualType();
3645 break;
3646 }
3647 }
3648 }
3649 } else {
3650 // Try to determine the parameter type from the type of the expression
3651 // being called.
3652 QualType FunctionType = Fn->getType();
3653 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3654 FunctionType = Ptr->getPointeeType();
3655 else if (const BlockPointerType *BlockPtr
3656 = FunctionType->getAs<BlockPointerType>())
3657 FunctionType = BlockPtr->getPointeeType();
3658 else if (const MemberPointerType *MemPtr
3659 = FunctionType->getAs<MemberPointerType>())
3660 FunctionType = MemPtr->getPointeeType();
3661
3662 if (const FunctionProtoType *Proto
3663 = FunctionType->getAs<FunctionProtoType>()) {
3664 if (NumArgs < Proto->getNumArgs())
3665 ParamType = Proto->getArgType(NumArgs);
3666 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003667 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003668
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003669 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003670 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003671 else
3672 CodeCompleteExpression(S, ParamType);
3673
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003674 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003675 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3676 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003677}
3678
John McCalld226f652010-08-21 09:40:31 +00003679void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3680 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003681 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003682 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003683 return;
3684 }
3685
3686 CodeCompleteExpression(S, VD->getType());
3687}
3688
3689void Sema::CodeCompleteReturn(Scope *S) {
3690 QualType ResultType;
3691 if (isa<BlockDecl>(CurContext)) {
3692 if (BlockScopeInfo *BSI = getCurBlock())
3693 ResultType = BSI->ReturnType;
3694 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3695 ResultType = Function->getResultType();
3696 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3697 ResultType = Method->getResultType();
3698
3699 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003700 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003701 else
3702 CodeCompleteExpression(S, ResultType);
3703}
3704
Douglas Gregord2d8be62011-07-30 08:36:53 +00003705void Sema::CodeCompleteAfterIf(Scope *S) {
3706 typedef CodeCompletionResult Result;
3707 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3708 mapCodeCompletionContext(*this, PCC_Statement));
3709 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3710 Results.EnterNewScope();
3711
3712 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3713 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3714 CodeCompleter->includeGlobals());
3715
3716 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3717
3718 // "else" block
3719 CodeCompletionBuilder Builder(Results.getAllocator());
3720 Builder.AddTypedTextChunk("else");
3721 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3722 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3723 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3724 Builder.AddPlaceholderChunk("statements");
3725 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3726 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3727 Results.AddResult(Builder.TakeString());
3728
3729 // "else if" block
3730 Builder.AddTypedTextChunk("else");
3731 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3732 Builder.AddTextChunk("if");
3733 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3734 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3735 if (getLangOptions().CPlusPlus)
3736 Builder.AddPlaceholderChunk("condition");
3737 else
3738 Builder.AddPlaceholderChunk("expression");
3739 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3740 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3741 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3742 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3743 Builder.AddPlaceholderChunk("statements");
3744 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3745 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3746 Results.AddResult(Builder.TakeString());
3747
3748 Results.ExitScope();
3749
3750 if (S->getFnParent())
3751 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3752
3753 if (CodeCompleter->includeMacros())
3754 AddMacroResults(PP, Results);
3755
3756 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3757 Results.data(),Results.size());
3758}
3759
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003760void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3761 if (LHS)
3762 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3763 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003764 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003765}
3766
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003767void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003768 bool EnteringContext) {
3769 if (!SS.getScopeRep() || !CodeCompleter)
3770 return;
3771
Douglas Gregor86d9a522009-09-21 16:56:56 +00003772 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3773 if (!Ctx)
3774 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003775
3776 // Try to instantiate any non-dependent declaration contexts before
3777 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003778 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003779 return;
3780
Douglas Gregor218937c2011-02-01 19:23:04 +00003781 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3782 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003783 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003784
Douglas Gregor86d9a522009-09-21 16:56:56 +00003785 // The "template" keyword can follow "::" in the grammar, but only
3786 // put it into the grammar if the nested-name-specifier is dependent.
3787 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3788 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003789 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003790
3791 // Add calls to overridden virtual functions, if there are any.
3792 //
3793 // FIXME: This isn't wonderful, because we don't know whether we're actually
3794 // in a context that permits expressions. This is a general issue with
3795 // qualified-id completions.
3796 if (!EnteringContext)
3797 MaybeAddOverrideCalls(*this, Ctx, Results);
3798 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003799
Douglas Gregorf6961522010-08-27 21:18:54 +00003800 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3801 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3802
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003803 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003804 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003805 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003806}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003807
3808void Sema::CodeCompleteUsing(Scope *S) {
3809 if (!CodeCompleter)
3810 return;
3811
Douglas Gregor218937c2011-02-01 19:23:04 +00003812 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003813 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3814 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003815 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003816
3817 // If we aren't in class scope, we could see the "namespace" keyword.
3818 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003819 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003820
3821 // After "using", we can see anything that would start a
3822 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003823 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003824 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3825 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003826 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003827
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003828 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003829 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003830 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003831}
3832
3833void Sema::CodeCompleteUsingDirective(Scope *S) {
3834 if (!CodeCompleter)
3835 return;
3836
Douglas Gregor86d9a522009-09-21 16:56:56 +00003837 // After "using namespace", we expect to see a namespace name or namespace
3838 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003839 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3840 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003841 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003842 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003843 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003844 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3845 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003846 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003847 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003848 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003849 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003850}
3851
3852void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3853 if (!CodeCompleter)
3854 return;
3855
Douglas Gregor86d9a522009-09-21 16:56:56 +00003856 DeclContext *Ctx = (DeclContext *)S->getEntity();
3857 if (!S->getParent())
3858 Ctx = Context.getTranslationUnitDecl();
3859
Douglas Gregor52779fb2010-09-23 23:01:17 +00003860 bool SuppressedGlobalResults
3861 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3862
Douglas Gregor218937c2011-02-01 19:23:04 +00003863 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003864 SuppressedGlobalResults
3865 ? CodeCompletionContext::CCC_Namespace
3866 : CodeCompletionContext::CCC_Other,
3867 &ResultBuilder::IsNamespace);
3868
3869 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003870 // We only want to see those namespaces that have already been defined
3871 // within this scope, because its likely that the user is creating an
3872 // extended namespace declaration. Keep track of the most recent
3873 // definition of each namespace.
3874 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3875 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3876 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3877 NS != NSEnd; ++NS)
3878 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3879
3880 // Add the most recent definition (or extended definition) of each
3881 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003882 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003883 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3884 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3885 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003886 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003887 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003888 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003889 }
3890
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003891 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003892 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003893 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003894}
3895
3896void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3897 if (!CodeCompleter)
3898 return;
3899
Douglas Gregor86d9a522009-09-21 16:56:56 +00003900 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003901 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3902 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003903 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003904 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003905 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3906 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003907 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003908 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003909 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003910}
3911
Douglas Gregored8d3222009-09-18 20:05:18 +00003912void Sema::CodeCompleteOperatorName(Scope *S) {
3913 if (!CodeCompleter)
3914 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003915
John McCall0a2c5e22010-08-25 06:19:51 +00003916 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003917 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3918 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003919 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003920 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003921
Douglas Gregor86d9a522009-09-21 16:56:56 +00003922 // Add the names of overloadable operators.
3923#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3924 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003925 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003926#include "clang/Basic/OperatorKinds.def"
3927
3928 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003929 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003930 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003931 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3932 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003933
3934 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003935 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003936 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003937
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003938 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003939 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003940 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003941}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003942
Douglas Gregor0133f522010-08-28 00:00:50 +00003943void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00003944 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00003945 unsigned NumInitializers) {
John McCallf85e1932011-06-15 23:02:42 +00003946 PrintingPolicy Policy(Context.PrintingPolicy);
3947 Policy.AnonymousTagLocations = false;
3948 Policy.SuppressStrongLifetime = true;
3949
Douglas Gregor0133f522010-08-28 00:00:50 +00003950 CXXConstructorDecl *Constructor
3951 = static_cast<CXXConstructorDecl *>(ConstructorD);
3952 if (!Constructor)
3953 return;
3954
Douglas Gregor218937c2011-02-01 19:23:04 +00003955 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003956 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003957 Results.EnterNewScope();
3958
3959 // Fill in any already-initialized fields or base classes.
3960 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3961 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3962 for (unsigned I = 0; I != NumInitializers; ++I) {
3963 if (Initializers[I]->isBaseInitializer())
3964 InitializedBases.insert(
3965 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3966 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003967 InitializedFields.insert(cast<FieldDecl>(
3968 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00003969 }
3970
3971 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00003972 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00003973 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003974 CXXRecordDecl *ClassDecl = Constructor->getParent();
3975 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3976 BaseEnd = ClassDecl->bases_end();
3977 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003978 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3979 SawLastInitializer
3980 = NumInitializers > 0 &&
3981 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3982 Context.hasSameUnqualifiedType(Base->getType(),
3983 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003984 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003985 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003986
Douglas Gregor218937c2011-02-01 19:23:04 +00003987 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003988 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00003989 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00003990 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3991 Builder.AddPlaceholderChunk("args");
3992 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3993 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003994 SawLastInitializer? CCP_NextInitializer
3995 : CCP_MemberDeclaration));
3996 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003997 }
3998
3999 // Add completions for virtual base classes.
4000 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4001 BaseEnd = ClassDecl->vbases_end();
4002 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004003 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4004 SawLastInitializer
4005 = NumInitializers > 0 &&
4006 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4007 Context.hasSameUnqualifiedType(Base->getType(),
4008 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004009 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004010 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004011
Douglas Gregor218937c2011-02-01 19:23:04 +00004012 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004013 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004014 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004015 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4016 Builder.AddPlaceholderChunk("args");
4017 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4018 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004019 SawLastInitializer? CCP_NextInitializer
4020 : CCP_MemberDeclaration));
4021 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004022 }
4023
4024 // Add completions for members.
4025 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4026 FieldEnd = ClassDecl->field_end();
4027 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004028 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4029 SawLastInitializer
4030 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004031 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4032 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004033 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004034 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004035
4036 if (!Field->getDeclName())
4037 continue;
4038
Douglas Gregordae68752011-02-01 22:57:45 +00004039 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004040 Field->getIdentifier()->getName()));
4041 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4042 Builder.AddPlaceholderChunk("args");
4043 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4044 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004045 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004046 : CCP_MemberDeclaration,
4047 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004048 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004049 }
4050 Results.ExitScope();
4051
Douglas Gregor52779fb2010-09-23 23:01:17 +00004052 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004053 Results.data(), Results.size());
4054}
4055
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004056// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4057// true or false.
4058#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004059static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004060 ResultBuilder &Results,
4061 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004062 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004063 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004064 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004065
Douglas Gregor218937c2011-02-01 19:23:04 +00004066 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004067 if (LangOpts.ObjC2) {
4068 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004069 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4070 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4071 Builder.AddPlaceholderChunk("property");
4072 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004073
4074 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004075 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4076 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4077 Builder.AddPlaceholderChunk("property");
4078 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004079 }
4080}
4081
Douglas Gregorbca403c2010-01-13 23:51:12 +00004082static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004083 ResultBuilder &Results,
4084 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004085 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004086
4087 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004088 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004089
4090 if (LangOpts.ObjC2) {
4091 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004092 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004093
4094 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004095 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004096
4097 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004098 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004099 }
4100}
4101
Douglas Gregorbca403c2010-01-13 23:51:12 +00004102static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004103 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004104 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004105
4106 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004107 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4108 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4109 Builder.AddPlaceholderChunk("name");
4110 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004111
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004112 if (Results.includeCodePatterns()) {
4113 // @interface name
4114 // FIXME: Could introduce the whole pattern, including superclasses and
4115 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004116 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4117 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4118 Builder.AddPlaceholderChunk("class");
4119 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004120
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004121 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004122 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4123 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4124 Builder.AddPlaceholderChunk("protocol");
4125 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004126
4127 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004128 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4129 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4130 Builder.AddPlaceholderChunk("class");
4131 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004132 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004133
4134 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004135 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4136 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4137 Builder.AddPlaceholderChunk("alias");
4138 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4139 Builder.AddPlaceholderChunk("class");
4140 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004141}
4142
John McCalld226f652010-08-21 09:40:31 +00004143void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorc464ae82009-12-07 09:27:33 +00004144 bool InInterface) {
John McCall0a2c5e22010-08-25 06:19:51 +00004145 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004146 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4147 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004148 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004149 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00004150 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004151 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00004152 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004153 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004154 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004155 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004156 HandleCodeCompleteResults(this, CodeCompleter,
4157 CodeCompletionContext::CCC_Other,
4158 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004159}
4160
Douglas Gregorbca403c2010-01-13 23:51:12 +00004161static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004162 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004163 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004164
4165 // @encode ( type-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004166 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4167 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4168 Builder.AddPlaceholderChunk("type-name");
4169 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4170 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004171
4172 // @protocol ( protocol-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00004173 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4174 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4175 Builder.AddPlaceholderChunk("protocol-name");
4176 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4177 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004178
4179 // @selector ( selector )
Douglas Gregor218937c2011-02-01 19:23:04 +00004180 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4181 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4182 Builder.AddPlaceholderChunk("selector");
4183 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4184 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004185}
4186
Douglas Gregorbca403c2010-01-13 23:51:12 +00004187static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004188 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004189 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004190
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004191 if (Results.includeCodePatterns()) {
4192 // @try { statements } @catch ( declaration ) { statements } @finally
4193 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004194 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4195 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4196 Builder.AddPlaceholderChunk("statements");
4197 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4198 Builder.AddTextChunk("@catch");
4199 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4200 Builder.AddPlaceholderChunk("parameter");
4201 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4202 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4203 Builder.AddPlaceholderChunk("statements");
4204 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4205 Builder.AddTextChunk("@finally");
4206 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4207 Builder.AddPlaceholderChunk("statements");
4208 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4209 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004210 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004211
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004212 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004213 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4214 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4215 Builder.AddPlaceholderChunk("expression");
4216 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004217
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004218 if (Results.includeCodePatterns()) {
4219 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004220 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4221 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4222 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4223 Builder.AddPlaceholderChunk("expression");
4224 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4225 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4226 Builder.AddPlaceholderChunk("statements");
4227 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4228 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004229 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004230}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004231
Douglas Gregorbca403c2010-01-13 23:51:12 +00004232static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004233 ResultBuilder &Results,
4234 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004235 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004236 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4237 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4238 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004239 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004240 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004241}
4242
4243void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004244 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4245 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004246 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004247 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004248 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004249 HandleCodeCompleteResults(this, CodeCompleter,
4250 CodeCompletionContext::CCC_Other,
4251 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004252}
4253
4254void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004255 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4256 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004257 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004258 AddObjCStatementResults(Results, false);
4259 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004260 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004261 HandleCodeCompleteResults(this, CodeCompleter,
4262 CodeCompletionContext::CCC_Other,
4263 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004264}
4265
4266void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004267 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4268 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004269 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004270 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004271 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004272 HandleCodeCompleteResults(this, CodeCompleter,
4273 CodeCompletionContext::CCC_Other,
4274 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004275}
4276
Douglas Gregor988358f2009-11-19 00:14:45 +00004277/// \brief Determine whether the addition of the given flag to an Objective-C
4278/// property's attributes will cause a conflict.
4279static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4280 // Check if we've already added this flag.
4281 if (Attributes & NewFlag)
4282 return true;
4283
4284 Attributes |= NewFlag;
4285
4286 // Check for collisions with "readonly".
4287 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4288 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4289 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004290 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004291 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004292 ObjCDeclSpec::DQ_PR_retain |
4293 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004294 return true;
4295
John McCallf85e1932011-06-15 23:02:42 +00004296 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004297 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004298 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004299 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004300 ObjCDeclSpec::DQ_PR_retain|
4301 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004302 if (AssignCopyRetMask &&
4303 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004304 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004305 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004306 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4307 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004308 return true;
4309
4310 return false;
4311}
4312
Douglas Gregora93b1082009-11-18 23:08:07 +00004313void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004314 if (!CodeCompleter)
4315 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004316
Steve Naroffece8e712009-10-08 21:55:05 +00004317 unsigned Attributes = ODS.getPropertyAttributes();
4318
John McCall0a2c5e22010-08-25 06:19:51 +00004319 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004320 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4321 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004322 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004323 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004324 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004325 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004326 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004327 if (!ObjCPropertyFlagConflicts(Attributes,
4328 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4329 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004330 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004331 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004332 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004333 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004334 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4335 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004336 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004337 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004338 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004339 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004340 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4341 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004342 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004343 CodeCompletionBuilder Setter(Results.getAllocator());
4344 Setter.AddTypedTextChunk("setter");
4345 Setter.AddTextChunk(" = ");
4346 Setter.AddPlaceholderChunk("method");
4347 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004348 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004349 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004350 CodeCompletionBuilder Getter(Results.getAllocator());
4351 Getter.AddTypedTextChunk("getter");
4352 Getter.AddTextChunk(" = ");
4353 Getter.AddPlaceholderChunk("method");
4354 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004355 }
Steve Naroffece8e712009-10-08 21:55:05 +00004356 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004357 HandleCodeCompleteResults(this, CodeCompleter,
4358 CodeCompletionContext::CCC_Other,
4359 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004360}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004361
Douglas Gregor4ad96852009-11-19 07:41:15 +00004362/// \brief Descripts the kind of Objective-C method that we want to find
4363/// via code completion.
4364enum ObjCMethodKind {
4365 MK_Any, //< Any kind of method, provided it means other specified criteria.
4366 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4367 MK_OneArgSelector //< One-argument selector.
4368};
4369
Douglas Gregor458433d2010-08-26 15:07:07 +00004370static bool isAcceptableObjCSelector(Selector Sel,
4371 ObjCMethodKind WantKind,
4372 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004373 unsigned NumSelIdents,
4374 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004375 if (NumSelIdents > Sel.getNumArgs())
4376 return false;
4377
4378 switch (WantKind) {
4379 case MK_Any: break;
4380 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4381 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4382 }
4383
Douglas Gregorcf544262010-11-17 21:36:08 +00004384 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4385 return false;
4386
Douglas Gregor458433d2010-08-26 15:07:07 +00004387 for (unsigned I = 0; I != NumSelIdents; ++I)
4388 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4389 return false;
4390
4391 return true;
4392}
4393
Douglas Gregor4ad96852009-11-19 07:41:15 +00004394static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4395 ObjCMethodKind WantKind,
4396 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004397 unsigned NumSelIdents,
4398 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004399 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004400 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004401}
Douglas Gregord36adf52010-09-16 16:06:31 +00004402
4403namespace {
4404 /// \brief A set of selectors, which is used to avoid introducing multiple
4405 /// completions with the same selector into the result set.
4406 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4407}
4408
Douglas Gregor36ecb042009-11-17 23:22:23 +00004409/// \brief Add all of the Objective-C methods in the given Objective-C
4410/// container to the set of results.
4411///
4412/// The container will be a class, protocol, category, or implementation of
4413/// any of the above. This mether will recurse to include methods from
4414/// the superclasses of classes along with their categories, protocols, and
4415/// implementations.
4416///
4417/// \param Container the container in which we'll look to find methods.
4418///
4419/// \param WantInstance whether to add instance methods (only); if false, this
4420/// routine will add factory methods (only).
4421///
4422/// \param CurContext the context in which we're performing the lookup that
4423/// finds methods.
4424///
Douglas Gregorcf544262010-11-17 21:36:08 +00004425/// \param AllowSameLength Whether we allow a method to be added to the list
4426/// when it has the same number of parameters as we have selector identifiers.
4427///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004428/// \param Results the structure into which we'll add results.
4429static void AddObjCMethods(ObjCContainerDecl *Container,
4430 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004431 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004432 IdentifierInfo **SelIdents,
4433 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004434 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004435 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004436 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004437 ResultBuilder &Results,
4438 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004439 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004440 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4441 MEnd = Container->meth_end();
4442 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004443 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4444 // Check whether the selector identifiers we've been given are a
4445 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004446 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4447 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004448 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004449
Douglas Gregord36adf52010-09-16 16:06:31 +00004450 if (!Selectors.insert((*M)->getSelector()))
4451 continue;
4452
Douglas Gregord3c68542009-11-19 01:08:35 +00004453 Result R = Result(*M, 0);
4454 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004455 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004456 if (!InOriginalClass)
4457 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004458 Results.MaybeAddResult(R, CurContext);
4459 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004460 }
4461
Douglas Gregore396c7b2010-09-16 15:34:59 +00004462 // Visit the protocols of protocols.
4463 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4464 const ObjCList<ObjCProtocolDecl> &Protocols
4465 = Protocol->getReferencedProtocols();
4466 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4467 E = Protocols.end();
4468 I != E; ++I)
4469 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004470 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004471 }
4472
Douglas Gregor36ecb042009-11-17 23:22:23 +00004473 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4474 if (!IFace)
4475 return;
4476
4477 // Add methods in protocols.
4478 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4479 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4480 E = Protocols.end();
4481 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004482 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004483 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004484
4485 // Add methods in categories.
4486 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4487 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004488 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004489 NumSelIdents, CurContext, Selectors, AllowSameLength,
4490 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004491
4492 // Add a categories protocol methods.
4493 const ObjCList<ObjCProtocolDecl> &Protocols
4494 = CatDecl->getReferencedProtocols();
4495 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4496 E = Protocols.end();
4497 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004498 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004499 NumSelIdents, CurContext, Selectors, AllowSameLength,
4500 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004501
4502 // Add methods in category implementations.
4503 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004504 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004505 NumSelIdents, CurContext, Selectors, AllowSameLength,
4506 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004507 }
4508
4509 // Add methods in superclass.
4510 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004511 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004512 SelIdents, NumSelIdents, CurContext, Selectors,
4513 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004514
4515 // Add methods in our implementation, if any.
4516 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004517 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004518 NumSelIdents, CurContext, Selectors, AllowSameLength,
4519 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004520}
4521
4522
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004523void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004524 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004525
4526 // Try to find the interface where getters might live.
John McCalld226f652010-08-21 09:40:31 +00004527 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004528 if (!Class) {
4529 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004530 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004531 Class = Category->getClassInterface();
4532
4533 if (!Class)
4534 return;
4535 }
4536
4537 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004538 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4539 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004540 Results.EnterNewScope();
4541
Douglas Gregord36adf52010-09-16 16:06:31 +00004542 VisitedSelectorSet Selectors;
4543 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004544 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004545 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004546 HandleCodeCompleteResults(this, CodeCompleter,
4547 CodeCompletionContext::CCC_Other,
4548 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004549}
4550
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004551void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004552 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004553
4554 // Try to find the interface where setters might live.
4555 ObjCInterfaceDecl *Class
John McCalld226f652010-08-21 09:40:31 +00004556 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004557 if (!Class) {
4558 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004559 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004560 Class = Category->getClassInterface();
4561
4562 if (!Class)
4563 return;
4564 }
4565
4566 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004567 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4568 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004569 Results.EnterNewScope();
4570
Douglas Gregord36adf52010-09-16 16:06:31 +00004571 VisitedSelectorSet Selectors;
4572 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004573 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004574
4575 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004576 HandleCodeCompleteResults(this, CodeCompleter,
4577 CodeCompletionContext::CCC_Other,
4578 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004579}
4580
Douglas Gregorafc45782011-02-15 22:19:42 +00004581void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4582 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004583 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004584 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4585 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004586 Results.EnterNewScope();
4587
4588 // Add context-sensitive, Objective-C parameter-passing keywords.
4589 bool AddedInOut = false;
4590 if ((DS.getObjCDeclQualifier() &
4591 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4592 Results.AddResult("in");
4593 Results.AddResult("inout");
4594 AddedInOut = true;
4595 }
4596 if ((DS.getObjCDeclQualifier() &
4597 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4598 Results.AddResult("out");
4599 if (!AddedInOut)
4600 Results.AddResult("inout");
4601 }
4602 if ((DS.getObjCDeclQualifier() &
4603 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4604 ObjCDeclSpec::DQ_Oneway)) == 0) {
4605 Results.AddResult("bycopy");
4606 Results.AddResult("byref");
4607 Results.AddResult("oneway");
4608 }
4609
Douglas Gregorafc45782011-02-15 22:19:42 +00004610 // If we're completing the return type of an Objective-C method and the
4611 // identifier IBAction refers to a macro, provide a completion item for
4612 // an action, e.g.,
4613 // IBAction)<#selector#>:(id)sender
4614 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4615 Context.Idents.get("IBAction").hasMacroDefinition()) {
4616 typedef CodeCompletionString::Chunk Chunk;
4617 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4618 CXAvailability_Available);
4619 Builder.AddTypedTextChunk("IBAction");
4620 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4621 Builder.AddPlaceholderChunk("selector");
4622 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4623 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4624 Builder.AddTextChunk("id");
4625 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4626 Builder.AddTextChunk("sender");
4627 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4628 }
4629
Douglas Gregord32b0222010-08-24 01:06:58 +00004630 // Add various builtin type names and specifiers.
4631 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4632 Results.ExitScope();
4633
4634 // Add the various type names
4635 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4636 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4637 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4638 CodeCompleter->includeGlobals());
4639
4640 if (CodeCompleter->includeMacros())
4641 AddMacroResults(PP, Results);
4642
4643 HandleCodeCompleteResults(this, CodeCompleter,
4644 CodeCompletionContext::CCC_Type,
4645 Results.data(), Results.size());
4646}
4647
Douglas Gregor22f56992010-04-06 19:22:33 +00004648/// \brief When we have an expression with type "id", we may assume
4649/// that it has some more-specific class type based on knowledge of
4650/// common uses of Objective-C. This routine returns that class type,
4651/// or NULL if no better result could be determined.
4652static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004653 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004654 if (!Msg)
4655 return 0;
4656
4657 Selector Sel = Msg->getSelector();
4658 if (Sel.isNull())
4659 return 0;
4660
4661 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4662 if (!Id)
4663 return 0;
4664
4665 ObjCMethodDecl *Method = Msg->getMethodDecl();
4666 if (!Method)
4667 return 0;
4668
4669 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004670 ObjCInterfaceDecl *IFace = 0;
4671 switch (Msg->getReceiverKind()) {
4672 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004673 if (const ObjCObjectType *ObjType
4674 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4675 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004676 break;
4677
4678 case ObjCMessageExpr::Instance: {
4679 QualType T = Msg->getInstanceReceiver()->getType();
4680 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4681 IFace = Ptr->getInterfaceDecl();
4682 break;
4683 }
4684
4685 case ObjCMessageExpr::SuperInstance:
4686 case ObjCMessageExpr::SuperClass:
4687 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004688 }
4689
4690 if (!IFace)
4691 return 0;
4692
4693 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4694 if (Method->isInstanceMethod())
4695 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4696 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004697 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004698 .Case("autorelease", IFace)
4699 .Case("copy", IFace)
4700 .Case("copyWithZone", IFace)
4701 .Case("mutableCopy", IFace)
4702 .Case("mutableCopyWithZone", IFace)
4703 .Case("awakeFromCoder", IFace)
4704 .Case("replacementObjectFromCoder", IFace)
4705 .Case("class", IFace)
4706 .Case("classForCoder", IFace)
4707 .Case("superclass", Super)
4708 .Default(0);
4709
4710 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4711 .Case("new", IFace)
4712 .Case("alloc", IFace)
4713 .Case("allocWithZone", IFace)
4714 .Case("class", IFace)
4715 .Case("superclass", Super)
4716 .Default(0);
4717}
4718
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004719// Add a special completion for a message send to "super", which fills in the
4720// most likely case of forwarding all of our arguments to the superclass
4721// function.
4722///
4723/// \param S The semantic analysis object.
4724///
4725/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4726/// the "super" keyword. Otherwise, we just need to provide the arguments.
4727///
4728/// \param SelIdents The identifiers in the selector that have already been
4729/// provided as arguments for a send to "super".
4730///
4731/// \param NumSelIdents The number of identifiers in \p SelIdents.
4732///
4733/// \param Results The set of results to augment.
4734///
4735/// \returns the Objective-C method declaration that would be invoked by
4736/// this "super" completion. If NULL, no completion was added.
4737static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4738 IdentifierInfo **SelIdents,
4739 unsigned NumSelIdents,
4740 ResultBuilder &Results) {
4741 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4742 if (!CurMethod)
4743 return 0;
4744
4745 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4746 if (!Class)
4747 return 0;
4748
4749 // Try to find a superclass method with the same selector.
4750 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004751 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4752 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004753 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4754 CurMethod->isInstanceMethod());
4755
Douglas Gregor78bcd912011-02-16 00:51:18 +00004756 // Check in categories or class extensions.
4757 if (!SuperMethod) {
4758 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4759 Category = Category->getNextClassCategory())
4760 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4761 CurMethod->isInstanceMethod())))
4762 break;
4763 }
4764 }
4765
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004766 if (!SuperMethod)
4767 return 0;
4768
4769 // Check whether the superclass method has the same signature.
4770 if (CurMethod->param_size() != SuperMethod->param_size() ||
4771 CurMethod->isVariadic() != SuperMethod->isVariadic())
4772 return 0;
4773
4774 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4775 CurPEnd = CurMethod->param_end(),
4776 SuperP = SuperMethod->param_begin();
4777 CurP != CurPEnd; ++CurP, ++SuperP) {
4778 // Make sure the parameter types are compatible.
4779 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4780 (*SuperP)->getType()))
4781 return 0;
4782
4783 // Make sure we have a parameter name to forward!
4784 if (!(*CurP)->getIdentifier())
4785 return 0;
4786 }
4787
4788 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004789 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004790
4791 // Give this completion a return type.
Douglas Gregor218937c2011-02-01 19:23:04 +00004792 AddResultTypeChunk(S.Context, SuperMethod, Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004793
4794 // If we need the "super" keyword, add it (plus some spacing).
4795 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004796 Builder.AddTypedTextChunk("super");
4797 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004798 }
4799
4800 Selector Sel = CurMethod->getSelector();
4801 if (Sel.isUnarySelector()) {
4802 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004803 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004804 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004805 else
Douglas Gregordae68752011-02-01 22:57:45 +00004806 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004807 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004808 } else {
4809 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4810 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4811 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004812 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004813
4814 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004815 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004816 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004817 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004818 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004819 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004820 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004821 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004822 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004823 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004824 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004825 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004826 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004827 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004828 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004829 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004830 }
4831 }
4832 }
4833
Douglas Gregor218937c2011-02-01 19:23:04 +00004834 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004835 SuperMethod->isInstanceMethod()
4836 ? CXCursor_ObjCInstanceMethodDecl
4837 : CXCursor_ObjCClassMethodDecl));
4838 return SuperMethod;
4839}
4840
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004841void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004842 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004843 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4844 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004845 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004846
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004847 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4848 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004849 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4850 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004851
4852 // If we are in an Objective-C method inside a class that has a superclass,
4853 // add "super" as an option.
4854 if (ObjCMethodDecl *Method = getCurMethodDecl())
4855 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004856 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004857 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004858
4859 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4860 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004861
4862 Results.ExitScope();
4863
4864 if (CodeCompleter->includeMacros())
4865 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004866 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004867 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004868
4869}
4870
Douglas Gregor2725ca82010-04-21 19:57:20 +00004871void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4872 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004873 unsigned NumSelIdents,
4874 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004875 ObjCInterfaceDecl *CDecl = 0;
4876 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4877 // Figure out which interface we're in.
4878 CDecl = CurMethod->getClassInterface();
4879 if (!CDecl)
4880 return;
4881
4882 // Find the superclass of this class.
4883 CDecl = CDecl->getSuperClass();
4884 if (!CDecl)
4885 return;
4886
4887 if (CurMethod->isInstanceMethod()) {
4888 // We are inside an instance method, which means that the message
4889 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004890 // current object.
4891 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004892 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004893 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004894 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004895 }
4896
4897 // Fall through to send to the superclass in CDecl.
4898 } else {
4899 // "super" may be the name of a type or variable. Figure out which
4900 // it is.
4901 IdentifierInfo *Super = &Context.Idents.get("super");
4902 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4903 LookupOrdinaryName);
4904 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4905 // "super" names an interface. Use it.
4906 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004907 if (const ObjCObjectType *Iface
4908 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4909 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004910 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4911 // "super" names an unresolved type; we can't be more specific.
4912 } else {
4913 // Assume that "super" names some kind of value and parse that way.
4914 CXXScopeSpec SS;
4915 UnqualifiedId id;
4916 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004917 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004918 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004919 SelIdents, NumSelIdents,
4920 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004921 }
4922
4923 // Fall through
4924 }
4925
John McCallb3d87482010-08-24 05:47:05 +00004926 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004927 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004928 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004929 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004930 NumSelIdents, AtArgumentExpression,
4931 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004932}
4933
Douglas Gregorb9d77572010-09-21 00:03:25 +00004934/// \brief Given a set of code-completion results for the argument of a message
4935/// send, determine the preferred type (if any) for that argument expression.
4936static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4937 unsigned NumSelIdents) {
4938 typedef CodeCompletionResult Result;
4939 ASTContext &Context = Results.getSema().Context;
4940
4941 QualType PreferredType;
4942 unsigned BestPriority = CCP_Unlikely * 2;
4943 Result *ResultsData = Results.data();
4944 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4945 Result &R = ResultsData[I];
4946 if (R.Kind == Result::RK_Declaration &&
4947 isa<ObjCMethodDecl>(R.Declaration)) {
4948 if (R.Priority <= BestPriority) {
4949 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4950 if (NumSelIdents <= Method->param_size()) {
4951 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4952 ->getType();
4953 if (R.Priority < BestPriority || PreferredType.isNull()) {
4954 BestPriority = R.Priority;
4955 PreferredType = MyPreferredType;
4956 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4957 MyPreferredType)) {
4958 PreferredType = QualType();
4959 }
4960 }
4961 }
4962 }
4963 }
4964
4965 return PreferredType;
4966}
4967
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004968static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4969 ParsedType Receiver,
4970 IdentifierInfo **SelIdents,
4971 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004972 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004973 bool IsSuper,
4974 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004975 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004976 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004977
Douglas Gregor24a069f2009-11-17 17:59:40 +00004978 // If the given name refers to an interface type, retrieve the
4979 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004980 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004981 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004982 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004983 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4984 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004985 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004986
Douglas Gregor36ecb042009-11-17 23:22:23 +00004987 // Add all of the factory methods in this Objective-C class, its protocols,
4988 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004989 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004990
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004991 // If this is a send-to-super, try to add the special "super" send
4992 // completion.
4993 if (IsSuper) {
4994 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004995 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4996 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004997 Results.Ignore(SuperMethod);
4998 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004999
Douglas Gregor265f7492010-08-27 15:29:55 +00005000 // If we're inside an Objective-C method definition, prefer its selector to
5001 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005002 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005003 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005004
Douglas Gregord36adf52010-09-16 16:06:31 +00005005 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005006 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005007 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005008 SemaRef.CurContext, Selectors, AtArgumentExpression,
5009 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005010 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005011 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005012
Douglas Gregor719770d2010-04-06 17:30:22 +00005013 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005014 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005015 if (SemaRef.ExternalSource) {
5016 for (uint32_t I = 0,
5017 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005018 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005019 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5020 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005021 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005022
5023 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005024 }
5025 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005026
5027 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5028 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005029 M != MEnd; ++M) {
5030 for (ObjCMethodList *MethList = &M->second.second;
5031 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005032 MethList = MethList->Next) {
5033 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5034 NumSelIdents))
5035 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005036
Douglas Gregor13438f92010-04-06 16:40:00 +00005037 Result R(MethList->Method, 0);
5038 R.StartParameter = NumSelIdents;
5039 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005040 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005041 }
5042 }
5043 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005044
5045 Results.ExitScope();
5046}
Douglas Gregor13438f92010-04-06 16:40:00 +00005047
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005048void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5049 IdentifierInfo **SelIdents,
5050 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005051 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005052 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005053
5054 QualType T = this->GetTypeFromParser(Receiver);
5055
Douglas Gregor218937c2011-02-01 19:23:04 +00005056 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005057 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005058 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005059
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005060 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5061 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005062
5063 // If we're actually at the argument expression (rather than prior to the
5064 // selector), we're actually performing code completion for an expression.
5065 // Determine whether we have a single, best method. If so, we can
5066 // code-complete the expression using the corresponding parameter type as
5067 // our preferred type, improving completion results.
5068 if (AtArgumentExpression) {
5069 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005070 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005071 if (PreferredType.isNull())
5072 CodeCompleteOrdinaryName(S, PCC_Expression);
5073 else
5074 CodeCompleteExpression(S, PreferredType);
5075 return;
5076 }
5077
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005078 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005079 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005080 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005081}
5082
Douglas Gregord3c68542009-11-19 01:08:35 +00005083void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
5084 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005085 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005086 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005087 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005088 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005089
5090 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005091
Douglas Gregor36ecb042009-11-17 23:22:23 +00005092 // If necessary, apply function/array conversion to the receiver.
5093 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005094 if (RecExpr) {
5095 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5096 if (Conv.isInvalid()) // conversion failed. bail.
5097 return;
5098 RecExpr = Conv.take();
5099 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005100 QualType ReceiverType = RecExpr? RecExpr->getType()
5101 : Super? Context.getObjCObjectPointerType(
5102 Context.getObjCInterfaceType(Super))
5103 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005104
Douglas Gregorda892642010-11-08 21:12:30 +00005105 // If we're messaging an expression with type "id" or "Class", check
5106 // whether we know something special about the receiver that allows
5107 // us to assume a more-specific receiver type.
5108 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5109 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5110 if (ReceiverType->isObjCClassType())
5111 return CodeCompleteObjCClassMessage(S,
5112 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5113 SelIdents, NumSelIdents,
5114 AtArgumentExpression, Super);
5115
5116 ReceiverType = Context.getObjCObjectPointerType(
5117 Context.getObjCInterfaceType(IFace));
5118 }
5119
Douglas Gregor36ecb042009-11-17 23:22:23 +00005120 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005121 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005122 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005123 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005124
Douglas Gregor36ecb042009-11-17 23:22:23 +00005125 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005126
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005127 // If this is a send-to-super, try to add the special "super" send
5128 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005129 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005130 if (ObjCMethodDecl *SuperMethod
5131 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5132 Results))
5133 Results.Ignore(SuperMethod);
5134 }
5135
Douglas Gregor265f7492010-08-27 15:29:55 +00005136 // If we're inside an Objective-C method definition, prefer its selector to
5137 // others.
5138 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5139 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005140
Douglas Gregord36adf52010-09-16 16:06:31 +00005141 // Keep track of the selectors we've already added.
5142 VisitedSelectorSet Selectors;
5143
Douglas Gregorf74a4192009-11-18 00:06:18 +00005144 // Handle messages to Class. This really isn't a message to an instance
5145 // method, so we treat it the same way we would treat a message send to a
5146 // class method.
5147 if (ReceiverType->isObjCClassType() ||
5148 ReceiverType->isObjCQualifiedClassType()) {
5149 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5150 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005151 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005152 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005153 }
5154 }
5155 // Handle messages to a qualified ID ("id<foo>").
5156 else if (const ObjCObjectPointerType *QualID
5157 = ReceiverType->getAsObjCQualifiedIdType()) {
5158 // Search protocols for instance methods.
5159 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5160 E = QualID->qual_end();
5161 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005162 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005163 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005164 }
5165 // Handle messages to a pointer to interface type.
5166 else if (const ObjCObjectPointerType *IFacePtr
5167 = ReceiverType->getAsObjCInterfacePointerType()) {
5168 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005169 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005170 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5171 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005172
5173 // Search protocols for instance methods.
5174 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5175 E = IFacePtr->qual_end();
5176 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005177 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005178 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005179 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005180 // Handle messages to "id".
5181 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005182 // We're messaging "id", so provide all instance methods we know
5183 // about as code-completion results.
5184
5185 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005186 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005187 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005188 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5189 I != N; ++I) {
5190 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005191 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005192 continue;
5193
Sebastian Redldb9d2142010-08-02 23:18:59 +00005194 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005195 }
5196 }
5197
Sebastian Redldb9d2142010-08-02 23:18:59 +00005198 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5199 MEnd = MethodPool.end();
5200 M != MEnd; ++M) {
5201 for (ObjCMethodList *MethList = &M->second.first;
5202 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005203 MethList = MethList->Next) {
5204 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5205 NumSelIdents))
5206 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005207
5208 if (!Selectors.insert(MethList->Method->getSelector()))
5209 continue;
5210
Douglas Gregor13438f92010-04-06 16:40:00 +00005211 Result R(MethList->Method, 0);
5212 R.StartParameter = NumSelIdents;
5213 R.AllParametersAreInformative = false;
5214 Results.MaybeAddResult(R, CurContext);
5215 }
5216 }
5217 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005218 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005219
5220
5221 // If we're actually at the argument expression (rather than prior to the
5222 // selector), we're actually performing code completion for an expression.
5223 // Determine whether we have a single, best method. If so, we can
5224 // code-complete the expression using the corresponding parameter type as
5225 // our preferred type, improving completion results.
5226 if (AtArgumentExpression) {
5227 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5228 NumSelIdents);
5229 if (PreferredType.isNull())
5230 CodeCompleteOrdinaryName(S, PCC_Expression);
5231 else
5232 CodeCompleteExpression(S, PreferredType);
5233 return;
5234 }
5235
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005236 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005237 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005238 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005239}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005240
Douglas Gregorfb629412010-08-23 21:17:50 +00005241void Sema::CodeCompleteObjCForCollection(Scope *S,
5242 DeclGroupPtrTy IterationVar) {
5243 CodeCompleteExpressionData Data;
5244 Data.ObjCCollection = true;
5245
5246 if (IterationVar.getAsOpaquePtr()) {
5247 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5248 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5249 if (*I)
5250 Data.IgnoreDecls.push_back(*I);
5251 }
5252 }
5253
5254 CodeCompleteExpression(S, Data);
5255}
5256
Douglas Gregor458433d2010-08-26 15:07:07 +00005257void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5258 unsigned NumSelIdents) {
5259 // If we have an external source, load the entire class method
5260 // pool from the AST file.
5261 if (ExternalSource) {
5262 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5263 I != N; ++I) {
5264 Selector Sel = ExternalSource->GetExternalSelector(I);
5265 if (Sel.isNull() || MethodPool.count(Sel))
5266 continue;
5267
5268 ReadMethodPool(Sel);
5269 }
5270 }
5271
Douglas Gregor218937c2011-02-01 19:23:04 +00005272 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5273 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005274 Results.EnterNewScope();
5275 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5276 MEnd = MethodPool.end();
5277 M != MEnd; ++M) {
5278
5279 Selector Sel = M->first;
5280 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5281 continue;
5282
Douglas Gregor218937c2011-02-01 19:23:04 +00005283 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005284 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005285 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005286 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005287 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005288 continue;
5289 }
5290
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005291 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005292 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005293 if (I == NumSelIdents) {
5294 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005295 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005296 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005297 Accumulator.clear();
5298 }
5299 }
5300
Benjamin Kramera0651c52011-07-26 16:59:25 +00005301 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005302 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005303 }
Douglas Gregordae68752011-02-01 22:57:45 +00005304 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005305 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005306 }
5307 Results.ExitScope();
5308
5309 HandleCodeCompleteResults(this, CodeCompleter,
5310 CodeCompletionContext::CCC_SelectorName,
5311 Results.data(), Results.size());
5312}
5313
Douglas Gregor55385fe2009-11-18 04:19:12 +00005314/// \brief Add all of the protocol declarations that we find in the given
5315/// (translation unit) context.
5316static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005317 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005318 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005319 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005320
5321 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5322 DEnd = Ctx->decls_end();
5323 D != DEnd; ++D) {
5324 // Record any protocols we find.
5325 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005326 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005327 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005328
5329 // Record any forward-declared protocols we find.
5330 if (ObjCForwardProtocolDecl *Forward
5331 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5332 for (ObjCForwardProtocolDecl::protocol_iterator
5333 P = Forward->protocol_begin(),
5334 PEnd = Forward->protocol_end();
5335 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005336 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005337 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005338 }
5339 }
5340}
5341
5342void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5343 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005344 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5345 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005346
Douglas Gregor70c23352010-12-09 21:44:02 +00005347 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5348 Results.EnterNewScope();
5349
5350 // Tell the result set to ignore all of the protocols we have
5351 // already seen.
5352 // FIXME: This doesn't work when caching code-completion results.
5353 for (unsigned I = 0; I != NumProtocols; ++I)
5354 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5355 Protocols[I].second))
5356 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005357
Douglas Gregor70c23352010-12-09 21:44:02 +00005358 // Add all protocols.
5359 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5360 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005361
Douglas Gregor70c23352010-12-09 21:44:02 +00005362 Results.ExitScope();
5363 }
5364
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005365 HandleCodeCompleteResults(this, CodeCompleter,
5366 CodeCompletionContext::CCC_ObjCProtocolName,
5367 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005368}
5369
5370void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005371 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5372 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005373
Douglas Gregor70c23352010-12-09 21:44:02 +00005374 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5375 Results.EnterNewScope();
5376
5377 // Add all protocols.
5378 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5379 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005380
Douglas Gregor70c23352010-12-09 21:44:02 +00005381 Results.ExitScope();
5382 }
5383
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005384 HandleCodeCompleteResults(this, CodeCompleter,
5385 CodeCompletionContext::CCC_ObjCProtocolName,
5386 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005387}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005388
5389/// \brief Add all of the Objective-C interface declarations that we find in
5390/// the given (translation unit) context.
5391static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5392 bool OnlyForwardDeclarations,
5393 bool OnlyUnimplemented,
5394 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005395 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005396
5397 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5398 DEnd = Ctx->decls_end();
5399 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005400 // Record any interfaces we find.
5401 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5402 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5403 (!OnlyUnimplemented || !Class->getImplementation()))
5404 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005405
5406 // Record any forward-declared interfaces we find.
5407 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
5408 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005409 C != CEnd; ++C)
5410 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
5411 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
5412 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00005413 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005414 }
5415 }
5416}
5417
5418void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005419 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5420 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005421 Results.EnterNewScope();
5422
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005423 if (CodeCompleter->includeGlobals()) {
5424 // Add all classes.
5425 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5426 false, Results);
5427 }
5428
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005429 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005430
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005431 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005432 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005433 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005434}
5435
Douglas Gregorc83c6872010-04-15 22:33:43 +00005436void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5437 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005438 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005439 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005440 Results.EnterNewScope();
5441
5442 // Make sure that we ignore the class we're currently defining.
5443 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005444 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005445 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005446 Results.Ignore(CurClass);
5447
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005448 if (CodeCompleter->includeGlobals()) {
5449 // Add all classes.
5450 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5451 false, Results);
5452 }
5453
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005454 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005455
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005456 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005457 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005458 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005459}
5460
5461void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005462 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5463 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005464 Results.EnterNewScope();
5465
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005466 if (CodeCompleter->includeGlobals()) {
5467 // Add all unimplemented classes.
5468 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5469 true, Results);
5470 }
5471
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005472 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005473
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005474 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005475 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005476 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005477}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005478
5479void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005480 IdentifierInfo *ClassName,
5481 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005482 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005483
Douglas Gregor218937c2011-02-01 19:23:04 +00005484 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005485 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005486
5487 // Ignore any categories we find that have already been implemented by this
5488 // interface.
5489 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5490 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005491 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005492 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5493 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5494 Category = Category->getNextClassCategory())
5495 CategoryNames.insert(Category->getIdentifier());
5496
5497 // Add all of the categories we know about.
5498 Results.EnterNewScope();
5499 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5500 for (DeclContext::decl_iterator D = TU->decls_begin(),
5501 DEnd = TU->decls_end();
5502 D != DEnd; ++D)
5503 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5504 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005505 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005506 Results.ExitScope();
5507
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005508 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005509 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005510 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005511}
5512
5513void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005514 IdentifierInfo *ClassName,
5515 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005516 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005517
5518 // Find the corresponding interface. If we couldn't find the interface, the
5519 // program itself is ill-formed. However, we'll try to be helpful still by
5520 // providing the list of all of the categories we know about.
5521 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005522 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005523 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5524 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005525 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005526
Douglas Gregor218937c2011-02-01 19:23:04 +00005527 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005528 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005529
5530 // Add all of the categories that have have corresponding interface
5531 // declarations in this class and any of its superclasses, except for
5532 // already-implemented categories in the class itself.
5533 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5534 Results.EnterNewScope();
5535 bool IgnoreImplemented = true;
5536 while (Class) {
5537 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5538 Category = Category->getNextClassCategory())
5539 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5540 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005541 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005542
5543 Class = Class->getSuperClass();
5544 IgnoreImplemented = false;
5545 }
5546 Results.ExitScope();
5547
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005548 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005549 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005550 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005551}
Douglas Gregor322328b2009-11-18 22:32:06 +00005552
John McCalld226f652010-08-21 09:40:31 +00005553void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005554 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005555 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5556 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005557
5558 // Figure out where this @synthesize lives.
5559 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005560 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005561 if (!Container ||
5562 (!isa<ObjCImplementationDecl>(Container) &&
5563 !isa<ObjCCategoryImplDecl>(Container)))
5564 return;
5565
5566 // Ignore any properties that have already been implemented.
5567 for (DeclContext::decl_iterator D = Container->decls_begin(),
5568 DEnd = Container->decls_end();
5569 D != DEnd; ++D)
5570 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5571 Results.Ignore(PropertyImpl->getPropertyDecl());
5572
5573 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005574 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005575 Results.EnterNewScope();
5576 if (ObjCImplementationDecl *ClassImpl
5577 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005578 AddObjCProperties(ClassImpl->getClassInterface(), false,
5579 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005580 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005581 else
5582 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005583 false, /*AllowNullaryMethods=*/false, CurContext,
5584 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005585 Results.ExitScope();
5586
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005587 HandleCodeCompleteResults(this, CodeCompleter,
5588 CodeCompletionContext::CCC_Other,
5589 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005590}
5591
5592void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5593 IdentifierInfo *PropertyName,
John McCalld226f652010-08-21 09:40:31 +00005594 Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005595 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005596 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5597 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005598
5599 // Figure out where this @synthesize lives.
5600 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005601 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005602 if (!Container ||
5603 (!isa<ObjCImplementationDecl>(Container) &&
5604 !isa<ObjCCategoryImplDecl>(Container)))
5605 return;
5606
5607 // Figure out which interface we're looking into.
5608 ObjCInterfaceDecl *Class = 0;
5609 if (ObjCImplementationDecl *ClassImpl
5610 = dyn_cast<ObjCImplementationDecl>(Container))
5611 Class = ClassImpl->getClassInterface();
5612 else
5613 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5614 ->getClassInterface();
5615
Douglas Gregore8426052011-04-18 14:40:46 +00005616 // Determine the type of the property we're synthesizing.
5617 QualType PropertyType = Context.getObjCIdType();
5618 if (Class) {
5619 if (ObjCPropertyDecl *Property
5620 = Class->FindPropertyDeclaration(PropertyName)) {
5621 PropertyType
5622 = Property->getType().getNonReferenceType().getUnqualifiedType();
5623
5624 // Give preference to ivars
5625 Results.setPreferredType(PropertyType);
5626 }
5627 }
5628
Douglas Gregor322328b2009-11-18 22:32:06 +00005629 // Add all of the instance variables in this class and its superclasses.
5630 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005631 bool SawSimilarlyNamedIvar = false;
5632 std::string NameWithPrefix;
5633 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005634 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005635 std::string NameWithSuffix = PropertyName->getName().str();
5636 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005637 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005638 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5639 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005640 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5641
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005642 // Determine whether we've seen an ivar with a name similar to the
5643 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005644 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005645 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005646 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005647 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005648
5649 // Reduce the priority of this result by one, to give it a slight
5650 // advantage over other results whose names don't match so closely.
5651 if (Results.size() &&
5652 Results.data()[Results.size() - 1].Kind
5653 == CodeCompletionResult::RK_Declaration &&
5654 Results.data()[Results.size() - 1].Declaration == Ivar)
5655 Results.data()[Results.size() - 1].Priority--;
5656 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005657 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005658 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005659
5660 if (!SawSimilarlyNamedIvar) {
5661 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005662 // an ivar of the appropriate type.
5663 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005664 typedef CodeCompletionResult Result;
5665 CodeCompletionAllocator &Allocator = Results.getAllocator();
5666 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5667
Douglas Gregore8426052011-04-18 14:40:46 +00005668 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
5669 Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005670 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5671 Results.AddResult(Result(Builder.TakeString(), Priority,
5672 CXCursor_ObjCIvarDecl));
5673 }
5674
Douglas Gregor322328b2009-11-18 22:32:06 +00005675 Results.ExitScope();
5676
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005677 HandleCodeCompleteResults(this, CodeCompleter,
5678 CodeCompletionContext::CCC_Other,
5679 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005680}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005681
Douglas Gregor408be5a2010-08-25 01:08:01 +00005682// Mapping from selectors to the methods that implement that selector, along
5683// with the "in original class" flag.
5684typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5685 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005686
5687/// \brief Find all of the methods that reside in the given container
5688/// (and its superclasses, protocols, etc.) that meet the given
5689/// criteria. Insert those methods into the map of known methods,
5690/// indexed by selector so they can be easily found.
5691static void FindImplementableMethods(ASTContext &Context,
5692 ObjCContainerDecl *Container,
5693 bool WantInstanceMethods,
5694 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005695 KnownMethodsMap &KnownMethods,
5696 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005697 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5698 // Recurse into protocols.
5699 const ObjCList<ObjCProtocolDecl> &Protocols
5700 = IFace->getReferencedProtocols();
5701 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005702 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005703 I != E; ++I)
5704 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005705 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005706
Douglas Gregorea766182010-10-18 18:21:28 +00005707 // Add methods from any class extensions and categories.
5708 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5709 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005710 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5711 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005712 KnownMethods, false);
5713
5714 // Visit the superclass.
5715 if (IFace->getSuperClass())
5716 FindImplementableMethods(Context, IFace->getSuperClass(),
5717 WantInstanceMethods, ReturnType,
5718 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005719 }
5720
5721 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5722 // Recurse into protocols.
5723 const ObjCList<ObjCProtocolDecl> &Protocols
5724 = Category->getReferencedProtocols();
5725 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005726 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005727 I != E; ++I)
5728 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005729 KnownMethods, InOriginalClass);
5730
5731 // If this category is the original class, jump to the interface.
5732 if (InOriginalClass && Category->getClassInterface())
5733 FindImplementableMethods(Context, Category->getClassInterface(),
5734 WantInstanceMethods, ReturnType, KnownMethods,
5735 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005736 }
5737
5738 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5739 // Recurse into protocols.
5740 const ObjCList<ObjCProtocolDecl> &Protocols
5741 = Protocol->getReferencedProtocols();
5742 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5743 E = Protocols.end();
5744 I != E; ++I)
5745 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005746 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005747 }
5748
5749 // Add methods in this container. This operation occurs last because
5750 // we want the methods from this container to override any methods
5751 // we've previously seen with the same selector.
5752 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5753 MEnd = Container->meth_end();
5754 M != MEnd; ++M) {
5755 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5756 if (!ReturnType.isNull() &&
5757 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5758 continue;
5759
Douglas Gregor408be5a2010-08-25 01:08:01 +00005760 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005761 }
5762 }
5763}
5764
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005765/// \brief Add the parenthesized return or parameter type chunk to a code
5766/// completion string.
5767static void AddObjCPassingTypeChunk(QualType Type,
5768 ASTContext &Context,
5769 CodeCompletionBuilder &Builder) {
5770 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5771 Builder.AddTextChunk(GetCompletionTypeString(Type, Context,
5772 Builder.getAllocator()));
5773 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5774}
5775
5776/// \brief Determine whether the given class is or inherits from a class by
5777/// the given name.
5778static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005779 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005780 if (!Class)
5781 return false;
5782
5783 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5784 return true;
5785
5786 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5787}
5788
5789/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5790/// Key-Value Observing (KVO).
5791static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5792 bool IsInstanceMethod,
5793 QualType ReturnType,
5794 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005795 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005796 ResultBuilder &Results) {
5797 IdentifierInfo *PropName = Property->getIdentifier();
5798 if (!PropName || PropName->getLength() == 0)
5799 return;
5800
5801
5802 // Builder that will create each code completion.
5803 typedef CodeCompletionResult Result;
5804 CodeCompletionAllocator &Allocator = Results.getAllocator();
5805 CodeCompletionBuilder Builder(Allocator);
5806
5807 // The selector table.
5808 SelectorTable &Selectors = Context.Selectors;
5809
5810 // The property name, copied into the code completion allocation region
5811 // on demand.
5812 struct KeyHolder {
5813 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005814 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005815 const char *CopiedKey;
5816
Chris Lattner5f9e2722011-07-23 10:55:15 +00005817 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005818 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5819
5820 operator const char *() {
5821 if (CopiedKey)
5822 return CopiedKey;
5823
5824 return CopiedKey = Allocator.CopyString(Key);
5825 }
5826 } Key(Allocator, PropName->getName());
5827
5828 // The uppercased name of the property name.
5829 std::string UpperKey = PropName->getName();
5830 if (!UpperKey.empty())
5831 UpperKey[0] = toupper(UpperKey[0]);
5832
5833 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5834 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5835 Property->getType());
5836 bool ReturnTypeMatchesVoid
5837 = ReturnType.isNull() || ReturnType->isVoidType();
5838
5839 // Add the normal accessor -(type)key.
5840 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005841 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005842 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5843 if (ReturnType.isNull())
5844 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5845
5846 Builder.AddTypedTextChunk(Key);
5847 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5848 CXCursor_ObjCInstanceMethodDecl));
5849 }
5850
5851 // If we have an integral or boolean property (or the user has provided
5852 // an integral or boolean return type), add the accessor -(type)isKey.
5853 if (IsInstanceMethod &&
5854 ((!ReturnType.isNull() &&
5855 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5856 (ReturnType.isNull() &&
5857 (Property->getType()->isIntegerType() ||
5858 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005859 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005860 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005861 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005862 if (ReturnType.isNull()) {
5863 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5864 Builder.AddTextChunk("BOOL");
5865 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5866 }
5867
5868 Builder.AddTypedTextChunk(
5869 Allocator.CopyString(SelectorId->getName()));
5870 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5871 CXCursor_ObjCInstanceMethodDecl));
5872 }
5873 }
5874
5875 // Add the normal mutator.
5876 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5877 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005878 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005879 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005880 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005881 if (ReturnType.isNull()) {
5882 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5883 Builder.AddTextChunk("void");
5884 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5885 }
5886
5887 Builder.AddTypedTextChunk(
5888 Allocator.CopyString(SelectorId->getName()));
5889 Builder.AddTypedTextChunk(":");
5890 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5891 Builder.AddTextChunk(Key);
5892 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5893 CXCursor_ObjCInstanceMethodDecl));
5894 }
5895 }
5896
5897 // Indexed and unordered accessors
5898 unsigned IndexedGetterPriority = CCP_CodePattern;
5899 unsigned IndexedSetterPriority = CCP_CodePattern;
5900 unsigned UnorderedGetterPriority = CCP_CodePattern;
5901 unsigned UnorderedSetterPriority = CCP_CodePattern;
5902 if (const ObjCObjectPointerType *ObjCPointer
5903 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5904 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5905 // If this interface type is not provably derived from a known
5906 // collection, penalize the corresponding completions.
5907 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5908 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5909 if (!InheritsFromClassNamed(IFace, "NSArray"))
5910 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5911 }
5912
5913 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5914 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5915 if (!InheritsFromClassNamed(IFace, "NSSet"))
5916 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5917 }
5918 }
5919 } else {
5920 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5921 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5922 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5923 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5924 }
5925
5926 // Add -(NSUInteger)countOf<key>
5927 if (IsInstanceMethod &&
5928 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005929 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005930 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005931 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005932 if (ReturnType.isNull()) {
5933 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5934 Builder.AddTextChunk("NSUInteger");
5935 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5936 }
5937
5938 Builder.AddTypedTextChunk(
5939 Allocator.CopyString(SelectorId->getName()));
5940 Results.AddResult(Result(Builder.TakeString(),
5941 std::min(IndexedGetterPriority,
5942 UnorderedGetterPriority),
5943 CXCursor_ObjCInstanceMethodDecl));
5944 }
5945 }
5946
5947 // Indexed getters
5948 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
5949 if (IsInstanceMethod &&
5950 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005951 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005952 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005953 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005954 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005955 if (ReturnType.isNull()) {
5956 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5957 Builder.AddTextChunk("id");
5958 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5959 }
5960
5961 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5962 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5963 Builder.AddTextChunk("NSUInteger");
5964 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5965 Builder.AddTextChunk("index");
5966 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5967 CXCursor_ObjCInstanceMethodDecl));
5968 }
5969 }
5970
5971 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
5972 if (IsInstanceMethod &&
5973 (ReturnType.isNull() ||
5974 (ReturnType->isObjCObjectPointerType() &&
5975 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
5976 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
5977 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005978 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00005979 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00005980 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005981 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005982 if (ReturnType.isNull()) {
5983 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5984 Builder.AddTextChunk("NSArray *");
5985 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5986 }
5987
5988 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5989 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5990 Builder.AddTextChunk("NSIndexSet *");
5991 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5992 Builder.AddTextChunk("indexes");
5993 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5994 CXCursor_ObjCInstanceMethodDecl));
5995 }
5996 }
5997
5998 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
5999 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006000 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006001 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006002 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006003 &Context.Idents.get("range")
6004 };
6005
Douglas Gregore74c25c2011-05-04 23:50:46 +00006006 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006007 if (ReturnType.isNull()) {
6008 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6009 Builder.AddTextChunk("void");
6010 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6011 }
6012
6013 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6014 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6015 Builder.AddPlaceholderChunk("object-type");
6016 Builder.AddTextChunk(" **");
6017 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6018 Builder.AddTextChunk("buffer");
6019 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6020 Builder.AddTypedTextChunk("range:");
6021 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6022 Builder.AddTextChunk("NSRange");
6023 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6024 Builder.AddTextChunk("inRange");
6025 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6026 CXCursor_ObjCInstanceMethodDecl));
6027 }
6028 }
6029
6030 // Mutable indexed accessors
6031
6032 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6033 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006034 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006035 IdentifierInfo *SelectorIds[2] = {
6036 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006037 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006038 };
6039
Douglas Gregore74c25c2011-05-04 23:50:46 +00006040 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006041 if (ReturnType.isNull()) {
6042 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6043 Builder.AddTextChunk("void");
6044 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6045 }
6046
6047 Builder.AddTypedTextChunk("insertObject:");
6048 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6049 Builder.AddPlaceholderChunk("object-type");
6050 Builder.AddTextChunk(" *");
6051 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6052 Builder.AddTextChunk("object");
6053 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6054 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6055 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6056 Builder.AddPlaceholderChunk("NSUInteger");
6057 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6058 Builder.AddTextChunk("index");
6059 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6060 CXCursor_ObjCInstanceMethodDecl));
6061 }
6062 }
6063
6064 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6065 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006066 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006067 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006068 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006069 &Context.Idents.get("atIndexes")
6070 };
6071
Douglas Gregore74c25c2011-05-04 23:50:46 +00006072 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006073 if (ReturnType.isNull()) {
6074 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6075 Builder.AddTextChunk("void");
6076 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6077 }
6078
6079 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6080 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6081 Builder.AddTextChunk("NSArray *");
6082 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6083 Builder.AddTextChunk("array");
6084 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6085 Builder.AddTypedTextChunk("atIndexes:");
6086 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6087 Builder.AddPlaceholderChunk("NSIndexSet *");
6088 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6089 Builder.AddTextChunk("indexes");
6090 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6091 CXCursor_ObjCInstanceMethodDecl));
6092 }
6093 }
6094
6095 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6096 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006097 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006098 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006099 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006100 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006101 if (ReturnType.isNull()) {
6102 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6103 Builder.AddTextChunk("void");
6104 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6105 }
6106
6107 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6108 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6109 Builder.AddTextChunk("NSUInteger");
6110 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6111 Builder.AddTextChunk("index");
6112 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6113 CXCursor_ObjCInstanceMethodDecl));
6114 }
6115 }
6116
6117 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6118 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006119 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006120 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006121 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006122 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006123 if (ReturnType.isNull()) {
6124 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6125 Builder.AddTextChunk("void");
6126 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6127 }
6128
6129 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6130 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6131 Builder.AddTextChunk("NSIndexSet *");
6132 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6133 Builder.AddTextChunk("indexes");
6134 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6135 CXCursor_ObjCInstanceMethodDecl));
6136 }
6137 }
6138
6139 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6140 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006141 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006142 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006143 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006144 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006145 &Context.Idents.get("withObject")
6146 };
6147
Douglas Gregore74c25c2011-05-04 23:50:46 +00006148 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006149 if (ReturnType.isNull()) {
6150 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6151 Builder.AddTextChunk("void");
6152 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6153 }
6154
6155 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6156 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6157 Builder.AddPlaceholderChunk("NSUInteger");
6158 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6159 Builder.AddTextChunk("index");
6160 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6161 Builder.AddTypedTextChunk("withObject:");
6162 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6163 Builder.AddTextChunk("id");
6164 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6165 Builder.AddTextChunk("object");
6166 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6167 CXCursor_ObjCInstanceMethodDecl));
6168 }
6169 }
6170
6171 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6172 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006173 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006174 = (Twine("replace") + UpperKey + "AtIndexes").str();
6175 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006176 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006177 &Context.Idents.get(SelectorName1),
6178 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006179 };
6180
Douglas Gregore74c25c2011-05-04 23:50:46 +00006181 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006182 if (ReturnType.isNull()) {
6183 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6184 Builder.AddTextChunk("void");
6185 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6186 }
6187
6188 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6189 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6190 Builder.AddPlaceholderChunk("NSIndexSet *");
6191 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6192 Builder.AddTextChunk("indexes");
6193 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6194 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6195 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6196 Builder.AddTextChunk("NSArray *");
6197 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6198 Builder.AddTextChunk("array");
6199 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6200 CXCursor_ObjCInstanceMethodDecl));
6201 }
6202 }
6203
6204 // Unordered getters
6205 // - (NSEnumerator *)enumeratorOfKey
6206 if (IsInstanceMethod &&
6207 (ReturnType.isNull() ||
6208 (ReturnType->isObjCObjectPointerType() &&
6209 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6210 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6211 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006212 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006213 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006214 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006215 if (ReturnType.isNull()) {
6216 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6217 Builder.AddTextChunk("NSEnumerator *");
6218 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6219 }
6220
6221 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6222 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6223 CXCursor_ObjCInstanceMethodDecl));
6224 }
6225 }
6226
6227 // - (type *)memberOfKey:(type *)object
6228 if (IsInstanceMethod &&
6229 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006230 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006231 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006232 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006233 if (ReturnType.isNull()) {
6234 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6235 Builder.AddPlaceholderChunk("object-type");
6236 Builder.AddTextChunk(" *");
6237 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6238 }
6239
6240 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6241 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6242 if (ReturnType.isNull()) {
6243 Builder.AddPlaceholderChunk("object-type");
6244 Builder.AddTextChunk(" *");
6245 } else {
6246 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
6247 Builder.getAllocator()));
6248 }
6249 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6250 Builder.AddTextChunk("object");
6251 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6252 CXCursor_ObjCInstanceMethodDecl));
6253 }
6254 }
6255
6256 // Mutable unordered accessors
6257 // - (void)addKeyObject:(type *)object
6258 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006259 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006260 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006261 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006262 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006263 if (ReturnType.isNull()) {
6264 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6265 Builder.AddTextChunk("void");
6266 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6267 }
6268
6269 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6270 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6271 Builder.AddPlaceholderChunk("object-type");
6272 Builder.AddTextChunk(" *");
6273 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6274 Builder.AddTextChunk("object");
6275 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6276 CXCursor_ObjCInstanceMethodDecl));
6277 }
6278 }
6279
6280 // - (void)addKey:(NSSet *)objects
6281 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006282 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006283 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006284 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006285 if (ReturnType.isNull()) {
6286 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6287 Builder.AddTextChunk("void");
6288 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6289 }
6290
6291 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6292 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6293 Builder.AddTextChunk("NSSet *");
6294 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6295 Builder.AddTextChunk("objects");
6296 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6297 CXCursor_ObjCInstanceMethodDecl));
6298 }
6299 }
6300
6301 // - (void)removeKeyObject:(type *)object
6302 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006303 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006304 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006305 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006306 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006307 if (ReturnType.isNull()) {
6308 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6309 Builder.AddTextChunk("void");
6310 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6311 }
6312
6313 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6314 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6315 Builder.AddPlaceholderChunk("object-type");
6316 Builder.AddTextChunk(" *");
6317 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6318 Builder.AddTextChunk("object");
6319 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6320 CXCursor_ObjCInstanceMethodDecl));
6321 }
6322 }
6323
6324 // - (void)removeKey:(NSSet *)objects
6325 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006326 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006327 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006328 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006329 if (ReturnType.isNull()) {
6330 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6331 Builder.AddTextChunk("void");
6332 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6333 }
6334
6335 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6336 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6337 Builder.AddTextChunk("NSSet *");
6338 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6339 Builder.AddTextChunk("objects");
6340 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6341 CXCursor_ObjCInstanceMethodDecl));
6342 }
6343 }
6344
6345 // - (void)intersectKey:(NSSet *)objects
6346 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006347 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006348 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006349 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006350 if (ReturnType.isNull()) {
6351 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6352 Builder.AddTextChunk("void");
6353 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6354 }
6355
6356 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6357 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6358 Builder.AddTextChunk("NSSet *");
6359 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6360 Builder.AddTextChunk("objects");
6361 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6362 CXCursor_ObjCInstanceMethodDecl));
6363 }
6364 }
6365
6366 // Key-Value Observing
6367 // + (NSSet *)keyPathsForValuesAffectingKey
6368 if (!IsInstanceMethod &&
6369 (ReturnType.isNull() ||
6370 (ReturnType->isObjCObjectPointerType() &&
6371 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6372 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6373 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006374 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006375 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006376 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006377 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006378 if (ReturnType.isNull()) {
6379 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6380 Builder.AddTextChunk("NSSet *");
6381 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6382 }
6383
6384 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6385 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006386 CXCursor_ObjCClassMethodDecl));
6387 }
6388 }
6389
6390 // + (BOOL)automaticallyNotifiesObserversForKey
6391 if (!IsInstanceMethod &&
6392 (ReturnType.isNull() ||
6393 ReturnType->isIntegerType() ||
6394 ReturnType->isBooleanType())) {
6395 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006396 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006397 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6398 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6399 if (ReturnType.isNull()) {
6400 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6401 Builder.AddTextChunk("BOOL");
6402 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6403 }
6404
6405 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6406 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6407 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006408 }
6409 }
6410}
6411
Douglas Gregore8f5a172010-04-07 00:21:17 +00006412void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6413 bool IsInstanceMethod,
John McCallb3d87482010-08-24 05:47:05 +00006414 ParsedType ReturnTy,
John McCalld226f652010-08-21 09:40:31 +00006415 Decl *IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006416 // Determine the return type of the method we're declaring, if
6417 // provided.
6418 QualType ReturnType = GetTypeFromParser(ReturnTy);
6419
Douglas Gregorea766182010-10-18 18:21:28 +00006420 // Determine where we should start searching for methods.
6421 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006422 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006423 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006424 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6425 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006426 IsInImplementation = true;
6427 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006428 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006429 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006430 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006431 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006432 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006433 }
6434
6435 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006436 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006437 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006438 }
6439
Douglas Gregorea766182010-10-18 18:21:28 +00006440 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006441 HandleCodeCompleteResults(this, CodeCompleter,
6442 CodeCompletionContext::CCC_Other,
6443 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006444 return;
6445 }
6446
6447 // Find all of the methods that we could declare/implement here.
6448 KnownMethodsMap KnownMethods;
6449 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006450 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006451
Douglas Gregore8f5a172010-04-07 00:21:17 +00006452 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006453 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006454 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6455 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006456 Results.EnterNewScope();
6457 PrintingPolicy Policy(Context.PrintingPolicy);
6458 Policy.AnonymousTagLocations = false;
John McCallf85e1932011-06-15 23:02:42 +00006459 Policy.SuppressStrongLifetime = true;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006460 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6461 MEnd = KnownMethods.end();
6462 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006463 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006464 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006465
6466 // If the result type was not already provided, add it to the
6467 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006468 if (ReturnType.isNull())
6469 AddObjCPassingTypeChunk(Method->getResultType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006470
6471 Selector Sel = Method->getSelector();
6472
6473 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006474 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006475 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006476
6477 // Add parameters to the pattern.
6478 unsigned I = 0;
6479 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6480 PEnd = Method->param_end();
6481 P != PEnd; (void)++P, ++I) {
6482 // Add the part of the selector name.
6483 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006484 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006485 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006486 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6487 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006488 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006489 } else
6490 break;
6491
6492 // Add the parameter type.
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006493 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006494
6495 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006496 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006497 }
6498
6499 if (Method->isVariadic()) {
6500 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006501 Builder.AddChunk(CodeCompletionString::CK_Comma);
6502 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006503 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006504
Douglas Gregor447107d2010-05-28 00:57:46 +00006505 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006506 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006507 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6508 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6509 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006510 if (!Method->getResultType()->isVoidType()) {
6511 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006512 Builder.AddTextChunk("return");
6513 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6514 Builder.AddPlaceholderChunk("expression");
6515 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006516 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006517 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006518
Douglas Gregor218937c2011-02-01 19:23:04 +00006519 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6520 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006521 }
6522
Douglas Gregor408be5a2010-08-25 01:08:01 +00006523 unsigned Priority = CCP_CodePattern;
6524 if (!M->second.second)
6525 Priority += CCD_InBaseClass;
6526
Douglas Gregor218937c2011-02-01 19:23:04 +00006527 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006528 Method->isInstanceMethod()
6529 ? CXCursor_ObjCInstanceMethodDecl
6530 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006531 }
6532
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006533 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6534 // the properties in this class and its categories.
6535 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006536 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006537 Containers.push_back(SearchDecl);
6538
Douglas Gregore74c25c2011-05-04 23:50:46 +00006539 VisitedSelectorSet KnownSelectors;
6540 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6541 MEnd = KnownMethods.end();
6542 M != MEnd; ++M)
6543 KnownSelectors.insert(M->first);
6544
6545
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006546 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6547 if (!IFace)
6548 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6549 IFace = Category->getClassInterface();
6550
6551 if (IFace) {
6552 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6553 Category = Category->getNextClassCategory())
6554 Containers.push_back(Category);
6555 }
6556
6557 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6558 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6559 PEnd = Containers[I]->prop_end();
6560 P != PEnd; ++P) {
6561 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006562 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006563 }
6564 }
6565 }
6566
Douglas Gregore8f5a172010-04-07 00:21:17 +00006567 Results.ExitScope();
6568
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006569 HandleCodeCompleteResults(this, CodeCompleter,
6570 CodeCompletionContext::CCC_Other,
6571 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006572}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006573
6574void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6575 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006576 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006577 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006578 IdentifierInfo **SelIdents,
6579 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006580 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006581 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006582 if (ExternalSource) {
6583 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6584 I != N; ++I) {
6585 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006586 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006587 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006588
6589 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006590 }
6591 }
6592
6593 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006594 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006595 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6596 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006597
6598 if (ReturnTy)
6599 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006600
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006601 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006602 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6603 MEnd = MethodPool.end();
6604 M != MEnd; ++M) {
6605 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6606 &M->second.second;
6607 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006608 MethList = MethList->Next) {
6609 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6610 NumSelIdents))
6611 continue;
6612
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006613 if (AtParameterName) {
6614 // Suggest parameter names we've seen before.
6615 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6616 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6617 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006618 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006619 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006620 Param->getIdentifier()->getName()));
6621 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006622 }
6623 }
6624
6625 continue;
6626 }
6627
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006628 Result R(MethList->Method, 0);
6629 R.StartParameter = NumSelIdents;
6630 R.AllParametersAreInformative = false;
6631 R.DeclaringEntity = true;
6632 Results.MaybeAddResult(R, CurContext);
6633 }
6634 }
6635
6636 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006637 HandleCodeCompleteResults(this, CodeCompleter,
6638 CodeCompletionContext::CCC_Other,
6639 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006640}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006641
Douglas Gregorf29c5232010-08-24 22:20:20 +00006642void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006643 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006644 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006645 Results.EnterNewScope();
6646
6647 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006648 CodeCompletionBuilder Builder(Results.getAllocator());
6649 Builder.AddTypedTextChunk("if");
6650 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6651 Builder.AddPlaceholderChunk("condition");
6652 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006653
6654 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006655 Builder.AddTypedTextChunk("ifdef");
6656 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6657 Builder.AddPlaceholderChunk("macro");
6658 Results.AddResult(Builder.TakeString());
6659
Douglas Gregorf44e8542010-08-24 19:08:16 +00006660 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006661 Builder.AddTypedTextChunk("ifndef");
6662 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6663 Builder.AddPlaceholderChunk("macro");
6664 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006665
6666 if (InConditional) {
6667 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006668 Builder.AddTypedTextChunk("elif");
6669 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6670 Builder.AddPlaceholderChunk("condition");
6671 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006672
6673 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006674 Builder.AddTypedTextChunk("else");
6675 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006676
6677 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006678 Builder.AddTypedTextChunk("endif");
6679 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006680 }
6681
6682 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006683 Builder.AddTypedTextChunk("include");
6684 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6685 Builder.AddTextChunk("\"");
6686 Builder.AddPlaceholderChunk("header");
6687 Builder.AddTextChunk("\"");
6688 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006689
6690 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006691 Builder.AddTypedTextChunk("include");
6692 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6693 Builder.AddTextChunk("<");
6694 Builder.AddPlaceholderChunk("header");
6695 Builder.AddTextChunk(">");
6696 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006697
6698 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006699 Builder.AddTypedTextChunk("define");
6700 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6701 Builder.AddPlaceholderChunk("macro");
6702 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006703
6704 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006705 Builder.AddTypedTextChunk("define");
6706 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6707 Builder.AddPlaceholderChunk("macro");
6708 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6709 Builder.AddPlaceholderChunk("args");
6710 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6711 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006712
6713 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006714 Builder.AddTypedTextChunk("undef");
6715 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6716 Builder.AddPlaceholderChunk("macro");
6717 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006718
6719 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006720 Builder.AddTypedTextChunk("line");
6721 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6722 Builder.AddPlaceholderChunk("number");
6723 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006724
6725 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006726 Builder.AddTypedTextChunk("line");
6727 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6728 Builder.AddPlaceholderChunk("number");
6729 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6730 Builder.AddTextChunk("\"");
6731 Builder.AddPlaceholderChunk("filename");
6732 Builder.AddTextChunk("\"");
6733 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006734
6735 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006736 Builder.AddTypedTextChunk("error");
6737 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6738 Builder.AddPlaceholderChunk("message");
6739 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006740
6741 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006742 Builder.AddTypedTextChunk("pragma");
6743 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6744 Builder.AddPlaceholderChunk("arguments");
6745 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006746
6747 if (getLangOptions().ObjC1) {
6748 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006749 Builder.AddTypedTextChunk("import");
6750 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6751 Builder.AddTextChunk("\"");
6752 Builder.AddPlaceholderChunk("header");
6753 Builder.AddTextChunk("\"");
6754 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006755
6756 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006757 Builder.AddTypedTextChunk("import");
6758 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6759 Builder.AddTextChunk("<");
6760 Builder.AddPlaceholderChunk("header");
6761 Builder.AddTextChunk(">");
6762 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006763 }
6764
6765 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006766 Builder.AddTypedTextChunk("include_next");
6767 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6768 Builder.AddTextChunk("\"");
6769 Builder.AddPlaceholderChunk("header");
6770 Builder.AddTextChunk("\"");
6771 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006772
6773 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006774 Builder.AddTypedTextChunk("include_next");
6775 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6776 Builder.AddTextChunk("<");
6777 Builder.AddPlaceholderChunk("header");
6778 Builder.AddTextChunk(">");
6779 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006780
6781 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006782 Builder.AddTypedTextChunk("warning");
6783 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6784 Builder.AddPlaceholderChunk("message");
6785 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006786
6787 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6788 // completions for them. And __include_macros is a Clang-internal extension
6789 // that we don't want to encourage anyone to use.
6790
6791 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6792 Results.ExitScope();
6793
Douglas Gregorf44e8542010-08-24 19:08:16 +00006794 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006795 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006796 Results.data(), Results.size());
6797}
6798
6799void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006800 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006801 S->getFnParent()? Sema::PCC_RecoveryInFunction
6802 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006803}
6804
Douglas Gregorf29c5232010-08-24 22:20:20 +00006805void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006806 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006807 IsDefinition? CodeCompletionContext::CCC_MacroName
6808 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006809 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6810 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006811 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006812 Results.EnterNewScope();
6813 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6814 MEnd = PP.macro_end();
6815 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006816 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006817 M->first->getName()));
6818 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006819 }
6820 Results.ExitScope();
6821 } else if (IsDefinition) {
6822 // FIXME: Can we detect when the user just wrote an include guard above?
6823 }
6824
Douglas Gregor52779fb2010-09-23 23:01:17 +00006825 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006826 Results.data(), Results.size());
6827}
6828
Douglas Gregorf29c5232010-08-24 22:20:20 +00006829void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006830 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006831 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006832
6833 if (!CodeCompleter || CodeCompleter->includeMacros())
6834 AddMacroResults(PP, Results);
6835
6836 // defined (<macro>)
6837 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006838 CodeCompletionBuilder Builder(Results.getAllocator());
6839 Builder.AddTypedTextChunk("defined");
6840 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6841 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6842 Builder.AddPlaceholderChunk("macro");
6843 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6844 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006845 Results.ExitScope();
6846
6847 HandleCodeCompleteResults(this, CodeCompleter,
6848 CodeCompletionContext::CCC_PreprocessorExpression,
6849 Results.data(), Results.size());
6850}
6851
6852void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6853 IdentifierInfo *Macro,
6854 MacroInfo *MacroInfo,
6855 unsigned Argument) {
6856 // FIXME: In the future, we could provide "overload" results, much like we
6857 // do for function calls.
6858
6859 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006860 S->getFnParent()? Sema::PCC_RecoveryInFunction
6861 : Sema::PCC_Namespace);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006862}
6863
Douglas Gregor55817af2010-08-25 17:04:25 +00006864void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006865 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006866 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006867 0, 0);
6868}
6869
Douglas Gregordae68752011-02-01 22:57:45 +00006870void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006871 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006872 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006873 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6874 CodeCompletionDeclConsumer Consumer(Builder,
6875 Context.getTranslationUnitDecl());
6876 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6877 Consumer);
6878 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006879
6880 if (!CodeCompleter || CodeCompleter->includeMacros())
6881 AddMacroResults(PP, Builder);
6882
6883 Results.clear();
6884 Results.insert(Results.end(),
6885 Builder.data(), Builder.data() + Builder.size());
6886}