blob: df3722f2e812cef00e2638fc449577b9550dbb44 [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();
670
671 return T.getNonReferenceType();
672}
673
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000674void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
675 // If this is an Objective-C method declaration whose selector matches our
676 // preferred selector, give it a priority boost.
677 if (!PreferredSelector.isNull())
678 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
679 if (PreferredSelector == Method->getSelector())
680 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000681
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000682 // If we have a preferred type, adjust the priority for results with exactly-
683 // matching or nearly-matching types.
684 if (!PreferredType.isNull()) {
685 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
686 if (!T.isNull()) {
687 CanQualType TC = SemaRef.Context.getCanonicalType(T);
688 // Check for exactly-matching types (modulo qualifiers).
689 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
690 R.Priority /= CCF_ExactTypeMatch;
691 // Check for nearly-matching types, based on classification of each.
692 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000693 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000694 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
695 R.Priority /= CCF_SimilarTypeMatch;
696 }
697 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000698}
699
Douglas Gregor6f942b22010-09-21 16:06:22 +0000700void ResultBuilder::MaybeAddConstructorResults(Result R) {
701 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
702 !CompletionContext.wantConstructorResults())
703 return;
704
705 ASTContext &Context = SemaRef.Context;
706 NamedDecl *D = R.Declaration;
707 CXXRecordDecl *Record = 0;
708 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
709 Record = ClassTemplate->getTemplatedDecl();
710 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
711 // Skip specializations and partial specializations.
712 if (isa<ClassTemplateSpecializationDecl>(Record))
713 return;
714 } else {
715 // There are no constructors here.
716 return;
717 }
718
719 Record = Record->getDefinition();
720 if (!Record)
721 return;
722
723
724 QualType RecordTy = Context.getTypeDeclType(Record);
725 DeclarationName ConstructorName
726 = Context.DeclarationNames.getCXXConstructorName(
727 Context.getCanonicalType(RecordTy));
728 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
729 Ctors.first != Ctors.second; ++Ctors.first) {
730 R.Declaration = *Ctors.first;
731 R.CursorKind = getCursorKindForDecl(R.Declaration);
732 Results.push_back(R);
733 }
734}
735
Douglas Gregore495b7f2010-01-14 00:20:49 +0000736void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
737 assert(!ShadowMaps.empty() && "Must enter into a results scope");
738
739 if (R.Kind != Result::RK_Declaration) {
740 // For non-declaration results, just add the result.
741 Results.push_back(R);
742 return;
743 }
744
745 // Look through using declarations.
746 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
747 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
748 return;
749 }
750
751 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
752 unsigned IDNS = CanonDecl->getIdentifierNamespace();
753
Douglas Gregor45bcd432010-01-14 03:21:49 +0000754 bool AsNestedNameSpecifier = false;
755 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000756 return;
757
Douglas Gregor6f942b22010-09-21 16:06:22 +0000758 // C++ constructors are never found by name lookup.
759 if (isa<CXXConstructorDecl>(R.Declaration))
760 return;
761
Douglas Gregor86d9a522009-09-21 16:56:56 +0000762 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000763 ShadowMapEntry::iterator I, IEnd;
764 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
765 if (NamePos != SMap.end()) {
766 I = NamePos->second.begin();
767 IEnd = NamePos->second.end();
768 }
769
770 for (; I != IEnd; ++I) {
771 NamedDecl *ND = I->first;
772 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000773 if (ND->getCanonicalDecl() == CanonDecl) {
774 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000775 Results[Index].Declaration = R.Declaration;
776
Douglas Gregor86d9a522009-09-21 16:56:56 +0000777 // We're done.
778 return;
779 }
780 }
781
782 // This is a new declaration in this scope. However, check whether this
783 // declaration name is hidden by a similarly-named declaration in an outer
784 // scope.
785 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
786 --SMEnd;
787 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000788 ShadowMapEntry::iterator I, IEnd;
789 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
790 if (NamePos != SM->end()) {
791 I = NamePos->second.begin();
792 IEnd = NamePos->second.end();
793 }
794 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000795 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000796 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000797 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
798 Decl::IDNS_ObjCProtocol)))
799 continue;
800
801 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000802 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000803 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000804 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000805 continue;
806
807 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000808 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000809 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000810
811 break;
812 }
813 }
814
815 // Make sure that any given declaration only shows up in the result set once.
816 if (!AllDeclsFound.insert(CanonDecl))
817 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000818
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000819 // If the filter is for nested-name-specifiers, then this result starts a
820 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000821 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000822 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000823 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000824 } else
825 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000826
Douglas Gregor0563c262009-09-22 23:15:58 +0000827 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000828 if (R.QualifierIsInformative && !R.Qualifier &&
829 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000830 DeclContext *Ctx = R.Declaration->getDeclContext();
831 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
832 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
833 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
834 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
835 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
836 else
837 R.QualifierIsInformative = false;
838 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000839
Douglas Gregor86d9a522009-09-21 16:56:56 +0000840 // Insert this result into the set of results and into the current shadow
841 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000842 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000843 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000844
845 if (!AsNestedNameSpecifier)
846 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000847}
848
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000849void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000850 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000851 if (R.Kind != Result::RK_Declaration) {
852 // For non-declaration results, just add the result.
853 Results.push_back(R);
854 return;
855 }
856
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000857 // Look through using declarations.
858 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
859 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
860 return;
861 }
862
Douglas Gregor45bcd432010-01-14 03:21:49 +0000863 bool AsNestedNameSpecifier = false;
864 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000865 return;
866
Douglas Gregor6f942b22010-09-21 16:06:22 +0000867 // C++ constructors are never found by name lookup.
868 if (isa<CXXConstructorDecl>(R.Declaration))
869 return;
870
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000871 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
872 return;
873
874 // Make sure that any given declaration only shows up in the result set once.
875 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
876 return;
877
878 // If the filter is for nested-name-specifiers, then this result starts a
879 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000880 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000881 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000882 R.Priority = CCP_NestedNameSpecifier;
883 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000884 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
885 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000886 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000887 R.QualifierIsInformative = true;
888
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000889 // If this result is supposed to have an informative qualifier, add one.
890 if (R.QualifierIsInformative && !R.Qualifier &&
891 !R.StartsNestedNameSpecifier) {
892 DeclContext *Ctx = R.Declaration->getDeclContext();
893 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
894 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
895 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
896 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000897 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000898 else
899 R.QualifierIsInformative = false;
900 }
901
Douglas Gregor12e13132010-05-26 22:00:08 +0000902 // Adjust the priority if this result comes from a base class.
903 if (InBaseClass)
904 R.Priority += CCD_InBaseClass;
905
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000906 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000907
Douglas Gregor3cdee122010-08-26 16:36:48 +0000908 if (HasObjectTypeQualifiers)
909 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
910 if (Method->isInstance()) {
911 Qualifiers MethodQuals
912 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
913 if (ObjectTypeQualifiers == MethodQuals)
914 R.Priority += CCD_ObjectQualifierMatch;
915 else if (ObjectTypeQualifiers - MethodQuals) {
916 // The method cannot be invoked, because doing so would drop
917 // qualifiers.
918 return;
919 }
920 }
921
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000922 // Insert this result into the set of results.
923 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000924
925 if (!AsNestedNameSpecifier)
926 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000927}
928
Douglas Gregora4477812010-01-14 16:01:26 +0000929void ResultBuilder::AddResult(Result R) {
930 assert(R.Kind != Result::RK_Declaration &&
931 "Declaration results need more context");
932 Results.push_back(R);
933}
934
Douglas Gregor86d9a522009-09-21 16:56:56 +0000935/// \brief Enter into a new scope.
936void ResultBuilder::EnterNewScope() {
937 ShadowMaps.push_back(ShadowMap());
938}
939
940/// \brief Exit from the current scope.
941void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000942 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
943 EEnd = ShadowMaps.back().end();
944 E != EEnd;
945 ++E)
946 E->second.Destroy();
947
Douglas Gregor86d9a522009-09-21 16:56:56 +0000948 ShadowMaps.pop_back();
949}
950
Douglas Gregor791215b2009-09-21 20:51:25 +0000951/// \brief Determines whether this given declaration will be found by
952/// ordinary name lookup.
953bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000954 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
955
Douglas Gregor791215b2009-09-21 20:51:25 +0000956 unsigned IDNS = Decl::IDNS_Ordinary;
957 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000958 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000959 else if (SemaRef.getLangOptions().ObjC1) {
960 if (isa<ObjCIvarDecl>(ND))
961 return true;
962 if (isa<ObjCPropertyDecl>(ND) &&
963 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
964 return true;
965 }
966
Douglas Gregor791215b2009-09-21 20:51:25 +0000967 return ND->getIdentifierNamespace() & IDNS;
968}
969
Douglas Gregor01dfea02010-01-10 23:08:15 +0000970/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000971/// ordinary name lookup but is not a type name.
972bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
973 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
974 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
975 return false;
976
977 unsigned IDNS = Decl::IDNS_Ordinary;
978 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000979 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000980 else if (SemaRef.getLangOptions().ObjC1) {
981 if (isa<ObjCIvarDecl>(ND))
982 return true;
983 if (isa<ObjCPropertyDecl>(ND) &&
984 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
985 return true;
986 }
987
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000988 return ND->getIdentifierNamespace() & IDNS;
989}
990
Douglas Gregorf9578432010-07-28 21:50:18 +0000991bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
992 if (!IsOrdinaryNonTypeName(ND))
993 return 0;
994
995 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
996 if (VD->getType()->isIntegralOrEnumerationType())
997 return true;
998
999 return false;
1000}
1001
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001002/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +00001003/// ordinary name lookup.
1004bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001005 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1006
Douglas Gregor01dfea02010-01-10 23:08:15 +00001007 unsigned IDNS = Decl::IDNS_Ordinary;
1008 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +00001009 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001010
1011 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001012 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1013 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001014}
1015
Douglas Gregor86d9a522009-09-21 16:56:56 +00001016/// \brief Determines whether the given declaration is suitable as the
1017/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1018bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1019 // Allow us to find class templates, too.
1020 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1021 ND = ClassTemplate->getTemplatedDecl();
1022
1023 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1024}
1025
1026/// \brief Determines whether the given declaration is an enumeration.
1027bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1028 return isa<EnumDecl>(ND);
1029}
1030
1031/// \brief Determines whether the given declaration is a class or struct.
1032bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1033 // Allow us to find class templates, too.
1034 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1035 ND = ClassTemplate->getTemplatedDecl();
1036
1037 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001038 return RD->getTagKind() == TTK_Class ||
1039 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001040
1041 return false;
1042}
1043
1044/// \brief Determines whether the given declaration is a union.
1045bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1046 // Allow us to find class templates, too.
1047 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1048 ND = ClassTemplate->getTemplatedDecl();
1049
1050 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001051 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001052
1053 return false;
1054}
1055
1056/// \brief Determines whether the given declaration is a namespace.
1057bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1058 return isa<NamespaceDecl>(ND);
1059}
1060
1061/// \brief Determines whether the given declaration is a namespace or
1062/// namespace alias.
1063bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1064 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1065}
1066
Douglas Gregor76282942009-12-11 17:31:05 +00001067/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001068bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001069 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1070 ND = Using->getTargetDecl();
1071
1072 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001073}
1074
Douglas Gregor76282942009-12-11 17:31:05 +00001075/// \brief Determines which members of a class should be visible via
1076/// "." or "->". Only value declarations, nested name specifiers, and
1077/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001078bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001079 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1080 ND = Using->getTargetDecl();
1081
Douglas Gregorce821962009-12-11 18:14:22 +00001082 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1083 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001084}
1085
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001086static bool isObjCReceiverType(ASTContext &C, QualType T) {
1087 T = C.getCanonicalType(T);
1088 switch (T->getTypeClass()) {
1089 case Type::ObjCObject:
1090 case Type::ObjCInterface:
1091 case Type::ObjCObjectPointer:
1092 return true;
1093
1094 case Type::Builtin:
1095 switch (cast<BuiltinType>(T)->getKind()) {
1096 case BuiltinType::ObjCId:
1097 case BuiltinType::ObjCClass:
1098 case BuiltinType::ObjCSel:
1099 return true;
1100
1101 default:
1102 break;
1103 }
1104 return false;
1105
1106 default:
1107 break;
1108 }
1109
1110 if (!C.getLangOptions().CPlusPlus)
1111 return false;
1112
1113 // FIXME: We could perform more analysis here to determine whether a
1114 // particular class type has any conversions to Objective-C types. For now,
1115 // just accept all class types.
1116 return T->isDependentType() || T->isRecordType();
1117}
1118
1119bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1120 QualType T = getDeclUsageType(SemaRef.Context, ND);
1121 if (T.isNull())
1122 return false;
1123
1124 T = SemaRef.Context.getBaseElementType(T);
1125 return isObjCReceiverType(SemaRef.Context, T);
1126}
1127
Douglas Gregorfb629412010-08-23 21:17:50 +00001128bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1129 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1130 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1131 return false;
1132
1133 QualType T = getDeclUsageType(SemaRef.Context, ND);
1134 if (T.isNull())
1135 return false;
1136
1137 T = SemaRef.Context.getBaseElementType(T);
1138 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1139 T->isObjCIdType() ||
1140 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1141}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001142
Douglas Gregor52779fb2010-09-23 23:01:17 +00001143bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1144 return false;
1145}
1146
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001147/// \rief Determines whether the given declaration is an Objective-C
1148/// instance variable.
1149bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1150 return isa<ObjCIvarDecl>(ND);
1151}
1152
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001153namespace {
1154 /// \brief Visible declaration consumer that adds a code-completion result
1155 /// for each visible declaration.
1156 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1157 ResultBuilder &Results;
1158 DeclContext *CurContext;
1159
1160 public:
1161 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1162 : Results(Results), CurContext(CurContext) { }
1163
Douglas Gregor0cc84042010-01-14 15:47:35 +00001164 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1165 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001166 }
1167 };
1168}
1169
Douglas Gregor86d9a522009-09-21 16:56:56 +00001170/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001171static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001172 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001173 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001174 Results.AddResult(Result("short", CCP_Type));
1175 Results.AddResult(Result("long", CCP_Type));
1176 Results.AddResult(Result("signed", CCP_Type));
1177 Results.AddResult(Result("unsigned", CCP_Type));
1178 Results.AddResult(Result("void", CCP_Type));
1179 Results.AddResult(Result("char", CCP_Type));
1180 Results.AddResult(Result("int", CCP_Type));
1181 Results.AddResult(Result("float", CCP_Type));
1182 Results.AddResult(Result("double", CCP_Type));
1183 Results.AddResult(Result("enum", CCP_Type));
1184 Results.AddResult(Result("struct", CCP_Type));
1185 Results.AddResult(Result("union", CCP_Type));
1186 Results.AddResult(Result("const", CCP_Type));
1187 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001188
Douglas Gregor86d9a522009-09-21 16:56:56 +00001189 if (LangOpts.C99) {
1190 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001191 Results.AddResult(Result("_Complex", CCP_Type));
1192 Results.AddResult(Result("_Imaginary", CCP_Type));
1193 Results.AddResult(Result("_Bool", CCP_Type));
1194 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001195 }
1196
Douglas Gregor218937c2011-02-01 19:23:04 +00001197 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001198 if (LangOpts.CPlusPlus) {
1199 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001200 Results.AddResult(Result("bool", CCP_Type +
1201 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001202 Results.AddResult(Result("class", CCP_Type));
1203 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001204
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001205 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001206 Builder.AddTypedTextChunk("typename");
1207 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1208 Builder.AddPlaceholderChunk("qualifier");
1209 Builder.AddTextChunk("::");
1210 Builder.AddPlaceholderChunk("name");
1211 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001212
Douglas Gregor86d9a522009-09-21 16:56:56 +00001213 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001214 Results.AddResult(Result("auto", CCP_Type));
1215 Results.AddResult(Result("char16_t", CCP_Type));
1216 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001217
Douglas Gregor218937c2011-02-01 19:23:04 +00001218 Builder.AddTypedTextChunk("decltype");
1219 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1220 Builder.AddPlaceholderChunk("expression");
1221 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1222 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001223 }
1224 }
1225
1226 // GNU extensions
1227 if (LangOpts.GNUMode) {
1228 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001229 // Results.AddResult(Result("_Decimal32"));
1230 // Results.AddResult(Result("_Decimal64"));
1231 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001232
Douglas Gregor218937c2011-02-01 19:23:04 +00001233 Builder.AddTypedTextChunk("typeof");
1234 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1235 Builder.AddPlaceholderChunk("expression");
1236 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001237
Douglas Gregor218937c2011-02-01 19:23:04 +00001238 Builder.AddTypedTextChunk("typeof");
1239 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1240 Builder.AddPlaceholderChunk("type");
1241 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1242 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001243 }
1244}
1245
John McCallf312b1e2010-08-26 23:41:50 +00001246static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001247 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001248 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001249 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001250 // Note: we don't suggest either "auto" or "register", because both
1251 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1252 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001253 Results.AddResult(Result("extern"));
1254 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001255}
1256
John McCallf312b1e2010-08-26 23:41:50 +00001257static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001258 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001259 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001260 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001261 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001262 case Sema::PCC_Class:
1263 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001264 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001265 Results.AddResult(Result("explicit"));
1266 Results.AddResult(Result("friend"));
1267 Results.AddResult(Result("mutable"));
1268 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001269 }
1270 // Fall through
1271
John McCallf312b1e2010-08-26 23:41:50 +00001272 case Sema::PCC_ObjCInterface:
1273 case Sema::PCC_ObjCImplementation:
1274 case Sema::PCC_Namespace:
1275 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001276 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001277 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001278 break;
1279
John McCallf312b1e2010-08-26 23:41:50 +00001280 case Sema::PCC_ObjCInstanceVariableList:
1281 case Sema::PCC_Expression:
1282 case Sema::PCC_Statement:
1283 case Sema::PCC_ForInit:
1284 case Sema::PCC_Condition:
1285 case Sema::PCC_RecoveryInFunction:
1286 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001287 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001288 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001289 break;
1290 }
1291}
1292
Douglas Gregorbca403c2010-01-13 23:51:12 +00001293static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1294static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1295static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001296 ResultBuilder &Results,
1297 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001298static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001299 ResultBuilder &Results,
1300 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001301static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001302 ResultBuilder &Results,
1303 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001304static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001305
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001306static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001307 CodeCompletionBuilder Builder(Results.getAllocator());
1308 Builder.AddTypedTextChunk("typedef");
1309 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1310 Builder.AddPlaceholderChunk("type");
1311 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1312 Builder.AddPlaceholderChunk("name");
1313 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001314}
1315
John McCallf312b1e2010-08-26 23:41:50 +00001316static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001317 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001318 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001319 case Sema::PCC_Namespace:
1320 case Sema::PCC_Class:
1321 case Sema::PCC_ObjCInstanceVariableList:
1322 case Sema::PCC_Template:
1323 case Sema::PCC_MemberTemplate:
1324 case Sema::PCC_Statement:
1325 case Sema::PCC_RecoveryInFunction:
1326 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001327 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001328 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001329 return true;
1330
John McCallf312b1e2010-08-26 23:41:50 +00001331 case Sema::PCC_Expression:
1332 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001333 return LangOpts.CPlusPlus;
1334
1335 case Sema::PCC_ObjCInterface:
1336 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001337 return false;
1338
John McCallf312b1e2010-08-26 23:41:50 +00001339 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001340 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001341 }
1342
1343 return false;
1344}
1345
Douglas Gregor01dfea02010-01-10 23:08:15 +00001346/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001347static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001348 Scope *S,
1349 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001350 ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001351 CodeCompletionBuilder Builder(Results.getAllocator());
1352
John McCall0a2c5e22010-08-25 06:19:51 +00001353 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001354 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001355 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001356 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001357 if (Results.includeCodePatterns()) {
1358 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001359 Builder.AddTypedTextChunk("namespace");
1360 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1361 Builder.AddPlaceholderChunk("identifier");
1362 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1363 Builder.AddPlaceholderChunk("declarations");
1364 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1365 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1366 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001367 }
1368
Douglas Gregor01dfea02010-01-10 23:08:15 +00001369 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001370 Builder.AddTypedTextChunk("namespace");
1371 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1372 Builder.AddPlaceholderChunk("name");
1373 Builder.AddChunk(CodeCompletionString::CK_Equal);
1374 Builder.AddPlaceholderChunk("namespace");
1375 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001376
1377 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001378 Builder.AddTypedTextChunk("using");
1379 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1380 Builder.AddTextChunk("namespace");
1381 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1382 Builder.AddPlaceholderChunk("identifier");
1383 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001384
1385 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001386 Builder.AddTypedTextChunk("asm");
1387 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1388 Builder.AddPlaceholderChunk("string-literal");
1389 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1390 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001391
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001392 if (Results.includeCodePatterns()) {
1393 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001394 Builder.AddTypedTextChunk("template");
1395 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1396 Builder.AddPlaceholderChunk("declaration");
1397 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001398 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001399 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001400
1401 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001402 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001403
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001404 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001405 // Fall through
1406
John McCallf312b1e2010-08-26 23:41:50 +00001407 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001408 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001409 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001410 Builder.AddTypedTextChunk("using");
1411 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1412 Builder.AddPlaceholderChunk("qualifier");
1413 Builder.AddTextChunk("::");
1414 Builder.AddPlaceholderChunk("name");
1415 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001416
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001417 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001418 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001419 Builder.AddTypedTextChunk("using");
1420 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1421 Builder.AddTextChunk("typename");
1422 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1423 Builder.AddPlaceholderChunk("qualifier");
1424 Builder.AddTextChunk("::");
1425 Builder.AddPlaceholderChunk("name");
1426 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001427 }
1428
John McCallf312b1e2010-08-26 23:41:50 +00001429 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001430 AddTypedefResult(Results);
1431
Douglas Gregor01dfea02010-01-10 23:08:15 +00001432 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001433 Builder.AddTypedTextChunk("public");
1434 Builder.AddChunk(CodeCompletionString::CK_Colon);
1435 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001436
1437 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001438 Builder.AddTypedTextChunk("protected");
1439 Builder.AddChunk(CodeCompletionString::CK_Colon);
1440 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001441
1442 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001443 Builder.AddTypedTextChunk("private");
1444 Builder.AddChunk(CodeCompletionString::CK_Colon);
1445 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001446 }
1447 }
1448 // Fall through
1449
John McCallf312b1e2010-08-26 23:41:50 +00001450 case Sema::PCC_Template:
1451 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001452 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001453 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001454 Builder.AddTypedTextChunk("template");
1455 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1456 Builder.AddPlaceholderChunk("parameters");
1457 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1458 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001459 }
1460
Douglas Gregorbca403c2010-01-13 23:51:12 +00001461 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1462 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001463 break;
1464
John McCallf312b1e2010-08-26 23:41:50 +00001465 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001466 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1467 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1468 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001469 break;
1470
John McCallf312b1e2010-08-26 23:41:50 +00001471 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001472 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1473 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1474 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001475 break;
1476
John McCallf312b1e2010-08-26 23:41:50 +00001477 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001478 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001479 break;
1480
John McCallf312b1e2010-08-26 23:41:50 +00001481 case Sema::PCC_RecoveryInFunction:
1482 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001483 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001484
Douglas Gregord8e8a582010-05-25 21:41:55 +00001485 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001486 Builder.AddTypedTextChunk("try");
1487 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1488 Builder.AddPlaceholderChunk("statements");
1489 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1490 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1491 Builder.AddTextChunk("catch");
1492 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1493 Builder.AddPlaceholderChunk("declaration");
1494 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1495 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1496 Builder.AddPlaceholderChunk("statements");
1497 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1498 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1499 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001500 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001501 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001502 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001503
Douglas Gregord8e8a582010-05-25 21:41:55 +00001504 if (Results.includeCodePatterns()) {
1505 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001506 Builder.AddTypedTextChunk("if");
1507 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001508 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001509 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001510 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001511 Builder.AddPlaceholderChunk("expression");
1512 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1513 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1514 Builder.AddPlaceholderChunk("statements");
1515 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1516 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1517 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001518
Douglas Gregord8e8a582010-05-25 21:41:55 +00001519 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001520 Builder.AddTypedTextChunk("switch");
1521 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001522 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001523 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001524 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001525 Builder.AddPlaceholderChunk("expression");
1526 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1527 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1528 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1529 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1530 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001531 }
1532
Douglas Gregor01dfea02010-01-10 23:08:15 +00001533 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001534 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001535 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001536 Builder.AddTypedTextChunk("case");
1537 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1538 Builder.AddPlaceholderChunk("expression");
1539 Builder.AddChunk(CodeCompletionString::CK_Colon);
1540 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001541
1542 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001543 Builder.AddTypedTextChunk("default");
1544 Builder.AddChunk(CodeCompletionString::CK_Colon);
1545 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001546 }
1547
Douglas Gregord8e8a582010-05-25 21:41:55 +00001548 if (Results.includeCodePatterns()) {
1549 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001550 Builder.AddTypedTextChunk("while");
1551 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001552 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001553 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001554 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001555 Builder.AddPlaceholderChunk("expression");
1556 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1557 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1558 Builder.AddPlaceholderChunk("statements");
1559 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1560 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1561 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001562
1563 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001564 Builder.AddTypedTextChunk("do");
1565 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1566 Builder.AddPlaceholderChunk("statements");
1567 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1568 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1569 Builder.AddTextChunk("while");
1570 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1571 Builder.AddPlaceholderChunk("expression");
1572 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1573 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001574
Douglas Gregord8e8a582010-05-25 21:41:55 +00001575 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001576 Builder.AddTypedTextChunk("for");
1577 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001578 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001579 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001580 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001581 Builder.AddPlaceholderChunk("init-expression");
1582 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1583 Builder.AddPlaceholderChunk("condition");
1584 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1585 Builder.AddPlaceholderChunk("inc-expression");
1586 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1587 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1588 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1589 Builder.AddPlaceholderChunk("statements");
1590 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1591 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1592 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001593 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001594
1595 if (S->getContinueParent()) {
1596 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001597 Builder.AddTypedTextChunk("continue");
1598 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001599 }
1600
1601 if (S->getBreakParent()) {
1602 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001603 Builder.AddTypedTextChunk("break");
1604 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001605 }
1606
1607 // "return expression ;" or "return ;", depending on whether we
1608 // know the function is void or not.
1609 bool isVoid = false;
1610 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1611 isVoid = Function->getResultType()->isVoidType();
1612 else if (ObjCMethodDecl *Method
1613 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1614 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001615 else if (SemaRef.getCurBlock() &&
1616 !SemaRef.getCurBlock()->ReturnType.isNull())
1617 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001618 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001619 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001620 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1621 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001622 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001623 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001624
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001625 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001626 Builder.AddTypedTextChunk("goto");
1627 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1628 Builder.AddPlaceholderChunk("label");
1629 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001630
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001631 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001632 Builder.AddTypedTextChunk("using");
1633 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1634 Builder.AddTextChunk("namespace");
1635 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1636 Builder.AddPlaceholderChunk("identifier");
1637 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001638 }
1639
1640 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001641 case Sema::PCC_ForInit:
1642 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001643 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001644 // Fall through: conditions and statements can have expressions.
1645
Douglas Gregor02688102010-09-14 23:59:36 +00001646 case Sema::PCC_ParenthesizedExpression:
John McCallf312b1e2010-08-26 23:41:50 +00001647 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001648 if (SemaRef.getLangOptions().CPlusPlus) {
1649 // 'this', if we're in a non-static member function.
1650 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1651 if (!Method->isStatic())
Douglas Gregora4477812010-01-14 16:01:26 +00001652 Results.AddResult(Result("this"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001653
1654 // true, false
Douglas Gregora4477812010-01-14 16:01:26 +00001655 Results.AddResult(Result("true"));
1656 Results.AddResult(Result("false"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001657
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001658 // dynamic_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001659 Builder.AddTypedTextChunk("dynamic_cast");
1660 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1661 Builder.AddPlaceholderChunk("type");
1662 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1663 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1664 Builder.AddPlaceholderChunk("expression");
1665 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1666 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001667
1668 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001669 Builder.AddTypedTextChunk("static_cast");
1670 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1671 Builder.AddPlaceholderChunk("type");
1672 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1673 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1674 Builder.AddPlaceholderChunk("expression");
1675 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1676 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001677
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001678 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001679 Builder.AddTypedTextChunk("reinterpret_cast");
1680 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1681 Builder.AddPlaceholderChunk("type");
1682 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1683 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1684 Builder.AddPlaceholderChunk("expression");
1685 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1686 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001687
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001688 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001689 Builder.AddTypedTextChunk("const_cast");
1690 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1691 Builder.AddPlaceholderChunk("type");
1692 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1693 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1694 Builder.AddPlaceholderChunk("expression");
1695 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1696 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001697
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001698 // typeid ( expression-or-type )
Douglas Gregor218937c2011-02-01 19:23:04 +00001699 Builder.AddTypedTextChunk("typeid");
1700 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1701 Builder.AddPlaceholderChunk("expression-or-type");
1702 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1703 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001704
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001705 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001706 Builder.AddTypedTextChunk("new");
1707 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1708 Builder.AddPlaceholderChunk("type");
1709 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1710 Builder.AddPlaceholderChunk("expressions");
1711 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1712 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001713
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001714 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001715 Builder.AddTypedTextChunk("new");
1716 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1717 Builder.AddPlaceholderChunk("type");
1718 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1719 Builder.AddPlaceholderChunk("size");
1720 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1721 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1722 Builder.AddPlaceholderChunk("expressions");
1723 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1724 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001725
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001726 // delete expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001727 Builder.AddTypedTextChunk("delete");
1728 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1729 Builder.AddPlaceholderChunk("expression");
1730 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001731
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001732 // delete [] expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001733 Builder.AddTypedTextChunk("delete");
1734 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1735 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1736 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1737 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1738 Builder.AddPlaceholderChunk("expression");
1739 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001740
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001741 // throw expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001742 Builder.AddTypedTextChunk("throw");
1743 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1744 Builder.AddPlaceholderChunk("expression");
1745 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor12e13132010-05-26 22:00:08 +00001746
1747 // FIXME: Rethrow?
Douglas Gregor01dfea02010-01-10 23:08:15 +00001748 }
1749
1750 if (SemaRef.getLangOptions().ObjC1) {
1751 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001752 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1753 // The interface can be NULL.
1754 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1755 if (ID->getSuperClass())
1756 Results.AddResult(Result("super"));
1757 }
1758
Douglas Gregorbca403c2010-01-13 23:51:12 +00001759 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001760 }
1761
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001762 // sizeof expression
Douglas Gregor218937c2011-02-01 19:23:04 +00001763 Builder.AddTypedTextChunk("sizeof");
1764 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1765 Builder.AddPlaceholderChunk("expression-or-type");
1766 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1767 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001768 break;
1769 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001770
John McCallf312b1e2010-08-26 23:41:50 +00001771 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001772 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001773 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001774 }
1775
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001776 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1777 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001778
John McCallf312b1e2010-08-26 23:41:50 +00001779 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001780 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001781}
1782
Douglas Gregora63f6de2011-02-01 21:15:40 +00001783/// \brief Retrieve the string representation of the given type as a string
1784/// that has the appropriate lifetime for code completion.
1785///
1786/// This routine provides a fast path where we provide constant strings for
1787/// common type names.
Benjamin Kramerda57f3e2011-03-26 12:38:21 +00001788static const char *GetCompletionTypeString(QualType T,
1789 ASTContext &Context,
1790 CodeCompletionAllocator &Allocator) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00001791 PrintingPolicy Policy(Context.PrintingPolicy);
1792 Policy.AnonymousTagLocations = false;
1793
1794 if (!T.getLocalQualifiers()) {
1795 // Built-in type names are constant strings.
1796 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1797 return BT->getName(Context.getLangOptions());
1798
1799 // Anonymous tag types are constant strings.
1800 if (const TagType *TagT = dyn_cast<TagType>(T))
1801 if (TagDecl *Tag = TagT->getDecl())
1802 if (!Tag->getIdentifier() && !Tag->getTypedefForAnonDecl()) {
1803 switch (Tag->getTagKind()) {
1804 case TTK_Struct: return "struct <anonymous>";
1805 case TTK_Class: return "class <anonymous>";
1806 case TTK_Union: return "union <anonymous>";
1807 case TTK_Enum: return "enum <anonymous>";
1808 }
1809 }
1810 }
1811
1812 // Slow path: format the type as a string.
1813 std::string Result;
1814 T.getAsStringInternal(Result, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00001815 return Allocator.CopyString(Result);
Douglas Gregora63f6de2011-02-01 21:15:40 +00001816}
1817
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001818/// \brief If the given declaration has an associated type, add it as a result
1819/// type chunk.
1820static void AddResultTypeChunk(ASTContext &Context,
1821 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001822 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001823 if (!ND)
1824 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001825
1826 // Skip constructors and conversion functions, which have their return types
1827 // built into their names.
1828 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1829 return;
1830
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001831 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001832 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001833 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1834 T = Function->getResultType();
1835 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1836 T = Method->getResultType();
1837 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1838 T = FunTmpl->getTemplatedDecl()->getResultType();
1839 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1840 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1841 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1842 /* Do nothing: ignore unresolved using declarations*/
1843 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1844 T = Value->getType();
1845 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1846 T = Property->getType();
1847
1848 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1849 return;
1850
Douglas Gregora63f6de2011-02-01 21:15:40 +00001851 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context,
1852 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001853}
1854
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001855static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001856 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001857 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1858 if (Sentinel->getSentinel() == 0) {
1859 if (Context.getLangOptions().ObjC1 &&
1860 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001861 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001862 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001863 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001864 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001865 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001866 }
1867}
1868
Douglas Gregor83482d12010-08-24 16:15:59 +00001869static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregoraba48082010-08-29 19:47:46 +00001870 ParmVarDecl *Param,
1871 bool SuppressName = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00001872 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1873 if (Param->getType()->isDependentType() ||
1874 !Param->getType()->isBlockPointerType()) {
1875 // The argument for a dependent or non-block parameter is a placeholder
1876 // containing that parameter's type.
1877 std::string Result;
1878
Douglas Gregoraba48082010-08-29 19:47:46 +00001879 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001880 Result = Param->getIdentifier()->getName();
1881
1882 Param->getType().getAsStringInternal(Result,
1883 Context.PrintingPolicy);
1884
1885 if (ObjCMethodParam) {
1886 Result = "(" + Result;
1887 Result += ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00001888 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00001889 Result += Param->getIdentifier()->getName();
1890 }
1891 return Result;
1892 }
1893
1894 // The argument for a block pointer parameter is a block literal with
1895 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00001896 FunctionTypeLoc *Block = 0;
1897 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00001898 TypeLoc TL;
1899 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1900 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1901 while (true) {
1902 // Look through typedefs.
1903 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1904 if (TypeSourceInfo *InnerTSInfo
1905 = TypedefTL->getTypedefDecl()->getTypeSourceInfo()) {
1906 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1907 continue;
1908 }
1909 }
1910
1911 // Look through qualified types
1912 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1913 TL = QualifiedTL->getUnqualifiedLoc();
1914 continue;
1915 }
1916
1917 // Try to get the function prototype behind the block pointer type,
1918 // then we're done.
1919 if (BlockPointerTypeLoc *BlockPtr
1920 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00001921 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00001922 Block = dyn_cast<FunctionTypeLoc>(&TL);
1923 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00001924 }
1925 break;
1926 }
1927 }
1928
1929 if (!Block) {
1930 // We were unable to find a FunctionProtoTypeLoc with parameter names
1931 // for the block; just use the parameter type as a placeholder.
1932 std::string Result;
1933 Param->getType().getUnqualifiedType().
1934 getAsStringInternal(Result, Context.PrintingPolicy);
1935
1936 if (ObjCMethodParam) {
1937 Result = "(" + Result;
1938 Result += ")";
1939 if (Param->getIdentifier())
1940 Result += Param->getIdentifier()->getName();
1941 }
1942
1943 return Result;
1944 }
1945
1946 // We have the function prototype behind the block pointer type, as it was
1947 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00001948 std::string Result;
1949 QualType ResultType = Block->getTypePtr()->getResultType();
1950 if (!ResultType->isVoidType())
1951 ResultType.getAsStringInternal(Result, Context.PrintingPolicy);
1952
1953 Result = '^' + Result;
Douglas Gregor830072c2011-02-15 22:37:09 +00001954 if (!BlockProto || Block->getNumArgs() == 0) {
1955 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00001956 Result += "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00001957 else
1958 Result += "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00001959 } else {
1960 Result += "(";
1961 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
1962 if (I)
1963 Result += ", ";
1964 Result += FormatFunctionParameter(Context, Block->getArg(I));
1965
Douglas Gregor830072c2011-02-15 22:37:09 +00001966 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregor38276252010-09-08 22:47:51 +00001967 Result += ", ...";
1968 }
1969 Result += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00001970 }
Douglas Gregor38276252010-09-08 22:47:51 +00001971
Douglas Gregorc2760bc2010-10-02 23:49:58 +00001972 if (Param->getIdentifier())
1973 Result += Param->getIdentifier()->getName();
1974
Douglas Gregor83482d12010-08-24 16:15:59 +00001975 return Result;
1976}
1977
Douglas Gregor86d9a522009-09-21 16:56:56 +00001978/// \brief Add function parameter chunks to the given code completion string.
1979static void AddFunctionParameterChunks(ASTContext &Context,
1980 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00001981 CodeCompletionBuilder &Result,
1982 unsigned Start = 0,
1983 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001984 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00001985 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001986
Douglas Gregor218937c2011-02-01 19:23:04 +00001987 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00001988 ParmVarDecl *Param = Function->getParamDecl(P);
1989
Douglas Gregor218937c2011-02-01 19:23:04 +00001990 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00001991 // When we see an optional default argument, put that argument and
1992 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00001993 CodeCompletionBuilder Opt(Result.getAllocator());
1994 if (!FirstParameter)
1995 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
1996 AddFunctionParameterChunks(Context, Function, Opt, P, true);
1997 Result.AddOptionalChunk(Opt.TakeString());
1998 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001999 }
2000
Douglas Gregor218937c2011-02-01 19:23:04 +00002001 if (FirstParameter)
2002 FirstParameter = false;
2003 else
2004 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2005
2006 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002007
2008 // Format the placeholder string.
Douglas Gregor83482d12010-08-24 16:15:59 +00002009 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
2010
Douglas Gregore17794f2010-08-31 05:13:43 +00002011 if (Function->isVariadic() && P == N - 1)
2012 PlaceholderStr += ", ...";
2013
Douglas Gregor86d9a522009-09-21 16:56:56 +00002014 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002015 Result.AddPlaceholderChunk(
2016 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002017 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002018
2019 if (const FunctionProtoType *Proto
2020 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002021 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002022 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002023 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002024
Douglas Gregor218937c2011-02-01 19:23:04 +00002025 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002026 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002027}
2028
2029/// \brief Add template parameter chunks to the given code completion string.
2030static void AddTemplateParameterChunks(ASTContext &Context,
2031 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002032 CodeCompletionBuilder &Result,
2033 unsigned MaxParameters = 0,
2034 unsigned Start = 0,
2035 bool InDefaultArg = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002036 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002037 bool FirstParameter = true;
2038
2039 TemplateParameterList *Params = Template->getTemplateParameters();
2040 TemplateParameterList::iterator PEnd = Params->end();
2041 if (MaxParameters)
2042 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002043 for (TemplateParameterList::iterator P = Params->begin() + Start;
2044 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002045 bool HasDefaultArg = false;
2046 std::string PlaceholderStr;
2047 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2048 if (TTP->wasDeclaredWithTypename())
2049 PlaceholderStr = "typename";
2050 else
2051 PlaceholderStr = "class";
2052
2053 if (TTP->getIdentifier()) {
2054 PlaceholderStr += ' ';
2055 PlaceholderStr += TTP->getIdentifier()->getName();
2056 }
2057
2058 HasDefaultArg = TTP->hasDefaultArgument();
2059 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002060 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002061 if (NTTP->getIdentifier())
2062 PlaceholderStr = NTTP->getIdentifier()->getName();
2063 NTTP->getType().getAsStringInternal(PlaceholderStr,
2064 Context.PrintingPolicy);
2065 HasDefaultArg = NTTP->hasDefaultArgument();
2066 } else {
2067 assert(isa<TemplateTemplateParmDecl>(*P));
2068 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2069
2070 // Since putting the template argument list into the placeholder would
2071 // be very, very long, we just use an abbreviation.
2072 PlaceholderStr = "template<...> class";
2073 if (TTP->getIdentifier()) {
2074 PlaceholderStr += ' ';
2075 PlaceholderStr += TTP->getIdentifier()->getName();
2076 }
2077
2078 HasDefaultArg = TTP->hasDefaultArgument();
2079 }
2080
Douglas Gregor218937c2011-02-01 19:23:04 +00002081 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002082 // When we see an optional default argument, put that argument and
2083 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002084 CodeCompletionBuilder Opt(Result.getAllocator());
2085 if (!FirstParameter)
2086 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2087 AddTemplateParameterChunks(Context, Template, Opt, MaxParameters,
2088 P - Params->begin(), true);
2089 Result.AddOptionalChunk(Opt.TakeString());
2090 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002091 }
2092
Douglas Gregor218937c2011-02-01 19:23:04 +00002093 InDefaultArg = false;
2094
Douglas Gregor86d9a522009-09-21 16:56:56 +00002095 if (FirstParameter)
2096 FirstParameter = false;
2097 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002098 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002099
2100 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002101 Result.AddPlaceholderChunk(
2102 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002103 }
2104}
2105
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002106/// \brief Add a qualifier to the given code-completion string, if the
2107/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002108static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002109AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002110 NestedNameSpecifier *Qualifier,
2111 bool QualifierIsInformative,
2112 ASTContext &Context) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002113 if (!Qualifier)
2114 return;
2115
2116 std::string PrintedNNS;
2117 {
2118 llvm::raw_string_ostream OS(PrintedNNS);
2119 Qualifier->print(OS, Context.PrintingPolicy);
2120 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002121 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002122 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002123 else
Douglas Gregordae68752011-02-01 22:57:45 +00002124 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002125}
2126
Douglas Gregor218937c2011-02-01 19:23:04 +00002127static void
2128AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2129 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002130 const FunctionProtoType *Proto
2131 = Function->getType()->getAs<FunctionProtoType>();
2132 if (!Proto || !Proto->getTypeQuals())
2133 return;
2134
Douglas Gregora63f6de2011-02-01 21:15:40 +00002135 // FIXME: Add ref-qualifier!
2136
2137 // Handle single qualifiers without copying
2138 if (Proto->getTypeQuals() == Qualifiers::Const) {
2139 Result.AddInformativeChunk(" const");
2140 return;
2141 }
2142
2143 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2144 Result.AddInformativeChunk(" volatile");
2145 return;
2146 }
2147
2148 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2149 Result.AddInformativeChunk(" restrict");
2150 return;
2151 }
2152
2153 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002154 std::string QualsStr;
2155 if (Proto->getTypeQuals() & Qualifiers::Const)
2156 QualsStr += " const";
2157 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2158 QualsStr += " volatile";
2159 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2160 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002161 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002162}
2163
Douglas Gregor6f942b22010-09-21 16:06:22 +00002164/// \brief Add the name of the given declaration
2165static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00002166 CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002167 typedef CodeCompletionString::Chunk Chunk;
2168
2169 DeclarationName Name = ND->getDeclName();
2170 if (!Name)
2171 return;
2172
2173 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002174 case DeclarationName::CXXOperatorName: {
2175 const char *OperatorName = 0;
2176 switch (Name.getCXXOverloadedOperator()) {
2177 case OO_None:
2178 case OO_Conditional:
2179 case NUM_OVERLOADED_OPERATORS:
2180 OperatorName = "operator";
2181 break;
2182
2183#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2184 case OO_##Name: OperatorName = "operator" Spelling; break;
2185#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2186#include "clang/Basic/OperatorKinds.def"
2187
2188 case OO_New: OperatorName = "operator new"; break;
2189 case OO_Delete: OperatorName = "operator delete"; break;
2190 case OO_Array_New: OperatorName = "operator new[]"; break;
2191 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2192 case OO_Call: OperatorName = "operator()"; break;
2193 case OO_Subscript: OperatorName = "operator[]"; break;
2194 }
2195 Result.AddTypedTextChunk(OperatorName);
2196 break;
2197 }
2198
Douglas Gregor6f942b22010-09-21 16:06:22 +00002199 case DeclarationName::Identifier:
2200 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002201 case DeclarationName::CXXDestructorName:
2202 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002203 Result.AddTypedTextChunk(
2204 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002205 break;
2206
2207 case DeclarationName::CXXUsingDirective:
2208 case DeclarationName::ObjCZeroArgSelector:
2209 case DeclarationName::ObjCOneArgSelector:
2210 case DeclarationName::ObjCMultiArgSelector:
2211 break;
2212
2213 case DeclarationName::CXXConstructorName: {
2214 CXXRecordDecl *Record = 0;
2215 QualType Ty = Name.getCXXNameType();
2216 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2217 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2218 else if (const InjectedClassNameType *InjectedTy
2219 = Ty->getAs<InjectedClassNameType>())
2220 Record = InjectedTy->getDecl();
2221 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002222 Result.AddTypedTextChunk(
2223 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002224 break;
2225 }
2226
Douglas Gregordae68752011-02-01 22:57:45 +00002227 Result.AddTypedTextChunk(
2228 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002229 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002230 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002231 AddTemplateParameterChunks(Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002232 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002233 }
2234 break;
2235 }
2236 }
2237}
2238
Douglas Gregor86d9a522009-09-21 16:56:56 +00002239/// \brief If possible, create a new code completion string for the given
2240/// result.
2241///
2242/// \returns Either a new, heap-allocated code completion string describing
2243/// how to use this result, or NULL to indicate that the string or name of the
2244/// result is all that is needed.
2245CodeCompletionString *
John McCall0a2c5e22010-08-25 06:19:51 +00002246CodeCompletionResult::CreateCodeCompletionString(Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002247 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002248 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002249 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002250
Douglas Gregor218937c2011-02-01 19:23:04 +00002251 if (Kind == RK_Pattern) {
2252 Pattern->Priority = Priority;
2253 Pattern->Availability = Availability;
2254 return Pattern;
2255 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002256
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002257 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002258 Result.AddTypedTextChunk(Keyword);
2259 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002260 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002261
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002262 if (Kind == RK_Macro) {
2263 MacroInfo *MI = S.PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002264 assert(MI && "Not a macro?");
2265
Douglas Gregordae68752011-02-01 22:57:45 +00002266 Result.AddTypedTextChunk(
2267 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002268
2269 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002270 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002271
2272 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002273 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002274 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2275 A != AEnd; ++A) {
2276 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002277 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002278
2279 if (!MI->isVariadic() || A != AEnd - 1) {
2280 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002281 Result.AddPlaceholderChunk(
2282 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002283 continue;
2284 }
2285
2286 // Variadic argument; cope with the different between GNU and C99
2287 // variadic macros, providing a single placeholder for the rest of the
2288 // arguments.
2289 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002290 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002291 else {
2292 std::string Arg = (*A)->getName();
2293 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002294 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002295 }
2296 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002297 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2298 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002299 }
2300
Douglas Gregord8e8a582010-05-25 21:41:55 +00002301 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002302 NamedDecl *ND = Declaration;
2303
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002304 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002305 Result.AddTypedTextChunk(
2306 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002307 Result.AddTextChunk("::");
2308 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002309 }
2310
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002311 AddResultTypeChunk(S.Context, ND, Result);
2312
Douglas Gregor86d9a522009-09-21 16:56:56 +00002313 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002314 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2315 S.Context);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002316 AddTypedNameChunk(S.Context, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002317 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002318 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002319 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002320 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002321 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002322 }
2323
2324 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002325 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2326 S.Context);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002327 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Douglas Gregor6f942b22010-09-21 16:06:22 +00002328 AddTypedNameChunk(S.Context, Function, Result);
2329
Douglas Gregor86d9a522009-09-21 16:56:56 +00002330 // Figure out which template parameters are deduced (or have default
2331 // arguments).
2332 llvm::SmallVector<bool, 16> Deduced;
2333 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2334 unsigned LastDeducibleArgument;
2335 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2336 --LastDeducibleArgument) {
2337 if (!Deduced[LastDeducibleArgument - 1]) {
2338 // C++0x: Figure out if the template argument has a default. If so,
2339 // the user doesn't need to type this argument.
2340 // FIXME: We need to abstract template parameters better!
2341 bool HasDefaultArg = false;
2342 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002343 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002344 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2345 HasDefaultArg = TTP->hasDefaultArgument();
2346 else if (NonTypeTemplateParmDecl *NTTP
2347 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2348 HasDefaultArg = NTTP->hasDefaultArgument();
2349 else {
2350 assert(isa<TemplateTemplateParmDecl>(Param));
2351 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002352 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002353 }
2354
2355 if (!HasDefaultArg)
2356 break;
2357 }
2358 }
2359
2360 if (LastDeducibleArgument) {
2361 // Some of the function template arguments cannot be deduced from a
2362 // function call, so we introduce an explicit template argument list
2363 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002364 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002365 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2366 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002367 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002368 }
2369
2370 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002371 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002372 AddFunctionParameterChunks(S.Context, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002373 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002374 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002375 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002376 }
2377
2378 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002379 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2380 S.Context);
Douglas Gregordae68752011-02-01 22:57:45 +00002381 Result.AddTypedTextChunk(
2382 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002383 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002384 AddTemplateParameterChunks(S.Context, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002385 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2386 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002387 }
2388
Douglas Gregor9630eb62009-11-17 16:44:22 +00002389 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002390 Selector Sel = Method->getSelector();
2391 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002392 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002393 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002394 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002395 }
2396
Douglas Gregor813d8342011-02-18 22:29:55 +00002397 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002398 SelName += ':';
2399 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002400 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002401 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002402 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002403
2404 // If there is only one parameter, and we're past it, add an empty
2405 // typed-text chunk since there is nothing to type.
2406 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002407 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002408 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002409 unsigned Idx = 0;
2410 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2411 PEnd = Method->param_end();
2412 P != PEnd; (void)++P, ++Idx) {
2413 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002414 std::string Keyword;
2415 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002416 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002417 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2418 Keyword += II->getName().str();
2419 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002420 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002421 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002422 else
Douglas Gregordae68752011-02-01 22:57:45 +00002423 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002424 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002425
2426 // If we're before the starting parameter, skip the placeholder.
2427 if (Idx < StartParameter)
2428 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002429
2430 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002431
2432 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Douglas Gregoraba48082010-08-29 19:47:46 +00002433 Arg = FormatFunctionParameter(S.Context, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002434 else {
2435 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
2436 Arg = "(" + Arg + ")";
2437 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002438 if (DeclaringEntity || AllParametersAreInformative)
2439 Arg += II->getName().str();
Douglas Gregor83482d12010-08-24 16:15:59 +00002440 }
2441
Douglas Gregore17794f2010-08-31 05:13:43 +00002442 if (Method->isVariadic() && (P + 1) == PEnd)
2443 Arg += ", ...";
2444
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002445 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002446 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002447 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002448 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002449 else
Douglas Gregordae68752011-02-01 22:57:45 +00002450 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002451 }
2452
Douglas Gregor2a17af02009-12-23 00:21:46 +00002453 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002454 if (Method->param_size() == 0) {
2455 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002456 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002457 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002458 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002459 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002460 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002461 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002462
2463 MaybeAddSentinel(S.Context, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002464 }
2465
Douglas Gregor218937c2011-02-01 19:23:04 +00002466 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002467 }
2468
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002469 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002470 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2471 S.Context);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002472
Douglas Gregordae68752011-02-01 22:57:45 +00002473 Result.AddTypedTextChunk(
2474 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002475 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002476}
2477
Douglas Gregor86d802e2009-09-23 00:34:09 +00002478CodeCompletionString *
2479CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2480 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002481 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002482 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002483 typedef CodeCompletionString::Chunk Chunk;
2484
Douglas Gregor218937c2011-02-01 19:23:04 +00002485 // FIXME: Set priority, availability appropriately.
2486 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002487 FunctionDecl *FDecl = getFunction();
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002488 AddResultTypeChunk(S.Context, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002489 const FunctionProtoType *Proto
2490 = dyn_cast<FunctionProtoType>(getFunctionType());
2491 if (!FDecl && !Proto) {
2492 // Function without a prototype. Just give the return type and a
2493 // highlighted ellipsis.
2494 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002495 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
2496 S.Context,
2497 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002498 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2499 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2500 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2501 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002502 }
2503
2504 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002505 Result.AddTextChunk(
2506 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002507 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002508 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002509 Result.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002510 Proto->getResultType().getAsString(S.Context.PrintingPolicy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002511
Douglas Gregor218937c2011-02-01 19:23:04 +00002512 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002513 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2514 for (unsigned I = 0; I != NumParams; ++I) {
2515 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002516 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002517
2518 std::string ArgString;
2519 QualType ArgType;
2520
2521 if (FDecl) {
2522 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2523 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2524 } else {
2525 ArgType = Proto->getArgType(I);
2526 }
2527
2528 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2529
2530 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002531 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002532 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002533 else
Douglas Gregordae68752011-02-01 22:57:45 +00002534 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002535 }
2536
2537 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002538 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002539 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002540 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002541 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002542 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002543 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002544 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002545
Douglas Gregor218937c2011-02-01 19:23:04 +00002546 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002547}
2548
Douglas Gregor1827e102010-08-16 16:18:59 +00002549unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002550 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002551 bool PreferredTypeIsPointer) {
2552 unsigned Priority = CCP_Macro;
2553
Douglas Gregorb05496d2010-09-20 21:11:48 +00002554 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2555 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2556 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002557 Priority = CCP_Constant;
2558 if (PreferredTypeIsPointer)
2559 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002560 }
2561 // Treat "YES", "NO", "true", and "false" as constants.
2562 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2563 MacroName.equals("true") || MacroName.equals("false"))
2564 Priority = CCP_Constant;
2565 // Treat "bool" as a type.
2566 else if (MacroName.equals("bool"))
2567 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2568
Douglas Gregor1827e102010-08-16 16:18:59 +00002569
2570 return Priority;
2571}
2572
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002573CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2574 if (!D)
2575 return CXCursor_UnexposedDecl;
2576
2577 switch (D->getKind()) {
2578 case Decl::Enum: return CXCursor_EnumDecl;
2579 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2580 case Decl::Field: return CXCursor_FieldDecl;
2581 case Decl::Function:
2582 return CXCursor_FunctionDecl;
2583 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2584 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2585 case Decl::ObjCClass:
2586 // FIXME
2587 return CXCursor_UnexposedDecl;
2588 case Decl::ObjCForwardProtocol:
2589 // FIXME
2590 return CXCursor_UnexposedDecl;
2591 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2592 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2593 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2594 case Decl::ObjCMethod:
2595 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2596 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2597 case Decl::CXXMethod: return CXCursor_CXXMethod;
2598 case Decl::CXXConstructor: return CXCursor_Constructor;
2599 case Decl::CXXDestructor: return CXCursor_Destructor;
2600 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2601 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2602 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2603 case Decl::ParmVar: return CXCursor_ParmDecl;
2604 case Decl::Typedef: return CXCursor_TypedefDecl;
2605 case Decl::Var: return CXCursor_VarDecl;
2606 case Decl::Namespace: return CXCursor_Namespace;
2607 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2608 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2609 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2610 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2611 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2612 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2613 case Decl::ClassTemplatePartialSpecialization:
2614 return CXCursor_ClassTemplatePartialSpecialization;
2615 case Decl::UsingDirective: return CXCursor_UsingDirective;
2616
2617 case Decl::Using:
2618 case Decl::UnresolvedUsingValue:
2619 case Decl::UnresolvedUsingTypename:
2620 return CXCursor_UsingDeclaration;
2621
2622 default:
2623 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2624 switch (TD->getTagKind()) {
2625 case TTK_Struct: return CXCursor_StructDecl;
2626 case TTK_Class: return CXCursor_ClassDecl;
2627 case TTK_Union: return CXCursor_UnionDecl;
2628 case TTK_Enum: return CXCursor_EnumDecl;
2629 }
2630 }
2631 }
2632
2633 return CXCursor_UnexposedDecl;
2634}
2635
Douglas Gregor590c7d52010-07-08 20:55:51 +00002636static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2637 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002638 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002639
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002640 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002641
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002642 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2643 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002644 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002645 Results.AddResult(Result(M->first,
2646 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002647 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002648 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002649 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002650
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002651 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002652
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002653}
2654
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002655static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2656 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002657 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002658
2659 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002660
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002661 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2662 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2663 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2664 Results.AddResult(Result("__func__", CCP_Constant));
2665 Results.ExitScope();
2666}
2667
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002668static void HandleCodeCompleteResults(Sema *S,
2669 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002670 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002671 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002672 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002673 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002674 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002675}
2676
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002677static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2678 Sema::ParserCompletionContext PCC) {
2679 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002680 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002681 return CodeCompletionContext::CCC_TopLevel;
2682
John McCallf312b1e2010-08-26 23:41:50 +00002683 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002684 return CodeCompletionContext::CCC_ClassStructUnion;
2685
John McCallf312b1e2010-08-26 23:41:50 +00002686 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002687 return CodeCompletionContext::CCC_ObjCInterface;
2688
John McCallf312b1e2010-08-26 23:41:50 +00002689 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002690 return CodeCompletionContext::CCC_ObjCImplementation;
2691
John McCallf312b1e2010-08-26 23:41:50 +00002692 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002693 return CodeCompletionContext::CCC_ObjCIvarList;
2694
John McCallf312b1e2010-08-26 23:41:50 +00002695 case Sema::PCC_Template:
2696 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002697 if (S.CurContext->isFileContext())
2698 return CodeCompletionContext::CCC_TopLevel;
2699 else if (S.CurContext->isRecord())
2700 return CodeCompletionContext::CCC_ClassStructUnion;
2701 else
2702 return CodeCompletionContext::CCC_Other;
2703
John McCallf312b1e2010-08-26 23:41:50 +00002704 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002705 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002706
John McCallf312b1e2010-08-26 23:41:50 +00002707 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002708 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2709 S.getLangOptions().ObjC1)
2710 return CodeCompletionContext::CCC_ParenthesizedExpression;
2711 else
2712 return CodeCompletionContext::CCC_Expression;
2713
2714 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002715 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002716 return CodeCompletionContext::CCC_Expression;
2717
John McCallf312b1e2010-08-26 23:41:50 +00002718 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002719 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002720
John McCallf312b1e2010-08-26 23:41:50 +00002721 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002722 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002723
2724 case Sema::PCC_ParenthesizedExpression:
2725 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002726
2727 case Sema::PCC_LocalDeclarationSpecifiers:
2728 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002729 }
2730
2731 return CodeCompletionContext::CCC_Other;
2732}
2733
Douglas Gregorf6961522010-08-27 21:18:54 +00002734/// \brief If we're in a C++ virtual member function, add completion results
2735/// that invoke the functions we override, since it's common to invoke the
2736/// overridden function as well as adding new functionality.
2737///
2738/// \param S The semantic analysis object for which we are generating results.
2739///
2740/// \param InContext This context in which the nested-name-specifier preceding
2741/// the code-completion point
2742static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2743 ResultBuilder &Results) {
2744 // Look through blocks.
2745 DeclContext *CurContext = S.CurContext;
2746 while (isa<BlockDecl>(CurContext))
2747 CurContext = CurContext->getParent();
2748
2749
2750 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2751 if (!Method || !Method->isVirtual())
2752 return;
2753
2754 // We need to have names for all of the parameters, if we're going to
2755 // generate a forwarding call.
2756 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2757 PEnd = Method->param_end();
2758 P != PEnd;
2759 ++P) {
2760 if (!(*P)->getDeclName())
2761 return;
2762 }
2763
2764 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2765 MEnd = Method->end_overridden_methods();
2766 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002767 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002768 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2769 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2770 continue;
2771
2772 // If we need a nested-name-specifier, add one now.
2773 if (!InContext) {
2774 NestedNameSpecifier *NNS
2775 = getRequiredQualification(S.Context, CurContext,
2776 Overridden->getDeclContext());
2777 if (NNS) {
2778 std::string Str;
2779 llvm::raw_string_ostream OS(Str);
2780 NNS->print(OS, S.Context.PrintingPolicy);
Douglas Gregordae68752011-02-01 22:57:45 +00002781 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002782 }
2783 } else if (!InContext->Equals(Overridden->getDeclContext()))
2784 continue;
2785
Douglas Gregordae68752011-02-01 22:57:45 +00002786 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002787 Overridden->getNameAsString()));
2788 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00002789 bool FirstParam = true;
2790 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2791 PEnd = Method->param_end();
2792 P != PEnd; ++P) {
2793 if (FirstParam)
2794 FirstParam = false;
2795 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002796 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00002797
Douglas Gregordae68752011-02-01 22:57:45 +00002798 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00002799 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00002800 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002801 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2802 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00002803 CCP_SuperCompletion,
2804 CXCursor_CXXMethod));
2805 Results.Ignore(Overridden);
2806 }
2807}
2808
Douglas Gregor01dfea02010-01-10 23:08:15 +00002809void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002810 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00002811 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002812 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002813 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00002814 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002815
Douglas Gregor01dfea02010-01-10 23:08:15 +00002816 // Determine how to filter results, e.g., so that the names of
2817 // values (functions, enumerators, function templates, etc.) are
2818 // only allowed where we can have an expression.
2819 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002820 case PCC_Namespace:
2821 case PCC_Class:
2822 case PCC_ObjCInterface:
2823 case PCC_ObjCImplementation:
2824 case PCC_ObjCInstanceVariableList:
2825 case PCC_Template:
2826 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00002827 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002828 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00002829 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2830 break;
2831
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002832 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00002833 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00002834 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002835 case PCC_ForInit:
2836 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00002837 if (WantTypesInContext(CompletionContext, getLangOptions()))
2838 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2839 else
2840 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00002841
2842 if (getLangOptions().CPlusPlus)
2843 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00002844 break;
Douglas Gregordc845342010-05-25 05:58:43 +00002845
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002846 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00002847 // Unfiltered
2848 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00002849 }
2850
Douglas Gregor3cdee122010-08-26 16:36:48 +00002851 // If we are in a C++ non-static member function, check the qualifiers on
2852 // the member function to filter/prioritize the results list.
2853 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2854 if (CurMethod->isInstance())
2855 Results.setObjectTypeQualifiers(
2856 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2857
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00002858 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00002859 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2860 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002861
Douglas Gregorbca403c2010-01-13 23:51:12 +00002862 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00002863 Results.ExitScope();
2864
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002865 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00002866 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00002867 case PCC_Expression:
2868 case PCC_Statement:
2869 case PCC_RecoveryInFunction:
2870 if (S->getFnParent())
2871 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2872 break;
2873
2874 case PCC_Namespace:
2875 case PCC_Class:
2876 case PCC_ObjCInterface:
2877 case PCC_ObjCImplementation:
2878 case PCC_ObjCInstanceVariableList:
2879 case PCC_Template:
2880 case PCC_MemberTemplate:
2881 case PCC_ForInit:
2882 case PCC_Condition:
2883 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002884 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00002885 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002886 }
2887
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002888 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00002889 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002890
Douglas Gregorcee9ff12010-09-20 22:39:41 +00002891 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002892 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00002893}
2894
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002895static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
2896 ParsedType Receiver,
2897 IdentifierInfo **SelIdents,
2898 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00002899 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002900 bool IsSuper,
2901 ResultBuilder &Results);
2902
2903void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
2904 bool AllowNonIdentifiers,
2905 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00002906 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002907 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00002908 AllowNestedNameSpecifiers
2909 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2910 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002911 Results.EnterNewScope();
2912
2913 // Type qualifiers can come after names.
2914 Results.AddResult(Result("const"));
2915 Results.AddResult(Result("volatile"));
2916 if (getLangOptions().C99)
2917 Results.AddResult(Result("restrict"));
2918
2919 if (getLangOptions().CPlusPlus) {
2920 if (AllowNonIdentifiers) {
2921 Results.AddResult(Result("operator"));
2922 }
2923
2924 // Add nested-name-specifiers.
2925 if (AllowNestedNameSpecifiers) {
2926 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00002927 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002928 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2929 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
2930 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00002931 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002932 }
2933 }
2934 Results.ExitScope();
2935
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002936 // If we're in a context where we might have an expression (rather than a
2937 // declaration), and what we've seen so far is an Objective-C type that could
2938 // be a receiver of a class message, this may be a class message send with
2939 // the initial opening bracket '[' missing. Add appropriate completions.
2940 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
2941 DS.getTypeSpecType() == DeclSpec::TST_typename &&
2942 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
2943 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
2944 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
2945 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
2946 DS.getTypeQualifiers() == 0 &&
2947 S &&
2948 (S->getFlags() & Scope::DeclScope) != 0 &&
2949 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
2950 Scope::FunctionPrototypeScope |
2951 Scope::AtCatchScope)) == 0) {
2952 ParsedType T = DS.getRepAsType();
2953 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00002954 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00002955 }
2956
Douglas Gregor4497dd42010-08-24 04:59:56 +00002957 // Note that we intentionally suppress macro results here, since we do not
2958 // encourage using macros to produce the names of entities.
2959
Douglas Gregor52779fb2010-09-23 23:01:17 +00002960 HandleCodeCompleteResults(this, CodeCompleter,
2961 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002962 Results.data(), Results.size());
2963}
2964
Douglas Gregorfb629412010-08-23 21:17:50 +00002965struct Sema::CodeCompleteExpressionData {
2966 CodeCompleteExpressionData(QualType PreferredType = QualType())
2967 : PreferredType(PreferredType), IntegralConstantExpression(false),
2968 ObjCCollection(false) { }
2969
2970 QualType PreferredType;
2971 bool IntegralConstantExpression;
2972 bool ObjCCollection;
2973 llvm::SmallVector<Decl *, 4> IgnoreDecls;
2974};
2975
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002976/// \brief Perform code-completion in an expression context when we know what
2977/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00002978///
2979/// \param IntegralConstantExpression Only permit integral constant
2980/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00002981void Sema::CodeCompleteExpression(Scope *S,
2982 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00002983 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00002984 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
2985 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00002986 if (Data.ObjCCollection)
2987 Results.setFilter(&ResultBuilder::IsObjCCollection);
2988 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00002989 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002990 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00002991 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2992 else
2993 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00002994
2995 if (!Data.PreferredType.isNull())
2996 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
2997
2998 // Ignore any declarations that we were told that we don't care about.
2999 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3000 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003001
3002 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003003 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3004 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003005
3006 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003007 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003008 Results.ExitScope();
3009
Douglas Gregor590c7d52010-07-08 20:55:51 +00003010 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003011 if (!Data.PreferredType.isNull())
3012 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3013 || Data.PreferredType->isMemberPointerType()
3014 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003015
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003016 if (S->getFnParent() &&
3017 !Data.ObjCCollection &&
3018 !Data.IntegralConstantExpression)
3019 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3020
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003021 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003022 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003023 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003024 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3025 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003026 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003027}
3028
Douglas Gregorac5fd842010-09-18 01:28:11 +00003029void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3030 if (E.isInvalid())
3031 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3032 else if (getLangOptions().ObjC1)
3033 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003034}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003035
Douglas Gregor73449212010-12-09 23:01:55 +00003036/// \brief The set of properties that have already been added, referenced by
3037/// property name.
3038typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3039
Douglas Gregor95ac6552009-11-18 01:29:26 +00003040static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003041 bool AllowCategories,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003042 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003043 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003044 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003045 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003046
3047 // Add properties in this container.
3048 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3049 PEnd = Container->prop_end();
3050 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003051 ++P) {
3052 if (AddedProperties.insert(P->getIdentifier()))
3053 Results.MaybeAddResult(Result(*P, 0), CurContext);
3054 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003055
3056 // Add properties in referenced protocols.
3057 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3058 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3059 PEnd = Protocol->protocol_end();
3060 P != PEnd; ++P)
Douglas Gregor73449212010-12-09 23:01:55 +00003061 AddObjCProperties(*P, AllowCategories, CurContext, AddedProperties,
3062 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003063 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003064 if (AllowCategories) {
3065 // Look through categories.
3066 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3067 Category; Category = Category->getNextClassCategory())
Douglas Gregor73449212010-12-09 23:01:55 +00003068 AddObjCProperties(Category, AllowCategories, CurContext,
3069 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003070 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003071
3072 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003073 for (ObjCInterfaceDecl::all_protocol_iterator
3074 I = IFace->all_referenced_protocol_begin(),
3075 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor73449212010-12-09 23:01:55 +00003076 AddObjCProperties(*I, AllowCategories, CurContext, AddedProperties,
3077 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003078
3079 // Look in the superclass.
3080 if (IFace->getSuperClass())
Douglas Gregor322328b2009-11-18 22:32:06 +00003081 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003082 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003083 } else if (const ObjCCategoryDecl *Category
3084 = dyn_cast<ObjCCategoryDecl>(Container)) {
3085 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003086 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3087 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003088 P != PEnd; ++P)
Douglas Gregor73449212010-12-09 23:01:55 +00003089 AddObjCProperties(*P, AllowCategories, CurContext, AddedProperties,
3090 Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003091 }
3092}
3093
Douglas Gregor81b747b2009-09-17 21:32:03 +00003094void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
3095 SourceLocation OpLoc,
3096 bool IsArrow) {
3097 if (!BaseE || !CodeCompleter)
3098 return;
3099
John McCall0a2c5e22010-08-25 06:19:51 +00003100 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003101
Douglas Gregor81b747b2009-09-17 21:32:03 +00003102 Expr *Base = static_cast<Expr *>(BaseE);
3103 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003104
3105 if (IsArrow) {
3106 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3107 BaseType = Ptr->getPointeeType();
3108 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003109 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003110 else
3111 return;
3112 }
3113
Douglas Gregor218937c2011-02-01 19:23:04 +00003114 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003115 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
3116 BaseType),
3117 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003118 Results.EnterNewScope();
3119 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003120 // Indicate that we are performing a member access, and the cv-qualifiers
3121 // for the base object type.
3122 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3123
Douglas Gregor95ac6552009-11-18 01:29:26 +00003124 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003125 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003126 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003127 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3128 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003129
Douglas Gregor95ac6552009-11-18 01:29:26 +00003130 if (getLangOptions().CPlusPlus) {
3131 if (!Results.empty()) {
3132 // The "template" keyword can follow "->" or "." in the grammar.
3133 // However, we only want to suggest the template keyword if something
3134 // is dependent.
3135 bool IsDependent = BaseType->isDependentType();
3136 if (!IsDependent) {
3137 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3138 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3139 IsDependent = Ctx->isDependentContext();
3140 break;
3141 }
3142 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003143
Douglas Gregor95ac6552009-11-18 01:29:26 +00003144 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003145 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003146 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003147 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003148 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3149 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003150 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003151
3152 // Add property results based on our interface.
3153 const ObjCObjectPointerType *ObjCPtr
3154 = BaseType->getAsObjCInterfacePointerType();
3155 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor73449212010-12-09 23:01:55 +00003156 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext,
3157 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003158
3159 // Add properties from the protocols in a qualified interface.
3160 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3161 E = ObjCPtr->qual_end();
3162 I != E; ++I)
Douglas Gregor73449212010-12-09 23:01:55 +00003163 AddObjCProperties(*I, true, CurContext, AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003164 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003165 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003166 // Objective-C instance variable access.
3167 ObjCInterfaceDecl *Class = 0;
3168 if (const ObjCObjectPointerType *ObjCPtr
3169 = BaseType->getAs<ObjCObjectPointerType>())
3170 Class = ObjCPtr->getInterfaceDecl();
3171 else
John McCallc12c5bb2010-05-15 11:32:37 +00003172 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003173
3174 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003175 if (Class) {
3176 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3177 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003178 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3179 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003180 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003181 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003182
3183 // FIXME: How do we cope with isa?
3184
3185 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003186
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003187 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003188 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003189 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003190 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003191}
3192
Douglas Gregor374929f2009-09-18 15:37:17 +00003193void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3194 if (!CodeCompleter)
3195 return;
3196
John McCall0a2c5e22010-08-25 06:19:51 +00003197 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003198 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003199 enum CodeCompletionContext::Kind ContextKind
3200 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003201 switch ((DeclSpec::TST)TagSpec) {
3202 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003203 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003204 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003205 break;
3206
3207 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003208 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003209 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003210 break;
3211
3212 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003213 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003214 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003215 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003216 break;
3217
3218 default:
3219 assert(false && "Unknown type specifier kind in CodeCompleteTag");
3220 return;
3221 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003222
Douglas Gregor218937c2011-02-01 19:23:04 +00003223 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003224 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003225
3226 // First pass: look for tags.
3227 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003228 LookupVisibleDecls(S, LookupTagName, Consumer,
3229 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003230
Douglas Gregor8071e422010-08-15 06:18:01 +00003231 if (CodeCompleter->includeGlobals()) {
3232 // Second pass: look for nested name specifiers.
3233 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3234 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3235 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003236
Douglas Gregor52779fb2010-09-23 23:01:17 +00003237 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003238 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003239}
3240
Douglas Gregor1a480c42010-08-27 17:35:51 +00003241void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003242 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3243 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003244 Results.EnterNewScope();
3245 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3246 Results.AddResult("const");
3247 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3248 Results.AddResult("volatile");
3249 if (getLangOptions().C99 &&
3250 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3251 Results.AddResult("restrict");
3252 Results.ExitScope();
3253 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003254 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003255 Results.data(), Results.size());
3256}
3257
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003258void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003259 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003260 return;
3261
John McCall781472f2010-08-25 08:40:02 +00003262 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
Douglas Gregorf9578432010-07-28 21:50:18 +00003263 if (!Switch->getCond()->getType()->isEnumeralType()) {
Douglas Gregorfb629412010-08-23 21:17:50 +00003264 CodeCompleteExpressionData Data(Switch->getCond()->getType());
3265 Data.IntegralConstantExpression = true;
3266 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003267 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003268 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003269
3270 // Code-complete the cases of a switch statement over an enumeration type
3271 // by providing the list of
3272 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
3273
3274 // Determine which enumerators we have already seen in the switch statement.
3275 // FIXME: Ideally, we would also be able to look *past* the code-completion
3276 // token, in case we are code-completing in the middle of the switch and not
3277 // at the end. However, we aren't able to do so at the moment.
3278 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003279 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003280 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3281 SC = SC->getNextSwitchCase()) {
3282 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3283 if (!Case)
3284 continue;
3285
3286 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3287 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3288 if (EnumConstantDecl *Enumerator
3289 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3290 // We look into the AST of the case statement to determine which
3291 // enumerator was named. Alternatively, we could compute the value of
3292 // the integral constant expression, then compare it against the
3293 // values of each enumerator. However, value-based approach would not
3294 // work as well with C++ templates where enumerators declared within a
3295 // template are type- and value-dependent.
3296 EnumeratorsSeen.insert(Enumerator);
3297
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003298 // If this is a qualified-id, keep track of the nested-name-specifier
3299 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003300 //
3301 // switch (TagD.getKind()) {
3302 // case TagDecl::TK_enum:
3303 // break;
3304 // case XXX
3305 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003306 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003307 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3308 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003309 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003310 }
3311 }
3312
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003313 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3314 // If there are no prior enumerators in C++, check whether we have to
3315 // qualify the names of the enumerators that we suggest, because they
3316 // may not be visible in this scope.
3317 Qualifier = getRequiredQualification(Context, CurContext,
3318 Enum->getDeclContext());
3319
3320 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3321 }
3322
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003323 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003324 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3325 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003326 Results.EnterNewScope();
3327 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3328 EEnd = Enum->enumerator_end();
3329 E != EEnd; ++E) {
3330 if (EnumeratorsSeen.count(*E))
3331 continue;
3332
Douglas Gregor5c722c702011-02-18 23:30:37 +00003333 CodeCompletionResult R(*E, Qualifier);
3334 R.Priority = CCP_EnumInCase;
3335 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003336 }
3337 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003338
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003339 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003340 AddMacroResults(PP, Results);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003341 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor5c722c702011-02-18 23:30:37 +00003342 CodeCompletionContext::CCC_OtherWithMacros,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003343 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003344}
3345
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003346namespace {
3347 struct IsBetterOverloadCandidate {
3348 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003349 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003350
3351 public:
John McCall5769d612010-02-08 23:07:23 +00003352 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3353 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003354
3355 bool
3356 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003357 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003358 }
3359 };
3360}
3361
Douglas Gregord28dcd72010-05-30 06:10:08 +00003362static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3363 if (NumArgs && !Args)
3364 return true;
3365
3366 for (unsigned I = 0; I != NumArgs; ++I)
3367 if (!Args[I])
3368 return true;
3369
3370 return false;
3371}
3372
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003373void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
3374 ExprTy **ArgsIn, unsigned NumArgs) {
3375 if (!CodeCompleter)
3376 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003377
3378 // When we're code-completing for a call, we fall back to ordinary
3379 // name code-completion whenever we can't produce specific
3380 // results. We may want to revisit this strategy in the future,
3381 // e.g., by merging the two kinds of results.
3382
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003383 Expr *Fn = (Expr *)FnIn;
3384 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003385
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003386 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003387 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003388 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003389 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003390 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003391 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003392
John McCall3b4294e2009-12-16 12:17:52 +00003393 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003394 SourceLocation Loc = Fn->getExprLoc();
3395 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003396
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003397 // FIXME: What if we're calling something that isn't a function declaration?
3398 // FIXME: What if we're calling a pseudo-destructor?
3399 // FIXME: What if we're calling a member function?
3400
Douglas Gregorc0265402010-01-21 15:46:19 +00003401 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3402 llvm::SmallVector<ResultCandidate, 8> Results;
3403
John McCall3b4294e2009-12-16 12:17:52 +00003404 Expr *NakedFn = Fn->IgnoreParenCasts();
3405 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3406 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3407 /*PartialOverloading=*/ true);
3408 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3409 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003410 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003411 if (!getLangOptions().CPlusPlus ||
3412 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003413 Results.push_back(ResultCandidate(FDecl));
3414 else
John McCall86820f52010-01-26 01:37:31 +00003415 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003416 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3417 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003418 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003419 }
John McCall3b4294e2009-12-16 12:17:52 +00003420 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003421
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003422 QualType ParamType;
3423
Douglas Gregorc0265402010-01-21 15:46:19 +00003424 if (!CandidateSet.empty()) {
3425 // Sort the overload candidate set by placing the best overloads first.
3426 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003427 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003428
Douglas Gregorc0265402010-01-21 15:46:19 +00003429 // Add the remaining viable overload candidates as code-completion reslults.
3430 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3431 CandEnd = CandidateSet.end();
3432 Cand != CandEnd; ++Cand) {
3433 if (Cand->Viable)
3434 Results.push_back(ResultCandidate(Cand->Function));
3435 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003436
3437 // From the viable candidates, try to determine the type of this parameter.
3438 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3439 if (const FunctionType *FType = Results[I].getFunctionType())
3440 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3441 if (NumArgs < Proto->getNumArgs()) {
3442 if (ParamType.isNull())
3443 ParamType = Proto->getArgType(NumArgs);
3444 else if (!Context.hasSameUnqualifiedType(
3445 ParamType.getNonReferenceType(),
3446 Proto->getArgType(NumArgs).getNonReferenceType())) {
3447 ParamType = QualType();
3448 break;
3449 }
3450 }
3451 }
3452 } else {
3453 // Try to determine the parameter type from the type of the expression
3454 // being called.
3455 QualType FunctionType = Fn->getType();
3456 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3457 FunctionType = Ptr->getPointeeType();
3458 else if (const BlockPointerType *BlockPtr
3459 = FunctionType->getAs<BlockPointerType>())
3460 FunctionType = BlockPtr->getPointeeType();
3461 else if (const MemberPointerType *MemPtr
3462 = FunctionType->getAs<MemberPointerType>())
3463 FunctionType = MemPtr->getPointeeType();
3464
3465 if (const FunctionProtoType *Proto
3466 = FunctionType->getAs<FunctionProtoType>()) {
3467 if (NumArgs < Proto->getNumArgs())
3468 ParamType = Proto->getArgType(NumArgs);
3469 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003470 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003471
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003472 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003473 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003474 else
3475 CodeCompleteExpression(S, ParamType);
3476
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003477 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003478 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3479 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003480}
3481
John McCalld226f652010-08-21 09:40:31 +00003482void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3483 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003484 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003485 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003486 return;
3487 }
3488
3489 CodeCompleteExpression(S, VD->getType());
3490}
3491
3492void Sema::CodeCompleteReturn(Scope *S) {
3493 QualType ResultType;
3494 if (isa<BlockDecl>(CurContext)) {
3495 if (BlockScopeInfo *BSI = getCurBlock())
3496 ResultType = BSI->ReturnType;
3497 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3498 ResultType = Function->getResultType();
3499 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3500 ResultType = Method->getResultType();
3501
3502 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003503 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003504 else
3505 CodeCompleteExpression(S, ResultType);
3506}
3507
3508void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3509 if (LHS)
3510 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3511 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003512 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003513}
3514
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003515void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003516 bool EnteringContext) {
3517 if (!SS.getScopeRep() || !CodeCompleter)
3518 return;
3519
Douglas Gregor86d9a522009-09-21 16:56:56 +00003520 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3521 if (!Ctx)
3522 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003523
3524 // Try to instantiate any non-dependent declaration contexts before
3525 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003526 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003527 return;
3528
Douglas Gregor218937c2011-02-01 19:23:04 +00003529 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3530 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003531 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003532
Douglas Gregor86d9a522009-09-21 16:56:56 +00003533 // The "template" keyword can follow "::" in the grammar, but only
3534 // put it into the grammar if the nested-name-specifier is dependent.
3535 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3536 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003537 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003538
3539 // Add calls to overridden virtual functions, if there are any.
3540 //
3541 // FIXME: This isn't wonderful, because we don't know whether we're actually
3542 // in a context that permits expressions. This is a general issue with
3543 // qualified-id completions.
3544 if (!EnteringContext)
3545 MaybeAddOverrideCalls(*this, Ctx, Results);
3546 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003547
Douglas Gregorf6961522010-08-27 21:18:54 +00003548 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3549 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3550
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003551 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorf6961522010-08-27 21:18:54 +00003552 CodeCompletionContext::CCC_Name,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003553 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003554}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003555
3556void Sema::CodeCompleteUsing(Scope *S) {
3557 if (!CodeCompleter)
3558 return;
3559
Douglas Gregor218937c2011-02-01 19:23:04 +00003560 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003561 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3562 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003563 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003564
3565 // If we aren't in class scope, we could see the "namespace" keyword.
3566 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003567 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003568
3569 // After "using", we can see anything that would start a
3570 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003571 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003572 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3573 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003574 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003575
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003576 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003577 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003578 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003579}
3580
3581void Sema::CodeCompleteUsingDirective(Scope *S) {
3582 if (!CodeCompleter)
3583 return;
3584
Douglas Gregor86d9a522009-09-21 16:56:56 +00003585 // After "using namespace", we expect to see a namespace name or namespace
3586 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003587 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3588 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003589 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003590 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003591 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003592 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3593 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003594 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003595 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003596 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003597 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003598}
3599
3600void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3601 if (!CodeCompleter)
3602 return;
3603
Douglas Gregor86d9a522009-09-21 16:56:56 +00003604 DeclContext *Ctx = (DeclContext *)S->getEntity();
3605 if (!S->getParent())
3606 Ctx = Context.getTranslationUnitDecl();
3607
Douglas Gregor52779fb2010-09-23 23:01:17 +00003608 bool SuppressedGlobalResults
3609 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3610
Douglas Gregor218937c2011-02-01 19:23:04 +00003611 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003612 SuppressedGlobalResults
3613 ? CodeCompletionContext::CCC_Namespace
3614 : CodeCompletionContext::CCC_Other,
3615 &ResultBuilder::IsNamespace);
3616
3617 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003618 // We only want to see those namespaces that have already been defined
3619 // within this scope, because its likely that the user is creating an
3620 // extended namespace declaration. Keep track of the most recent
3621 // definition of each namespace.
3622 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3623 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3624 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3625 NS != NSEnd; ++NS)
3626 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3627
3628 // Add the most recent definition (or extended definition) of each
3629 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003630 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003631 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3632 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3633 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003634 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003635 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003636 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003637 }
3638
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003639 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003640 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003641 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003642}
3643
3644void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3645 if (!CodeCompleter)
3646 return;
3647
Douglas Gregor86d9a522009-09-21 16:56:56 +00003648 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003649 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3650 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003651 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003652 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003653 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3654 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003655 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003656 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003657 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003658}
3659
Douglas Gregored8d3222009-09-18 20:05:18 +00003660void Sema::CodeCompleteOperatorName(Scope *S) {
3661 if (!CodeCompleter)
3662 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003663
John McCall0a2c5e22010-08-25 06:19:51 +00003664 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003665 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3666 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003667 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003668 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00003669
Douglas Gregor86d9a522009-09-21 16:56:56 +00003670 // Add the names of overloadable operators.
3671#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3672 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00003673 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003674#include "clang/Basic/OperatorKinds.def"
3675
3676 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00003677 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003678 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003679 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3680 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00003681
3682 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00003683 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003684 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003685
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003686 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003687 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003688 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00003689}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003690
Douglas Gregor0133f522010-08-28 00:00:50 +00003691void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00003692 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00003693 unsigned NumInitializers) {
3694 CXXConstructorDecl *Constructor
3695 = static_cast<CXXConstructorDecl *>(ConstructorD);
3696 if (!Constructor)
3697 return;
3698
Douglas Gregor218937c2011-02-01 19:23:04 +00003699 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003700 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00003701 Results.EnterNewScope();
3702
3703 // Fill in any already-initialized fields or base classes.
3704 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3705 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3706 for (unsigned I = 0; I != NumInitializers; ++I) {
3707 if (Initializers[I]->isBaseInitializer())
3708 InitializedBases.insert(
3709 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3710 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003711 InitializedFields.insert(cast<FieldDecl>(
3712 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00003713 }
3714
3715 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00003716 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00003717 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00003718 CXXRecordDecl *ClassDecl = Constructor->getParent();
3719 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3720 BaseEnd = ClassDecl->bases_end();
3721 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003722 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3723 SawLastInitializer
3724 = NumInitializers > 0 &&
3725 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3726 Context.hasSameUnqualifiedType(Base->getType(),
3727 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003728 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003729 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003730
Douglas Gregor218937c2011-02-01 19:23:04 +00003731 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003732 Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003733 Base->getType().getAsString(Context.PrintingPolicy)));
3734 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3735 Builder.AddPlaceholderChunk("args");
3736 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3737 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003738 SawLastInitializer? CCP_NextInitializer
3739 : CCP_MemberDeclaration));
3740 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003741 }
3742
3743 // Add completions for virtual base classes.
3744 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3745 BaseEnd = ClassDecl->vbases_end();
3746 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003747 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3748 SawLastInitializer
3749 = NumInitializers > 0 &&
3750 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3751 Context.hasSameUnqualifiedType(Base->getType(),
3752 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00003753 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003754 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003755
Douglas Gregor218937c2011-02-01 19:23:04 +00003756 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00003757 Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003758 Base->getType().getAsString(Context.PrintingPolicy)));
3759 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3760 Builder.AddPlaceholderChunk("args");
3761 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3762 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003763 SawLastInitializer? CCP_NextInitializer
3764 : CCP_MemberDeclaration));
3765 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003766 }
3767
3768 // Add completions for members.
3769 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3770 FieldEnd = ClassDecl->field_end();
3771 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00003772 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
3773 SawLastInitializer
3774 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00003775 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
3776 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00003777 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00003778 }
Douglas Gregor0133f522010-08-28 00:00:50 +00003779
3780 if (!Field->getDeclName())
3781 continue;
3782
Douglas Gregordae68752011-02-01 22:57:45 +00003783 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003784 Field->getIdentifier()->getName()));
3785 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3786 Builder.AddPlaceholderChunk("args");
3787 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3788 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00003789 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00003790 : CCP_MemberDeclaration,
3791 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00003792 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00003793 }
3794 Results.ExitScope();
3795
Douglas Gregor52779fb2010-09-23 23:01:17 +00003796 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00003797 Results.data(), Results.size());
3798}
3799
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003800// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3801// true or false.
3802#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00003803static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003804 ResultBuilder &Results,
3805 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003806 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003807 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003808 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003809
Douglas Gregor218937c2011-02-01 19:23:04 +00003810 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003811 if (LangOpts.ObjC2) {
3812 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00003813 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3814 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3815 Builder.AddPlaceholderChunk("property");
3816 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003817
3818 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00003819 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3820 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3821 Builder.AddPlaceholderChunk("property");
3822 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003823 }
3824}
3825
Douglas Gregorbca403c2010-01-13 23:51:12 +00003826static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003827 ResultBuilder &Results,
3828 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003829 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003830
3831 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00003832 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003833
3834 if (LangOpts.ObjC2) {
3835 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00003836 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003837
3838 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00003839 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003840
3841 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00003842 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003843 }
3844}
3845
Douglas Gregorbca403c2010-01-13 23:51:12 +00003846static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003847 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003848 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003849
3850 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00003851 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3852 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3853 Builder.AddPlaceholderChunk("name");
3854 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003855
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003856 if (Results.includeCodePatterns()) {
3857 // @interface name
3858 // FIXME: Could introduce the whole pattern, including superclasses and
3859 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00003860 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
3861 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3862 Builder.AddPlaceholderChunk("class");
3863 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003864
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003865 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00003866 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3867 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3868 Builder.AddPlaceholderChunk("protocol");
3869 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003870
3871 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00003872 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
3873 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3874 Builder.AddPlaceholderChunk("class");
3875 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003876 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003877
3878 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00003879 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
3880 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3881 Builder.AddPlaceholderChunk("alias");
3882 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3883 Builder.AddPlaceholderChunk("class");
3884 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003885}
3886
John McCalld226f652010-08-21 09:40:31 +00003887void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
Douglas Gregorc464ae82009-12-07 09:27:33 +00003888 bool InInterface) {
John McCall0a2c5e22010-08-25 06:19:51 +00003889 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003890 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3891 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003892 Results.EnterNewScope();
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003893 if (ObjCImpDecl)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003894 AddObjCImplementationResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003895 else if (InInterface)
Douglas Gregorbca403c2010-01-13 23:51:12 +00003896 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003897 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00003898 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00003899 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003900 HandleCodeCompleteResults(this, CodeCompleter,
3901 CodeCompletionContext::CCC_Other,
3902 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00003903}
3904
Douglas Gregorbca403c2010-01-13 23:51:12 +00003905static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003906 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003907 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003908
3909 // @encode ( type-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00003910 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
3911 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3912 Builder.AddPlaceholderChunk("type-name");
3913 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3914 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003915
3916 // @protocol ( protocol-name )
Douglas Gregor218937c2011-02-01 19:23:04 +00003917 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3918 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3919 Builder.AddPlaceholderChunk("protocol-name");
3920 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3921 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003922
3923 // @selector ( selector )
Douglas Gregor218937c2011-02-01 19:23:04 +00003924 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
3925 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3926 Builder.AddPlaceholderChunk("selector");
3927 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3928 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003929}
3930
Douglas Gregorbca403c2010-01-13 23:51:12 +00003931static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003932 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003933 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003934
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003935 if (Results.includeCodePatterns()) {
3936 // @try { statements } @catch ( declaration ) { statements } @finally
3937 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00003938 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
3939 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3940 Builder.AddPlaceholderChunk("statements");
3941 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3942 Builder.AddTextChunk("@catch");
3943 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3944 Builder.AddPlaceholderChunk("parameter");
3945 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3946 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3947 Builder.AddPlaceholderChunk("statements");
3948 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3949 Builder.AddTextChunk("@finally");
3950 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3951 Builder.AddPlaceholderChunk("statements");
3952 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3953 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003954 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003955
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003956 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00003957 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
3958 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3959 Builder.AddPlaceholderChunk("expression");
3960 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003961
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003962 if (Results.includeCodePatterns()) {
3963 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00003964 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3965 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3966 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3967 Builder.AddPlaceholderChunk("expression");
3968 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3969 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3970 Builder.AddPlaceholderChunk("statements");
3971 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3972 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00003973 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00003974}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00003975
Douglas Gregorbca403c2010-01-13 23:51:12 +00003976static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003977 ResultBuilder &Results,
3978 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00003979 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00003980 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3981 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3982 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003983 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00003984 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003985}
3986
3987void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003988 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3989 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003990 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00003991 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003992 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003993 HandleCodeCompleteResults(this, CodeCompleter,
3994 CodeCompletionContext::CCC_Other,
3995 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00003996}
3997
3998void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003999 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4000 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004001 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004002 AddObjCStatementResults(Results, false);
4003 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004004 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004005 HandleCodeCompleteResults(this, CodeCompleter,
4006 CodeCompletionContext::CCC_Other,
4007 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004008}
4009
4010void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004011 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4012 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004013 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004014 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004015 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004016 HandleCodeCompleteResults(this, CodeCompleter,
4017 CodeCompletionContext::CCC_Other,
4018 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004019}
4020
Douglas Gregor988358f2009-11-19 00:14:45 +00004021/// \brief Determine whether the addition of the given flag to an Objective-C
4022/// property's attributes will cause a conflict.
4023static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4024 // Check if we've already added this flag.
4025 if (Attributes & NewFlag)
4026 return true;
4027
4028 Attributes |= NewFlag;
4029
4030 // Check for collisions with "readonly".
4031 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4032 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4033 ObjCDeclSpec::DQ_PR_assign |
4034 ObjCDeclSpec::DQ_PR_copy |
4035 ObjCDeclSpec::DQ_PR_retain)))
4036 return true;
4037
4038 // Check for more than one of { assign, copy, retain }.
4039 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
4040 ObjCDeclSpec::DQ_PR_copy |
4041 ObjCDeclSpec::DQ_PR_retain);
4042 if (AssignCopyRetMask &&
4043 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
4044 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
4045 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
4046 return true;
4047
4048 return false;
4049}
4050
Douglas Gregora93b1082009-11-18 23:08:07 +00004051void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004052 if (!CodeCompleter)
4053 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004054
Steve Naroffece8e712009-10-08 21:55:05 +00004055 unsigned Attributes = ODS.getPropertyAttributes();
4056
John McCall0a2c5e22010-08-25 06:19:51 +00004057 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004058 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4059 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004060 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004061 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004062 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004063 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004064 Results.AddResult(CodeCompletionResult("assign"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004065 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004066 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004067 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004068 Results.AddResult(CodeCompletionResult("retain"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004069 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004070 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004071 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004072 Results.AddResult(CodeCompletionResult("nonatomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004073 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004074 CodeCompletionBuilder Setter(Results.getAllocator());
4075 Setter.AddTypedTextChunk("setter");
4076 Setter.AddTextChunk(" = ");
4077 Setter.AddPlaceholderChunk("method");
4078 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004079 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004080 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004081 CodeCompletionBuilder Getter(Results.getAllocator());
4082 Getter.AddTypedTextChunk("getter");
4083 Getter.AddTextChunk(" = ");
4084 Getter.AddPlaceholderChunk("method");
4085 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004086 }
Steve Naroffece8e712009-10-08 21:55:05 +00004087 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004088 HandleCodeCompleteResults(this, CodeCompleter,
4089 CodeCompletionContext::CCC_Other,
4090 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004091}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004092
Douglas Gregor4ad96852009-11-19 07:41:15 +00004093/// \brief Descripts the kind of Objective-C method that we want to find
4094/// via code completion.
4095enum ObjCMethodKind {
4096 MK_Any, //< Any kind of method, provided it means other specified criteria.
4097 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4098 MK_OneArgSelector //< One-argument selector.
4099};
4100
Douglas Gregor458433d2010-08-26 15:07:07 +00004101static bool isAcceptableObjCSelector(Selector Sel,
4102 ObjCMethodKind WantKind,
4103 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004104 unsigned NumSelIdents,
4105 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004106 if (NumSelIdents > Sel.getNumArgs())
4107 return false;
4108
4109 switch (WantKind) {
4110 case MK_Any: break;
4111 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4112 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4113 }
4114
Douglas Gregorcf544262010-11-17 21:36:08 +00004115 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4116 return false;
4117
Douglas Gregor458433d2010-08-26 15:07:07 +00004118 for (unsigned I = 0; I != NumSelIdents; ++I)
4119 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4120 return false;
4121
4122 return true;
4123}
4124
Douglas Gregor4ad96852009-11-19 07:41:15 +00004125static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4126 ObjCMethodKind WantKind,
4127 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004128 unsigned NumSelIdents,
4129 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004130 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004131 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004132}
Douglas Gregord36adf52010-09-16 16:06:31 +00004133
4134namespace {
4135 /// \brief A set of selectors, which is used to avoid introducing multiple
4136 /// completions with the same selector into the result set.
4137 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4138}
4139
Douglas Gregor36ecb042009-11-17 23:22:23 +00004140/// \brief Add all of the Objective-C methods in the given Objective-C
4141/// container to the set of results.
4142///
4143/// The container will be a class, protocol, category, or implementation of
4144/// any of the above. This mether will recurse to include methods from
4145/// the superclasses of classes along with their categories, protocols, and
4146/// implementations.
4147///
4148/// \param Container the container in which we'll look to find methods.
4149///
4150/// \param WantInstance whether to add instance methods (only); if false, this
4151/// routine will add factory methods (only).
4152///
4153/// \param CurContext the context in which we're performing the lookup that
4154/// finds methods.
4155///
Douglas Gregorcf544262010-11-17 21:36:08 +00004156/// \param AllowSameLength Whether we allow a method to be added to the list
4157/// when it has the same number of parameters as we have selector identifiers.
4158///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004159/// \param Results the structure into which we'll add results.
4160static void AddObjCMethods(ObjCContainerDecl *Container,
4161 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004162 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004163 IdentifierInfo **SelIdents,
4164 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004165 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004166 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004167 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004168 ResultBuilder &Results,
4169 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004170 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004171 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4172 MEnd = Container->meth_end();
4173 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004174 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4175 // Check whether the selector identifiers we've been given are a
4176 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004177 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4178 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004179 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004180
Douglas Gregord36adf52010-09-16 16:06:31 +00004181 if (!Selectors.insert((*M)->getSelector()))
4182 continue;
4183
Douglas Gregord3c68542009-11-19 01:08:35 +00004184 Result R = Result(*M, 0);
4185 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004186 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004187 if (!InOriginalClass)
4188 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004189 Results.MaybeAddResult(R, CurContext);
4190 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004191 }
4192
Douglas Gregore396c7b2010-09-16 15:34:59 +00004193 // Visit the protocols of protocols.
4194 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4195 const ObjCList<ObjCProtocolDecl> &Protocols
4196 = Protocol->getReferencedProtocols();
4197 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4198 E = Protocols.end();
4199 I != E; ++I)
4200 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004201 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregore396c7b2010-09-16 15:34:59 +00004202 }
4203
Douglas Gregor36ecb042009-11-17 23:22:23 +00004204 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4205 if (!IFace)
4206 return;
4207
4208 // Add methods in protocols.
4209 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4210 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4211 E = Protocols.end();
4212 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004213 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004214 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004215
4216 // Add methods in categories.
4217 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4218 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004219 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004220 NumSelIdents, CurContext, Selectors, AllowSameLength,
4221 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004222
4223 // Add a categories protocol methods.
4224 const ObjCList<ObjCProtocolDecl> &Protocols
4225 = CatDecl->getReferencedProtocols();
4226 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4227 E = Protocols.end();
4228 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004229 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004230 NumSelIdents, CurContext, Selectors, AllowSameLength,
4231 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004232
4233 // Add methods in category implementations.
4234 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004235 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004236 NumSelIdents, CurContext, Selectors, AllowSameLength,
4237 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004238 }
4239
4240 // Add methods in superclass.
4241 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004242 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004243 SelIdents, NumSelIdents, CurContext, Selectors,
4244 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004245
4246 // Add methods in our implementation, if any.
4247 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004248 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004249 NumSelIdents, CurContext, Selectors, AllowSameLength,
4250 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004251}
4252
4253
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004254void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004255 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004256
4257 // Try to find the interface where getters might live.
John McCalld226f652010-08-21 09:40:31 +00004258 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004259 if (!Class) {
4260 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004261 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004262 Class = Category->getClassInterface();
4263
4264 if (!Class)
4265 return;
4266 }
4267
4268 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004269 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4270 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004271 Results.EnterNewScope();
4272
Douglas Gregord36adf52010-09-16 16:06:31 +00004273 VisitedSelectorSet Selectors;
4274 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004275 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004276 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004277 HandleCodeCompleteResults(this, CodeCompleter,
4278 CodeCompletionContext::CCC_Other,
4279 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004280}
4281
Douglas Gregorbdb2d502010-12-21 17:34:17 +00004282void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00004283 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004284
4285 // Try to find the interface where setters might live.
4286 ObjCInterfaceDecl *Class
John McCalld226f652010-08-21 09:40:31 +00004287 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004288 if (!Class) {
4289 if (ObjCCategoryDecl *Category
John McCalld226f652010-08-21 09:40:31 +00004290 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004291 Class = Category->getClassInterface();
4292
4293 if (!Class)
4294 return;
4295 }
4296
4297 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004298 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4299 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004300 Results.EnterNewScope();
4301
Douglas Gregord36adf52010-09-16 16:06:31 +00004302 VisitedSelectorSet Selectors;
4303 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004304 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004305
4306 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004307 HandleCodeCompleteResults(this, CodeCompleter,
4308 CodeCompletionContext::CCC_Other,
4309 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004310}
4311
Douglas Gregorafc45782011-02-15 22:19:42 +00004312void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4313 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004314 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004315 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4316 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004317 Results.EnterNewScope();
4318
4319 // Add context-sensitive, Objective-C parameter-passing keywords.
4320 bool AddedInOut = false;
4321 if ((DS.getObjCDeclQualifier() &
4322 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4323 Results.AddResult("in");
4324 Results.AddResult("inout");
4325 AddedInOut = true;
4326 }
4327 if ((DS.getObjCDeclQualifier() &
4328 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4329 Results.AddResult("out");
4330 if (!AddedInOut)
4331 Results.AddResult("inout");
4332 }
4333 if ((DS.getObjCDeclQualifier() &
4334 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4335 ObjCDeclSpec::DQ_Oneway)) == 0) {
4336 Results.AddResult("bycopy");
4337 Results.AddResult("byref");
4338 Results.AddResult("oneway");
4339 }
4340
Douglas Gregorafc45782011-02-15 22:19:42 +00004341 // If we're completing the return type of an Objective-C method and the
4342 // identifier IBAction refers to a macro, provide a completion item for
4343 // an action, e.g.,
4344 // IBAction)<#selector#>:(id)sender
4345 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4346 Context.Idents.get("IBAction").hasMacroDefinition()) {
4347 typedef CodeCompletionString::Chunk Chunk;
4348 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4349 CXAvailability_Available);
4350 Builder.AddTypedTextChunk("IBAction");
4351 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4352 Builder.AddPlaceholderChunk("selector");
4353 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4354 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4355 Builder.AddTextChunk("id");
4356 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4357 Builder.AddTextChunk("sender");
4358 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4359 }
4360
Douglas Gregord32b0222010-08-24 01:06:58 +00004361 // Add various builtin type names and specifiers.
4362 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4363 Results.ExitScope();
4364
4365 // Add the various type names
4366 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4367 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4368 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4369 CodeCompleter->includeGlobals());
4370
4371 if (CodeCompleter->includeMacros())
4372 AddMacroResults(PP, Results);
4373
4374 HandleCodeCompleteResults(this, CodeCompleter,
4375 CodeCompletionContext::CCC_Type,
4376 Results.data(), Results.size());
4377}
4378
Douglas Gregor22f56992010-04-06 19:22:33 +00004379/// \brief When we have an expression with type "id", we may assume
4380/// that it has some more-specific class type based on knowledge of
4381/// common uses of Objective-C. This routine returns that class type,
4382/// or NULL if no better result could be determined.
4383static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004384 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004385 if (!Msg)
4386 return 0;
4387
4388 Selector Sel = Msg->getSelector();
4389 if (Sel.isNull())
4390 return 0;
4391
4392 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4393 if (!Id)
4394 return 0;
4395
4396 ObjCMethodDecl *Method = Msg->getMethodDecl();
4397 if (!Method)
4398 return 0;
4399
4400 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004401 ObjCInterfaceDecl *IFace = 0;
4402 switch (Msg->getReceiverKind()) {
4403 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004404 if (const ObjCObjectType *ObjType
4405 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4406 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004407 break;
4408
4409 case ObjCMessageExpr::Instance: {
4410 QualType T = Msg->getInstanceReceiver()->getType();
4411 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4412 IFace = Ptr->getInterfaceDecl();
4413 break;
4414 }
4415
4416 case ObjCMessageExpr::SuperInstance:
4417 case ObjCMessageExpr::SuperClass:
4418 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004419 }
4420
4421 if (!IFace)
4422 return 0;
4423
4424 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4425 if (Method->isInstanceMethod())
4426 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4427 .Case("retain", IFace)
4428 .Case("autorelease", IFace)
4429 .Case("copy", IFace)
4430 .Case("copyWithZone", IFace)
4431 .Case("mutableCopy", IFace)
4432 .Case("mutableCopyWithZone", IFace)
4433 .Case("awakeFromCoder", IFace)
4434 .Case("replacementObjectFromCoder", IFace)
4435 .Case("class", IFace)
4436 .Case("classForCoder", IFace)
4437 .Case("superclass", Super)
4438 .Default(0);
4439
4440 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4441 .Case("new", IFace)
4442 .Case("alloc", IFace)
4443 .Case("allocWithZone", IFace)
4444 .Case("class", IFace)
4445 .Case("superclass", Super)
4446 .Default(0);
4447}
4448
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004449// Add a special completion for a message send to "super", which fills in the
4450// most likely case of forwarding all of our arguments to the superclass
4451// function.
4452///
4453/// \param S The semantic analysis object.
4454///
4455/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4456/// the "super" keyword. Otherwise, we just need to provide the arguments.
4457///
4458/// \param SelIdents The identifiers in the selector that have already been
4459/// provided as arguments for a send to "super".
4460///
4461/// \param NumSelIdents The number of identifiers in \p SelIdents.
4462///
4463/// \param Results The set of results to augment.
4464///
4465/// \returns the Objective-C method declaration that would be invoked by
4466/// this "super" completion. If NULL, no completion was added.
4467static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4468 IdentifierInfo **SelIdents,
4469 unsigned NumSelIdents,
4470 ResultBuilder &Results) {
4471 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4472 if (!CurMethod)
4473 return 0;
4474
4475 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4476 if (!Class)
4477 return 0;
4478
4479 // Try to find a superclass method with the same selector.
4480 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004481 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4482 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004483 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4484 CurMethod->isInstanceMethod());
4485
Douglas Gregor78bcd912011-02-16 00:51:18 +00004486 // Check in categories or class extensions.
4487 if (!SuperMethod) {
4488 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4489 Category = Category->getNextClassCategory())
4490 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4491 CurMethod->isInstanceMethod())))
4492 break;
4493 }
4494 }
4495
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004496 if (!SuperMethod)
4497 return 0;
4498
4499 // Check whether the superclass method has the same signature.
4500 if (CurMethod->param_size() != SuperMethod->param_size() ||
4501 CurMethod->isVariadic() != SuperMethod->isVariadic())
4502 return 0;
4503
4504 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4505 CurPEnd = CurMethod->param_end(),
4506 SuperP = SuperMethod->param_begin();
4507 CurP != CurPEnd; ++CurP, ++SuperP) {
4508 // Make sure the parameter types are compatible.
4509 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4510 (*SuperP)->getType()))
4511 return 0;
4512
4513 // Make sure we have a parameter name to forward!
4514 if (!(*CurP)->getIdentifier())
4515 return 0;
4516 }
4517
4518 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004519 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004520
4521 // Give this completion a return type.
Douglas Gregor218937c2011-02-01 19:23:04 +00004522 AddResultTypeChunk(S.Context, SuperMethod, Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004523
4524 // If we need the "super" keyword, add it (plus some spacing).
4525 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004526 Builder.AddTypedTextChunk("super");
4527 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004528 }
4529
4530 Selector Sel = CurMethod->getSelector();
4531 if (Sel.isUnarySelector()) {
4532 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004533 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004534 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004535 else
Douglas Gregordae68752011-02-01 22:57:45 +00004536 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004537 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004538 } else {
4539 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4540 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4541 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004542 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004543
4544 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004545 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004546 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004547 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004548 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004549 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004550 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004551 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004552 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004553 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004554 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004555 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004556 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004557 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004558 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004559 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004560 }
4561 }
4562 }
4563
Douglas Gregor218937c2011-02-01 19:23:04 +00004564 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004565 SuperMethod->isInstanceMethod()
4566 ? CXCursor_ObjCInstanceMethodDecl
4567 : CXCursor_ObjCClassMethodDecl));
4568 return SuperMethod;
4569}
4570
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004571void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004572 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004573 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4574 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004575 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004576
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004577 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4578 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004579 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4580 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004581
4582 // If we are in an Objective-C method inside a class that has a superclass,
4583 // add "super" as an option.
4584 if (ObjCMethodDecl *Method = getCurMethodDecl())
4585 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004586 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004587 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004588
4589 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4590 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004591
4592 Results.ExitScope();
4593
4594 if (CodeCompleter->includeMacros())
4595 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004596 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004597 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004598
4599}
4600
Douglas Gregor2725ca82010-04-21 19:57:20 +00004601void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4602 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004603 unsigned NumSelIdents,
4604 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004605 ObjCInterfaceDecl *CDecl = 0;
4606 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4607 // Figure out which interface we're in.
4608 CDecl = CurMethod->getClassInterface();
4609 if (!CDecl)
4610 return;
4611
4612 // Find the superclass of this class.
4613 CDecl = CDecl->getSuperClass();
4614 if (!CDecl)
4615 return;
4616
4617 if (CurMethod->isInstanceMethod()) {
4618 // We are inside an instance method, which means that the message
4619 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004620 // current object.
4621 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004622 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004623 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004624 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004625 }
4626
4627 // Fall through to send to the superclass in CDecl.
4628 } else {
4629 // "super" may be the name of a type or variable. Figure out which
4630 // it is.
4631 IdentifierInfo *Super = &Context.Idents.get("super");
4632 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4633 LookupOrdinaryName);
4634 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4635 // "super" names an interface. Use it.
4636 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004637 if (const ObjCObjectType *Iface
4638 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4639 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00004640 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4641 // "super" names an unresolved type; we can't be more specific.
4642 } else {
4643 // Assume that "super" names some kind of value and parse that way.
4644 CXXScopeSpec SS;
4645 UnqualifiedId id;
4646 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00004647 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004648 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004649 SelIdents, NumSelIdents,
4650 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004651 }
4652
4653 // Fall through
4654 }
4655
John McCallb3d87482010-08-24 05:47:05 +00004656 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00004657 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00004658 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00004659 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004660 NumSelIdents, AtArgumentExpression,
4661 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004662}
4663
Douglas Gregorb9d77572010-09-21 00:03:25 +00004664/// \brief Given a set of code-completion results for the argument of a message
4665/// send, determine the preferred type (if any) for that argument expression.
4666static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4667 unsigned NumSelIdents) {
4668 typedef CodeCompletionResult Result;
4669 ASTContext &Context = Results.getSema().Context;
4670
4671 QualType PreferredType;
4672 unsigned BestPriority = CCP_Unlikely * 2;
4673 Result *ResultsData = Results.data();
4674 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4675 Result &R = ResultsData[I];
4676 if (R.Kind == Result::RK_Declaration &&
4677 isa<ObjCMethodDecl>(R.Declaration)) {
4678 if (R.Priority <= BestPriority) {
4679 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4680 if (NumSelIdents <= Method->param_size()) {
4681 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4682 ->getType();
4683 if (R.Priority < BestPriority || PreferredType.isNull()) {
4684 BestPriority = R.Priority;
4685 PreferredType = MyPreferredType;
4686 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4687 MyPreferredType)) {
4688 PreferredType = QualType();
4689 }
4690 }
4691 }
4692 }
4693 }
4694
4695 return PreferredType;
4696}
4697
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004698static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4699 ParsedType Receiver,
4700 IdentifierInfo **SelIdents,
4701 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004702 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004703 bool IsSuper,
4704 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00004705 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00004706 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004707
Douglas Gregor24a069f2009-11-17 17:59:40 +00004708 // If the given name refers to an interface type, retrieve the
4709 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00004710 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004711 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004712 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00004713 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4714 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00004715 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004716
Douglas Gregor36ecb042009-11-17 23:22:23 +00004717 // Add all of the factory methods in this Objective-C class, its protocols,
4718 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00004719 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004720
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004721 // If this is a send-to-super, try to add the special "super" send
4722 // completion.
4723 if (IsSuper) {
4724 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004725 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4726 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004727 Results.Ignore(SuperMethod);
4728 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004729
Douglas Gregor265f7492010-08-27 15:29:55 +00004730 // If we're inside an Objective-C method definition, prefer its selector to
4731 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004732 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00004733 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004734
Douglas Gregord36adf52010-09-16 16:06:31 +00004735 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00004736 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004737 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004738 SemaRef.CurContext, Selectors, AtArgumentExpression,
4739 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00004740 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00004741 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004742
Douglas Gregor719770d2010-04-06 17:30:22 +00004743 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004744 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004745 if (SemaRef.ExternalSource) {
4746 for (uint32_t I = 0,
4747 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00004748 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004749 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
4750 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004751 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004752
4753 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004754 }
4755 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004756
4757 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
4758 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00004759 M != MEnd; ++M) {
4760 for (ObjCMethodList *MethList = &M->second.second;
4761 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004762 MethList = MethList->Next) {
4763 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4764 NumSelIdents))
4765 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004766
Douglas Gregor13438f92010-04-06 16:40:00 +00004767 Result R(MethList->Method, 0);
4768 R.StartParameter = NumSelIdents;
4769 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004770 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00004771 }
4772 }
4773 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004774
4775 Results.ExitScope();
4776}
Douglas Gregor13438f92010-04-06 16:40:00 +00004777
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004778void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4779 IdentifierInfo **SelIdents,
4780 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004781 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00004782 bool IsSuper) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004783 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4784 CodeCompletionContext::CCC_Other);
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004785 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
4786 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00004787
4788 // If we're actually at the argument expression (rather than prior to the
4789 // selector), we're actually performing code completion for an expression.
4790 // Determine whether we have a single, best method. If so, we can
4791 // code-complete the expression using the corresponding parameter type as
4792 // our preferred type, improving completion results.
4793 if (AtArgumentExpression) {
4794 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4795 NumSelIdents);
4796 if (PreferredType.isNull())
4797 CodeCompleteOrdinaryName(S, PCC_Expression);
4798 else
4799 CodeCompleteExpression(S, PreferredType);
4800 return;
4801 }
4802
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004803 HandleCodeCompleteResults(this, CodeCompleter,
4804 CodeCompletionContext::CCC_Other,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004805 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004806}
4807
Douglas Gregord3c68542009-11-19 01:08:35 +00004808void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4809 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004810 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004811 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004812 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00004813 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00004814
4815 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00004816
Douglas Gregor36ecb042009-11-17 23:22:23 +00004817 // If necessary, apply function/array conversion to the receiver.
4818 // C99 6.7.5.3p[7,8].
Douglas Gregor78edf512010-09-15 16:23:04 +00004819 if (RecExpr)
4820 DefaultFunctionArrayLvalueConversion(RecExpr);
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004821 QualType ReceiverType = RecExpr? RecExpr->getType()
4822 : Super? Context.getObjCObjectPointerType(
4823 Context.getObjCInterfaceType(Super))
4824 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00004825
Douglas Gregorda892642010-11-08 21:12:30 +00004826 // If we're messaging an expression with type "id" or "Class", check
4827 // whether we know something special about the receiver that allows
4828 // us to assume a more-specific receiver type.
4829 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
4830 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
4831 if (ReceiverType->isObjCClassType())
4832 return CodeCompleteObjCClassMessage(S,
4833 ParsedType::make(Context.getObjCInterfaceType(IFace)),
4834 SelIdents, NumSelIdents,
4835 AtArgumentExpression, Super);
4836
4837 ReceiverType = Context.getObjCObjectPointerType(
4838 Context.getObjCInterfaceType(IFace));
4839 }
4840
Douglas Gregor36ecb042009-11-17 23:22:23 +00004841 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00004842 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4843 CodeCompletionContext::CCC_Other);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004844 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00004845
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004846 // If this is a send-to-super, try to add the special "super" send
4847 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00004848 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004849 if (ObjCMethodDecl *SuperMethod
4850 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
4851 Results))
4852 Results.Ignore(SuperMethod);
4853 }
4854
Douglas Gregor265f7492010-08-27 15:29:55 +00004855 // If we're inside an Objective-C method definition, prefer its selector to
4856 // others.
4857 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
4858 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004859
Douglas Gregord36adf52010-09-16 16:06:31 +00004860 // Keep track of the selectors we've already added.
4861 VisitedSelectorSet Selectors;
4862
Douglas Gregorf74a4192009-11-18 00:06:18 +00004863 // Handle messages to Class. This really isn't a message to an instance
4864 // method, so we treat it the same way we would treat a message send to a
4865 // class method.
4866 if (ReceiverType->isObjCClassType() ||
4867 ReceiverType->isObjCQualifiedClassType()) {
4868 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4869 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004870 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004871 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004872 }
4873 }
4874 // Handle messages to a qualified ID ("id<foo>").
4875 else if (const ObjCObjectPointerType *QualID
4876 = ReceiverType->getAsObjCQualifiedIdType()) {
4877 // Search protocols for instance methods.
4878 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
4879 E = QualID->qual_end();
4880 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004881 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004882 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004883 }
4884 // Handle messages to a pointer to interface type.
4885 else if (const ObjCObjectPointerType *IFacePtr
4886 = ReceiverType->getAsObjCInterfacePointerType()) {
4887 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00004888 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004889 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
4890 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004891
4892 // Search protocols for instance methods.
4893 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
4894 E = IFacePtr->qual_end();
4895 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004896 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004897 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00004898 }
Douglas Gregor13438f92010-04-06 16:40:00 +00004899 // Handle messages to "id".
4900 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00004901 // We're messaging "id", so provide all instance methods we know
4902 // about as code-completion results.
4903
4904 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004905 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00004906 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00004907 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4908 I != N; ++I) {
4909 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00004910 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00004911 continue;
4912
Sebastian Redldb9d2142010-08-02 23:18:59 +00004913 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00004914 }
4915 }
4916
Sebastian Redldb9d2142010-08-02 23:18:59 +00004917 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4918 MEnd = MethodPool.end();
4919 M != MEnd; ++M) {
4920 for (ObjCMethodList *MethList = &M->second.first;
4921 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00004922 MethList = MethList->Next) {
4923 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4924 NumSelIdents))
4925 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00004926
4927 if (!Selectors.insert(MethList->Method->getSelector()))
4928 continue;
4929
Douglas Gregor13438f92010-04-06 16:40:00 +00004930 Result R(MethList->Method, 0);
4931 R.StartParameter = NumSelIdents;
4932 R.AllParametersAreInformative = false;
4933 Results.MaybeAddResult(R, CurContext);
4934 }
4935 }
4936 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00004937 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00004938
4939
4940 // If we're actually at the argument expression (rather than prior to the
4941 // selector), we're actually performing code completion for an expression.
4942 // Determine whether we have a single, best method. If so, we can
4943 // code-complete the expression using the corresponding parameter type as
4944 // our preferred type, improving completion results.
4945 if (AtArgumentExpression) {
4946 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4947 NumSelIdents);
4948 if (PreferredType.isNull())
4949 CodeCompleteOrdinaryName(S, PCC_Expression);
4950 else
4951 CodeCompleteExpression(S, PreferredType);
4952 return;
4953 }
4954
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004955 HandleCodeCompleteResults(this, CodeCompleter,
4956 CodeCompletionContext::CCC_Other,
4957 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00004958}
Douglas Gregor55385fe2009-11-18 04:19:12 +00004959
Douglas Gregorfb629412010-08-23 21:17:50 +00004960void Sema::CodeCompleteObjCForCollection(Scope *S,
4961 DeclGroupPtrTy IterationVar) {
4962 CodeCompleteExpressionData Data;
4963 Data.ObjCCollection = true;
4964
4965 if (IterationVar.getAsOpaquePtr()) {
4966 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
4967 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
4968 if (*I)
4969 Data.IgnoreDecls.push_back(*I);
4970 }
4971 }
4972
4973 CodeCompleteExpression(S, Data);
4974}
4975
Douglas Gregor458433d2010-08-26 15:07:07 +00004976void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
4977 unsigned NumSelIdents) {
4978 // If we have an external source, load the entire class method
4979 // pool from the AST file.
4980 if (ExternalSource) {
4981 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4982 I != N; ++I) {
4983 Selector Sel = ExternalSource->GetExternalSelector(I);
4984 if (Sel.isNull() || MethodPool.count(Sel))
4985 continue;
4986
4987 ReadMethodPool(Sel);
4988 }
4989 }
4990
Douglas Gregor218937c2011-02-01 19:23:04 +00004991 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4992 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00004993 Results.EnterNewScope();
4994 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4995 MEnd = MethodPool.end();
4996 M != MEnd; ++M) {
4997
4998 Selector Sel = M->first;
4999 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5000 continue;
5001
Douglas Gregor218937c2011-02-01 19:23:04 +00005002 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005003 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005004 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005005 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005006 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005007 continue;
5008 }
5009
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005010 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005011 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005012 if (I == NumSelIdents) {
5013 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005014 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005015 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005016 Accumulator.clear();
5017 }
5018 }
5019
Douglas Gregor813d8342011-02-18 22:29:55 +00005020 Accumulator += Sel.getNameForSlot(I).str();
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005021 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005022 }
Douglas Gregordae68752011-02-01 22:57:45 +00005023 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005024 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005025 }
5026 Results.ExitScope();
5027
5028 HandleCodeCompleteResults(this, CodeCompleter,
5029 CodeCompletionContext::CCC_SelectorName,
5030 Results.data(), Results.size());
5031}
5032
Douglas Gregor55385fe2009-11-18 04:19:12 +00005033/// \brief Add all of the protocol declarations that we find in the given
5034/// (translation unit) context.
5035static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005036 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005037 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005038 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005039
5040 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5041 DEnd = Ctx->decls_end();
5042 D != DEnd; ++D) {
5043 // Record any protocols we find.
5044 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor083128f2009-11-18 04:49:41 +00005045 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005046 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005047
5048 // Record any forward-declared protocols we find.
5049 if (ObjCForwardProtocolDecl *Forward
5050 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
5051 for (ObjCForwardProtocolDecl::protocol_iterator
5052 P = Forward->protocol_begin(),
5053 PEnd = Forward->protocol_end();
5054 P != PEnd; ++P)
Douglas Gregor083128f2009-11-18 04:49:41 +00005055 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
Douglas Gregor608300b2010-01-14 16:14:35 +00005056 Results.AddResult(Result(*P, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005057 }
5058 }
5059}
5060
5061void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5062 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005063 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5064 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005065
Douglas Gregor70c23352010-12-09 21:44:02 +00005066 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5067 Results.EnterNewScope();
5068
5069 // Tell the result set to ignore all of the protocols we have
5070 // already seen.
5071 // FIXME: This doesn't work when caching code-completion results.
5072 for (unsigned I = 0; I != NumProtocols; ++I)
5073 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5074 Protocols[I].second))
5075 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005076
Douglas Gregor70c23352010-12-09 21:44:02 +00005077 // Add all protocols.
5078 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5079 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005080
Douglas Gregor70c23352010-12-09 21:44:02 +00005081 Results.ExitScope();
5082 }
5083
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005084 HandleCodeCompleteResults(this, CodeCompleter,
5085 CodeCompletionContext::CCC_ObjCProtocolName,
5086 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005087}
5088
5089void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005090 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5091 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005092
Douglas Gregor70c23352010-12-09 21:44:02 +00005093 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5094 Results.EnterNewScope();
5095
5096 // Add all protocols.
5097 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5098 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005099
Douglas Gregor70c23352010-12-09 21:44:02 +00005100 Results.ExitScope();
5101 }
5102
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005103 HandleCodeCompleteResults(this, CodeCompleter,
5104 CodeCompletionContext::CCC_ObjCProtocolName,
5105 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005106}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005107
5108/// \brief Add all of the Objective-C interface declarations that we find in
5109/// the given (translation unit) context.
5110static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5111 bool OnlyForwardDeclarations,
5112 bool OnlyUnimplemented,
5113 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005114 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005115
5116 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5117 DEnd = Ctx->decls_end();
5118 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005119 // Record any interfaces we find.
5120 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5121 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5122 (!OnlyUnimplemented || !Class->getImplementation()))
5123 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005124
5125 // Record any forward-declared interfaces we find.
5126 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
5127 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005128 C != CEnd; ++C)
5129 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
5130 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
5131 Results.AddResult(Result(C->getInterface(), 0), CurContext,
Douglas Gregor608300b2010-01-14 16:14:35 +00005132 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005133 }
5134 }
5135}
5136
5137void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005138 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5139 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005140 Results.EnterNewScope();
5141
5142 // Add all classes.
5143 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
5144 false, Results);
5145
5146 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005147 // FIXME: Add a special context for this, use cached global completion
5148 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005149 HandleCodeCompleteResults(this, CodeCompleter,
5150 CodeCompletionContext::CCC_Other,
5151 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005152}
5153
Douglas Gregorc83c6872010-04-15 22:33:43 +00005154void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5155 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005156 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5157 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005158 Results.EnterNewScope();
5159
5160 // Make sure that we ignore the class we're currently defining.
5161 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005162 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005163 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005164 Results.Ignore(CurClass);
5165
5166 // Add all classes.
5167 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5168 false, Results);
5169
5170 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005171 // FIXME: Add a special context for this, use cached global completion
5172 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005173 HandleCodeCompleteResults(this, CodeCompleter,
5174 CodeCompletionContext::CCC_Other,
5175 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005176}
5177
5178void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005179 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5180 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005181 Results.EnterNewScope();
5182
5183 // Add all unimplemented classes.
5184 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5185 true, Results);
5186
5187 Results.ExitScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00005188 // FIXME: Add a special context for this, use cached global completion
5189 // results.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005190 HandleCodeCompleteResults(this, CodeCompleter,
5191 CodeCompletionContext::CCC_Other,
5192 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005193}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005194
5195void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005196 IdentifierInfo *ClassName,
5197 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005198 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005199
Douglas Gregor218937c2011-02-01 19:23:04 +00005200 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5201 CodeCompletionContext::CCC_Other);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005202
5203 // Ignore any categories we find that have already been implemented by this
5204 // interface.
5205 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5206 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005207 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005208 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5209 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5210 Category = Category->getNextClassCategory())
5211 CategoryNames.insert(Category->getIdentifier());
5212
5213 // Add all of the categories we know about.
5214 Results.EnterNewScope();
5215 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5216 for (DeclContext::decl_iterator D = TU->decls_begin(),
5217 DEnd = TU->decls_end();
5218 D != DEnd; ++D)
5219 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5220 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005221 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005222 Results.ExitScope();
5223
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005224 HandleCodeCompleteResults(this, CodeCompleter,
5225 CodeCompletionContext::CCC_Other,
5226 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005227}
5228
5229void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005230 IdentifierInfo *ClassName,
5231 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005232 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005233
5234 // Find the corresponding interface. If we couldn't find the interface, the
5235 // program itself is ill-formed. However, we'll try to be helpful still by
5236 // providing the list of all of the categories we know about.
5237 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005238 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005239 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5240 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005241 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005242
Douglas Gregor218937c2011-02-01 19:23:04 +00005243 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5244 CodeCompletionContext::CCC_Other);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005245
5246 // Add all of the categories that have have corresponding interface
5247 // declarations in this class and any of its superclasses, except for
5248 // already-implemented categories in the class itself.
5249 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5250 Results.EnterNewScope();
5251 bool IgnoreImplemented = true;
5252 while (Class) {
5253 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5254 Category = Category->getNextClassCategory())
5255 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5256 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005257 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005258
5259 Class = Class->getSuperClass();
5260 IgnoreImplemented = false;
5261 }
5262 Results.ExitScope();
5263
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005264 HandleCodeCompleteResults(this, CodeCompleter,
5265 CodeCompletionContext::CCC_Other,
5266 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005267}
Douglas Gregor322328b2009-11-18 22:32:06 +00005268
John McCalld226f652010-08-21 09:40:31 +00005269void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005270 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005271 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5272 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005273
5274 // Figure out where this @synthesize lives.
5275 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005276 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005277 if (!Container ||
5278 (!isa<ObjCImplementationDecl>(Container) &&
5279 !isa<ObjCCategoryImplDecl>(Container)))
5280 return;
5281
5282 // Ignore any properties that have already been implemented.
5283 for (DeclContext::decl_iterator D = Container->decls_begin(),
5284 DEnd = Container->decls_end();
5285 D != DEnd; ++D)
5286 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5287 Results.Ignore(PropertyImpl->getPropertyDecl());
5288
5289 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005290 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005291 Results.EnterNewScope();
5292 if (ObjCImplementationDecl *ClassImpl
5293 = dyn_cast<ObjCImplementationDecl>(Container))
5294 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005295 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005296 else
5297 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor73449212010-12-09 23:01:55 +00005298 false, CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005299 Results.ExitScope();
5300
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005301 HandleCodeCompleteResults(this, CodeCompleter,
5302 CodeCompletionContext::CCC_Other,
5303 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005304}
5305
5306void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5307 IdentifierInfo *PropertyName,
John McCalld226f652010-08-21 09:40:31 +00005308 Decl *ObjCImpDecl) {
John McCall0a2c5e22010-08-25 06:19:51 +00005309 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005310 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5311 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005312
5313 // Figure out where this @synthesize lives.
5314 ObjCContainerDecl *Container
John McCalld226f652010-08-21 09:40:31 +00005315 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
Douglas Gregor322328b2009-11-18 22:32:06 +00005316 if (!Container ||
5317 (!isa<ObjCImplementationDecl>(Container) &&
5318 !isa<ObjCCategoryImplDecl>(Container)))
5319 return;
5320
5321 // Figure out which interface we're looking into.
5322 ObjCInterfaceDecl *Class = 0;
5323 if (ObjCImplementationDecl *ClassImpl
5324 = dyn_cast<ObjCImplementationDecl>(Container))
5325 Class = ClassImpl->getClassInterface();
5326 else
5327 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5328 ->getClassInterface();
5329
5330 // Add all of the instance variables in this class and its superclasses.
5331 Results.EnterNewScope();
5332 for(; Class; Class = Class->getSuperClass()) {
5333 // FIXME: We could screen the type of each ivar for compatibility with
5334 // the property, but is that being too paternal?
5335 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
5336 IVarEnd = Class->ivar_end();
5337 IVar != IVarEnd; ++IVar)
Douglas Gregor608300b2010-01-14 16:14:35 +00005338 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
Douglas Gregor322328b2009-11-18 22:32:06 +00005339 }
5340 Results.ExitScope();
5341
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005342 HandleCodeCompleteResults(this, CodeCompleter,
5343 CodeCompletionContext::CCC_Other,
5344 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005345}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005346
Douglas Gregor408be5a2010-08-25 01:08:01 +00005347// Mapping from selectors to the methods that implement that selector, along
5348// with the "in original class" flag.
5349typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5350 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005351
5352/// \brief Find all of the methods that reside in the given container
5353/// (and its superclasses, protocols, etc.) that meet the given
5354/// criteria. Insert those methods into the map of known methods,
5355/// indexed by selector so they can be easily found.
5356static void FindImplementableMethods(ASTContext &Context,
5357 ObjCContainerDecl *Container,
5358 bool WantInstanceMethods,
5359 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005360 KnownMethodsMap &KnownMethods,
5361 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005362 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5363 // Recurse into protocols.
5364 const ObjCList<ObjCProtocolDecl> &Protocols
5365 = IFace->getReferencedProtocols();
5366 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005367 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005368 I != E; ++I)
5369 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005370 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005371
Douglas Gregorea766182010-10-18 18:21:28 +00005372 // Add methods from any class extensions and categories.
5373 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5374 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005375 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5376 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005377 KnownMethods, false);
5378
5379 // Visit the superclass.
5380 if (IFace->getSuperClass())
5381 FindImplementableMethods(Context, IFace->getSuperClass(),
5382 WantInstanceMethods, ReturnType,
5383 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005384 }
5385
5386 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5387 // Recurse into protocols.
5388 const ObjCList<ObjCProtocolDecl> &Protocols
5389 = Category->getReferencedProtocols();
5390 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005391 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005392 I != E; ++I)
5393 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005394 KnownMethods, InOriginalClass);
5395
5396 // If this category is the original class, jump to the interface.
5397 if (InOriginalClass && Category->getClassInterface())
5398 FindImplementableMethods(Context, Category->getClassInterface(),
5399 WantInstanceMethods, ReturnType, KnownMethods,
5400 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005401 }
5402
5403 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5404 // Recurse into protocols.
5405 const ObjCList<ObjCProtocolDecl> &Protocols
5406 = Protocol->getReferencedProtocols();
5407 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5408 E = Protocols.end();
5409 I != E; ++I)
5410 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005411 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005412 }
5413
5414 // Add methods in this container. This operation occurs last because
5415 // we want the methods from this container to override any methods
5416 // we've previously seen with the same selector.
5417 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5418 MEnd = Container->meth_end();
5419 M != MEnd; ++M) {
5420 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5421 if (!ReturnType.isNull() &&
5422 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5423 continue;
5424
Douglas Gregor408be5a2010-08-25 01:08:01 +00005425 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005426 }
5427 }
5428}
5429
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005430/// \brief Add the parenthesized return or parameter type chunk to a code
5431/// completion string.
5432static void AddObjCPassingTypeChunk(QualType Type,
5433 ASTContext &Context,
5434 CodeCompletionBuilder &Builder) {
5435 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5436 Builder.AddTextChunk(GetCompletionTypeString(Type, Context,
5437 Builder.getAllocator()));
5438 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5439}
5440
5441/// \brief Determine whether the given class is or inherits from a class by
5442/// the given name.
5443static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
5444 llvm::StringRef Name) {
5445 if (!Class)
5446 return false;
5447
5448 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5449 return true;
5450
5451 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5452}
5453
5454/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5455/// Key-Value Observing (KVO).
5456static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5457 bool IsInstanceMethod,
5458 QualType ReturnType,
5459 ASTContext &Context,
5460 const KnownMethodsMap &KnownMethods,
5461 ResultBuilder &Results) {
5462 IdentifierInfo *PropName = Property->getIdentifier();
5463 if (!PropName || PropName->getLength() == 0)
5464 return;
5465
5466
5467 // Builder that will create each code completion.
5468 typedef CodeCompletionResult Result;
5469 CodeCompletionAllocator &Allocator = Results.getAllocator();
5470 CodeCompletionBuilder Builder(Allocator);
5471
5472 // The selector table.
5473 SelectorTable &Selectors = Context.Selectors;
5474
5475 // The property name, copied into the code completion allocation region
5476 // on demand.
5477 struct KeyHolder {
5478 CodeCompletionAllocator &Allocator;
5479 llvm::StringRef Key;
5480 const char *CopiedKey;
5481
5482 KeyHolder(CodeCompletionAllocator &Allocator, llvm::StringRef Key)
5483 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5484
5485 operator const char *() {
5486 if (CopiedKey)
5487 return CopiedKey;
5488
5489 return CopiedKey = Allocator.CopyString(Key);
5490 }
5491 } Key(Allocator, PropName->getName());
5492
5493 // The uppercased name of the property name.
5494 std::string UpperKey = PropName->getName();
5495 if (!UpperKey.empty())
5496 UpperKey[0] = toupper(UpperKey[0]);
5497
5498 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5499 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5500 Property->getType());
5501 bool ReturnTypeMatchesVoid
5502 = ReturnType.isNull() || ReturnType->isVoidType();
5503
5504 // Add the normal accessor -(type)key.
5505 if (IsInstanceMethod &&
5506 !KnownMethods.count(Selectors.getNullarySelector(PropName)) &&
5507 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5508 if (ReturnType.isNull())
5509 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5510
5511 Builder.AddTypedTextChunk(Key);
5512 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5513 CXCursor_ObjCInstanceMethodDecl));
5514 }
5515
5516 // If we have an integral or boolean property (or the user has provided
5517 // an integral or boolean return type), add the accessor -(type)isKey.
5518 if (IsInstanceMethod &&
5519 ((!ReturnType.isNull() &&
5520 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5521 (ReturnType.isNull() &&
5522 (Property->getType()->isIntegerType() ||
5523 Property->getType()->isBooleanType())))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005524 std::string SelectorName = (llvm::Twine("is") + UpperKey).str();
5525 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005526 if (!KnownMethods.count(Selectors.getNullarySelector(SelectorId))) {
5527 if (ReturnType.isNull()) {
5528 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5529 Builder.AddTextChunk("BOOL");
5530 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5531 }
5532
5533 Builder.AddTypedTextChunk(
5534 Allocator.CopyString(SelectorId->getName()));
5535 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5536 CXCursor_ObjCInstanceMethodDecl));
5537 }
5538 }
5539
5540 // Add the normal mutator.
5541 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5542 !Property->getSetterMethodDecl()) {
Douglas Gregor62041592011-02-17 03:19:26 +00005543 std::string SelectorName = (llvm::Twine("set") + UpperKey).str();
5544 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005545 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) {
5546 if (ReturnType.isNull()) {
5547 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5548 Builder.AddTextChunk("void");
5549 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5550 }
5551
5552 Builder.AddTypedTextChunk(
5553 Allocator.CopyString(SelectorId->getName()));
5554 Builder.AddTypedTextChunk(":");
5555 AddObjCPassingTypeChunk(Property->getType(), Context, Builder);
5556 Builder.AddTextChunk(Key);
5557 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5558 CXCursor_ObjCInstanceMethodDecl));
5559 }
5560 }
5561
5562 // Indexed and unordered accessors
5563 unsigned IndexedGetterPriority = CCP_CodePattern;
5564 unsigned IndexedSetterPriority = CCP_CodePattern;
5565 unsigned UnorderedGetterPriority = CCP_CodePattern;
5566 unsigned UnorderedSetterPriority = CCP_CodePattern;
5567 if (const ObjCObjectPointerType *ObjCPointer
5568 = Property->getType()->getAs<ObjCObjectPointerType>()) {
5569 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
5570 // If this interface type is not provably derived from a known
5571 // collection, penalize the corresponding completions.
5572 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
5573 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5574 if (!InheritsFromClassNamed(IFace, "NSArray"))
5575 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5576 }
5577
5578 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
5579 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5580 if (!InheritsFromClassNamed(IFace, "NSSet"))
5581 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5582 }
5583 }
5584 } else {
5585 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
5586 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
5587 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
5588 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
5589 }
5590
5591 // Add -(NSUInteger)countOf<key>
5592 if (IsInstanceMethod &&
5593 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005594 std::string SelectorName = (llvm::Twine("countOf") + UpperKey).str();
5595 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005596 if (!KnownMethods.count(Selectors.getNullarySelector(SelectorId))) {
5597 if (ReturnType.isNull()) {
5598 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5599 Builder.AddTextChunk("NSUInteger");
5600 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5601 }
5602
5603 Builder.AddTypedTextChunk(
5604 Allocator.CopyString(SelectorId->getName()));
5605 Results.AddResult(Result(Builder.TakeString(),
5606 std::min(IndexedGetterPriority,
5607 UnorderedGetterPriority),
5608 CXCursor_ObjCInstanceMethodDecl));
5609 }
5610 }
5611
5612 // Indexed getters
5613 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
5614 if (IsInstanceMethod &&
5615 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005616 std::string SelectorName
5617 = (llvm::Twine("objectIn") + UpperKey + "AtIndex").str();
5618 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005619 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) {
5620 if (ReturnType.isNull()) {
5621 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5622 Builder.AddTextChunk("id");
5623 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5624 }
5625
5626 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5627 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5628 Builder.AddTextChunk("NSUInteger");
5629 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5630 Builder.AddTextChunk("index");
5631 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5632 CXCursor_ObjCInstanceMethodDecl));
5633 }
5634 }
5635
5636 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
5637 if (IsInstanceMethod &&
5638 (ReturnType.isNull() ||
5639 (ReturnType->isObjCObjectPointerType() &&
5640 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
5641 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
5642 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005643 std::string SelectorName
5644 = (llvm::Twine(Property->getName()) + "AtIndexes").str();
5645 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005646 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) {
5647 if (ReturnType.isNull()) {
5648 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5649 Builder.AddTextChunk("NSArray *");
5650 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5651 }
5652
5653 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5654 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5655 Builder.AddTextChunk("NSIndexSet *");
5656 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5657 Builder.AddTextChunk("indexes");
5658 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5659 CXCursor_ObjCInstanceMethodDecl));
5660 }
5661 }
5662
5663 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
5664 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005665 std::string SelectorName = (llvm::Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005666 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005667 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005668 &Context.Idents.get("range")
5669 };
5670
5671 if (!KnownMethods.count(Selectors.getSelector(2, SelectorIds))) {
5672 if (ReturnType.isNull()) {
5673 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5674 Builder.AddTextChunk("void");
5675 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5676 }
5677
5678 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5679 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5680 Builder.AddPlaceholderChunk("object-type");
5681 Builder.AddTextChunk(" **");
5682 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5683 Builder.AddTextChunk("buffer");
5684 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5685 Builder.AddTypedTextChunk("range:");
5686 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5687 Builder.AddTextChunk("NSRange");
5688 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5689 Builder.AddTextChunk("inRange");
5690 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
5691 CXCursor_ObjCInstanceMethodDecl));
5692 }
5693 }
5694
5695 // Mutable indexed accessors
5696
5697 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
5698 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005699 std::string SelectorName = (llvm::Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005700 IdentifierInfo *SelectorIds[2] = {
5701 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00005702 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005703 };
5704
5705 if (!KnownMethods.count(Selectors.getSelector(2, SelectorIds))) {
5706 if (ReturnType.isNull()) {
5707 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5708 Builder.AddTextChunk("void");
5709 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5710 }
5711
5712 Builder.AddTypedTextChunk("insertObject:");
5713 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5714 Builder.AddPlaceholderChunk("object-type");
5715 Builder.AddTextChunk(" *");
5716 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5717 Builder.AddTextChunk("object");
5718 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5719 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5720 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5721 Builder.AddPlaceholderChunk("NSUInteger");
5722 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5723 Builder.AddTextChunk("index");
5724 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5725 CXCursor_ObjCInstanceMethodDecl));
5726 }
5727 }
5728
5729 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
5730 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005731 std::string SelectorName = (llvm::Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005732 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005733 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005734 &Context.Idents.get("atIndexes")
5735 };
5736
5737 if (!KnownMethods.count(Selectors.getSelector(2, SelectorIds))) {
5738 if (ReturnType.isNull()) {
5739 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5740 Builder.AddTextChunk("void");
5741 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5742 }
5743
5744 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5745 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5746 Builder.AddTextChunk("NSArray *");
5747 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5748 Builder.AddTextChunk("array");
5749 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5750 Builder.AddTypedTextChunk("atIndexes:");
5751 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5752 Builder.AddPlaceholderChunk("NSIndexSet *");
5753 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5754 Builder.AddTextChunk("indexes");
5755 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5756 CXCursor_ObjCInstanceMethodDecl));
5757 }
5758 }
5759
5760 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
5761 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005762 std::string SelectorName
5763 = (llvm::Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
5764 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005765 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) {
5766 if (ReturnType.isNull()) {
5767 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5768 Builder.AddTextChunk("void");
5769 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5770 }
5771
5772 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5773 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5774 Builder.AddTextChunk("NSUInteger");
5775 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5776 Builder.AddTextChunk("index");
5777 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5778 CXCursor_ObjCInstanceMethodDecl));
5779 }
5780 }
5781
5782 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
5783 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005784 std::string SelectorName
5785 = (llvm::Twine("remove") + UpperKey + "AtIndexes").str();
5786 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005787 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) {
5788 if (ReturnType.isNull()) {
5789 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5790 Builder.AddTextChunk("void");
5791 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5792 }
5793
5794 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5795 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5796 Builder.AddTextChunk("NSIndexSet *");
5797 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5798 Builder.AddTextChunk("indexes");
5799 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5800 CXCursor_ObjCInstanceMethodDecl));
5801 }
5802 }
5803
5804 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
5805 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005806 std::string SelectorName
5807 = (llvm::Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005808 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005809 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005810 &Context.Idents.get("withObject")
5811 };
5812
5813 if (!KnownMethods.count(Selectors.getSelector(2, SelectorIds))) {
5814 if (ReturnType.isNull()) {
5815 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5816 Builder.AddTextChunk("void");
5817 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5818 }
5819
5820 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5821 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5822 Builder.AddPlaceholderChunk("NSUInteger");
5823 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5824 Builder.AddTextChunk("index");
5825 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5826 Builder.AddTypedTextChunk("withObject:");
5827 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5828 Builder.AddTextChunk("id");
5829 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5830 Builder.AddTextChunk("object");
5831 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5832 CXCursor_ObjCInstanceMethodDecl));
5833 }
5834 }
5835
5836 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
5837 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005838 std::string SelectorName1
5839 = (llvm::Twine("replace") + UpperKey + "AtIndexes").str();
5840 std::string SelectorName2 = (llvm::Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005841 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00005842 &Context.Idents.get(SelectorName1),
5843 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005844 };
5845
5846 if (!KnownMethods.count(Selectors.getSelector(2, SelectorIds))) {
5847 if (ReturnType.isNull()) {
5848 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5849 Builder.AddTextChunk("void");
5850 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5851 }
5852
5853 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
5854 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5855 Builder.AddPlaceholderChunk("NSIndexSet *");
5856 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5857 Builder.AddTextChunk("indexes");
5858 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5859 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
5860 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5861 Builder.AddTextChunk("NSArray *");
5862 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5863 Builder.AddTextChunk("array");
5864 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
5865 CXCursor_ObjCInstanceMethodDecl));
5866 }
5867 }
5868
5869 // Unordered getters
5870 // - (NSEnumerator *)enumeratorOfKey
5871 if (IsInstanceMethod &&
5872 (ReturnType.isNull() ||
5873 (ReturnType->isObjCObjectPointerType() &&
5874 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
5875 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
5876 ->getName() == "NSEnumerator"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00005877 std::string SelectorName = (llvm::Twine("enumeratorOf") + UpperKey).str();
5878 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005879 if (!KnownMethods.count(Selectors.getNullarySelector(SelectorId))) {
5880 if (ReturnType.isNull()) {
5881 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5882 Builder.AddTextChunk("NSEnumerator *");
5883 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5884 }
5885
5886 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
5887 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
5888 CXCursor_ObjCInstanceMethodDecl));
5889 }
5890 }
5891
5892 // - (type *)memberOfKey:(type *)object
5893 if (IsInstanceMethod &&
5894 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00005895 std::string SelectorName = (llvm::Twine("memberOf") + UpperKey).str();
5896 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005897 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) {
5898 if (ReturnType.isNull()) {
5899 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5900 Builder.AddPlaceholderChunk("object-type");
5901 Builder.AddTextChunk(" *");
5902 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5903 }
5904
5905 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5906 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5907 if (ReturnType.isNull()) {
5908 Builder.AddPlaceholderChunk("object-type");
5909 Builder.AddTextChunk(" *");
5910 } else {
5911 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
5912 Builder.getAllocator()));
5913 }
5914 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5915 Builder.AddTextChunk("object");
5916 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
5917 CXCursor_ObjCInstanceMethodDecl));
5918 }
5919 }
5920
5921 // Mutable unordered accessors
5922 // - (void)addKeyObject:(type *)object
5923 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005924 std::string SelectorName
5925 = (llvm::Twine("add") + UpperKey + llvm::Twine("Object")).str();
5926 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005927 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) {
5928 if (ReturnType.isNull()) {
5929 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5930 Builder.AddTextChunk("void");
5931 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5932 }
5933
5934 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5935 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5936 Builder.AddPlaceholderChunk("object-type");
5937 Builder.AddTextChunk(" *");
5938 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5939 Builder.AddTextChunk("object");
5940 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
5941 CXCursor_ObjCInstanceMethodDecl));
5942 }
5943 }
5944
5945 // - (void)addKey:(NSSet *)objects
5946 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005947 std::string SelectorName = (llvm::Twine("add") + UpperKey).str();
5948 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005949 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) {
5950 if (ReturnType.isNull()) {
5951 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5952 Builder.AddTextChunk("void");
5953 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5954 }
5955
5956 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5957 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5958 Builder.AddTextChunk("NSSet *");
5959 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5960 Builder.AddTextChunk("objects");
5961 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
5962 CXCursor_ObjCInstanceMethodDecl));
5963 }
5964 }
5965
5966 // - (void)removeKeyObject:(type *)object
5967 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005968 std::string SelectorName
5969 = (llvm::Twine("remove") + UpperKey + llvm::Twine("Object")).str();
5970 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005971 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) {
5972 if (ReturnType.isNull()) {
5973 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5974 Builder.AddTextChunk("void");
5975 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5976 }
5977
5978 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
5979 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5980 Builder.AddPlaceholderChunk("object-type");
5981 Builder.AddTextChunk(" *");
5982 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5983 Builder.AddTextChunk("object");
5984 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
5985 CXCursor_ObjCInstanceMethodDecl));
5986 }
5987 }
5988
5989 // - (void)removeKey:(NSSet *)objects
5990 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00005991 std::string SelectorName = (llvm::Twine("remove") + UpperKey).str();
5992 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005993 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) {
5994 if (ReturnType.isNull()) {
5995 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5996 Builder.AddTextChunk("void");
5997 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5998 }
5999
6000 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6001 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6002 Builder.AddTextChunk("NSSet *");
6003 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6004 Builder.AddTextChunk("objects");
6005 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6006 CXCursor_ObjCInstanceMethodDecl));
6007 }
6008 }
6009
6010 // - (void)intersectKey:(NSSet *)objects
6011 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006012 std::string SelectorName = (llvm::Twine("intersect") + UpperKey).str();
6013 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006014 if (!KnownMethods.count(Selectors.getUnarySelector(SelectorId))) {
6015 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("NSSet *");
6024 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6025 Builder.AddTextChunk("objects");
6026 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6027 CXCursor_ObjCInstanceMethodDecl));
6028 }
6029 }
6030
6031 // Key-Value Observing
6032 // + (NSSet *)keyPathsForValuesAffectingKey
6033 if (!IsInstanceMethod &&
6034 (ReturnType.isNull() ||
6035 (ReturnType->isObjCObjectPointerType() &&
6036 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6037 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6038 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006039 std::string SelectorName
6040 = (llvm::Twine("keyPathsForValuesAffecting") + UpperKey).str();
6041 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006042 if (!KnownMethods.count(Selectors.getNullarySelector(SelectorId))) {
6043 if (ReturnType.isNull()) {
6044 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6045 Builder.AddTextChunk("NSSet *");
6046 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6047 }
6048
6049 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6050 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6051 CXCursor_ObjCInstanceMethodDecl));
6052 }
6053 }
6054}
6055
Douglas Gregore8f5a172010-04-07 00:21:17 +00006056void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6057 bool IsInstanceMethod,
John McCallb3d87482010-08-24 05:47:05 +00006058 ParsedType ReturnTy,
John McCalld226f652010-08-21 09:40:31 +00006059 Decl *IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006060 // Determine the return type of the method we're declaring, if
6061 // provided.
6062 QualType ReturnType = GetTypeFromParser(ReturnTy);
6063
Douglas Gregorea766182010-10-18 18:21:28 +00006064 // Determine where we should start searching for methods.
6065 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006066 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006067 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006068 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6069 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006070 IsInImplementation = true;
6071 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006072 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006073 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006074 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006075 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006076 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006077 }
6078
6079 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006080 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006081 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006082 }
6083
Douglas Gregorea766182010-10-18 18:21:28 +00006084 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006085 HandleCodeCompleteResults(this, CodeCompleter,
6086 CodeCompletionContext::CCC_Other,
6087 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006088 return;
6089 }
6090
6091 // Find all of the methods that we could declare/implement here.
6092 KnownMethodsMap KnownMethods;
6093 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006094 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006095
Douglas Gregore8f5a172010-04-07 00:21:17 +00006096 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006097 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006098 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6099 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006100 Results.EnterNewScope();
6101 PrintingPolicy Policy(Context.PrintingPolicy);
6102 Policy.AnonymousTagLocations = false;
6103 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6104 MEnd = KnownMethods.end();
6105 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006106 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006107 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006108
6109 // If the result type was not already provided, add it to the
6110 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006111 if (ReturnType.isNull())
6112 AddObjCPassingTypeChunk(Method->getResultType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006113
6114 Selector Sel = Method->getSelector();
6115
6116 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006117 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006118 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006119
6120 // Add parameters to the pattern.
6121 unsigned I = 0;
6122 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6123 PEnd = Method->param_end();
6124 P != PEnd; (void)++P, ++I) {
6125 // Add the part of the selector name.
6126 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006127 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006128 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006129 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6130 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006131 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006132 } else
6133 break;
6134
6135 // Add the parameter type.
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006136 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006137
6138 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006139 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006140 }
6141
6142 if (Method->isVariadic()) {
6143 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006144 Builder.AddChunk(CodeCompletionString::CK_Comma);
6145 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006146 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006147
Douglas Gregor447107d2010-05-28 00:57:46 +00006148 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006149 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006150 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6151 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6152 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006153 if (!Method->getResultType()->isVoidType()) {
6154 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006155 Builder.AddTextChunk("return");
6156 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6157 Builder.AddPlaceholderChunk("expression");
6158 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006159 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006160 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006161
Douglas Gregor218937c2011-02-01 19:23:04 +00006162 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6163 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006164 }
6165
Douglas Gregor408be5a2010-08-25 01:08:01 +00006166 unsigned Priority = CCP_CodePattern;
6167 if (!M->second.second)
6168 Priority += CCD_InBaseClass;
6169
Douglas Gregor218937c2011-02-01 19:23:04 +00006170 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006171 Method->isInstanceMethod()
6172 ? CXCursor_ObjCInstanceMethodDecl
6173 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006174 }
6175
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006176 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6177 // the properties in this class and its categories.
6178 if (Context.getLangOptions().ObjC2) {
6179 llvm::SmallVector<ObjCContainerDecl *, 4> Containers;
6180 Containers.push_back(SearchDecl);
6181
6182 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6183 if (!IFace)
6184 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6185 IFace = Category->getClassInterface();
6186
6187 if (IFace) {
6188 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6189 Category = Category->getNextClassCategory())
6190 Containers.push_back(Category);
6191 }
6192
6193 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6194 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6195 PEnd = Containers[I]->prop_end();
6196 P != PEnd; ++P) {
6197 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
6198 KnownMethods, Results);
6199 }
6200 }
6201 }
6202
Douglas Gregore8f5a172010-04-07 00:21:17 +00006203 Results.ExitScope();
6204
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006205 HandleCodeCompleteResults(this, CodeCompleter,
6206 CodeCompletionContext::CCC_Other,
6207 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006208}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006209
6210void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6211 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006212 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006213 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006214 IdentifierInfo **SelIdents,
6215 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006216 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006217 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006218 if (ExternalSource) {
6219 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6220 I != N; ++I) {
6221 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006222 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006223 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006224
6225 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006226 }
6227 }
6228
6229 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006230 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006231 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6232 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006233
6234 if (ReturnTy)
6235 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006236
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006237 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006238 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6239 MEnd = MethodPool.end();
6240 M != MEnd; ++M) {
6241 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6242 &M->second.second;
6243 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006244 MethList = MethList->Next) {
6245 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6246 NumSelIdents))
6247 continue;
6248
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006249 if (AtParameterName) {
6250 // Suggest parameter names we've seen before.
6251 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6252 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6253 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006254 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006255 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006256 Param->getIdentifier()->getName()));
6257 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006258 }
6259 }
6260
6261 continue;
6262 }
6263
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006264 Result R(MethList->Method, 0);
6265 R.StartParameter = NumSelIdents;
6266 R.AllParametersAreInformative = false;
6267 R.DeclaringEntity = true;
6268 Results.MaybeAddResult(R, CurContext);
6269 }
6270 }
6271
6272 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006273 HandleCodeCompleteResults(this, CodeCompleter,
6274 CodeCompletionContext::CCC_Other,
6275 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006276}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006277
Douglas Gregorf29c5232010-08-24 22:20:20 +00006278void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006279 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006280 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006281 Results.EnterNewScope();
6282
6283 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006284 CodeCompletionBuilder Builder(Results.getAllocator());
6285 Builder.AddTypedTextChunk("if");
6286 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6287 Builder.AddPlaceholderChunk("condition");
6288 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006289
6290 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006291 Builder.AddTypedTextChunk("ifdef");
6292 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6293 Builder.AddPlaceholderChunk("macro");
6294 Results.AddResult(Builder.TakeString());
6295
Douglas Gregorf44e8542010-08-24 19:08:16 +00006296 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006297 Builder.AddTypedTextChunk("ifndef");
6298 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6299 Builder.AddPlaceholderChunk("macro");
6300 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006301
6302 if (InConditional) {
6303 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006304 Builder.AddTypedTextChunk("elif");
6305 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6306 Builder.AddPlaceholderChunk("condition");
6307 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006308
6309 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006310 Builder.AddTypedTextChunk("else");
6311 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006312
6313 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006314 Builder.AddTypedTextChunk("endif");
6315 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006316 }
6317
6318 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006319 Builder.AddTypedTextChunk("include");
6320 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6321 Builder.AddTextChunk("\"");
6322 Builder.AddPlaceholderChunk("header");
6323 Builder.AddTextChunk("\"");
6324 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006325
6326 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006327 Builder.AddTypedTextChunk("include");
6328 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6329 Builder.AddTextChunk("<");
6330 Builder.AddPlaceholderChunk("header");
6331 Builder.AddTextChunk(">");
6332 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006333
6334 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006335 Builder.AddTypedTextChunk("define");
6336 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6337 Builder.AddPlaceholderChunk("macro");
6338 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006339
6340 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006341 Builder.AddTypedTextChunk("define");
6342 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6343 Builder.AddPlaceholderChunk("macro");
6344 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6345 Builder.AddPlaceholderChunk("args");
6346 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6347 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006348
6349 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006350 Builder.AddTypedTextChunk("undef");
6351 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6352 Builder.AddPlaceholderChunk("macro");
6353 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006354
6355 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006356 Builder.AddTypedTextChunk("line");
6357 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6358 Builder.AddPlaceholderChunk("number");
6359 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006360
6361 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006362 Builder.AddTypedTextChunk("line");
6363 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6364 Builder.AddPlaceholderChunk("number");
6365 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6366 Builder.AddTextChunk("\"");
6367 Builder.AddPlaceholderChunk("filename");
6368 Builder.AddTextChunk("\"");
6369 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006370
6371 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006372 Builder.AddTypedTextChunk("error");
6373 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6374 Builder.AddPlaceholderChunk("message");
6375 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006376
6377 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006378 Builder.AddTypedTextChunk("pragma");
6379 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6380 Builder.AddPlaceholderChunk("arguments");
6381 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006382
6383 if (getLangOptions().ObjC1) {
6384 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006385 Builder.AddTypedTextChunk("import");
6386 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6387 Builder.AddTextChunk("\"");
6388 Builder.AddPlaceholderChunk("header");
6389 Builder.AddTextChunk("\"");
6390 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006391
6392 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006393 Builder.AddTypedTextChunk("import");
6394 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6395 Builder.AddTextChunk("<");
6396 Builder.AddPlaceholderChunk("header");
6397 Builder.AddTextChunk(">");
6398 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006399 }
6400
6401 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006402 Builder.AddTypedTextChunk("include_next");
6403 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6404 Builder.AddTextChunk("\"");
6405 Builder.AddPlaceholderChunk("header");
6406 Builder.AddTextChunk("\"");
6407 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006408
6409 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006410 Builder.AddTypedTextChunk("include_next");
6411 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6412 Builder.AddTextChunk("<");
6413 Builder.AddPlaceholderChunk("header");
6414 Builder.AddTextChunk(">");
6415 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006416
6417 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006418 Builder.AddTypedTextChunk("warning");
6419 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6420 Builder.AddPlaceholderChunk("message");
6421 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006422
6423 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6424 // completions for them. And __include_macros is a Clang-internal extension
6425 // that we don't want to encourage anyone to use.
6426
6427 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6428 Results.ExitScope();
6429
Douglas Gregorf44e8542010-08-24 19:08:16 +00006430 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006431 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006432 Results.data(), Results.size());
6433}
6434
6435void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006436 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006437 S->getFnParent()? Sema::PCC_RecoveryInFunction
6438 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006439}
6440
Douglas Gregorf29c5232010-08-24 22:20:20 +00006441void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006442 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006443 IsDefinition? CodeCompletionContext::CCC_MacroName
6444 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006445 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6446 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006447 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006448 Results.EnterNewScope();
6449 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6450 MEnd = PP.macro_end();
6451 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006452 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006453 M->first->getName()));
6454 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006455 }
6456 Results.ExitScope();
6457 } else if (IsDefinition) {
6458 // FIXME: Can we detect when the user just wrote an include guard above?
6459 }
6460
Douglas Gregor52779fb2010-09-23 23:01:17 +00006461 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006462 Results.data(), Results.size());
6463}
6464
Douglas Gregorf29c5232010-08-24 22:20:20 +00006465void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006466 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006467 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006468
6469 if (!CodeCompleter || CodeCompleter->includeMacros())
6470 AddMacroResults(PP, Results);
6471
6472 // defined (<macro>)
6473 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006474 CodeCompletionBuilder Builder(Results.getAllocator());
6475 Builder.AddTypedTextChunk("defined");
6476 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6477 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6478 Builder.AddPlaceholderChunk("macro");
6479 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6480 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006481 Results.ExitScope();
6482
6483 HandleCodeCompleteResults(this, CodeCompleter,
6484 CodeCompletionContext::CCC_PreprocessorExpression,
6485 Results.data(), Results.size());
6486}
6487
6488void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6489 IdentifierInfo *Macro,
6490 MacroInfo *MacroInfo,
6491 unsigned Argument) {
6492 // FIXME: In the future, we could provide "overload" results, much like we
6493 // do for function calls.
6494
6495 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006496 S->getFnParent()? Sema::PCC_RecoveryInFunction
6497 : Sema::PCC_Namespace);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006498}
6499
Douglas Gregor55817af2010-08-25 17:04:25 +00006500void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006501 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006502 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006503 0, 0);
6504}
6505
Douglas Gregordae68752011-02-01 22:57:45 +00006506void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
John McCall0a2c5e22010-08-25 06:19:51 +00006507 llvm::SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006508 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006509 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6510 CodeCompletionDeclConsumer Consumer(Builder,
6511 Context.getTranslationUnitDecl());
6512 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6513 Consumer);
6514 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006515
6516 if (!CodeCompleter || CodeCompleter->includeMacros())
6517 AddMacroResults(PP, Builder);
6518
6519 Results.clear();
6520 Results.insert(Results.end(),
6521 Builder.data(), Builder.data() + Builder.size());
6522}