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