blob: c280ac2990783410d0784fdca04145118ff7350b [file] [log] [blame]
Douglas Gregor81b747b2009-09-17 21:32:03 +00001//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the code-completion semantic actions.
11//
12//===----------------------------------------------------------------------===//
John McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Lookup.h"
John McCall120d63c2010-08-24 20:38:10 +000015#include "clang/Sema/Overload.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000016#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregor719770d2010-04-06 17:30:22 +000017#include "clang/Sema/ExternalSemaSource.h"
John McCall5f1e0942010-08-24 08:50:51 +000018#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorb9d0ef72009-09-21 19:57:38 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor24a069f2009-11-17 17:59:40 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor3f7c7f42009-10-30 16:50:04 +000023#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
Douglas Gregord36adf52010-09-16 16:06:31 +000025#include "llvm/ADT/DenseSet.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000026#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor6a684032009-09-28 03:51:44 +000027#include "llvm/ADT/StringExtras.h"
Douglas Gregor22f56992010-04-06 19:22:33 +000028#include "llvm/ADT/StringSwitch.h"
Douglas Gregor458433d2010-08-26 15:07:07 +000029#include "llvm/ADT/Twine.h"
Douglas Gregor86d9a522009-09-21 16:56:56 +000030#include <list>
31#include <map>
32#include <vector>
Douglas Gregor81b747b2009-09-17 21:32:03 +000033
34using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000035using namespace sema;
Douglas Gregor81b747b2009-09-17 21:32:03 +000036
Douglas Gregor86d9a522009-09-21 16:56:56 +000037namespace {
38 /// \brief A container of code-completion results.
39 class ResultBuilder {
40 public:
41 /// \brief The type of a name-lookup filter, which can be provided to the
42 /// name-lookup routines to specify which declarations should be included in
43 /// the result set (when it returns true) and which declarations should be
44 /// filtered out (returns false).
45 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
46
John McCall0a2c5e22010-08-25 06:19:51 +000047 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +000048
49 private:
50 /// \brief The actual results we have found.
51 std::vector<Result> Results;
52
53 /// \brief A record of all of the declarations we have found and placed
54 /// into the result set, used to ensure that no declaration ever gets into
55 /// the result set twice.
56 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
57
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000058 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
59
60 /// \brief An entry in the shadow map, which is optimized to store
61 /// a single (declaration, index) mapping (the common case) but
62 /// can also store a list of (declaration, index) mappings.
63 class ShadowMapEntry {
Chris Lattner5f9e2722011-07-23 10:55:15 +000064 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
Douglas Gregorfbcb5d62009-12-06 20:23:50 +000065
66 /// \brief Contains either the solitary NamedDecl * or a vector
67 /// of (declaration, index) pairs.
68 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
69
70 /// \brief When the entry contains a single declaration, this is
71 /// the index associated with that entry.
72 unsigned SingleDeclIndex;
73
74 public:
75 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
76
77 void Add(NamedDecl *ND, unsigned Index) {
78 if (DeclOrVector.isNull()) {
79 // 0 - > 1 elements: just set the single element information.
80 DeclOrVector = ND;
81 SingleDeclIndex = Index;
82 return;
83 }
84
85 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
86 // 1 -> 2 elements: create the vector of results and push in the
87 // existing declaration.
88 DeclIndexPairVector *Vec = new DeclIndexPairVector;
89 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
90 DeclOrVector = Vec;
91 }
92
93 // Add the new element to the end of the vector.
94 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
95 DeclIndexPair(ND, Index));
96 }
97
98 void Destroy() {
99 if (DeclIndexPairVector *Vec
100 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
101 delete Vec;
102 DeclOrVector = ((NamedDecl *)0);
103 }
104 }
105
106 // Iteration.
107 class iterator;
108 iterator begin() const;
109 iterator end() const;
110 };
111
Douglas Gregor86d9a522009-09-21 16:56:56 +0000112 /// \brief A mapping from declaration names to the declarations that have
113 /// this name within a particular scope and their index within the list of
114 /// results.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000115 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000116
117 /// \brief The semantic analysis object for which results are being
118 /// produced.
119 Sema &SemaRef;
Douglas Gregor218937c2011-02-01 19:23:04 +0000120
121 /// \brief The allocator used to allocate new code-completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000122 CodeCompletionAllocator &Allocator;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000123
124 /// \brief If non-NULL, a filter function used to remove any code-completion
125 /// results that are not desirable.
126 LookupFilter Filter;
Douglas Gregor45bcd432010-01-14 03:21:49 +0000127
128 /// \brief Whether we should allow declarations as
129 /// nested-name-specifiers that would otherwise be filtered out.
130 bool AllowNestedNameSpecifiers;
131
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000132 /// \brief If set, the type that we would prefer our resulting value
133 /// declarations to have.
134 ///
135 /// Closely matching the preferred type gives a boost to a result's
136 /// priority.
137 CanQualType PreferredType;
138
Douglas Gregor86d9a522009-09-21 16:56:56 +0000139 /// \brief A list of shadow maps, which is used to model name hiding at
140 /// different levels of, e.g., the inheritance hierarchy.
141 std::list<ShadowMap> ShadowMaps;
142
Douglas Gregor3cdee122010-08-26 16:36:48 +0000143 /// \brief If we're potentially referring to a C++ member function, the set
144 /// of qualifiers applied to the object type.
145 Qualifiers ObjectTypeQualifiers;
146
147 /// \brief Whether the \p ObjectTypeQualifiers field is active.
148 bool HasObjectTypeQualifiers;
149
Douglas Gregor265f7492010-08-27 15:29:55 +0000150 /// \brief The selector that we prefer.
151 Selector PreferredSelector;
152
Douglas Gregorca45da02010-11-02 20:36:02 +0000153 /// \brief The completion context in which we are gathering results.
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000154 CodeCompletionContext CompletionContext;
155
Douglas Gregorca45da02010-11-02 20:36:02 +0000156 /// \brief If we are in an instance method definition, the @implementation
157 /// object.
158 ObjCImplementationDecl *ObjCImplementation;
159
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000160 void AdjustResultPriorityForDecl(Result &R);
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000161
Douglas Gregor6f942b22010-09-21 16:06:22 +0000162 void MaybeAddConstructorResults(Result R);
163
Douglas Gregor86d9a522009-09-21 16:56:56 +0000164 public:
Douglas Gregordae68752011-02-01 22:57:45 +0000165 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
Douglas Gregor52779fb2010-09-23 23:01:17 +0000166 const CodeCompletionContext &CompletionContext,
167 LookupFilter Filter = 0)
Douglas Gregor218937c2011-02-01 19:23:04 +0000168 : SemaRef(SemaRef), Allocator(Allocator), Filter(Filter),
169 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
Douglas Gregorca45da02010-11-02 20:36:02 +0000170 CompletionContext(CompletionContext),
171 ObjCImplementation(0)
172 {
173 // If this is an Objective-C instance method definition, dig out the
174 // corresponding implementation.
175 switch (CompletionContext.getKind()) {
176 case CodeCompletionContext::CCC_Expression:
177 case CodeCompletionContext::CCC_ObjCMessageReceiver:
178 case CodeCompletionContext::CCC_ParenthesizedExpression:
179 case CodeCompletionContext::CCC_Statement:
180 case CodeCompletionContext::CCC_Recovery:
181 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
182 if (Method->isInstanceMethod())
183 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
184 ObjCImplementation = Interface->getImplementation();
185 break;
186
187 default:
188 break;
189 }
190 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000191
Douglas Gregord8e8a582010-05-25 21:41:55 +0000192 /// \brief Whether we should include code patterns in the completion
193 /// results.
194 bool includeCodePatterns() const {
195 return SemaRef.CodeCompleter &&
Douglas Gregorf6961522010-08-27 21:18:54 +0000196 SemaRef.CodeCompleter->includeCodePatterns();
Douglas Gregord8e8a582010-05-25 21:41:55 +0000197 }
198
Douglas Gregor86d9a522009-09-21 16:56:56 +0000199 /// \brief Set the filter used for code-completion results.
200 void setFilter(LookupFilter Filter) {
201 this->Filter = Filter;
202 }
203
Douglas Gregor86d9a522009-09-21 16:56:56 +0000204 Result *data() { return Results.empty()? 0 : &Results.front(); }
205 unsigned size() const { return Results.size(); }
206 bool empty() const { return Results.empty(); }
207
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000208 /// \brief Specify the preferred type.
209 void setPreferredType(QualType T) {
210 PreferredType = SemaRef.Context.getCanonicalType(T);
211 }
212
Douglas Gregor3cdee122010-08-26 16:36:48 +0000213 /// \brief Set the cv-qualifiers on the object type, for us in filtering
214 /// calls to member functions.
215 ///
216 /// When there are qualifiers in this set, they will be used to filter
217 /// out member functions that aren't available (because there will be a
218 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
219 /// match.
220 void setObjectTypeQualifiers(Qualifiers Quals) {
221 ObjectTypeQualifiers = Quals;
222 HasObjectTypeQualifiers = true;
223 }
224
Douglas Gregor265f7492010-08-27 15:29:55 +0000225 /// \brief Set the preferred selector.
226 ///
227 /// When an Objective-C method declaration result is added, and that
228 /// method's selector matches this preferred selector, we give that method
229 /// a slight priority boost.
230 void setPreferredSelector(Selector Sel) {
231 PreferredSelector = Sel;
232 }
Douglas Gregorca45da02010-11-02 20:36:02 +0000233
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000234 /// \brief Retrieve the code-completion context for which results are
235 /// being collected.
236 const CodeCompletionContext &getCompletionContext() const {
237 return CompletionContext;
238 }
239
Douglas Gregor45bcd432010-01-14 03:21:49 +0000240 /// \brief Specify whether nested-name-specifiers are allowed.
241 void allowNestedNameSpecifiers(bool Allow = true) {
242 AllowNestedNameSpecifiers = Allow;
243 }
244
Douglas Gregorb9d77572010-09-21 00:03:25 +0000245 /// \brief Return the semantic analysis object for which we are collecting
246 /// code completion results.
247 Sema &getSema() const { return SemaRef; }
248
Douglas Gregor218937c2011-02-01 19:23:04 +0000249 /// \brief Retrieve the allocator used to allocate code completion strings.
Douglas Gregordae68752011-02-01 22:57:45 +0000250 CodeCompletionAllocator &getAllocator() const { return Allocator; }
Douglas Gregor218937c2011-02-01 19:23:04 +0000251
Douglas Gregore495b7f2010-01-14 00:20:49 +0000252 /// \brief Determine whether the given declaration is at all interesting
253 /// as a code-completion result.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000254 ///
255 /// \param ND the declaration that we are inspecting.
256 ///
257 /// \param AsNestedNameSpecifier will be set true if this declaration is
258 /// only interesting when it is a nested-name-specifier.
259 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
Douglas Gregor6660d842010-01-14 00:41:07 +0000260
261 /// \brief Check whether the result is hidden by the Hiding declaration.
262 ///
263 /// \returns true if the result is hidden and cannot be found, false if
264 /// the hidden result could still be found. When false, \p R may be
265 /// modified to describe how the result can be found (e.g., via extra
266 /// qualification).
267 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
268 NamedDecl *Hiding);
269
Douglas Gregor86d9a522009-09-21 16:56:56 +0000270 /// \brief Add a new result to this result set (if it isn't already in one
271 /// of the shadow maps), or replace an existing result (for, e.g., a
272 /// redeclaration).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000273 ///
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000274 /// \param CurContext the result to add (if it is unique).
Douglas Gregor456c4a12009-09-21 20:12:40 +0000275 ///
276 /// \param R the context in which this result will be named.
277 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000278
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000279 /// \brief Add a new result to this result set, where we already know
280 /// the hiding declation (if any).
281 ///
282 /// \param R the result to add (if it is unique).
283 ///
284 /// \param CurContext the context in which this result will be named.
285 ///
286 /// \param Hiding the declaration that hides the result.
Douglas Gregor0cc84042010-01-14 15:47:35 +0000287 ///
288 /// \param InBaseClass whether the result was found in a base
289 /// class of the searched context.
290 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
291 bool InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000292
Douglas Gregora4477812010-01-14 16:01:26 +0000293 /// \brief Add a new non-declaration result to this result set.
294 void AddResult(Result R);
295
Douglas Gregor86d9a522009-09-21 16:56:56 +0000296 /// \brief Enter into a new scope.
297 void EnterNewScope();
298
299 /// \brief Exit from the current scope.
300 void ExitScope();
301
Douglas Gregor55385fe2009-11-18 04:19:12 +0000302 /// \brief Ignore this declaration, if it is seen again.
303 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
304
Douglas Gregor86d9a522009-09-21 16:56:56 +0000305 /// \name Name lookup predicates
306 ///
307 /// These predicates can be passed to the name lookup functions to filter the
308 /// results of name lookup. All of the predicates have the same type, so that
309 ///
310 //@{
Douglas Gregor791215b2009-09-21 20:51:25 +0000311 bool IsOrdinaryName(NamedDecl *ND) const;
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000312 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
Douglas Gregorf9578432010-07-28 21:50:18 +0000313 bool IsIntegralConstantValue(NamedDecl *ND) const;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000314 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000315 bool IsNestedNameSpecifier(NamedDecl *ND) const;
316 bool IsEnum(NamedDecl *ND) const;
317 bool IsClassOrStruct(NamedDecl *ND) const;
318 bool IsUnion(NamedDecl *ND) const;
319 bool IsNamespace(NamedDecl *ND) const;
320 bool IsNamespaceOrAlias(NamedDecl *ND) const;
321 bool IsType(NamedDecl *ND) const;
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000322 bool IsMember(NamedDecl *ND) const;
Douglas Gregor80f4f4c2010-01-14 16:08:12 +0000323 bool IsObjCIvar(NamedDecl *ND) const;
Douglas Gregor8e254cf2010-05-27 23:06:34 +0000324 bool IsObjCMessageReceiver(NamedDecl *ND) const;
Douglas Gregorfb629412010-08-23 21:17:50 +0000325 bool IsObjCCollection(NamedDecl *ND) const;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000326 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000327 //@}
328 };
329}
330
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000331class ResultBuilder::ShadowMapEntry::iterator {
332 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
333 unsigned SingleDeclIndex;
334
335public:
336 typedef DeclIndexPair value_type;
337 typedef value_type reference;
338 typedef std::ptrdiff_t difference_type;
339 typedef std::input_iterator_tag iterator_category;
340
341 class pointer {
342 DeclIndexPair Value;
343
344 public:
345 pointer(const DeclIndexPair &Value) : Value(Value) { }
346
347 const DeclIndexPair *operator->() const {
348 return &Value;
349 }
350 };
351
352 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
353
354 iterator(NamedDecl *SingleDecl, unsigned Index)
355 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
356
357 iterator(const DeclIndexPair *Iterator)
358 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
359
360 iterator &operator++() {
361 if (DeclOrIterator.is<NamedDecl *>()) {
362 DeclOrIterator = (NamedDecl *)0;
363 SingleDeclIndex = 0;
364 return *this;
365 }
366
367 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
368 ++I;
369 DeclOrIterator = I;
370 return *this;
371 }
372
Chris Lattner66392d42010-09-04 18:12:20 +0000373 /*iterator operator++(int) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000374 iterator tmp(*this);
375 ++(*this);
376 return tmp;
Chris Lattner66392d42010-09-04 18:12:20 +0000377 }*/
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000378
379 reference operator*() const {
380 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
381 return reference(ND, SingleDeclIndex);
382
Douglas Gregord490f952009-12-06 21:27:58 +0000383 return *DeclOrIterator.get<const DeclIndexPair*>();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000384 }
385
386 pointer operator->() const {
387 return pointer(**this);
388 }
389
390 friend bool operator==(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000391 return X.DeclOrIterator.getOpaqueValue()
392 == Y.DeclOrIterator.getOpaqueValue() &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000393 X.SingleDeclIndex == Y.SingleDeclIndex;
394 }
395
396 friend bool operator!=(const iterator &X, const iterator &Y) {
Douglas Gregord490f952009-12-06 21:27:58 +0000397 return !(X == Y);
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000398 }
399};
400
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000401ResultBuilder::ShadowMapEntry::iterator
402ResultBuilder::ShadowMapEntry::begin() const {
403 if (DeclOrVector.isNull())
404 return iterator();
405
406 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
407 return iterator(ND, SingleDeclIndex);
408
409 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
410}
411
412ResultBuilder::ShadowMapEntry::iterator
413ResultBuilder::ShadowMapEntry::end() const {
414 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
415 return iterator();
416
417 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
418}
419
Douglas Gregor456c4a12009-09-21 20:12:40 +0000420/// \brief Compute the qualification required to get from the current context
421/// (\p CurContext) to the target context (\p TargetContext).
422///
423/// \param Context the AST context in which the qualification will be used.
424///
425/// \param CurContext the context where an entity is being named, which is
426/// typically based on the current scope.
427///
428/// \param TargetContext the context in which the named entity actually
429/// resides.
430///
431/// \returns a nested name specifier that refers into the target context, or
432/// NULL if no qualification is needed.
433static NestedNameSpecifier *
434getRequiredQualification(ASTContext &Context,
435 DeclContext *CurContext,
436 DeclContext *TargetContext) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000437 SmallVector<DeclContext *, 4> TargetParents;
Douglas Gregor456c4a12009-09-21 20:12:40 +0000438
439 for (DeclContext *CommonAncestor = TargetContext;
440 CommonAncestor && !CommonAncestor->Encloses(CurContext);
441 CommonAncestor = CommonAncestor->getLookupParent()) {
442 if (CommonAncestor->isTransparentContext() ||
443 CommonAncestor->isFunctionOrMethod())
444 continue;
445
446 TargetParents.push_back(CommonAncestor);
447 }
448
449 NestedNameSpecifier *Result = 0;
450 while (!TargetParents.empty()) {
451 DeclContext *Parent = TargetParents.back();
452 TargetParents.pop_back();
453
Douglas Gregorfb629412010-08-23 21:17:50 +0000454 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
455 if (!Namespace->getIdentifier())
456 continue;
457
Douglas Gregor456c4a12009-09-21 20:12:40 +0000458 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
Douglas Gregorfb629412010-08-23 21:17:50 +0000459 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000460 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
461 Result = NestedNameSpecifier::Create(Context, Result,
462 false,
463 Context.getTypeDeclType(TD).getTypePtr());
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000464 }
Douglas Gregor456c4a12009-09-21 20:12:40 +0000465 return Result;
466}
467
Douglas Gregor45bcd432010-01-14 03:21:49 +0000468bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
469 bool &AsNestedNameSpecifier) const {
470 AsNestedNameSpecifier = false;
471
Douglas Gregore495b7f2010-01-14 00:20:49 +0000472 ND = ND->getUnderlyingDecl();
473 unsigned IDNS = ND->getIdentifierNamespace();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000474
475 // Skip unnamed entities.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000476 if (!ND->getDeclName())
477 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000478
479 // Friend declarations and declarations introduced due to friends are never
480 // added as results.
John McCall92b7f702010-03-11 07:50:04 +0000481 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000482 return false;
483
Douglas Gregor76282942009-12-11 17:31:05 +0000484 // Class template (partial) specializations are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000485 if (isa<ClassTemplateSpecializationDecl>(ND) ||
486 isa<ClassTemplatePartialSpecializationDecl>(ND))
487 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000488
Douglas Gregor76282942009-12-11 17:31:05 +0000489 // Using declarations themselves are never added as results.
Douglas Gregore495b7f2010-01-14 00:20:49 +0000490 if (isa<UsingDecl>(ND))
491 return false;
492
493 // Some declarations have reserved names that we don't want to ever show.
494 if (const IdentifierInfo *Id = ND->getIdentifier()) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000495 // __va_list_tag is a freak of nature. Find it and skip it.
496 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000497 return false;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000498
Douglas Gregorf52cede2009-10-09 22:16:47 +0000499 // Filter out names reserved for the implementation (C99 7.1.3,
Douglas Gregor797efb52010-07-14 17:44:04 +0000500 // C++ [lib.global.names]) if they come from a system header.
Daniel Dunbare013d682009-10-18 20:26:12 +0000501 //
502 // FIXME: Add predicate for this.
Douglas Gregorf52cede2009-10-09 22:16:47 +0000503 if (Id->getLength() >= 2) {
Daniel Dunbare013d682009-10-18 20:26:12 +0000504 const char *Name = Id->getNameStart();
Douglas Gregorf52cede2009-10-09 22:16:47 +0000505 if (Name[0] == '_' &&
Douglas Gregor797efb52010-07-14 17:44:04 +0000506 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
507 (ND->getLocation().isInvalid() ||
508 SemaRef.SourceMgr.isInSystemHeader(
509 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000510 return false;
Douglas Gregorf52cede2009-10-09 22:16:47 +0000511 }
Douglas Gregor86d9a522009-09-21 16:56:56 +0000512 }
Douglas Gregor6f942b22010-09-21 16:06:22 +0000513
Douglas Gregor9b0ba872010-11-09 03:59:40 +0000514 // Skip out-of-line declarations and definitions.
515 // NOTE: Unless it's an Objective-C property, method, or ivar, where
516 // the contexts can be messy.
517 if (!ND->getDeclContext()->Equals(ND->getLexicalDeclContext()) &&
518 !(isa<ObjCPropertyDecl>(ND) || isa<ObjCIvarDecl>(ND) ||
519 isa<ObjCMethodDecl>(ND)))
520 return false;
521
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000522 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
523 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
524 Filter != &ResultBuilder::IsNamespace &&
Douglas Gregor52779fb2010-09-23 23:01:17 +0000525 Filter != &ResultBuilder::IsNamespaceOrAlias &&
526 Filter != 0))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000527 AsNestedNameSpecifier = true;
528
Douglas Gregor86d9a522009-09-21 16:56:56 +0000529 // Filter out any unwanted results.
Douglas Gregor45bcd432010-01-14 03:21:49 +0000530 if (Filter && !(this->*Filter)(ND)) {
531 // Check whether it is interesting as a nested-name-specifier.
532 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
533 IsNestedNameSpecifier(ND) &&
534 (Filter != &ResultBuilder::IsMember ||
535 (isa<CXXRecordDecl>(ND) &&
536 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
537 AsNestedNameSpecifier = true;
538 return true;
539 }
540
Douglas Gregore495b7f2010-01-14 00:20:49 +0000541 return false;
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000542 }
Douglas Gregore495b7f2010-01-14 00:20:49 +0000543 // ... then it must be interesting!
544 return true;
545}
546
Douglas Gregor6660d842010-01-14 00:41:07 +0000547bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
548 NamedDecl *Hiding) {
549 // In C, there is no way to refer to a hidden name.
550 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
551 // name if we introduce the tag type.
552 if (!SemaRef.getLangOptions().CPlusPlus)
553 return true;
554
Sebastian Redl7a126a42010-08-31 00:36:30 +0000555 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
Douglas Gregor6660d842010-01-14 00:41:07 +0000556
557 // There is no way to qualify a name declared in a function or method.
558 if (HiddenCtx->isFunctionOrMethod())
559 return true;
560
Sebastian Redl7a126a42010-08-31 00:36:30 +0000561 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
Douglas Gregor6660d842010-01-14 00:41:07 +0000562 return true;
563
564 // We can refer to the result with the appropriate qualification. Do it.
565 R.Hidden = true;
566 R.QualifierIsInformative = false;
567
568 if (!R.Qualifier)
569 R.Qualifier = getRequiredQualification(SemaRef.Context,
570 CurContext,
571 R.Declaration->getDeclContext());
572 return false;
573}
574
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000575/// \brief A simplified classification of types used to determine whether two
576/// types are "similar enough" when adjusting priorities.
Douglas Gregor1827e102010-08-16 16:18:59 +0000577SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000578 switch (T->getTypeClass()) {
579 case Type::Builtin:
580 switch (cast<BuiltinType>(T)->getKind()) {
581 case BuiltinType::Void:
582 return STC_Void;
583
584 case BuiltinType::NullPtr:
585 return STC_Pointer;
586
587 case BuiltinType::Overload:
588 case BuiltinType::Dependent:
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000589 return STC_Other;
590
591 case BuiltinType::ObjCId:
592 case BuiltinType::ObjCClass:
593 case BuiltinType::ObjCSel:
594 return STC_ObjectiveC;
595
596 default:
597 return STC_Arithmetic;
598 }
599 return STC_Other;
600
601 case Type::Complex:
602 return STC_Arithmetic;
603
604 case Type::Pointer:
605 return STC_Pointer;
606
607 case Type::BlockPointer:
608 return STC_Block;
609
610 case Type::LValueReference:
611 case Type::RValueReference:
612 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
613
614 case Type::ConstantArray:
615 case Type::IncompleteArray:
616 case Type::VariableArray:
617 case Type::DependentSizedArray:
618 return STC_Array;
619
620 case Type::DependentSizedExtVector:
621 case Type::Vector:
622 case Type::ExtVector:
623 return STC_Arithmetic;
624
625 case Type::FunctionProto:
626 case Type::FunctionNoProto:
627 return STC_Function;
628
629 case Type::Record:
630 return STC_Record;
631
632 case Type::Enum:
633 return STC_Arithmetic;
634
635 case Type::ObjCObject:
636 case Type::ObjCInterface:
637 case Type::ObjCObjectPointer:
638 return STC_ObjectiveC;
639
640 default:
641 return STC_Other;
642 }
643}
644
645/// \brief Get the type that a given expression will have if this declaration
646/// is used as an expression in its "typical" code-completion form.
Douglas Gregor1827e102010-08-16 16:18:59 +0000647QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000648 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
649
650 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
651 return C.getTypeDeclType(Type);
652 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
653 return C.getObjCInterfaceType(Iface);
654
655 QualType T;
656 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000657 T = Function->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000658 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000659 T = Method->getSendResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000660 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000661 T = FunTmpl->getTemplatedDecl()->getCallResultType();
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000662 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
663 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
664 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
665 T = Property->getType();
666 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
667 T = Value->getType();
668 else
669 return QualType();
Douglas Gregor3e64d562011-04-14 20:33:34 +0000670
671 // Dig through references, function pointers, and block pointers to
672 // get down to the likely type of an expression when the entity is
673 // used.
674 do {
675 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
676 T = Ref->getPointeeType();
677 continue;
678 }
679
680 if (const PointerType *Pointer = T->getAs<PointerType>()) {
681 if (Pointer->getPointeeType()->isFunctionType()) {
682 T = Pointer->getPointeeType();
683 continue;
684 }
685
686 break;
687 }
688
689 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
690 T = Block->getPointeeType();
691 continue;
692 }
693
694 if (const FunctionType *Function = T->getAs<FunctionType>()) {
695 T = Function->getResultType();
696 continue;
697 }
698
699 break;
700 } while (true);
701
702 return T;
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000703}
704
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000705void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
706 // If this is an Objective-C method declaration whose selector matches our
707 // preferred selector, give it a priority boost.
708 if (!PreferredSelector.isNull())
709 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
710 if (PreferredSelector == Method->getSelector())
711 R.Priority += CCD_SelectorMatch;
Douglas Gregor08f43cd2010-09-20 23:11:55 +0000712
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000713 // If we have a preferred type, adjust the priority for results with exactly-
714 // matching or nearly-matching types.
715 if (!PreferredType.isNull()) {
716 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
717 if (!T.isNull()) {
718 CanQualType TC = SemaRef.Context.getCanonicalType(T);
719 // Check for exactly-matching types (modulo qualifiers).
720 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
721 R.Priority /= CCF_ExactTypeMatch;
722 // Check for nearly-matching types, based on classification of each.
723 else if ((getSimplifiedTypeClass(PreferredType)
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000724 == getSimplifiedTypeClass(TC)) &&
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000725 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
726 R.Priority /= CCF_SimilarTypeMatch;
727 }
728 }
Douglas Gregor1f5537a2010-07-08 23:20:03 +0000729}
730
Douglas Gregor6f942b22010-09-21 16:06:22 +0000731void ResultBuilder::MaybeAddConstructorResults(Result R) {
732 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
733 !CompletionContext.wantConstructorResults())
734 return;
735
736 ASTContext &Context = SemaRef.Context;
737 NamedDecl *D = R.Declaration;
738 CXXRecordDecl *Record = 0;
739 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
740 Record = ClassTemplate->getTemplatedDecl();
741 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
742 // Skip specializations and partial specializations.
743 if (isa<ClassTemplateSpecializationDecl>(Record))
744 return;
745 } else {
746 // There are no constructors here.
747 return;
748 }
749
750 Record = Record->getDefinition();
751 if (!Record)
752 return;
753
754
755 QualType RecordTy = Context.getTypeDeclType(Record);
756 DeclarationName ConstructorName
757 = Context.DeclarationNames.getCXXConstructorName(
758 Context.getCanonicalType(RecordTy));
759 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
760 Ctors.first != Ctors.second; ++Ctors.first) {
761 R.Declaration = *Ctors.first;
762 R.CursorKind = getCursorKindForDecl(R.Declaration);
763 Results.push_back(R);
764 }
765}
766
Douglas Gregore495b7f2010-01-14 00:20:49 +0000767void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
768 assert(!ShadowMaps.empty() && "Must enter into a results scope");
769
770 if (R.Kind != Result::RK_Declaration) {
771 // For non-declaration results, just add the result.
772 Results.push_back(R);
773 return;
774 }
775
776 // Look through using declarations.
777 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
778 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
779 return;
780 }
781
782 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
783 unsigned IDNS = CanonDecl->getIdentifierNamespace();
784
Douglas Gregor45bcd432010-01-14 03:21:49 +0000785 bool AsNestedNameSpecifier = false;
786 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregore495b7f2010-01-14 00:20:49 +0000787 return;
788
Douglas Gregor6f942b22010-09-21 16:06:22 +0000789 // C++ constructors are never found by name lookup.
790 if (isa<CXXConstructorDecl>(R.Declaration))
791 return;
792
Douglas Gregor86d9a522009-09-21 16:56:56 +0000793 ShadowMap &SMap = ShadowMaps.back();
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000794 ShadowMapEntry::iterator I, IEnd;
795 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
796 if (NamePos != SMap.end()) {
797 I = NamePos->second.begin();
798 IEnd = NamePos->second.end();
799 }
800
801 for (; I != IEnd; ++I) {
802 NamedDecl *ND = I->first;
803 unsigned Index = I->second;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000804 if (ND->getCanonicalDecl() == CanonDecl) {
805 // This is a redeclaration. Always pick the newer declaration.
Douglas Gregor86d9a522009-09-21 16:56:56 +0000806 Results[Index].Declaration = R.Declaration;
807
Douglas Gregor86d9a522009-09-21 16:56:56 +0000808 // We're done.
809 return;
810 }
811 }
812
813 // This is a new declaration in this scope. However, check whether this
814 // declaration name is hidden by a similarly-named declaration in an outer
815 // scope.
816 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
817 --SMEnd;
818 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000819 ShadowMapEntry::iterator I, IEnd;
820 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
821 if (NamePos != SM->end()) {
822 I = NamePos->second.begin();
823 IEnd = NamePos->second.end();
824 }
825 for (; I != IEnd; ++I) {
Douglas Gregor86d9a522009-09-21 16:56:56 +0000826 // A tag declaration does not hide a non-tag declaration.
John McCall0d6b1642010-04-23 18:46:30 +0000827 if (I->first->hasTagIdentifierNamespace() &&
Douglas Gregor86d9a522009-09-21 16:56:56 +0000828 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
829 Decl::IDNS_ObjCProtocol)))
830 continue;
831
832 // Protocols are in distinct namespaces from everything else.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000833 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000834 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000835 I->first->getIdentifierNamespace() != IDNS)
Douglas Gregor86d9a522009-09-21 16:56:56 +0000836 continue;
837
838 // The newly-added result is hidden by an entry in the shadow map.
Douglas Gregor6660d842010-01-14 00:41:07 +0000839 if (CheckHiddenResult(R, CurContext, I->first))
Douglas Gregor86d9a522009-09-21 16:56:56 +0000840 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +0000841
842 break;
843 }
844 }
845
846 // Make sure that any given declaration only shows up in the result set once.
847 if (!AllDeclsFound.insert(CanonDecl))
848 return;
Douglas Gregor265f7492010-08-27 15:29:55 +0000849
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000850 // If the filter is for nested-name-specifiers, then this result starts a
851 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000852 if (AsNestedNameSpecifier) {
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000853 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000854 R.Priority = CCP_NestedNameSpecifier;
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000855 } else
856 AdjustResultPriorityForDecl(R);
Douglas Gregor265f7492010-08-27 15:29:55 +0000857
Douglas Gregor0563c262009-09-22 23:15:58 +0000858 // If this result is supposed to have an informative qualifier, add one.
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000859 if (R.QualifierIsInformative && !R.Qualifier &&
860 !R.StartsNestedNameSpecifier) {
Douglas Gregor0563c262009-09-22 23:15:58 +0000861 DeclContext *Ctx = R.Declaration->getDeclContext();
862 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
863 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
864 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
865 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
866 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
867 else
868 R.QualifierIsInformative = false;
869 }
Douglas Gregoreb5758b2009-09-23 22:26:46 +0000870
Douglas Gregor86d9a522009-09-21 16:56:56 +0000871 // Insert this result into the set of results and into the current shadow
872 // map.
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000873 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Douglas Gregor86d9a522009-09-21 16:56:56 +0000874 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000875
876 if (!AsNestedNameSpecifier)
877 MaybeAddConstructorResults(R);
Douglas Gregor86d9a522009-09-21 16:56:56 +0000878}
879
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000880void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
Douglas Gregor0cc84042010-01-14 15:47:35 +0000881 NamedDecl *Hiding, bool InBaseClass = false) {
Douglas Gregora4477812010-01-14 16:01:26 +0000882 if (R.Kind != Result::RK_Declaration) {
883 // For non-declaration results, just add the result.
884 Results.push_back(R);
885 return;
886 }
887
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000888 // Look through using declarations.
889 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
890 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
891 return;
892 }
893
Douglas Gregor45bcd432010-01-14 03:21:49 +0000894 bool AsNestedNameSpecifier = false;
895 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000896 return;
897
Douglas Gregor6f942b22010-09-21 16:06:22 +0000898 // C++ constructors are never found by name lookup.
899 if (isa<CXXConstructorDecl>(R.Declaration))
900 return;
901
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000902 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
903 return;
904
905 // Make sure that any given declaration only shows up in the result set once.
906 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
907 return;
908
909 // If the filter is for nested-name-specifiers, then this result starts a
910 // nested-name-specifier.
Douglas Gregor12e13132010-05-26 22:00:08 +0000911 if (AsNestedNameSpecifier) {
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000912 R.StartsNestedNameSpecifier = true;
Douglas Gregor12e13132010-05-26 22:00:08 +0000913 R.Priority = CCP_NestedNameSpecifier;
914 }
Douglas Gregor0cc84042010-01-14 15:47:35 +0000915 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
916 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
Sebastian Redl7a126a42010-08-31 00:36:30 +0000917 ->getRedeclContext()))
Douglas Gregor0cc84042010-01-14 15:47:35 +0000918 R.QualifierIsInformative = true;
919
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000920 // If this result is supposed to have an informative qualifier, add one.
921 if (R.QualifierIsInformative && !R.Qualifier &&
922 !R.StartsNestedNameSpecifier) {
923 DeclContext *Ctx = R.Declaration->getDeclContext();
924 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
925 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
926 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
927 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
Douglas Gregor45bcd432010-01-14 03:21:49 +0000928 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000929 else
930 R.QualifierIsInformative = false;
931 }
932
Douglas Gregor12e13132010-05-26 22:00:08 +0000933 // Adjust the priority if this result comes from a base class.
934 if (InBaseClass)
935 R.Priority += CCD_InBaseClass;
936
Douglas Gregorcee9ff12010-09-20 22:39:41 +0000937 AdjustResultPriorityForDecl(R);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +0000938
Douglas Gregor3cdee122010-08-26 16:36:48 +0000939 if (HasObjectTypeQualifiers)
940 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
941 if (Method->isInstance()) {
942 Qualifiers MethodQuals
943 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
944 if (ObjectTypeQualifiers == MethodQuals)
945 R.Priority += CCD_ObjectQualifierMatch;
946 else if (ObjectTypeQualifiers - MethodQuals) {
947 // The method cannot be invoked, because doing so would drop
948 // qualifiers.
949 return;
950 }
951 }
952
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000953 // Insert this result into the set of results.
954 Results.push_back(R);
Douglas Gregor6f942b22010-09-21 16:06:22 +0000955
956 if (!AsNestedNameSpecifier)
957 MaybeAddConstructorResults(R);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +0000958}
959
Douglas Gregora4477812010-01-14 16:01:26 +0000960void ResultBuilder::AddResult(Result R) {
961 assert(R.Kind != Result::RK_Declaration &&
962 "Declaration results need more context");
963 Results.push_back(R);
964}
965
Douglas Gregor86d9a522009-09-21 16:56:56 +0000966/// \brief Enter into a new scope.
967void ResultBuilder::EnterNewScope() {
968 ShadowMaps.push_back(ShadowMap());
969}
970
971/// \brief Exit from the current scope.
972void ResultBuilder::ExitScope() {
Douglas Gregorfbcb5d62009-12-06 20:23:50 +0000973 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
974 EEnd = ShadowMaps.back().end();
975 E != EEnd;
976 ++E)
977 E->second.Destroy();
978
Douglas Gregor86d9a522009-09-21 16:56:56 +0000979 ShadowMaps.pop_back();
980}
981
Douglas Gregor791215b2009-09-21 20:51:25 +0000982/// \brief Determines whether this given declaration will be found by
983/// ordinary name lookup.
984bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000985 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
986
Douglas Gregor791215b2009-09-21 20:51:25 +0000987 unsigned IDNS = Decl::IDNS_Ordinary;
988 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +0000989 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +0000990 else if (SemaRef.getLangOptions().ObjC1) {
991 if (isa<ObjCIvarDecl>(ND))
992 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +0000993 }
994
Douglas Gregor791215b2009-09-21 20:51:25 +0000995 return ND->getIdentifierNamespace() & IDNS;
996}
997
Douglas Gregor01dfea02010-01-10 23:08:15 +0000998/// \brief Determines whether this given declaration will be found by
Douglas Gregor4710e5b2010-05-28 00:49:12 +0000999/// ordinary name lookup but is not a type name.
1000bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
1001 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1002 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1003 return false;
1004
1005 unsigned IDNS = Decl::IDNS_Ordinary;
1006 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor9b30b262010-06-15 20:26:51 +00001007 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
Douglas Gregorca45da02010-11-02 20:36:02 +00001008 else if (SemaRef.getLangOptions().ObjC1) {
1009 if (isa<ObjCIvarDecl>(ND))
1010 return true;
Douglas Gregorca45da02010-11-02 20:36:02 +00001011 }
1012
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001013 return ND->getIdentifierNamespace() & IDNS;
1014}
1015
Douglas Gregorf9578432010-07-28 21:50:18 +00001016bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
1017 if (!IsOrdinaryNonTypeName(ND))
1018 return 0;
1019
1020 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1021 if (VD->getType()->isIntegralOrEnumerationType())
1022 return true;
1023
1024 return false;
1025}
1026
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001027/// \brief Determines whether this given declaration will be found by
Douglas Gregor01dfea02010-01-10 23:08:15 +00001028/// ordinary name lookup.
1029bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001030 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1031
Douglas Gregor01dfea02010-01-10 23:08:15 +00001032 unsigned IDNS = Decl::IDNS_Ordinary;
1033 if (SemaRef.getLangOptions().CPlusPlus)
John McCall0d6b1642010-04-23 18:46:30 +00001034 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001035
1036 return (ND->getIdentifierNamespace() & IDNS) &&
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001037 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1038 !isa<ObjCPropertyDecl>(ND);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001039}
1040
Douglas Gregor86d9a522009-09-21 16:56:56 +00001041/// \brief Determines whether the given declaration is suitable as the
1042/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1043bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1044 // Allow us to find class templates, too.
1045 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1046 ND = ClassTemplate->getTemplatedDecl();
1047
1048 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1049}
1050
1051/// \brief Determines whether the given declaration is an enumeration.
1052bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1053 return isa<EnumDecl>(ND);
1054}
1055
1056/// \brief Determines whether the given declaration is a class or struct.
1057bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1058 // Allow us to find class templates, too.
1059 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1060 ND = ClassTemplate->getTemplatedDecl();
1061
1062 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001063 return RD->getTagKind() == TTK_Class ||
1064 RD->getTagKind() == TTK_Struct;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001065
1066 return false;
1067}
1068
1069/// \brief Determines whether the given declaration is a union.
1070bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1071 // Allow us to find class templates, too.
1072 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1073 ND = ClassTemplate->getTemplatedDecl();
1074
1075 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001076 return RD->getTagKind() == TTK_Union;
Douglas Gregor86d9a522009-09-21 16:56:56 +00001077
1078 return false;
1079}
1080
1081/// \brief Determines whether the given declaration is a namespace.
1082bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1083 return isa<NamespaceDecl>(ND);
1084}
1085
1086/// \brief Determines whether the given declaration is a namespace or
1087/// namespace alias.
1088bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1089 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1090}
1091
Douglas Gregor76282942009-12-11 17:31:05 +00001092/// \brief Determines whether the given declaration is a type.
Douglas Gregor86d9a522009-09-21 16:56:56 +00001093bool ResultBuilder::IsType(NamedDecl *ND) const {
Douglas Gregord32b0222010-08-24 01:06:58 +00001094 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1095 ND = Using->getTargetDecl();
1096
1097 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor86d9a522009-09-21 16:56:56 +00001098}
1099
Douglas Gregor76282942009-12-11 17:31:05 +00001100/// \brief Determines which members of a class should be visible via
1101/// "." or "->". Only value declarations, nested name specifiers, and
1102/// using declarations thereof should show up.
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001103bool ResultBuilder::IsMember(NamedDecl *ND) const {
Douglas Gregor76282942009-12-11 17:31:05 +00001104 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1105 ND = Using->getTargetDecl();
1106
Douglas Gregorce821962009-12-11 18:14:22 +00001107 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1108 isa<ObjCPropertyDecl>(ND);
Douglas Gregoreb5758b2009-09-23 22:26:46 +00001109}
1110
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001111static bool isObjCReceiverType(ASTContext &C, QualType T) {
1112 T = C.getCanonicalType(T);
1113 switch (T->getTypeClass()) {
1114 case Type::ObjCObject:
1115 case Type::ObjCInterface:
1116 case Type::ObjCObjectPointer:
1117 return true;
1118
1119 case Type::Builtin:
1120 switch (cast<BuiltinType>(T)->getKind()) {
1121 case BuiltinType::ObjCId:
1122 case BuiltinType::ObjCClass:
1123 case BuiltinType::ObjCSel:
1124 return true;
1125
1126 default:
1127 break;
1128 }
1129 return false;
1130
1131 default:
1132 break;
1133 }
1134
1135 if (!C.getLangOptions().CPlusPlus)
1136 return false;
1137
1138 // FIXME: We could perform more analysis here to determine whether a
1139 // particular class type has any conversions to Objective-C types. For now,
1140 // just accept all class types.
1141 return T->isDependentType() || T->isRecordType();
1142}
1143
1144bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1145 QualType T = getDeclUsageType(SemaRef.Context, ND);
1146 if (T.isNull())
1147 return false;
1148
1149 T = SemaRef.Context.getBaseElementType(T);
1150 return isObjCReceiverType(SemaRef.Context, T);
1151}
1152
Douglas Gregorfb629412010-08-23 21:17:50 +00001153bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1154 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1155 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1156 return false;
1157
1158 QualType T = getDeclUsageType(SemaRef.Context, ND);
1159 if (T.isNull())
1160 return false;
1161
1162 T = SemaRef.Context.getBaseElementType(T);
1163 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1164 T->isObjCIdType() ||
1165 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1166}
Douglas Gregor8e254cf2010-05-27 23:06:34 +00001167
Douglas Gregor52779fb2010-09-23 23:01:17 +00001168bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1169 return false;
1170}
1171
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00001172/// \rief Determines whether the given declaration is an Objective-C
1173/// instance variable.
1174bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1175 return isa<ObjCIvarDecl>(ND);
1176}
1177
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001178namespace {
1179 /// \brief Visible declaration consumer that adds a code-completion result
1180 /// for each visible declaration.
1181 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1182 ResultBuilder &Results;
1183 DeclContext *CurContext;
1184
1185 public:
1186 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1187 : Results(Results), CurContext(CurContext) { }
1188
Erik Verbruggend1205962011-10-06 07:27:49 +00001189 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1190 bool InBaseClass) {
1191 bool Accessible = true;
Douglas Gregor17015ef2011-11-03 16:51:37 +00001192 if (Ctx)
1193 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
1194
Erik Verbruggend1205962011-10-06 07:27:49 +00001195 ResultBuilder::Result Result(ND, 0, false, Accessible);
1196 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00001197 }
1198 };
1199}
1200
Douglas Gregor86d9a522009-09-21 16:56:56 +00001201/// \brief Add type specifiers for the current language as keyword results.
Douglas Gregorbca403c2010-01-13 23:51:12 +00001202static void AddTypeSpecifierResults(const LangOptions &LangOpts,
Douglas Gregor86d9a522009-09-21 16:56:56 +00001203 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001204 typedef CodeCompletionResult Result;
Douglas Gregor12e13132010-05-26 22:00:08 +00001205 Results.AddResult(Result("short", CCP_Type));
1206 Results.AddResult(Result("long", CCP_Type));
1207 Results.AddResult(Result("signed", CCP_Type));
1208 Results.AddResult(Result("unsigned", CCP_Type));
1209 Results.AddResult(Result("void", CCP_Type));
1210 Results.AddResult(Result("char", CCP_Type));
1211 Results.AddResult(Result("int", CCP_Type));
1212 Results.AddResult(Result("float", CCP_Type));
1213 Results.AddResult(Result("double", CCP_Type));
1214 Results.AddResult(Result("enum", CCP_Type));
1215 Results.AddResult(Result("struct", CCP_Type));
1216 Results.AddResult(Result("union", CCP_Type));
1217 Results.AddResult(Result("const", CCP_Type));
1218 Results.AddResult(Result("volatile", CCP_Type));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001219
Douglas Gregor86d9a522009-09-21 16:56:56 +00001220 if (LangOpts.C99) {
1221 // C99-specific
Douglas Gregor12e13132010-05-26 22:00:08 +00001222 Results.AddResult(Result("_Complex", CCP_Type));
1223 Results.AddResult(Result("_Imaginary", CCP_Type));
1224 Results.AddResult(Result("_Bool", CCP_Type));
1225 Results.AddResult(Result("restrict", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001226 }
1227
Douglas Gregor218937c2011-02-01 19:23:04 +00001228 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor86d9a522009-09-21 16:56:56 +00001229 if (LangOpts.CPlusPlus) {
1230 // C++-specific
Douglas Gregorb05496d2010-09-20 21:11:48 +00001231 Results.AddResult(Result("bool", CCP_Type +
1232 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
Douglas Gregor12e13132010-05-26 22:00:08 +00001233 Results.AddResult(Result("class", CCP_Type));
1234 Results.AddResult(Result("wchar_t", CCP_Type));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001235
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001236 // typename qualified-id
Douglas Gregor218937c2011-02-01 19:23:04 +00001237 Builder.AddTypedTextChunk("typename");
1238 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1239 Builder.AddPlaceholderChunk("qualifier");
1240 Builder.AddTextChunk("::");
1241 Builder.AddPlaceholderChunk("name");
1242 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001243
Douglas Gregor86d9a522009-09-21 16:56:56 +00001244 if (LangOpts.CPlusPlus0x) {
Douglas Gregor12e13132010-05-26 22:00:08 +00001245 Results.AddResult(Result("auto", CCP_Type));
1246 Results.AddResult(Result("char16_t", CCP_Type));
1247 Results.AddResult(Result("char32_t", CCP_Type));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001248
Douglas Gregor218937c2011-02-01 19:23:04 +00001249 Builder.AddTypedTextChunk("decltype");
1250 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1251 Builder.AddPlaceholderChunk("expression");
1252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1253 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001254 }
1255 }
1256
1257 // GNU extensions
1258 if (LangOpts.GNUMode) {
1259 // FIXME: Enable when we actually support decimal floating point.
Douglas Gregora4477812010-01-14 16:01:26 +00001260 // Results.AddResult(Result("_Decimal32"));
1261 // Results.AddResult(Result("_Decimal64"));
1262 // Results.AddResult(Result("_Decimal128"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001263
Douglas Gregor218937c2011-02-01 19:23:04 +00001264 Builder.AddTypedTextChunk("typeof");
1265 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1266 Builder.AddPlaceholderChunk("expression");
1267 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001268
Douglas Gregor218937c2011-02-01 19:23:04 +00001269 Builder.AddTypedTextChunk("typeof");
1270 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1271 Builder.AddPlaceholderChunk("type");
1272 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1273 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor86d9a522009-09-21 16:56:56 +00001274 }
1275}
1276
John McCallf312b1e2010-08-26 23:41:50 +00001277static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001278 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001279 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001280 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001281 // Note: we don't suggest either "auto" or "register", because both
1282 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1283 // in C++0x as a type specifier.
Douglas Gregora4477812010-01-14 16:01:26 +00001284 Results.AddResult(Result("extern"));
1285 Results.AddResult(Result("static"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001286}
1287
John McCallf312b1e2010-08-26 23:41:50 +00001288static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001289 const LangOptions &LangOpts,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001290 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00001291 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001292 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001293 case Sema::PCC_Class:
1294 case Sema::PCC_MemberTemplate:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001295 if (LangOpts.CPlusPlus) {
Douglas Gregora4477812010-01-14 16:01:26 +00001296 Results.AddResult(Result("explicit"));
1297 Results.AddResult(Result("friend"));
1298 Results.AddResult(Result("mutable"));
1299 Results.AddResult(Result("virtual"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001300 }
1301 // Fall through
1302
John McCallf312b1e2010-08-26 23:41:50 +00001303 case Sema::PCC_ObjCInterface:
1304 case Sema::PCC_ObjCImplementation:
1305 case Sema::PCC_Namespace:
1306 case Sema::PCC_Template:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001307 if (LangOpts.CPlusPlus || LangOpts.C99)
Douglas Gregora4477812010-01-14 16:01:26 +00001308 Results.AddResult(Result("inline"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001309 break;
1310
John McCallf312b1e2010-08-26 23:41:50 +00001311 case Sema::PCC_ObjCInstanceVariableList:
1312 case Sema::PCC_Expression:
1313 case Sema::PCC_Statement:
1314 case Sema::PCC_ForInit:
1315 case Sema::PCC_Condition:
1316 case Sema::PCC_RecoveryInFunction:
1317 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001318 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001319 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00001320 break;
1321 }
1322}
1323
Douglas Gregorbca403c2010-01-13 23:51:12 +00001324static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1325static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1326static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001327 ResultBuilder &Results,
1328 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001329static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001330 ResultBuilder &Results,
1331 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001332static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001333 ResultBuilder &Results,
1334 bool NeedAt);
Douglas Gregorbca403c2010-01-13 23:51:12 +00001335static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001336
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001337static void AddTypedefResult(ResultBuilder &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001338 CodeCompletionBuilder Builder(Results.getAllocator());
1339 Builder.AddTypedTextChunk("typedef");
1340 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1341 Builder.AddPlaceholderChunk("type");
1342 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1343 Builder.AddPlaceholderChunk("name");
1344 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001345}
1346
John McCallf312b1e2010-08-26 23:41:50 +00001347static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001348 const LangOptions &LangOpts) {
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001349 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001350 case Sema::PCC_Namespace:
1351 case Sema::PCC_Class:
1352 case Sema::PCC_ObjCInstanceVariableList:
1353 case Sema::PCC_Template:
1354 case Sema::PCC_MemberTemplate:
1355 case Sema::PCC_Statement:
1356 case Sema::PCC_RecoveryInFunction:
1357 case Sema::PCC_Type:
Douglas Gregor02688102010-09-14 23:59:36 +00001358 case Sema::PCC_ParenthesizedExpression:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001359 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001360 return true;
1361
John McCallf312b1e2010-08-26 23:41:50 +00001362 case Sema::PCC_Expression:
1363 case Sema::PCC_Condition:
Douglas Gregor02688102010-09-14 23:59:36 +00001364 return LangOpts.CPlusPlus;
1365
1366 case Sema::PCC_ObjCInterface:
1367 case Sema::PCC_ObjCImplementation:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001368 return false;
1369
John McCallf312b1e2010-08-26 23:41:50 +00001370 case Sema::PCC_ForInit:
Douglas Gregor02688102010-09-14 23:59:36 +00001371 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001372 }
1373
1374 return false;
1375}
1376
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00001377static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1378 const Preprocessor &PP) {
1379 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Douglas Gregor8ca72082011-10-18 21:20:17 +00001380 Policy.AnonymousTagLocations = false;
1381 Policy.SuppressStrongLifetime = true;
Douglas Gregor25270b62011-11-03 00:16:13 +00001382 Policy.SuppressUnwrittenScope = true;
Douglas Gregor8ca72082011-10-18 21:20:17 +00001383 return Policy;
1384}
1385
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00001386/// \brief Retrieve a printing policy suitable for code completion.
1387static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1388 return getCompletionPrintingPolicy(S.Context, S.PP);
1389}
1390
Douglas Gregor8ca72082011-10-18 21:20:17 +00001391/// \brief Retrieve the string representation of the given type as a string
1392/// that has the appropriate lifetime for code completion.
1393///
1394/// This routine provides a fast path where we provide constant strings for
1395/// common type names.
1396static const char *GetCompletionTypeString(QualType T,
1397 ASTContext &Context,
1398 const PrintingPolicy &Policy,
1399 CodeCompletionAllocator &Allocator) {
1400 if (!T.getLocalQualifiers()) {
1401 // Built-in type names are constant strings.
1402 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1403 return BT->getName(Policy);
1404
1405 // Anonymous tag types are constant strings.
1406 if (const TagType *TagT = dyn_cast<TagType>(T))
1407 if (TagDecl *Tag = TagT->getDecl())
1408 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
1409 switch (Tag->getTagKind()) {
1410 case TTK_Struct: return "struct <anonymous>";
1411 case TTK_Class: return "class <anonymous>";
1412 case TTK_Union: return "union <anonymous>";
1413 case TTK_Enum: return "enum <anonymous>";
1414 }
1415 }
1416 }
1417
1418 // Slow path: format the type as a string.
1419 std::string Result;
1420 T.getAsStringInternal(Result, Policy);
1421 return Allocator.CopyString(Result);
1422}
1423
Douglas Gregor01dfea02010-01-10 23:08:15 +00001424/// \brief Add language constructs that show up for "ordinary" names.
John McCallf312b1e2010-08-26 23:41:50 +00001425static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001426 Scope *S,
1427 Sema &SemaRef,
Douglas Gregor01dfea02010-01-10 23:08:15 +00001428 ResultBuilder &Results) {
Douglas Gregor8ca72082011-10-18 21:20:17 +00001429 CodeCompletionAllocator &Allocator = Results.getAllocator();
1430 CodeCompletionBuilder Builder(Allocator);
1431 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
Douglas Gregor218937c2011-02-01 19:23:04 +00001432
John McCall0a2c5e22010-08-25 06:19:51 +00001433 typedef CodeCompletionResult Result;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001434 switch (CCC) {
John McCallf312b1e2010-08-26 23:41:50 +00001435 case Sema::PCC_Namespace:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001436 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001437 if (Results.includeCodePatterns()) {
1438 // namespace <identifier> { declarations }
Douglas Gregor218937c2011-02-01 19:23:04 +00001439 Builder.AddTypedTextChunk("namespace");
1440 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1441 Builder.AddPlaceholderChunk("identifier");
1442 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1443 Builder.AddPlaceholderChunk("declarations");
1444 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1445 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1446 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001447 }
1448
Douglas Gregor01dfea02010-01-10 23:08:15 +00001449 // namespace identifier = identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001450 Builder.AddTypedTextChunk("namespace");
1451 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1452 Builder.AddPlaceholderChunk("name");
1453 Builder.AddChunk(CodeCompletionString::CK_Equal);
1454 Builder.AddPlaceholderChunk("namespace");
1455 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001456
1457 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001458 Builder.AddTypedTextChunk("using");
1459 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1460 Builder.AddTextChunk("namespace");
1461 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1462 Builder.AddPlaceholderChunk("identifier");
1463 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001464
1465 // asm(string-literal)
Douglas Gregor218937c2011-02-01 19:23:04 +00001466 Builder.AddTypedTextChunk("asm");
1467 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1468 Builder.AddPlaceholderChunk("string-literal");
1469 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1470 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001471
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001472 if (Results.includeCodePatterns()) {
1473 // Explicit template instantiation
Douglas Gregor218937c2011-02-01 19:23:04 +00001474 Builder.AddTypedTextChunk("template");
1475 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1476 Builder.AddPlaceholderChunk("declaration");
1477 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001478 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001479 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001480
1481 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001482 AddObjCTopLevelResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001483
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001484 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001485 // Fall through
1486
John McCallf312b1e2010-08-26 23:41:50 +00001487 case Sema::PCC_Class:
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001488 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001489 // Using declaration
Douglas Gregor218937c2011-02-01 19:23:04 +00001490 Builder.AddTypedTextChunk("using");
1491 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1492 Builder.AddPlaceholderChunk("qualifier");
1493 Builder.AddTextChunk("::");
1494 Builder.AddPlaceholderChunk("name");
1495 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001496
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001497 // using typename qualifier::name (only in a dependent context)
Douglas Gregor01dfea02010-01-10 23:08:15 +00001498 if (SemaRef.CurContext->isDependentContext()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001499 Builder.AddTypedTextChunk("using");
1500 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1501 Builder.AddTextChunk("typename");
1502 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1503 Builder.AddPlaceholderChunk("qualifier");
1504 Builder.AddTextChunk("::");
1505 Builder.AddPlaceholderChunk("name");
1506 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001507 }
1508
John McCallf312b1e2010-08-26 23:41:50 +00001509 if (CCC == Sema::PCC_Class) {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001510 AddTypedefResult(Results);
1511
Douglas Gregor01dfea02010-01-10 23:08:15 +00001512 // public:
Douglas Gregor218937c2011-02-01 19:23:04 +00001513 Builder.AddTypedTextChunk("public");
1514 Builder.AddChunk(CodeCompletionString::CK_Colon);
1515 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001516
1517 // protected:
Douglas Gregor218937c2011-02-01 19:23:04 +00001518 Builder.AddTypedTextChunk("protected");
1519 Builder.AddChunk(CodeCompletionString::CK_Colon);
1520 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001521
1522 // private:
Douglas Gregor218937c2011-02-01 19:23:04 +00001523 Builder.AddTypedTextChunk("private");
1524 Builder.AddChunk(CodeCompletionString::CK_Colon);
1525 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001526 }
1527 }
1528 // Fall through
1529
John McCallf312b1e2010-08-26 23:41:50 +00001530 case Sema::PCC_Template:
1531 case Sema::PCC_MemberTemplate:
Douglas Gregord8e8a582010-05-25 21:41:55 +00001532 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001533 // template < parameters >
Douglas Gregor218937c2011-02-01 19:23:04 +00001534 Builder.AddTypedTextChunk("template");
1535 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1536 Builder.AddPlaceholderChunk("parameters");
1537 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1538 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001539 }
1540
Douglas Gregorbca403c2010-01-13 23:51:12 +00001541 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1542 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001543 break;
1544
John McCallf312b1e2010-08-26 23:41:50 +00001545 case Sema::PCC_ObjCInterface:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001546 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1547 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1548 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001549 break;
1550
John McCallf312b1e2010-08-26 23:41:50 +00001551 case Sema::PCC_ObjCImplementation:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001552 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1553 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1554 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001555 break;
1556
John McCallf312b1e2010-08-26 23:41:50 +00001557 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001558 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00001559 break;
1560
John McCallf312b1e2010-08-26 23:41:50 +00001561 case Sema::PCC_RecoveryInFunction:
1562 case Sema::PCC_Statement: {
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001563 AddTypedefResult(Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001564
Douglas Gregorec3310a2011-04-12 02:47:21 +00001565 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns() &&
1566 SemaRef.getLangOptions().CXXExceptions) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001567 Builder.AddTypedTextChunk("try");
1568 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1569 Builder.AddPlaceholderChunk("statements");
1570 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1571 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1572 Builder.AddTextChunk("catch");
1573 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1574 Builder.AddPlaceholderChunk("declaration");
1575 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1576 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1577 Builder.AddPlaceholderChunk("statements");
1578 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1579 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1580 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001581 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001582 if (SemaRef.getLangOptions().ObjC1)
Douglas Gregorbca403c2010-01-13 23:51:12 +00001583 AddObjCStatementResults(Results, true);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00001584
Douglas Gregord8e8a582010-05-25 21:41:55 +00001585 if (Results.includeCodePatterns()) {
1586 // if (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001587 Builder.AddTypedTextChunk("if");
1588 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001589 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001590 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001591 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001592 Builder.AddPlaceholderChunk("expression");
1593 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1594 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1595 Builder.AddPlaceholderChunk("statements");
1596 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1597 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1598 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001599
Douglas Gregord8e8a582010-05-25 21:41:55 +00001600 // switch (condition) { }
Douglas Gregor218937c2011-02-01 19:23:04 +00001601 Builder.AddTypedTextChunk("switch");
1602 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001603 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001604 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001605 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001606 Builder.AddPlaceholderChunk("expression");
1607 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1608 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1609 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1610 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1611 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001612 }
1613
Douglas Gregor01dfea02010-01-10 23:08:15 +00001614 // Switch-specific statements.
John McCall781472f2010-08-25 08:40:02 +00001615 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001616 // case expression:
Douglas Gregor218937c2011-02-01 19:23:04 +00001617 Builder.AddTypedTextChunk("case");
1618 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1619 Builder.AddPlaceholderChunk("expression");
1620 Builder.AddChunk(CodeCompletionString::CK_Colon);
1621 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001622
1623 // default:
Douglas Gregor218937c2011-02-01 19:23:04 +00001624 Builder.AddTypedTextChunk("default");
1625 Builder.AddChunk(CodeCompletionString::CK_Colon);
1626 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001627 }
1628
Douglas Gregord8e8a582010-05-25 21:41:55 +00001629 if (Results.includeCodePatterns()) {
1630 /// while (condition) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001631 Builder.AddTypedTextChunk("while");
1632 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001633 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor218937c2011-02-01 19:23:04 +00001634 Builder.AddPlaceholderChunk("condition");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001635 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001636 Builder.AddPlaceholderChunk("expression");
1637 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1638 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1639 Builder.AddPlaceholderChunk("statements");
1640 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1641 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1642 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001643
1644 // do { statements } while ( expression );
Douglas Gregor218937c2011-02-01 19:23:04 +00001645 Builder.AddTypedTextChunk("do");
1646 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1647 Builder.AddPlaceholderChunk("statements");
1648 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1649 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1650 Builder.AddTextChunk("while");
1651 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1652 Builder.AddPlaceholderChunk("expression");
1653 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1654 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001655
Douglas Gregord8e8a582010-05-25 21:41:55 +00001656 // for ( for-init-statement ; condition ; expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00001657 Builder.AddTypedTextChunk("for");
1658 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregord8e8a582010-05-25 21:41:55 +00001659 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
Douglas Gregor218937c2011-02-01 19:23:04 +00001660 Builder.AddPlaceholderChunk("init-statement");
Douglas Gregord8e8a582010-05-25 21:41:55 +00001661 else
Douglas Gregor218937c2011-02-01 19:23:04 +00001662 Builder.AddPlaceholderChunk("init-expression");
1663 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1664 Builder.AddPlaceholderChunk("condition");
1665 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1666 Builder.AddPlaceholderChunk("inc-expression");
1667 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1668 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1669 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1670 Builder.AddPlaceholderChunk("statements");
1671 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1672 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1673 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregord8e8a582010-05-25 21:41:55 +00001674 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001675
1676 if (S->getContinueParent()) {
1677 // continue ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001678 Builder.AddTypedTextChunk("continue");
1679 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001680 }
1681
1682 if (S->getBreakParent()) {
1683 // break ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001684 Builder.AddTypedTextChunk("break");
1685 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001686 }
1687
1688 // "return expression ;" or "return ;", depending on whether we
1689 // know the function is void or not.
1690 bool isVoid = false;
1691 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1692 isVoid = Function->getResultType()->isVoidType();
1693 else if (ObjCMethodDecl *Method
1694 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1695 isVoid = Method->getResultType()->isVoidType();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001696 else if (SemaRef.getCurBlock() &&
1697 !SemaRef.getCurBlock()->ReturnType.isNull())
1698 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
Douglas Gregor218937c2011-02-01 19:23:04 +00001699 Builder.AddTypedTextChunk("return");
Douglas Gregor93298002010-02-18 04:06:48 +00001700 if (!isVoid) {
Douglas Gregor218937c2011-02-01 19:23:04 +00001701 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1702 Builder.AddPlaceholderChunk("expression");
Douglas Gregor93298002010-02-18 04:06:48 +00001703 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001704 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001705
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001706 // goto identifier ;
Douglas Gregor218937c2011-02-01 19:23:04 +00001707 Builder.AddTypedTextChunk("goto");
1708 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1709 Builder.AddPlaceholderChunk("label");
1710 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001711
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001712 // Using directives
Douglas Gregor218937c2011-02-01 19:23:04 +00001713 Builder.AddTypedTextChunk("using");
1714 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1715 Builder.AddTextChunk("namespace");
1716 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1717 Builder.AddPlaceholderChunk("identifier");
1718 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001719 }
1720
1721 // Fall through (for statement expressions).
John McCallf312b1e2010-08-26 23:41:50 +00001722 case Sema::PCC_ForInit:
1723 case Sema::PCC_Condition:
Douglas Gregorbca403c2010-01-13 23:51:12 +00001724 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001725 // Fall through: conditions and statements can have expressions.
1726
Douglas Gregor02688102010-09-14 23:59:36 +00001727 case Sema::PCC_ParenthesizedExpression:
John McCallf85e1932011-06-15 23:02:42 +00001728 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1729 CCC == Sema::PCC_ParenthesizedExpression) {
1730 // (__bridge <type>)<expression>
1731 Builder.AddTypedTextChunk("__bridge");
1732 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1733 Builder.AddPlaceholderChunk("type");
1734 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1735 Builder.AddPlaceholderChunk("expression");
1736 Results.AddResult(Result(Builder.TakeString()));
1737
1738 // (__bridge_transfer <Objective-C type>)<expression>
1739 Builder.AddTypedTextChunk("__bridge_transfer");
1740 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1741 Builder.AddPlaceholderChunk("Objective-C type");
1742 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1743 Builder.AddPlaceholderChunk("expression");
1744 Results.AddResult(Result(Builder.TakeString()));
1745
1746 // (__bridge_retained <CF type>)<expression>
1747 Builder.AddTypedTextChunk("__bridge_retained");
1748 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1749 Builder.AddPlaceholderChunk("CF type");
1750 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1751 Builder.AddPlaceholderChunk("expression");
1752 Results.AddResult(Result(Builder.TakeString()));
1753 }
1754 // Fall through
1755
John McCallf312b1e2010-08-26 23:41:50 +00001756 case Sema::PCC_Expression: {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001757 if (SemaRef.getLangOptions().CPlusPlus) {
1758 // 'this', if we're in a non-static member function.
Eli Friedman72899c32012-01-07 04:59:52 +00001759 QualType ThisTy = SemaRef.getCurrentThisType();
Douglas Gregor8ca72082011-10-18 21:20:17 +00001760 if (!ThisTy.isNull()) {
1761 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1762 SemaRef.Context,
1763 Policy,
1764 Allocator));
1765 Builder.AddTypedTextChunk("this");
1766 Results.AddResult(Result(Builder.TakeString()));
1767 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001768
Douglas Gregor8ca72082011-10-18 21:20:17 +00001769 // true
1770 Builder.AddResultTypeChunk("bool");
1771 Builder.AddTypedTextChunk("true");
1772 Results.AddResult(Result(Builder.TakeString()));
1773
1774 // false
1775 Builder.AddResultTypeChunk("bool");
1776 Builder.AddTypedTextChunk("false");
1777 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001778
Douglas Gregorec3310a2011-04-12 02:47:21 +00001779 if (SemaRef.getLangOptions().RTTI) {
1780 // dynamic_cast < type-id > ( expression )
1781 Builder.AddTypedTextChunk("dynamic_cast");
1782 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1783 Builder.AddPlaceholderChunk("type");
1784 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1785 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1786 Builder.AddPlaceholderChunk("expression");
1787 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1788 Results.AddResult(Result(Builder.TakeString()));
1789 }
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001790
1791 // static_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001792 Builder.AddTypedTextChunk("static_cast");
1793 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1794 Builder.AddPlaceholderChunk("type");
1795 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1796 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1797 Builder.AddPlaceholderChunk("expression");
1798 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1799 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001800
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001801 // reinterpret_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001802 Builder.AddTypedTextChunk("reinterpret_cast");
1803 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1804 Builder.AddPlaceholderChunk("type");
1805 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1806 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1807 Builder.AddPlaceholderChunk("expression");
1808 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1809 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001810
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001811 // const_cast < type-id > ( expression )
Douglas Gregor218937c2011-02-01 19:23:04 +00001812 Builder.AddTypedTextChunk("const_cast");
1813 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1814 Builder.AddPlaceholderChunk("type");
1815 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1816 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1817 Builder.AddPlaceholderChunk("expression");
1818 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1819 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001820
Douglas Gregorec3310a2011-04-12 02:47:21 +00001821 if (SemaRef.getLangOptions().RTTI) {
1822 // typeid ( expression-or-type )
Douglas Gregor8ca72082011-10-18 21:20:17 +00001823 Builder.AddResultTypeChunk("std::type_info");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001824 Builder.AddTypedTextChunk("typeid");
1825 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1826 Builder.AddPlaceholderChunk("expression-or-type");
1827 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1828 Results.AddResult(Result(Builder.TakeString()));
1829 }
1830
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001831 // new T ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001832 Builder.AddTypedTextChunk("new");
1833 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1834 Builder.AddPlaceholderChunk("type");
1835 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1836 Builder.AddPlaceholderChunk("expressions");
1837 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1838 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001839
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001840 // new T [ ] ( ... )
Douglas Gregor218937c2011-02-01 19:23:04 +00001841 Builder.AddTypedTextChunk("new");
1842 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1843 Builder.AddPlaceholderChunk("type");
1844 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1845 Builder.AddPlaceholderChunk("size");
1846 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1847 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1848 Builder.AddPlaceholderChunk("expressions");
1849 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1850 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001851
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001852 // delete expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001853 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001854 Builder.AddTypedTextChunk("delete");
1855 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1856 Builder.AddPlaceholderChunk("expression");
1857 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001858
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001859 // delete [] expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001860 Builder.AddResultTypeChunk("void");
Douglas Gregor218937c2011-02-01 19:23:04 +00001861 Builder.AddTypedTextChunk("delete");
1862 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1863 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1864 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1865 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1866 Builder.AddPlaceholderChunk("expression");
1867 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001868
Douglas Gregorec3310a2011-04-12 02:47:21 +00001869 if (SemaRef.getLangOptions().CXXExceptions) {
1870 // throw expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001871 Builder.AddResultTypeChunk("void");
Douglas Gregorec3310a2011-04-12 02:47:21 +00001872 Builder.AddTypedTextChunk("throw");
1873 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1874 Builder.AddPlaceholderChunk("expression");
1875 Results.AddResult(Result(Builder.TakeString()));
1876 }
Douglas Gregora50216c2011-10-18 16:29:03 +00001877
Douglas Gregor12e13132010-05-26 22:00:08 +00001878 // FIXME: Rethrow?
Douglas Gregora50216c2011-10-18 16:29:03 +00001879
1880 if (SemaRef.getLangOptions().CPlusPlus0x) {
1881 // nullptr
Douglas Gregor8ca72082011-10-18 21:20:17 +00001882 Builder.AddResultTypeChunk("std::nullptr_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001883 Builder.AddTypedTextChunk("nullptr");
1884 Results.AddResult(Result(Builder.TakeString()));
1885
1886 // alignof
Douglas Gregor8ca72082011-10-18 21:20:17 +00001887 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001888 Builder.AddTypedTextChunk("alignof");
1889 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1890 Builder.AddPlaceholderChunk("type");
1891 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1892 Results.AddResult(Result(Builder.TakeString()));
1893
1894 // noexcept
Douglas Gregor8ca72082011-10-18 21:20:17 +00001895 Builder.AddResultTypeChunk("bool");
Douglas Gregora50216c2011-10-18 16:29:03 +00001896 Builder.AddTypedTextChunk("noexcept");
1897 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1898 Builder.AddPlaceholderChunk("expression");
1899 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1900 Results.AddResult(Result(Builder.TakeString()));
1901
1902 // sizeof... expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001903 Builder.AddResultTypeChunk("size_t");
Douglas Gregora50216c2011-10-18 16:29:03 +00001904 Builder.AddTypedTextChunk("sizeof...");
1905 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1906 Builder.AddPlaceholderChunk("parameter-pack");
1907 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1908 Results.AddResult(Result(Builder.TakeString()));
1909 }
Douglas Gregor01dfea02010-01-10 23:08:15 +00001910 }
1911
1912 if (SemaRef.getLangOptions().ObjC1) {
1913 // Add "super", if we're in an Objective-C class with a superclass.
Ted Kremenek681e2562010-05-31 21:43:10 +00001914 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1915 // The interface can be NULL.
1916 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
Douglas Gregor8ca72082011-10-18 21:20:17 +00001917 if (ID->getSuperClass()) {
1918 std::string SuperType;
1919 SuperType = ID->getSuperClass()->getNameAsString();
1920 if (Method->isInstanceMethod())
1921 SuperType += " *";
1922
1923 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
1924 Builder.AddTypedTextChunk("super");
1925 Results.AddResult(Result(Builder.TakeString()));
1926 }
Ted Kremenek681e2562010-05-31 21:43:10 +00001927 }
1928
Douglas Gregorbca403c2010-01-13 23:51:12 +00001929 AddObjCExpressionResults(Results, true);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001930 }
1931
Douglas Gregorc8bddde2010-05-28 00:22:41 +00001932 // sizeof expression
Douglas Gregor8ca72082011-10-18 21:20:17 +00001933 Builder.AddResultTypeChunk("size_t");
Douglas Gregor218937c2011-02-01 19:23:04 +00001934 Builder.AddTypedTextChunk("sizeof");
1935 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1936 Builder.AddPlaceholderChunk("expression-or-type");
1937 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1938 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001939 break;
1940 }
Douglas Gregord32b0222010-08-24 01:06:58 +00001941
John McCallf312b1e2010-08-26 23:41:50 +00001942 case Sema::PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00001943 case Sema::PCC_LocalDeclarationSpecifiers:
Douglas Gregord32b0222010-08-24 01:06:58 +00001944 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001945 }
1946
Douglas Gregor4710e5b2010-05-28 00:49:12 +00001947 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1948 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00001949
John McCallf312b1e2010-08-26 23:41:50 +00001950 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
Douglas Gregora4477812010-01-14 16:01:26 +00001951 Results.AddResult(Result("operator"));
Douglas Gregor01dfea02010-01-10 23:08:15 +00001952}
1953
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001954/// \brief If the given declaration has an associated type, add it as a result
1955/// type chunk.
1956static void AddResultTypeChunk(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00001957 const PrintingPolicy &Policy,
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001958 NamedDecl *ND,
Douglas Gregor218937c2011-02-01 19:23:04 +00001959 CodeCompletionBuilder &Result) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001960 if (!ND)
1961 return;
Douglas Gregor6f942b22010-09-21 16:06:22 +00001962
1963 // Skip constructors and conversion functions, which have their return types
1964 // built into their names.
1965 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1966 return;
1967
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001968 // Determine the type of the declaration (if it has a type).
Douglas Gregor6f942b22010-09-21 16:06:22 +00001969 QualType T;
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001970 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1971 T = Function->getResultType();
1972 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1973 T = Method->getResultType();
1974 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1975 T = FunTmpl->getTemplatedDecl()->getResultType();
1976 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1977 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1978 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1979 /* Do nothing: ignore unresolved using declarations*/
John McCallf85e1932011-06-15 23:02:42 +00001980 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001981 T = Value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001982 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001983 T = Property->getType();
1984
1985 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1986 return;
1987
Douglas Gregor8987b232011-09-27 23:30:47 +00001988 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00001989 Result.getAllocator()));
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001990}
1991
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001992static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
Douglas Gregor218937c2011-02-01 19:23:04 +00001993 CodeCompletionBuilder &Result) {
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001994 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1995 if (Sentinel->getSentinel() == 0) {
1996 if (Context.getLangOptions().ObjC1 &&
1997 Context.Idents.get("nil").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00001998 Result.AddTextChunk(", nil");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00001999 else if (Context.Idents.get("NULL").hasMacroDefinition())
Douglas Gregor218937c2011-02-01 19:23:04 +00002000 Result.AddTextChunk(", NULL");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002001 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002002 Result.AddTextChunk(", (void*)0");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002003 }
2004}
2005
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002006static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
2007 std::string Result;
2008 if (ObjCQuals & Decl::OBJC_TQ_In)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002009 Result += "in ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002010 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002011 Result += "inout ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002012 else if (ObjCQuals & Decl::OBJC_TQ_Out)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002013 Result += "out ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002014 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002015 Result += "bycopy ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002016 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002017 Result += "byref ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002018 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Douglas Gregor6ef92092011-11-09 02:13:45 +00002019 Result += "oneway ";
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002020 return Result;
2021}
2022
Douglas Gregor83482d12010-08-24 16:15:59 +00002023static std::string FormatFunctionParameter(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002024 const PrintingPolicy &Policy,
Douglas Gregoraba48082010-08-29 19:47:46 +00002025 ParmVarDecl *Param,
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002026 bool SuppressName = false,
2027 bool SuppressBlock = false) {
Douglas Gregor83482d12010-08-24 16:15:59 +00002028 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2029 if (Param->getType()->isDependentType() ||
2030 !Param->getType()->isBlockPointerType()) {
2031 // The argument for a dependent or non-block parameter is a placeholder
2032 // containing that parameter's type.
2033 std::string Result;
2034
Douglas Gregoraba48082010-08-29 19:47:46 +00002035 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002036 Result = Param->getIdentifier()->getName();
2037
John McCallf85e1932011-06-15 23:02:42 +00002038 Param->getType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002039
2040 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002041 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2042 + Result + ")";
Douglas Gregoraba48082010-08-29 19:47:46 +00002043 if (Param->getIdentifier() && !SuppressName)
Douglas Gregor83482d12010-08-24 16:15:59 +00002044 Result += Param->getIdentifier()->getName();
2045 }
2046 return Result;
2047 }
2048
2049 // The argument for a block pointer parameter is a block literal with
2050 // the appropriate type.
Douglas Gregor830072c2011-02-15 22:37:09 +00002051 FunctionTypeLoc *Block = 0;
2052 FunctionProtoTypeLoc *BlockProto = 0;
Douglas Gregor83482d12010-08-24 16:15:59 +00002053 TypeLoc TL;
2054 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2055 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2056 while (true) {
2057 // Look through typedefs.
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002058 if (!SuppressBlock) {
2059 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
2060 if (TypeSourceInfo *InnerTSInfo
2061 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
2062 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2063 continue;
2064 }
2065 }
2066
2067 // Look through qualified types
2068 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2069 TL = QualifiedTL->getUnqualifiedLoc();
Douglas Gregor83482d12010-08-24 16:15:59 +00002070 continue;
2071 }
2072 }
2073
Douglas Gregor83482d12010-08-24 16:15:59 +00002074 // Try to get the function prototype behind the block pointer type,
2075 // then we're done.
2076 if (BlockPointerTypeLoc *BlockPtr
2077 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
Abramo Bagnara723df242010-12-14 22:11:44 +00002078 TL = BlockPtr->getPointeeLoc().IgnoreParens();
Douglas Gregor830072c2011-02-15 22:37:09 +00002079 Block = dyn_cast<FunctionTypeLoc>(&TL);
2080 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
Douglas Gregor83482d12010-08-24 16:15:59 +00002081 }
2082 break;
2083 }
2084 }
2085
2086 if (!Block) {
2087 // We were unable to find a FunctionProtoTypeLoc with parameter names
2088 // for the block; just use the parameter type as a placeholder.
2089 std::string Result;
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002090 if (!ObjCMethodParam && Param->getIdentifier())
2091 Result = Param->getIdentifier()->getName();
2092
John McCallf85e1932011-06-15 23:02:42 +00002093 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
Douglas Gregor83482d12010-08-24 16:15:59 +00002094
2095 if (ObjCMethodParam) {
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002096 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2097 + Result + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002098 if (Param->getIdentifier())
2099 Result += Param->getIdentifier()->getName();
2100 }
2101
2102 return Result;
2103 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002104
Douglas Gregor83482d12010-08-24 16:15:59 +00002105 // We have the function prototype behind the block pointer type, as it was
2106 // written in the source.
Douglas Gregor38276252010-09-08 22:47:51 +00002107 std::string Result;
2108 QualType ResultType = Block->getTypePtr()->getResultType();
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002109 if (!ResultType->isVoidType() || SuppressBlock)
John McCallf85e1932011-06-15 23:02:42 +00002110 ResultType.getAsStringInternal(Result, Policy);
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002111
2112 // Format the parameter list.
2113 std::string Params;
Douglas Gregor830072c2011-02-15 22:37:09 +00002114 if (!BlockProto || Block->getNumArgs() == 0) {
2115 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002116 Params = "(...)";
Douglas Gregorc2760bc2010-10-02 23:49:58 +00002117 else
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002118 Params = "(void)";
Douglas Gregor38276252010-09-08 22:47:51 +00002119 } else {
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002120 Params += "(";
Douglas Gregor38276252010-09-08 22:47:51 +00002121 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2122 if (I)
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002123 Params += ", ";
2124 Params += FormatFunctionParameter(Context, Policy, Block->getArg(I),
2125 /*SuppressName=*/false,
2126 /*SuppressBlock=*/true);
Douglas Gregor38276252010-09-08 22:47:51 +00002127
Douglas Gregor830072c2011-02-15 22:37:09 +00002128 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002129 Params += ", ...";
Douglas Gregor38276252010-09-08 22:47:51 +00002130 }
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002131 Params += ")";
Douglas Gregore17794f2010-08-31 05:13:43 +00002132 }
Douglas Gregor38276252010-09-08 22:47:51 +00002133
Douglas Gregoree1c68a2011-10-18 04:23:19 +00002134 if (SuppressBlock) {
2135 // Format as a parameter.
2136 Result = Result + " (^";
2137 if (Param->getIdentifier())
2138 Result += Param->getIdentifier()->getName();
2139 Result += ")";
2140 Result += Params;
2141 } else {
2142 // Format as a block literal argument.
2143 Result = '^' + Result;
2144 Result += Params;
2145
2146 if (Param->getIdentifier())
2147 Result += Param->getIdentifier()->getName();
2148 }
2149
Douglas Gregor83482d12010-08-24 16:15:59 +00002150 return Result;
2151}
2152
Douglas Gregor86d9a522009-09-21 16:56:56 +00002153/// \brief Add function parameter chunks to the given code completion string.
2154static void AddFunctionParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002155 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002156 FunctionDecl *Function,
Douglas Gregor218937c2011-02-01 19:23:04 +00002157 CodeCompletionBuilder &Result,
2158 unsigned Start = 0,
2159 bool InOptional = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002160 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002161 bool FirstParameter = true;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002162
Douglas Gregor218937c2011-02-01 19:23:04 +00002163 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002164 ParmVarDecl *Param = Function->getParamDecl(P);
2165
Douglas Gregor218937c2011-02-01 19:23:04 +00002166 if (Param->hasDefaultArg() && !InOptional) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002167 // When we see an optional default argument, put that argument and
2168 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002169 CodeCompletionBuilder Opt(Result.getAllocator());
2170 if (!FirstParameter)
2171 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002172 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
Douglas Gregor218937c2011-02-01 19:23:04 +00002173 Result.AddOptionalChunk(Opt.TakeString());
2174 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002175 }
2176
Douglas Gregor218937c2011-02-01 19:23:04 +00002177 if (FirstParameter)
2178 FirstParameter = false;
2179 else
2180 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
2181
2182 InOptional = false;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002183
2184 // Format the placeholder string.
Douglas Gregor8987b232011-09-27 23:30:47 +00002185 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2186 Param);
Douglas Gregor83482d12010-08-24 16:15:59 +00002187
Douglas Gregore17794f2010-08-31 05:13:43 +00002188 if (Function->isVariadic() && P == N - 1)
2189 PlaceholderStr += ", ...";
2190
Douglas Gregor86d9a522009-09-21 16:56:56 +00002191 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002192 Result.AddPlaceholderChunk(
2193 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002194 }
Douglas Gregorb3d45252009-09-22 21:42:17 +00002195
2196 if (const FunctionProtoType *Proto
2197 = Function->getType()->getAs<FunctionProtoType>())
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002198 if (Proto->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002199 if (Proto->getNumArgs() == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00002200 Result.AddPlaceholderChunk("...");
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002201
Douglas Gregor218937c2011-02-01 19:23:04 +00002202 MaybeAddSentinel(Context, Function, Result);
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002203 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002204}
2205
2206/// \brief Add template parameter chunks to the given code completion string.
2207static void AddTemplateParameterChunks(ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00002208 const PrintingPolicy &Policy,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002209 TemplateDecl *Template,
Douglas Gregor218937c2011-02-01 19:23:04 +00002210 CodeCompletionBuilder &Result,
2211 unsigned MaxParameters = 0,
2212 unsigned Start = 0,
2213 bool InDefaultArg = false) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002214 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002215 bool FirstParameter = true;
2216
2217 TemplateParameterList *Params = Template->getTemplateParameters();
2218 TemplateParameterList::iterator PEnd = Params->end();
2219 if (MaxParameters)
2220 PEnd = Params->begin() + MaxParameters;
Douglas Gregor218937c2011-02-01 19:23:04 +00002221 for (TemplateParameterList::iterator P = Params->begin() + Start;
2222 P != PEnd; ++P) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002223 bool HasDefaultArg = false;
2224 std::string PlaceholderStr;
2225 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2226 if (TTP->wasDeclaredWithTypename())
2227 PlaceholderStr = "typename";
2228 else
2229 PlaceholderStr = "class";
2230
2231 if (TTP->getIdentifier()) {
2232 PlaceholderStr += ' ';
2233 PlaceholderStr += TTP->getIdentifier()->getName();
2234 }
2235
2236 HasDefaultArg = TTP->hasDefaultArgument();
2237 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor218937c2011-02-01 19:23:04 +00002238 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002239 if (NTTP->getIdentifier())
2240 PlaceholderStr = NTTP->getIdentifier()->getName();
John McCallf85e1932011-06-15 23:02:42 +00002241 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002242 HasDefaultArg = NTTP->hasDefaultArgument();
2243 } else {
2244 assert(isa<TemplateTemplateParmDecl>(*P));
2245 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2246
2247 // Since putting the template argument list into the placeholder would
2248 // be very, very long, we just use an abbreviation.
2249 PlaceholderStr = "template<...> class";
2250 if (TTP->getIdentifier()) {
2251 PlaceholderStr += ' ';
2252 PlaceholderStr += TTP->getIdentifier()->getName();
2253 }
2254
2255 HasDefaultArg = TTP->hasDefaultArgument();
2256 }
2257
Douglas Gregor218937c2011-02-01 19:23:04 +00002258 if (HasDefaultArg && !InDefaultArg) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002259 // When we see an optional default argument, put that argument and
2260 // the remaining default arguments into a new, optional string.
Douglas Gregor218937c2011-02-01 19:23:04 +00002261 CodeCompletionBuilder Opt(Result.getAllocator());
2262 if (!FirstParameter)
2263 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor8987b232011-09-27 23:30:47 +00002264 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
Douglas Gregor218937c2011-02-01 19:23:04 +00002265 P - Params->begin(), true);
2266 Result.AddOptionalChunk(Opt.TakeString());
2267 break;
Douglas Gregor86d9a522009-09-21 16:56:56 +00002268 }
2269
Douglas Gregor218937c2011-02-01 19:23:04 +00002270 InDefaultArg = false;
2271
Douglas Gregor86d9a522009-09-21 16:56:56 +00002272 if (FirstParameter)
2273 FirstParameter = false;
2274 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002275 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002276
2277 // Add the placeholder string.
Douglas Gregordae68752011-02-01 22:57:45 +00002278 Result.AddPlaceholderChunk(
2279 Result.getAllocator().CopyString(PlaceholderStr));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002280 }
2281}
2282
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002283/// \brief Add a qualifier to the given code-completion string, if the
2284/// provided nested-name-specifier is non-NULL.
Douglas Gregora61a8792009-12-11 18:44:16 +00002285static void
Douglas Gregor218937c2011-02-01 19:23:04 +00002286AddQualifierToCompletionString(CodeCompletionBuilder &Result,
Douglas Gregora61a8792009-12-11 18:44:16 +00002287 NestedNameSpecifier *Qualifier,
2288 bool QualifierIsInformative,
Douglas Gregor8987b232011-09-27 23:30:47 +00002289 ASTContext &Context,
2290 const PrintingPolicy &Policy) {
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002291 if (!Qualifier)
2292 return;
2293
2294 std::string PrintedNNS;
2295 {
2296 llvm::raw_string_ostream OS(PrintedNNS);
Douglas Gregor8987b232011-09-27 23:30:47 +00002297 Qualifier->print(OS, Policy);
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002298 }
Douglas Gregor0563c262009-09-22 23:15:58 +00002299 if (QualifierIsInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002300 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregor0563c262009-09-22 23:15:58 +00002301 else
Douglas Gregordae68752011-02-01 22:57:45 +00002302 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00002303}
2304
Douglas Gregor218937c2011-02-01 19:23:04 +00002305static void
2306AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2307 FunctionDecl *Function) {
Douglas Gregora61a8792009-12-11 18:44:16 +00002308 const FunctionProtoType *Proto
2309 = Function->getType()->getAs<FunctionProtoType>();
2310 if (!Proto || !Proto->getTypeQuals())
2311 return;
2312
Douglas Gregora63f6de2011-02-01 21:15:40 +00002313 // FIXME: Add ref-qualifier!
2314
2315 // Handle single qualifiers without copying
2316 if (Proto->getTypeQuals() == Qualifiers::Const) {
2317 Result.AddInformativeChunk(" const");
2318 return;
2319 }
2320
2321 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2322 Result.AddInformativeChunk(" volatile");
2323 return;
2324 }
2325
2326 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2327 Result.AddInformativeChunk(" restrict");
2328 return;
2329 }
2330
2331 // Handle multiple qualifiers.
Douglas Gregora61a8792009-12-11 18:44:16 +00002332 std::string QualsStr;
2333 if (Proto->getTypeQuals() & Qualifiers::Const)
2334 QualsStr += " const";
2335 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2336 QualsStr += " volatile";
2337 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2338 QualsStr += " restrict";
Douglas Gregordae68752011-02-01 22:57:45 +00002339 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
Douglas Gregora61a8792009-12-11 18:44:16 +00002340}
2341
Douglas Gregor6f942b22010-09-21 16:06:22 +00002342/// \brief Add the name of the given declaration
Douglas Gregor8987b232011-09-27 23:30:47 +00002343static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2344 NamedDecl *ND, CodeCompletionBuilder &Result) {
Douglas Gregor6f942b22010-09-21 16:06:22 +00002345 typedef CodeCompletionString::Chunk Chunk;
2346
2347 DeclarationName Name = ND->getDeclName();
2348 if (!Name)
2349 return;
2350
2351 switch (Name.getNameKind()) {
Douglas Gregora63f6de2011-02-01 21:15:40 +00002352 case DeclarationName::CXXOperatorName: {
2353 const char *OperatorName = 0;
2354 switch (Name.getCXXOverloadedOperator()) {
2355 case OO_None:
2356 case OO_Conditional:
2357 case NUM_OVERLOADED_OPERATORS:
2358 OperatorName = "operator";
2359 break;
2360
2361#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2362 case OO_##Name: OperatorName = "operator" Spelling; break;
2363#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2364#include "clang/Basic/OperatorKinds.def"
2365
2366 case OO_New: OperatorName = "operator new"; break;
2367 case OO_Delete: OperatorName = "operator delete"; break;
2368 case OO_Array_New: OperatorName = "operator new[]"; break;
2369 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2370 case OO_Call: OperatorName = "operator()"; break;
2371 case OO_Subscript: OperatorName = "operator[]"; break;
2372 }
2373 Result.AddTypedTextChunk(OperatorName);
2374 break;
2375 }
2376
Douglas Gregor6f942b22010-09-21 16:06:22 +00002377 case DeclarationName::Identifier:
2378 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor6f942b22010-09-21 16:06:22 +00002379 case DeclarationName::CXXDestructorName:
2380 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregordae68752011-02-01 22:57:45 +00002381 Result.AddTypedTextChunk(
2382 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002383 break;
2384
2385 case DeclarationName::CXXUsingDirective:
2386 case DeclarationName::ObjCZeroArgSelector:
2387 case DeclarationName::ObjCOneArgSelector:
2388 case DeclarationName::ObjCMultiArgSelector:
2389 break;
2390
2391 case DeclarationName::CXXConstructorName: {
2392 CXXRecordDecl *Record = 0;
2393 QualType Ty = Name.getCXXNameType();
2394 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2395 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2396 else if (const InjectedClassNameType *InjectedTy
2397 = Ty->getAs<InjectedClassNameType>())
2398 Record = InjectedTy->getDecl();
2399 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002400 Result.AddTypedTextChunk(
2401 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002402 break;
2403 }
2404
Douglas Gregordae68752011-02-01 22:57:45 +00002405 Result.AddTypedTextChunk(
2406 Result.getAllocator().CopyString(Record->getNameAsString()));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002407 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002408 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Douglas Gregor8987b232011-09-27 23:30:47 +00002409 AddTemplateParameterChunks(Context, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002410 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor6f942b22010-09-21 16:06:22 +00002411 }
2412 break;
2413 }
2414 }
2415}
2416
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002417CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
2418 CodeCompletionAllocator &Allocator) {
2419 return CreateCodeCompletionString(S.Context, S.PP, Allocator);
2420}
2421
Douglas Gregor86d9a522009-09-21 16:56:56 +00002422/// \brief If possible, create a new code completion string for the given
2423/// result.
2424///
2425/// \returns Either a new, heap-allocated code completion string describing
2426/// how to use this result, or NULL to indicate that the string or name of the
2427/// result is all that is needed.
2428CodeCompletionString *
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002429CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2430 Preprocessor &PP,
Douglas Gregordae68752011-02-01 22:57:45 +00002431 CodeCompletionAllocator &Allocator) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002432 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor218937c2011-02-01 19:23:04 +00002433 CodeCompletionBuilder Result(Allocator, Priority, Availability);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002434
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002435 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
Douglas Gregor218937c2011-02-01 19:23:04 +00002436 if (Kind == RK_Pattern) {
2437 Pattern->Priority = Priority;
2438 Pattern->Availability = Availability;
2439 return Pattern;
2440 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002441
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002442 if (Kind == RK_Keyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002443 Result.AddTypedTextChunk(Keyword);
2444 return Result.TakeString();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002445 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002446
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002447 if (Kind == RK_Macro) {
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002448 MacroInfo *MI = PP.getMacroInfo(Macro);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002449 assert(MI && "Not a macro?");
2450
Douglas Gregordae68752011-02-01 22:57:45 +00002451 Result.AddTypedTextChunk(
2452 Result.getAllocator().CopyString(Macro->getName()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002453
2454 if (!MI->isFunctionLike())
Douglas Gregor218937c2011-02-01 19:23:04 +00002455 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002456
2457 // Format a function-like macro with placeholders for the arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002458 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregore4244702011-07-30 08:17:44 +00002459 bool CombineVariadicArgument = false;
2460 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2461 if (MI->isVariadic() && AEnd - A > 1) {
2462 AEnd -= 2;
2463 CombineVariadicArgument = true;
2464 }
2465 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002466 if (A != MI->arg_begin())
Douglas Gregor218937c2011-02-01 19:23:04 +00002467 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002468
Douglas Gregore4244702011-07-30 08:17:44 +00002469 if (!MI->isVariadic() || A + 1 != AEnd) {
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002470 // Non-variadic argument.
Douglas Gregordae68752011-02-01 22:57:45 +00002471 Result.AddPlaceholderChunk(
2472 Result.getAllocator().CopyString((*A)->getName()));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002473 continue;
2474 }
2475
Douglas Gregore4244702011-07-30 08:17:44 +00002476 // Variadic argument; cope with the difference between GNU and C99
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002477 // variadic macros, providing a single placeholder for the rest of the
2478 // arguments.
2479 if ((*A)->isStr("__VA_ARGS__"))
Douglas Gregor218937c2011-02-01 19:23:04 +00002480 Result.AddPlaceholderChunk("...");
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002481 else {
2482 std::string Arg = (*A)->getName();
2483 Arg += "...";
Douglas Gregordae68752011-02-01 22:57:45 +00002484 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002485 }
2486 }
Douglas Gregore4244702011-07-30 08:17:44 +00002487
2488 if (CombineVariadicArgument) {
2489 // Handle the next-to-last argument, combining it with the variadic
2490 // argument.
2491 std::string LastArg = (*A)->getName();
2492 ++A;
2493 if ((*A)->isStr("__VA_ARGS__"))
2494 LastArg += ", ...";
2495 else
2496 LastArg += ", " + (*A)->getName().str() + "...";
2497 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(LastArg));
2498 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002499 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2500 return Result.TakeString();
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002501 }
2502
Douglas Gregord8e8a582010-05-25 21:41:55 +00002503 assert(Kind == RK_Declaration && "Missed a result kind?");
Douglas Gregor86d9a522009-09-21 16:56:56 +00002504 NamedDecl *ND = Declaration;
2505
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002506 if (StartsNestedNameSpecifier) {
Douglas Gregordae68752011-02-01 22:57:45 +00002507 Result.AddTypedTextChunk(
2508 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002509 Result.AddTextChunk("::");
2510 return Result.TakeString();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002511 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00002512
2513 for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2514 if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2515 Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2516 }
2517 }
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002518
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002519 AddResultTypeChunk(Ctx, Policy, ND, Result);
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00002520
Douglas Gregor86d9a522009-09-21 16:56:56 +00002521 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002522 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002523 Ctx, Policy);
2524 AddTypedNameChunk(Ctx, Policy, ND, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002525 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002526 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002527 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002528 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002529 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002530 }
2531
2532 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002533 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002534 Ctx, Policy);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002535 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002536 AddTypedNameChunk(Ctx, Policy, Function, Result);
Douglas Gregor6f942b22010-09-21 16:06:22 +00002537
Douglas Gregor86d9a522009-09-21 16:56:56 +00002538 // Figure out which template parameters are deduced (or have default
2539 // arguments).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002540 SmallVector<bool, 16> Deduced;
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002541 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002542 unsigned LastDeducibleArgument;
2543 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2544 --LastDeducibleArgument) {
2545 if (!Deduced[LastDeducibleArgument - 1]) {
2546 // C++0x: Figure out if the template argument has a default. If so,
2547 // the user doesn't need to type this argument.
2548 // FIXME: We need to abstract template parameters better!
2549 bool HasDefaultArg = false;
2550 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
Douglas Gregor218937c2011-02-01 19:23:04 +00002551 LastDeducibleArgument - 1);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002552 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2553 HasDefaultArg = TTP->hasDefaultArgument();
2554 else if (NonTypeTemplateParmDecl *NTTP
2555 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2556 HasDefaultArg = NTTP->hasDefaultArgument();
2557 else {
2558 assert(isa<TemplateTemplateParmDecl>(Param));
2559 HasDefaultArg
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002560 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002561 }
2562
2563 if (!HasDefaultArg)
2564 break;
2565 }
2566 }
2567
2568 if (LastDeducibleArgument) {
2569 // Some of the function template arguments cannot be deduced from a
2570 // function call, so we introduce an explicit template argument list
2571 // containing all of the arguments up to the first deducible argument.
Douglas Gregor218937c2011-02-01 19:23:04 +00002572 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002573 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
Douglas Gregor86d9a522009-09-21 16:56:56 +00002574 LastDeducibleArgument);
Douglas Gregor218937c2011-02-01 19:23:04 +00002575 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
Douglas Gregor86d9a522009-09-21 16:56:56 +00002576 }
2577
2578 // Add the function parameters
Douglas Gregor218937c2011-02-01 19:23:04 +00002579 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002580 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002581 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregora61a8792009-12-11 18:44:16 +00002582 AddFunctionTypeQualsToCompletionString(Result, Function);
Douglas Gregor218937c2011-02-01 19:23:04 +00002583 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002584 }
2585
2586 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
Douglas Gregor0563c262009-09-22 23:15:58 +00002587 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002588 Ctx, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00002589 Result.AddTypedTextChunk(
2590 Result.getAllocator().CopyString(Template->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002591 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002592 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Douglas Gregor218937c2011-02-01 19:23:04 +00002593 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2594 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002595 }
2596
Douglas Gregor9630eb62009-11-17 16:44:22 +00002597 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Douglas Gregor9630eb62009-11-17 16:44:22 +00002598 Selector Sel = Method->getSelector();
2599 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00002600 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00002601 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00002602 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002603 }
2604
Douglas Gregor813d8342011-02-18 22:29:55 +00002605 std::string SelName = Sel.getNameForSlot(0).str();
Douglas Gregord3c68542009-11-19 01:08:35 +00002606 SelName += ':';
2607 if (StartParameter == 0)
Douglas Gregordae68752011-02-01 22:57:45 +00002608 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002609 else {
Douglas Gregordae68752011-02-01 22:57:45 +00002610 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
Douglas Gregord3c68542009-11-19 01:08:35 +00002611
2612 // If there is only one parameter, and we're past it, add an empty
2613 // typed-text chunk since there is nothing to type.
2614 if (Method->param_size() == 1)
Douglas Gregor218937c2011-02-01 19:23:04 +00002615 Result.AddTypedTextChunk("");
Douglas Gregord3c68542009-11-19 01:08:35 +00002616 }
Douglas Gregor9630eb62009-11-17 16:44:22 +00002617 unsigned Idx = 0;
2618 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2619 PEnd = Method->param_end();
2620 P != PEnd; (void)++P, ++Idx) {
2621 if (Idx > 0) {
Douglas Gregord3c68542009-11-19 01:08:35 +00002622 std::string Keyword;
2623 if (Idx > StartParameter)
Douglas Gregor218937c2011-02-01 19:23:04 +00002624 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor9630eb62009-11-17 16:44:22 +00002625 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Benjamin Kramera0651c52011-07-26 16:59:25 +00002626 Keyword += II->getName();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002627 Keyword += ":";
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002628 if (Idx < StartParameter || AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002629 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002630 else
Douglas Gregordae68752011-02-01 22:57:45 +00002631 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002632 }
Douglas Gregord3c68542009-11-19 01:08:35 +00002633
2634 // If we're before the starting parameter, skip the placeholder.
2635 if (Idx < StartParameter)
2636 continue;
Douglas Gregor9630eb62009-11-17 16:44:22 +00002637
2638 std::string Arg;
Douglas Gregor83482d12010-08-24 16:15:59 +00002639
2640 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002641 Arg = FormatFunctionParameter(Ctx, Policy, *P, true);
Douglas Gregor83482d12010-08-24 16:15:59 +00002642 else {
John McCallf85e1932011-06-15 23:02:42 +00002643 (*P)->getType().getAsStringInternal(Arg, Policy);
Douglas Gregor6fa14dd2011-07-30 07:55:26 +00002644 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2645 + Arg + ")";
Douglas Gregor83482d12010-08-24 16:15:59 +00002646 if (IdentifierInfo *II = (*P)->getIdentifier())
Douglas Gregoraba48082010-08-29 19:47:46 +00002647 if (DeclaringEntity || AllParametersAreInformative)
Benjamin Kramera0651c52011-07-26 16:59:25 +00002648 Arg += II->getName();
Douglas Gregor83482d12010-08-24 16:15:59 +00002649 }
2650
Douglas Gregore17794f2010-08-31 05:13:43 +00002651 if (Method->isVariadic() && (P + 1) == PEnd)
2652 Arg += ", ...";
2653
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002654 if (DeclaringEntity)
Douglas Gregordae68752011-02-01 22:57:45 +00002655 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor1f5537a2010-07-08 23:20:03 +00002656 else if (AllParametersAreInformative)
Douglas Gregordae68752011-02-01 22:57:45 +00002657 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor4ad96852009-11-19 07:41:15 +00002658 else
Douglas Gregordae68752011-02-01 22:57:45 +00002659 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
Douglas Gregor9630eb62009-11-17 16:44:22 +00002660 }
2661
Douglas Gregor2a17af02009-12-23 00:21:46 +00002662 if (Method->isVariadic()) {
Douglas Gregore17794f2010-08-31 05:13:43 +00002663 if (Method->param_size() == 0) {
2664 if (DeclaringEntity)
Douglas Gregor218937c2011-02-01 19:23:04 +00002665 Result.AddTextChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002666 else if (AllParametersAreInformative)
Douglas Gregor218937c2011-02-01 19:23:04 +00002667 Result.AddInformativeChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002668 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002669 Result.AddPlaceholderChunk(", ...");
Douglas Gregore17794f2010-08-31 05:13:43 +00002670 }
Douglas Gregoraaa107a2010-08-23 23:51:41 +00002671
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002672 MaybeAddSentinel(Ctx, Method, Result);
Douglas Gregor2a17af02009-12-23 00:21:46 +00002673 }
2674
Douglas Gregor218937c2011-02-01 19:23:04 +00002675 return Result.TakeString();
Douglas Gregor9630eb62009-11-17 16:44:22 +00002676 }
2677
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002678 if (Qualifier)
Douglas Gregor0563c262009-09-22 23:15:58 +00002679 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Argyrios Kyrtzidisea8c59a2012-01-17 02:15:51 +00002680 Ctx, Policy);
Douglas Gregor2b4074f2009-12-01 05:55:20 +00002681
Douglas Gregordae68752011-02-01 22:57:45 +00002682 Result.AddTypedTextChunk(
2683 Result.getAllocator().CopyString(ND->getNameAsString()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002684 return Result.TakeString();
Douglas Gregor86d9a522009-09-21 16:56:56 +00002685}
2686
Douglas Gregor86d802e2009-09-23 00:34:09 +00002687CodeCompletionString *
2688CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2689 unsigned CurrentArg,
Douglas Gregor32be4a52010-10-11 21:37:58 +00002690 Sema &S,
Douglas Gregordae68752011-02-01 22:57:45 +00002691 CodeCompletionAllocator &Allocator) const {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002692 typedef CodeCompletionString::Chunk Chunk;
Douglas Gregor8987b232011-09-27 23:30:47 +00002693 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
John McCallf85e1932011-06-15 23:02:42 +00002694
Douglas Gregor218937c2011-02-01 19:23:04 +00002695 // FIXME: Set priority, availability appropriately.
2696 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002697 FunctionDecl *FDecl = getFunction();
Douglas Gregor8987b232011-09-27 23:30:47 +00002698 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002699 const FunctionProtoType *Proto
2700 = dyn_cast<FunctionProtoType>(getFunctionType());
2701 if (!FDecl && !Proto) {
2702 // Function without a prototype. Just give the return type and a
2703 // highlighted ellipsis.
2704 const FunctionType *FT = getFunctionType();
Douglas Gregora63f6de2011-02-01 21:15:40 +00002705 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
Douglas Gregor8987b232011-09-27 23:30:47 +00002706 S.Context, Policy,
Douglas Gregora63f6de2011-02-01 21:15:40 +00002707 Result.getAllocator()));
Douglas Gregor218937c2011-02-01 19:23:04 +00002708 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2709 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2710 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2711 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002712 }
2713
2714 if (FDecl)
Douglas Gregordae68752011-02-01 22:57:45 +00002715 Result.AddTextChunk(
2716 Result.getAllocator().CopyString(FDecl->getNameAsString()));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002717 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002718 Result.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00002719 Result.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00002720 Proto->getResultType().getAsString(Policy)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002721
Douglas Gregor218937c2011-02-01 19:23:04 +00002722 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002723 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2724 for (unsigned I = 0; I != NumParams; ++I) {
2725 if (I)
Douglas Gregor218937c2011-02-01 19:23:04 +00002726 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002727
2728 std::string ArgString;
2729 QualType ArgType;
2730
2731 if (FDecl) {
2732 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2733 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2734 } else {
2735 ArgType = Proto->getArgType(I);
2736 }
2737
John McCallf85e1932011-06-15 23:02:42 +00002738 ArgType.getAsStringInternal(ArgString, Policy);
Douglas Gregor86d802e2009-09-23 00:34:09 +00002739
2740 if (I == CurrentArg)
Douglas Gregor218937c2011-02-01 19:23:04 +00002741 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
Douglas Gregordae68752011-02-01 22:57:45 +00002742 Result.getAllocator().CopyString(ArgString)));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002743 else
Douglas Gregordae68752011-02-01 22:57:45 +00002744 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002745 }
2746
2747 if (Proto && Proto->isVariadic()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002748 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002749 if (CurrentArg < NumParams)
Douglas Gregor218937c2011-02-01 19:23:04 +00002750 Result.AddTextChunk("...");
Douglas Gregor86d802e2009-09-23 00:34:09 +00002751 else
Douglas Gregor218937c2011-02-01 19:23:04 +00002752 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002753 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002754 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
Douglas Gregor86d802e2009-09-23 00:34:09 +00002755
Douglas Gregor218937c2011-02-01 19:23:04 +00002756 return Result.TakeString();
Douglas Gregor86d802e2009-09-23 00:34:09 +00002757}
2758
Chris Lattner5f9e2722011-07-23 10:55:15 +00002759unsigned clang::getMacroUsagePriority(StringRef MacroName,
Douglas Gregorb05496d2010-09-20 21:11:48 +00002760 const LangOptions &LangOpts,
Douglas Gregor1827e102010-08-16 16:18:59 +00002761 bool PreferredTypeIsPointer) {
2762 unsigned Priority = CCP_Macro;
2763
Douglas Gregorb05496d2010-09-20 21:11:48 +00002764 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2765 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2766 MacroName.equals("Nil")) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002767 Priority = CCP_Constant;
2768 if (PreferredTypeIsPointer)
2769 Priority = Priority / CCF_SimilarTypeMatch;
Douglas Gregorb05496d2010-09-20 21:11:48 +00002770 }
2771 // Treat "YES", "NO", "true", and "false" as constants.
2772 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2773 MacroName.equals("true") || MacroName.equals("false"))
2774 Priority = CCP_Constant;
2775 // Treat "bool" as a type.
2776 else if (MacroName.equals("bool"))
2777 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2778
Douglas Gregor1827e102010-08-16 16:18:59 +00002779
2780 return Priority;
2781}
2782
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002783CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2784 if (!D)
2785 return CXCursor_UnexposedDecl;
2786
2787 switch (D->getKind()) {
2788 case Decl::Enum: return CXCursor_EnumDecl;
2789 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2790 case Decl::Field: return CXCursor_FieldDecl;
2791 case Decl::Function:
2792 return CXCursor_FunctionDecl;
2793 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2794 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002795 // FIXME
2796 return CXCursor_UnexposedDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002797 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
Douglas Gregor375bb142011-12-27 22:43:10 +00002798
2799 case Decl::ObjCInterface:
2800 if (cast<ObjCInterfaceDecl>(D)->isThisDeclarationADefinition())
2801 return CXCursor_ObjCInterfaceDecl;
2802
2803 // Forward declarations are not directly exposed.
2804 return CXCursor_UnexposedDecl;
2805
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002806 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2807 case Decl::ObjCMethod:
2808 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2809 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2810 case Decl::CXXMethod: return CXCursor_CXXMethod;
2811 case Decl::CXXConstructor: return CXCursor_Constructor;
2812 case Decl::CXXDestructor: return CXCursor_Destructor;
2813 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2814 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
Douglas Gregorbd9482d2012-01-01 21:23:57 +00002815 case Decl::ObjCProtocol:
2816 if (cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition())
2817 return CXCursor_ObjCProtocolDecl;
2818
2819 return CXCursor_UnexposedDecl;
2820
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002821 case Decl::ParmVar: return CXCursor_ParmDecl;
2822 case Decl::Typedef: return CXCursor_TypedefDecl;
Richard Smith162e1c12011-04-15 14:24:37 +00002823 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002824 case Decl::Var: return CXCursor_VarDecl;
2825 case Decl::Namespace: return CXCursor_Namespace;
2826 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2827 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2828 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2829 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2830 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2831 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00002832 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002833 case Decl::ClassTemplatePartialSpecialization:
2834 return CXCursor_ClassTemplatePartialSpecialization;
2835 case Decl::UsingDirective: return CXCursor_UsingDirective;
2836
2837 case Decl::Using:
2838 case Decl::UnresolvedUsingValue:
2839 case Decl::UnresolvedUsingTypename:
2840 return CXCursor_UsingDeclaration;
2841
Douglas Gregor352697a2011-06-03 23:08:58 +00002842 case Decl::ObjCPropertyImpl:
2843 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2844 case ObjCPropertyImplDecl::Dynamic:
2845 return CXCursor_ObjCDynamicDecl;
2846
2847 case ObjCPropertyImplDecl::Synthesize:
2848 return CXCursor_ObjCSynthesizeDecl;
2849 }
2850 break;
2851
Douglas Gregore8d7beb2010-09-03 23:30:36 +00002852 default:
2853 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2854 switch (TD->getTagKind()) {
2855 case TTK_Struct: return CXCursor_StructDecl;
2856 case TTK_Class: return CXCursor_ClassDecl;
2857 case TTK_Union: return CXCursor_UnionDecl;
2858 case TTK_Enum: return CXCursor_EnumDecl;
2859 }
2860 }
2861 }
2862
2863 return CXCursor_UnexposedDecl;
2864}
2865
Douglas Gregor590c7d52010-07-08 20:55:51 +00002866static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2867 bool TargetTypeIsPointer = false) {
John McCall0a2c5e22010-08-25 06:19:51 +00002868 typedef CodeCompletionResult Result;
Douglas Gregor590c7d52010-07-08 20:55:51 +00002869
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002870 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002871
Douglas Gregor0c8296d2009-11-07 00:00:49 +00002872 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2873 MEnd = PP.macro_end();
Douglas Gregor590c7d52010-07-08 20:55:51 +00002874 M != MEnd; ++M) {
Douglas Gregor1827e102010-08-16 16:18:59 +00002875 Results.AddResult(Result(M->first,
2876 getMacroUsagePriority(M->first->getName(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002877 PP.getLangOptions(),
Douglas Gregor1827e102010-08-16 16:18:59 +00002878 TargetTypeIsPointer)));
Douglas Gregor590c7d52010-07-08 20:55:51 +00002879 }
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002880
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002881 Results.ExitScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002882
Douglas Gregor3f7c7f42009-10-30 16:50:04 +00002883}
2884
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002885static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2886 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00002887 typedef CodeCompletionResult Result;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002888
2889 Results.EnterNewScope();
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +00002890
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00002891 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2892 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2893 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2894 Results.AddResult(Result("__func__", CCP_Constant));
2895 Results.ExitScope();
2896}
2897
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00002898static void HandleCodeCompleteResults(Sema *S,
2899 CodeCompleteConsumer *CodeCompleter,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002900 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002901 CodeCompletionResult *Results,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002902 unsigned NumResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00002903 if (CodeCompleter)
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002904 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
Douglas Gregor86d9a522009-09-21 16:56:56 +00002905}
2906
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002907static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2908 Sema::ParserCompletionContext PCC) {
2909 switch (PCC) {
John McCallf312b1e2010-08-26 23:41:50 +00002910 case Sema::PCC_Namespace:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002911 return CodeCompletionContext::CCC_TopLevel;
2912
John McCallf312b1e2010-08-26 23:41:50 +00002913 case Sema::PCC_Class:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002914 return CodeCompletionContext::CCC_ClassStructUnion;
2915
John McCallf312b1e2010-08-26 23:41:50 +00002916 case Sema::PCC_ObjCInterface:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002917 return CodeCompletionContext::CCC_ObjCInterface;
2918
John McCallf312b1e2010-08-26 23:41:50 +00002919 case Sema::PCC_ObjCImplementation:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002920 return CodeCompletionContext::CCC_ObjCImplementation;
2921
John McCallf312b1e2010-08-26 23:41:50 +00002922 case Sema::PCC_ObjCInstanceVariableList:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002923 return CodeCompletionContext::CCC_ObjCIvarList;
2924
John McCallf312b1e2010-08-26 23:41:50 +00002925 case Sema::PCC_Template:
2926 case Sema::PCC_MemberTemplate:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002927 if (S.CurContext->isFileContext())
2928 return CodeCompletionContext::CCC_TopLevel;
2929 else if (S.CurContext->isRecord())
2930 return CodeCompletionContext::CCC_ClassStructUnion;
2931 else
2932 return CodeCompletionContext::CCC_Other;
2933
John McCallf312b1e2010-08-26 23:41:50 +00002934 case Sema::PCC_RecoveryInFunction:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002935 return CodeCompletionContext::CCC_Recovery;
Douglas Gregora5450a02010-10-18 22:01:46 +00002936
John McCallf312b1e2010-08-26 23:41:50 +00002937 case Sema::PCC_ForInit:
Douglas Gregora5450a02010-10-18 22:01:46 +00002938 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2939 S.getLangOptions().ObjC1)
2940 return CodeCompletionContext::CCC_ParenthesizedExpression;
2941 else
2942 return CodeCompletionContext::CCC_Expression;
2943
2944 case Sema::PCC_Expression:
John McCallf312b1e2010-08-26 23:41:50 +00002945 case Sema::PCC_Condition:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002946 return CodeCompletionContext::CCC_Expression;
2947
John McCallf312b1e2010-08-26 23:41:50 +00002948 case Sema::PCC_Statement:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002949 return CodeCompletionContext::CCC_Statement;
Douglas Gregor72db1082010-08-24 01:11:00 +00002950
John McCallf312b1e2010-08-26 23:41:50 +00002951 case Sema::PCC_Type:
Douglas Gregor72db1082010-08-24 01:11:00 +00002952 return CodeCompletionContext::CCC_Type;
Douglas Gregor02688102010-09-14 23:59:36 +00002953
2954 case Sema::PCC_ParenthesizedExpression:
2955 return CodeCompletionContext::CCC_ParenthesizedExpression;
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00002956
2957 case Sema::PCC_LocalDeclarationSpecifiers:
2958 return CodeCompletionContext::CCC_Type;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00002959 }
2960
2961 return CodeCompletionContext::CCC_Other;
2962}
2963
Douglas Gregorf6961522010-08-27 21:18:54 +00002964/// \brief If we're in a C++ virtual member function, add completion results
2965/// that invoke the functions we override, since it's common to invoke the
2966/// overridden function as well as adding new functionality.
2967///
2968/// \param S The semantic analysis object for which we are generating results.
2969///
2970/// \param InContext This context in which the nested-name-specifier preceding
2971/// the code-completion point
2972static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2973 ResultBuilder &Results) {
2974 // Look through blocks.
2975 DeclContext *CurContext = S.CurContext;
2976 while (isa<BlockDecl>(CurContext))
2977 CurContext = CurContext->getParent();
2978
2979
2980 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2981 if (!Method || !Method->isVirtual())
2982 return;
2983
2984 // We need to have names for all of the parameters, if we're going to
2985 // generate a forwarding call.
2986 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2987 PEnd = Method->param_end();
2988 P != PEnd;
2989 ++P) {
2990 if (!(*P)->getDeclName())
2991 return;
2992 }
2993
Douglas Gregor8987b232011-09-27 23:30:47 +00002994 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Douglas Gregorf6961522010-08-27 21:18:54 +00002995 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2996 MEnd = Method->end_overridden_methods();
2997 M != MEnd; ++M) {
Douglas Gregor218937c2011-02-01 19:23:04 +00002998 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorf6961522010-08-27 21:18:54 +00002999 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
3000 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3001 continue;
3002
3003 // If we need a nested-name-specifier, add one now.
3004 if (!InContext) {
3005 NestedNameSpecifier *NNS
3006 = getRequiredQualification(S.Context, CurContext,
3007 Overridden->getDeclContext());
3008 if (NNS) {
3009 std::string Str;
3010 llvm::raw_string_ostream OS(Str);
Douglas Gregor8987b232011-09-27 23:30:47 +00003011 NNS->print(OS, Policy);
Douglas Gregordae68752011-02-01 22:57:45 +00003012 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003013 }
3014 } else if (!InContext->Equals(Overridden->getDeclContext()))
3015 continue;
3016
Douglas Gregordae68752011-02-01 22:57:45 +00003017 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003018 Overridden->getNameAsString()));
3019 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregorf6961522010-08-27 21:18:54 +00003020 bool FirstParam = true;
3021 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3022 PEnd = Method->param_end();
3023 P != PEnd; ++P) {
3024 if (FirstParam)
3025 FirstParam = false;
3026 else
Douglas Gregor218937c2011-02-01 19:23:04 +00003027 Builder.AddChunk(CodeCompletionString::CK_Comma);
Douglas Gregorf6961522010-08-27 21:18:54 +00003028
Douglas Gregordae68752011-02-01 22:57:45 +00003029 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00003030 (*P)->getIdentifier()->getName()));
Douglas Gregorf6961522010-08-27 21:18:54 +00003031 }
Douglas Gregor218937c2011-02-01 19:23:04 +00003032 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3033 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregorf6961522010-08-27 21:18:54 +00003034 CCP_SuperCompletion,
3035 CXCursor_CXXMethod));
3036 Results.Ignore(Overridden);
3037 }
3038}
3039
Douglas Gregor01dfea02010-01-10 23:08:15 +00003040void Sema::CodeCompleteOrdinaryName(Scope *S,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003041 ParserCompletionContext CompletionContext) {
John McCall0a2c5e22010-08-25 06:19:51 +00003042 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003043 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003044 mapCodeCompletionContext(*this, CompletionContext));
Douglas Gregorf6961522010-08-27 21:18:54 +00003045 Results.EnterNewScope();
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003046
Douglas Gregor01dfea02010-01-10 23:08:15 +00003047 // Determine how to filter results, e.g., so that the names of
3048 // values (functions, enumerators, function templates, etc.) are
3049 // only allowed where we can have an expression.
3050 switch (CompletionContext) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003051 case PCC_Namespace:
3052 case PCC_Class:
3053 case PCC_ObjCInterface:
3054 case PCC_ObjCImplementation:
3055 case PCC_ObjCInstanceVariableList:
3056 case PCC_Template:
3057 case PCC_MemberTemplate:
Douglas Gregor72db1082010-08-24 01:11:00 +00003058 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003059 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor01dfea02010-01-10 23:08:15 +00003060 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3061 break;
3062
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003063 case PCC_Statement:
Douglas Gregor02688102010-09-14 23:59:36 +00003064 case PCC_ParenthesizedExpression:
Douglas Gregoreb0d0142010-08-24 23:58:17 +00003065 case PCC_Expression:
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003066 case PCC_ForInit:
3067 case PCC_Condition:
Douglas Gregor4710e5b2010-05-28 00:49:12 +00003068 if (WantTypesInContext(CompletionContext, getLangOptions()))
3069 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3070 else
3071 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorf6961522010-08-27 21:18:54 +00003072
3073 if (getLangOptions().CPlusPlus)
3074 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
Douglas Gregor01dfea02010-01-10 23:08:15 +00003075 break;
Douglas Gregordc845342010-05-25 05:58:43 +00003076
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003077 case PCC_RecoveryInFunction:
Douglas Gregordc845342010-05-25 05:58:43 +00003078 // Unfiltered
3079 break;
Douglas Gregor01dfea02010-01-10 23:08:15 +00003080 }
3081
Douglas Gregor3cdee122010-08-26 16:36:48 +00003082 // If we are in a C++ non-static member function, check the qualifiers on
3083 // the member function to filter/prioritize the results list.
3084 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3085 if (CurMethod->isInstance())
3086 Results.setObjectTypeQualifiers(
3087 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3088
Douglas Gregor1ca6ae82010-01-14 01:09:38 +00003089 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003090 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3091 CodeCompleter->includeGlobals());
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003092
Douglas Gregorbca403c2010-01-13 23:51:12 +00003093 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Douglas Gregor2a7925c2009-12-07 09:54:55 +00003094 Results.ExitScope();
3095
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003096 switch (CompletionContext) {
Douglas Gregor02688102010-09-14 23:59:36 +00003097 case PCC_ParenthesizedExpression:
Douglas Gregor72db1082010-08-24 01:11:00 +00003098 case PCC_Expression:
3099 case PCC_Statement:
3100 case PCC_RecoveryInFunction:
3101 if (S->getFnParent())
3102 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3103 break;
3104
3105 case PCC_Namespace:
3106 case PCC_Class:
3107 case PCC_ObjCInterface:
3108 case PCC_ObjCImplementation:
3109 case PCC_ObjCInstanceVariableList:
3110 case PCC_Template:
3111 case PCC_MemberTemplate:
3112 case PCC_ForInit:
3113 case PCC_Condition:
3114 case PCC_Type:
Douglas Gregor68e3c2e2011-02-15 20:33:25 +00003115 case PCC_LocalDeclarationSpecifiers:
Douglas Gregor72db1082010-08-24 01:11:00 +00003116 break;
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003117 }
3118
Douglas Gregor0c8296d2009-11-07 00:00:49 +00003119 if (CodeCompleter->includeMacros())
Douglas Gregorbca403c2010-01-13 23:51:12 +00003120 AddMacroResults(PP, Results);
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003121
Douglas Gregorcee9ff12010-09-20 22:39:41 +00003122 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003123 Results.data(),Results.size());
Douglas Gregor791215b2009-09-21 20:51:25 +00003124}
3125
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003126static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3127 ParsedType Receiver,
3128 IdentifierInfo **SelIdents,
3129 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003130 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003131 bool IsSuper,
3132 ResultBuilder &Results);
3133
3134void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3135 bool AllowNonIdentifiers,
3136 bool AllowNestedNameSpecifiers) {
John McCall0a2c5e22010-08-25 06:19:51 +00003137 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003138 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003139 AllowNestedNameSpecifiers
3140 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3141 : CodeCompletionContext::CCC_Name);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003142 Results.EnterNewScope();
3143
3144 // Type qualifiers can come after names.
3145 Results.AddResult(Result("const"));
3146 Results.AddResult(Result("volatile"));
3147 if (getLangOptions().C99)
3148 Results.AddResult(Result("restrict"));
3149
3150 if (getLangOptions().CPlusPlus) {
3151 if (AllowNonIdentifiers) {
3152 Results.AddResult(Result("operator"));
3153 }
3154
3155 // Add nested-name-specifiers.
3156 if (AllowNestedNameSpecifiers) {
3157 Results.allowNestedNameSpecifiers();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003158 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003159 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3160 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3161 CodeCompleter->includeGlobals());
Douglas Gregor52779fb2010-09-23 23:01:17 +00003162 Results.setFilter(0);
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003163 }
3164 }
3165 Results.ExitScope();
3166
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003167 // If we're in a context where we might have an expression (rather than a
3168 // declaration), and what we've seen so far is an Objective-C type that could
3169 // be a receiver of a class message, this may be a class message send with
3170 // the initial opening bracket '[' missing. Add appropriate completions.
3171 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3172 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3173 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3174 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3175 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3176 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3177 DS.getTypeQualifiers() == 0 &&
3178 S &&
3179 (S->getFlags() & Scope::DeclScope) != 0 &&
3180 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3181 Scope::FunctionPrototypeScope |
3182 Scope::AtCatchScope)) == 0) {
3183 ParsedType T = DS.getRepAsType();
3184 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
Douglas Gregor70c5ac72010-09-20 23:34:21 +00003185 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
Douglas Gregorc7b6d882010-09-16 15:14:18 +00003186 }
3187
Douglas Gregor4497dd42010-08-24 04:59:56 +00003188 // Note that we intentionally suppress macro results here, since we do not
3189 // encourage using macros to produce the names of entities.
3190
Douglas Gregor52779fb2010-09-23 23:01:17 +00003191 HandleCodeCompleteResults(this, CodeCompleter,
3192 Results.getCompletionContext(),
Douglas Gregor2ccccb32010-08-23 18:23:48 +00003193 Results.data(), Results.size());
3194}
3195
Douglas Gregorfb629412010-08-23 21:17:50 +00003196struct Sema::CodeCompleteExpressionData {
3197 CodeCompleteExpressionData(QualType PreferredType = QualType())
3198 : PreferredType(PreferredType), IntegralConstantExpression(false),
3199 ObjCCollection(false) { }
3200
3201 QualType PreferredType;
3202 bool IntegralConstantExpression;
3203 bool ObjCCollection;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003204 SmallVector<Decl *, 4> IgnoreDecls;
Douglas Gregorfb629412010-08-23 21:17:50 +00003205};
3206
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003207/// \brief Perform code-completion in an expression context when we know what
3208/// type we're looking for.
Douglas Gregorf9578432010-07-28 21:50:18 +00003209///
3210/// \param IntegralConstantExpression Only permit integral constant
3211/// expressions.
Douglas Gregorfb629412010-08-23 21:17:50 +00003212void Sema::CodeCompleteExpression(Scope *S,
3213 const CodeCompleteExpressionData &Data) {
John McCall0a2c5e22010-08-25 06:19:51 +00003214 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00003215 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3216 CodeCompletionContext::CCC_Expression);
Douglas Gregorfb629412010-08-23 21:17:50 +00003217 if (Data.ObjCCollection)
3218 Results.setFilter(&ResultBuilder::IsObjCCollection);
3219 else if (Data.IntegralConstantExpression)
Douglas Gregorf9578432010-07-28 21:50:18 +00003220 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003221 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003222 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3223 else
3224 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
Douglas Gregorfb629412010-08-23 21:17:50 +00003225
3226 if (!Data.PreferredType.isNull())
3227 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3228
3229 // Ignore any declarations that we were told that we don't care about.
3230 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3231 Results.Ignore(Data.IgnoreDecls[I]);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003232
3233 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003234 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3235 CodeCompleter->includeGlobals());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003236
3237 Results.EnterNewScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003238 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003239 Results.ExitScope();
3240
Douglas Gregor590c7d52010-07-08 20:55:51 +00003241 bool PreferredTypeIsPointer = false;
Douglas Gregorfb629412010-08-23 21:17:50 +00003242 if (!Data.PreferredType.isNull())
3243 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3244 || Data.PreferredType->isMemberPointerType()
3245 || Data.PreferredType->isBlockPointerType();
Douglas Gregor590c7d52010-07-08 20:55:51 +00003246
Douglas Gregoraa5f77b2010-08-23 21:54:33 +00003247 if (S->getFnParent() &&
3248 !Data.ObjCCollection &&
3249 !Data.IntegralConstantExpression)
3250 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3251
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003252 if (CodeCompleter->includeMacros())
Douglas Gregor590c7d52010-07-08 20:55:51 +00003253 AddMacroResults(PP, Results, PreferredTypeIsPointer);
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003254 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregorfb629412010-08-23 21:17:50 +00003255 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3256 Data.PreferredType),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003257 Results.data(),Results.size());
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003258}
3259
Douglas Gregorac5fd842010-09-18 01:28:11 +00003260void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3261 if (E.isInvalid())
3262 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3263 else if (getLangOptions().ObjC1)
3264 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
Douglas Gregor78edf512010-09-15 16:23:04 +00003265}
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003266
Douglas Gregor73449212010-12-09 23:01:55 +00003267/// \brief The set of properties that have already been added, referenced by
3268/// property name.
3269typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3270
Douglas Gregor95ac6552009-11-18 01:29:26 +00003271static void AddObjCProperties(ObjCContainerDecl *Container,
Douglas Gregor322328b2009-11-18 22:32:06 +00003272 bool AllowCategories,
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003273 bool AllowNullaryMethods,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003274 DeclContext *CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003275 AddedPropertiesSet &AddedProperties,
Douglas Gregor95ac6552009-11-18 01:29:26 +00003276 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00003277 typedef CodeCompletionResult Result;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003278
3279 // Add properties in this container.
3280 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3281 PEnd = Container->prop_end();
3282 P != PEnd;
Douglas Gregor73449212010-12-09 23:01:55 +00003283 ++P) {
3284 if (AddedProperties.insert(P->getIdentifier()))
3285 Results.MaybeAddResult(Result(*P, 0), CurContext);
3286 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003287
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003288 // Add nullary methods
3289 if (AllowNullaryMethods) {
3290 ASTContext &Context = Container->getASTContext();
Douglas Gregor8987b232011-09-27 23:30:47 +00003291 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003292 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3293 MEnd = Container->meth_end();
3294 M != MEnd; ++M) {
3295 if (M->getSelector().isUnarySelector())
3296 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3297 if (AddedProperties.insert(Name)) {
3298 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor8987b232011-09-27 23:30:47 +00003299 AddResultTypeChunk(Context, Policy, *M, Builder);
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003300 Builder.AddTypedTextChunk(
3301 Results.getAllocator().CopyString(Name->getName()));
3302
3303 CXAvailabilityKind Availability = CXAvailability_Available;
3304 switch (M->getAvailability()) {
3305 case AR_Available:
3306 case AR_NotYetIntroduced:
3307 Availability = CXAvailability_Available;
3308 break;
3309
3310 case AR_Deprecated:
3311 Availability = CXAvailability_Deprecated;
3312 break;
3313
3314 case AR_Unavailable:
3315 Availability = CXAvailability_NotAvailable;
3316 break;
3317 }
3318
3319 Results.MaybeAddResult(Result(Builder.TakeString(),
3320 CCP_MemberDeclaration + CCD_MethodAsProperty,
3321 M->isInstanceMethod()
3322 ? CXCursor_ObjCInstanceMethodDecl
3323 : CXCursor_ObjCClassMethodDecl,
3324 Availability),
3325 CurContext);
3326 }
3327 }
3328 }
3329
3330
Douglas Gregor95ac6552009-11-18 01:29:26 +00003331 // Add properties in referenced protocols.
3332 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3333 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3334 PEnd = Protocol->protocol_end();
3335 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003336 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3337 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003338 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
Douglas Gregor322328b2009-11-18 22:32:06 +00003339 if (AllowCategories) {
3340 // Look through categories.
3341 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3342 Category; Category = Category->getNextClassCategory())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003343 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3344 CurContext, AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00003345 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003346
3347 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003348 for (ObjCInterfaceDecl::all_protocol_iterator
3349 I = IFace->all_referenced_protocol_begin(),
3350 E = IFace->all_referenced_protocol_end(); I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003351 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3352 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003353
3354 // Look in the superclass.
3355 if (IFace->getSuperClass())
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003356 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3357 AllowNullaryMethods, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003358 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003359 } else if (const ObjCCategoryDecl *Category
3360 = dyn_cast<ObjCCategoryDecl>(Container)) {
3361 // Look through protocols.
Ted Kremenek53b94412010-09-01 01:21:15 +00003362 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3363 PEnd = Category->protocol_end();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003364 P != PEnd; ++P)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003365 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3366 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003367 }
3368}
3369
Richard Trieuf81e5a92011-09-09 02:00:50 +00003370void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *BaseE,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003371 SourceLocation OpLoc,
3372 bool IsArrow) {
3373 if (!BaseE || !CodeCompleter)
3374 return;
3375
John McCall0a2c5e22010-08-25 06:19:51 +00003376 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003377
Douglas Gregor81b747b2009-09-17 21:32:03 +00003378 Expr *Base = static_cast<Expr *>(BaseE);
3379 QualType BaseType = Base->getType();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003380
3381 if (IsArrow) {
3382 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3383 BaseType = Ptr->getPointeeType();
3384 else if (BaseType->isObjCObjectPointerType())
Douglas Gregor3cdee122010-08-26 16:36:48 +00003385 /*Do nothing*/ ;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003386 else
3387 return;
3388 }
3389
Douglas Gregor3da626b2011-07-07 16:03:39 +00003390 enum CodeCompletionContext::Kind contextKind;
3391
3392 if (IsArrow) {
3393 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3394 }
3395 else {
3396 if (BaseType->isObjCObjectPointerType() ||
3397 BaseType->isObjCObjectOrInterfaceType()) {
3398 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3399 }
3400 else {
3401 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3402 }
3403 }
3404
Douglas Gregor218937c2011-02-01 19:23:04 +00003405 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00003406 CodeCompletionContext(contextKind,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003407 BaseType),
3408 &ResultBuilder::IsMember);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003409 Results.EnterNewScope();
3410 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
Douglas Gregor3cdee122010-08-26 16:36:48 +00003411 // Indicate that we are performing a member access, and the cv-qualifiers
3412 // for the base object type.
3413 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3414
Douglas Gregor95ac6552009-11-18 01:29:26 +00003415 // Access to a C/C++ class, struct, or union.
Douglas Gregor45bcd432010-01-14 03:21:49 +00003416 Results.allowNestedNameSpecifiers();
Douglas Gregor0cc84042010-01-14 15:47:35 +00003417 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003418 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3419 CodeCompleter->includeGlobals());
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003420
Douglas Gregor95ac6552009-11-18 01:29:26 +00003421 if (getLangOptions().CPlusPlus) {
3422 if (!Results.empty()) {
3423 // The "template" keyword can follow "->" or "." in the grammar.
3424 // However, we only want to suggest the template keyword if something
3425 // is dependent.
3426 bool IsDependent = BaseType->isDependentType();
3427 if (!IsDependent) {
3428 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3429 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3430 IsDependent = Ctx->isDependentContext();
3431 break;
3432 }
3433 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003434
Douglas Gregor95ac6552009-11-18 01:29:26 +00003435 if (IsDependent)
Douglas Gregora4477812010-01-14 16:01:26 +00003436 Results.AddResult(Result("template"));
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003437 }
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003438 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003439 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3440 // Objective-C property reference.
Douglas Gregor73449212010-12-09 23:01:55 +00003441 AddedPropertiesSet AddedProperties;
Douglas Gregor95ac6552009-11-18 01:29:26 +00003442
3443 // Add property results based on our interface.
3444 const ObjCObjectPointerType *ObjCPtr
3445 = BaseType->getAsObjCInterfacePointerType();
3446 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003447 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3448 /*AllowNullaryMethods=*/true, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00003449 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003450
3451 // Add properties from the protocols in a qualified interface.
3452 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3453 E = ObjCPtr->qual_end();
3454 I != E; ++I)
Douglas Gregor4b81cde2011-05-05 15:50:42 +00003455 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3456 AddedProperties, Results);
Douglas Gregor95ac6552009-11-18 01:29:26 +00003457 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003458 (!IsArrow && BaseType->isObjCObjectType())) {
Douglas Gregor95ac6552009-11-18 01:29:26 +00003459 // Objective-C instance variable access.
3460 ObjCInterfaceDecl *Class = 0;
3461 if (const ObjCObjectPointerType *ObjCPtr
3462 = BaseType->getAs<ObjCObjectPointerType>())
3463 Class = ObjCPtr->getInterfaceDecl();
3464 else
John McCallc12c5bb2010-05-15 11:32:37 +00003465 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor95ac6552009-11-18 01:29:26 +00003466
3467 // Add all ivars from this class and its superclasses.
Douglas Gregor80f4f4c2010-01-14 16:08:12 +00003468 if (Class) {
3469 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3470 Results.setFilter(&ResultBuilder::IsObjCIvar);
Douglas Gregor8071e422010-08-15 06:18:01 +00003471 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3472 CodeCompleter->includeGlobals());
Douglas Gregor95ac6552009-11-18 01:29:26 +00003473 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003474 }
Douglas Gregor95ac6552009-11-18 01:29:26 +00003475
3476 // FIXME: How do we cope with isa?
3477
3478 Results.ExitScope();
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003479
Daniel Dunbar3a2838d2009-11-13 08:58:20 +00003480 // Hand off the results found for code completion.
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003481 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003482 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003483 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003484}
3485
Douglas Gregor374929f2009-09-18 15:37:17 +00003486void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3487 if (!CodeCompleter)
3488 return;
3489
John McCall0a2c5e22010-08-25 06:19:51 +00003490 typedef CodeCompletionResult Result;
Douglas Gregor86d9a522009-09-21 16:56:56 +00003491 ResultBuilder::LookupFilter Filter = 0;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003492 enum CodeCompletionContext::Kind ContextKind
3493 = CodeCompletionContext::CCC_Other;
Douglas Gregor374929f2009-09-18 15:37:17 +00003494 switch ((DeclSpec::TST)TagSpec) {
3495 case DeclSpec::TST_enum:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003496 Filter = &ResultBuilder::IsEnum;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003497 ContextKind = CodeCompletionContext::CCC_EnumTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003498 break;
3499
3500 case DeclSpec::TST_union:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003501 Filter = &ResultBuilder::IsUnion;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003502 ContextKind = CodeCompletionContext::CCC_UnionTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003503 break;
3504
3505 case DeclSpec::TST_struct:
Douglas Gregor374929f2009-09-18 15:37:17 +00003506 case DeclSpec::TST_class:
Douglas Gregor86d9a522009-09-21 16:56:56 +00003507 Filter = &ResultBuilder::IsClassOrStruct;
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003508 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
Douglas Gregor374929f2009-09-18 15:37:17 +00003509 break;
3510
3511 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003512 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
Douglas Gregor374929f2009-09-18 15:37:17 +00003513 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003514
Douglas Gregor218937c2011-02-01 19:23:04 +00003515 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003516 CodeCompletionDeclConsumer Consumer(Results, CurContext);
John McCall0d6b1642010-04-23 18:46:30 +00003517
3518 // First pass: look for tags.
3519 Results.setFilter(Filter);
Douglas Gregor8071e422010-08-15 06:18:01 +00003520 LookupVisibleDecls(S, LookupTagName, Consumer,
3521 CodeCompleter->includeGlobals());
John McCall0d6b1642010-04-23 18:46:30 +00003522
Douglas Gregor8071e422010-08-15 06:18:01 +00003523 if (CodeCompleter->includeGlobals()) {
3524 // Second pass: look for nested name specifiers.
3525 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3526 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3527 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00003528
Douglas Gregor52779fb2010-09-23 23:01:17 +00003529 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003530 Results.data(),Results.size());
Douglas Gregor374929f2009-09-18 15:37:17 +00003531}
3532
Douglas Gregor1a480c42010-08-27 17:35:51 +00003533void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
Douglas Gregor218937c2011-02-01 19:23:04 +00003534 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3535 CodeCompletionContext::CCC_TypeQualifiers);
Douglas Gregor1a480c42010-08-27 17:35:51 +00003536 Results.EnterNewScope();
3537 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3538 Results.AddResult("const");
3539 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3540 Results.AddResult("volatile");
3541 if (getLangOptions().C99 &&
3542 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3543 Results.AddResult("restrict");
3544 Results.ExitScope();
3545 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003546 Results.getCompletionContext(),
Douglas Gregor1a480c42010-08-27 17:35:51 +00003547 Results.data(), Results.size());
3548}
3549
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003550void Sema::CodeCompleteCase(Scope *S) {
John McCall781472f2010-08-25 08:40:02 +00003551 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003552 return;
John McCalla8e0cd82011-08-06 07:30:58 +00003553
John McCall781472f2010-08-25 08:40:02 +00003554 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
John McCalla8e0cd82011-08-06 07:30:58 +00003555 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3556 if (!type->isEnumeralType()) {
3557 CodeCompleteExpressionData Data(type);
Douglas Gregorfb629412010-08-23 21:17:50 +00003558 Data.IntegralConstantExpression = true;
3559 CodeCompleteExpression(S, Data);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003560 return;
Douglas Gregorf9578432010-07-28 21:50:18 +00003561 }
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003562
3563 // Code-complete the cases of a switch statement over an enumeration type
3564 // by providing the list of
John McCalla8e0cd82011-08-06 07:30:58 +00003565 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003566
3567 // Determine which enumerators we have already seen in the switch statement.
3568 // FIXME: Ideally, we would also be able to look *past* the code-completion
3569 // token, in case we are code-completing in the middle of the switch and not
3570 // at the end. However, we aren't able to do so at the moment.
3571 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003572 NestedNameSpecifier *Qualifier = 0;
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003573 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3574 SC = SC->getNextSwitchCase()) {
3575 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3576 if (!Case)
3577 continue;
3578
3579 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3580 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3581 if (EnumConstantDecl *Enumerator
3582 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3583 // We look into the AST of the case statement to determine which
3584 // enumerator was named. Alternatively, we could compute the value of
3585 // the integral constant expression, then compare it against the
3586 // values of each enumerator. However, value-based approach would not
3587 // work as well with C++ templates where enumerators declared within a
3588 // template are type- and value-dependent.
3589 EnumeratorsSeen.insert(Enumerator);
3590
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003591 // If this is a qualified-id, keep track of the nested-name-specifier
3592 // so that we can reproduce it as part of code completion, e.g.,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003593 //
3594 // switch (TagD.getKind()) {
3595 // case TagDecl::TK_enum:
3596 // break;
3597 // case XXX
3598 //
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003599 // At the XXX, our completions are TagDecl::TK_union,
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003600 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3601 // TK_struct, and TK_class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003602 Qualifier = DRE->getQualifier();
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003603 }
3604 }
3605
Douglas Gregorb9d0ef72009-09-21 19:57:38 +00003606 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3607 // If there are no prior enumerators in C++, check whether we have to
3608 // qualify the names of the enumerators that we suggest, because they
3609 // may not be visible in this scope.
3610 Qualifier = getRequiredQualification(Context, CurContext,
3611 Enum->getDeclContext());
3612
3613 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3614 }
3615
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003616 // Add any enumerators that have not yet been mentioned.
Douglas Gregor218937c2011-02-01 19:23:04 +00003617 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3618 CodeCompletionContext::CCC_Expression);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003619 Results.EnterNewScope();
3620 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3621 EEnd = Enum->enumerator_end();
3622 E != EEnd; ++E) {
3623 if (EnumeratorsSeen.count(*E))
3624 continue;
3625
Douglas Gregor5c722c702011-02-18 23:30:37 +00003626 CodeCompletionResult R(*E, Qualifier);
3627 R.Priority = CCP_EnumInCase;
3628 Results.AddResult(R, CurContext, 0, false);
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003629 }
3630 Results.ExitScope();
Douglas Gregor2f880e42010-04-06 20:02:15 +00003631
Douglas Gregor3da626b2011-07-07 16:03:39 +00003632 //We need to make sure we're setting the right context,
3633 //so only say we include macros if the code completer says we do
3634 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3635 if (CodeCompleter->includeMacros()) {
Douglas Gregorbca403c2010-01-13 23:51:12 +00003636 AddMacroResults(PP, Results);
Douglas Gregor3da626b2011-07-07 16:03:39 +00003637 kind = CodeCompletionContext::CCC_OtherWithMacros;
3638 }
3639
3640
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003641 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00003642 kind,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003643 Results.data(),Results.size());
Douglas Gregor3e1005f2009-09-21 18:10:23 +00003644}
3645
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003646namespace {
3647 struct IsBetterOverloadCandidate {
3648 Sema &S;
John McCall5769d612010-02-08 23:07:23 +00003649 SourceLocation Loc;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003650
3651 public:
John McCall5769d612010-02-08 23:07:23 +00003652 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3653 : S(S), Loc(Loc) { }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003654
3655 bool
3656 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
John McCall120d63c2010-08-24 20:38:10 +00003657 return isBetterOverloadCandidate(S, X, Y, Loc);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003658 }
3659 };
3660}
3661
Douglas Gregord28dcd72010-05-30 06:10:08 +00003662static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3663 if (NumArgs && !Args)
3664 return true;
3665
3666 for (unsigned I = 0; I != NumArgs; ++I)
3667 if (!Args[I])
3668 return true;
3669
3670 return false;
3671}
3672
Richard Trieuf81e5a92011-09-09 02:00:50 +00003673void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3674 Expr **ArgsIn, unsigned NumArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003675 if (!CodeCompleter)
3676 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003677
3678 // When we're code-completing for a call, we fall back to ordinary
3679 // name code-completion whenever we can't produce specific
3680 // results. We may want to revisit this strategy in the future,
3681 // e.g., by merging the two kinds of results.
3682
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003683 Expr *Fn = (Expr *)FnIn;
3684 Expr **Args = (Expr **)ArgsIn;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003685
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003686 // Ignore type-dependent call expressions entirely.
Douglas Gregord28dcd72010-05-30 06:10:08 +00003687 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
Douglas Gregoref96eac2009-12-11 19:06:04 +00003688 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003689 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003690 return;
Douglas Gregoref96eac2009-12-11 19:06:04 +00003691 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003692
John McCall3b4294e2009-12-16 12:17:52 +00003693 // Build an overload candidate set based on the functions we find.
John McCall5769d612010-02-08 23:07:23 +00003694 SourceLocation Loc = Fn->getExprLoc();
3695 OverloadCandidateSet CandidateSet(Loc);
John McCall3b4294e2009-12-16 12:17:52 +00003696
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003697 // FIXME: What if we're calling something that isn't a function declaration?
3698 // FIXME: What if we're calling a pseudo-destructor?
3699 // FIXME: What if we're calling a member function?
3700
Douglas Gregorc0265402010-01-21 15:46:19 +00003701 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003702 SmallVector<ResultCandidate, 8> Results;
Douglas Gregorc0265402010-01-21 15:46:19 +00003703
John McCall3b4294e2009-12-16 12:17:52 +00003704 Expr *NakedFn = Fn->IgnoreParenCasts();
3705 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3706 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3707 /*PartialOverloading=*/ true);
3708 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3709 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
Douglas Gregorc0265402010-01-21 15:46:19 +00003710 if (FDecl) {
Douglas Gregord28dcd72010-05-30 06:10:08 +00003711 if (!getLangOptions().CPlusPlus ||
3712 !FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregorc0265402010-01-21 15:46:19 +00003713 Results.push_back(ResultCandidate(FDecl));
3714 else
John McCall86820f52010-01-26 01:37:31 +00003715 // FIXME: access?
John McCall9aa472c2010-03-19 07:35:19 +00003716 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3717 Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003718 false, /*PartialOverloading*/true);
Douglas Gregorc0265402010-01-21 15:46:19 +00003719 }
John McCall3b4294e2009-12-16 12:17:52 +00003720 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003721
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003722 QualType ParamType;
3723
Douglas Gregorc0265402010-01-21 15:46:19 +00003724 if (!CandidateSet.empty()) {
3725 // Sort the overload candidate set by placing the best overloads first.
3726 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
John McCall5769d612010-02-08 23:07:23 +00003727 IsBetterOverloadCandidate(*this, Loc));
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003728
Douglas Gregorc0265402010-01-21 15:46:19 +00003729 // Add the remaining viable overload candidates as code-completion reslults.
3730 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3731 CandEnd = CandidateSet.end();
3732 Cand != CandEnd; ++Cand) {
3733 if (Cand->Viable)
3734 Results.push_back(ResultCandidate(Cand->Function));
3735 }
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003736
3737 // From the viable candidates, try to determine the type of this parameter.
3738 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3739 if (const FunctionType *FType = Results[I].getFunctionType())
3740 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3741 if (NumArgs < Proto->getNumArgs()) {
3742 if (ParamType.isNull())
3743 ParamType = Proto->getArgType(NumArgs);
3744 else if (!Context.hasSameUnqualifiedType(
3745 ParamType.getNonReferenceType(),
3746 Proto->getArgType(NumArgs).getNonReferenceType())) {
3747 ParamType = QualType();
3748 break;
3749 }
3750 }
3751 }
3752 } else {
3753 // Try to determine the parameter type from the type of the expression
3754 // being called.
3755 QualType FunctionType = Fn->getType();
3756 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3757 FunctionType = Ptr->getPointeeType();
3758 else if (const BlockPointerType *BlockPtr
3759 = FunctionType->getAs<BlockPointerType>())
3760 FunctionType = BlockPtr->getPointeeType();
3761 else if (const MemberPointerType *MemPtr
3762 = FunctionType->getAs<MemberPointerType>())
3763 FunctionType = MemPtr->getPointeeType();
3764
3765 if (const FunctionProtoType *Proto
3766 = FunctionType->getAs<FunctionProtoType>()) {
3767 if (NumArgs < Proto->getNumArgs())
3768 ParamType = Proto->getArgType(NumArgs);
3769 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003770 }
Douglas Gregoref96eac2009-12-11 19:06:04 +00003771
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003772 if (ParamType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003773 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003774 else
3775 CodeCompleteExpression(S, ParamType);
3776
Douglas Gregor2e4c7a52010-04-06 20:19:47 +00003777 if (!Results.empty())
Douglas Gregoref96eac2009-12-11 19:06:04 +00003778 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3779 Results.size());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003780}
3781
John McCalld226f652010-08-21 09:40:31 +00003782void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3783 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003784 if (!VD) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003785 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003786 return;
3787 }
3788
3789 CodeCompleteExpression(S, VD->getType());
3790}
3791
3792void Sema::CodeCompleteReturn(Scope *S) {
3793 QualType ResultType;
3794 if (isa<BlockDecl>(CurContext)) {
3795 if (BlockScopeInfo *BSI = getCurBlock())
3796 ResultType = BSI->ReturnType;
3797 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3798 ResultType = Function->getResultType();
3799 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3800 ResultType = Method->getResultType();
3801
3802 if (ResultType.isNull())
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003803 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003804 else
3805 CodeCompleteExpression(S, ResultType);
3806}
3807
Douglas Gregord2d8be62011-07-30 08:36:53 +00003808void Sema::CodeCompleteAfterIf(Scope *S) {
3809 typedef CodeCompletionResult Result;
3810 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3811 mapCodeCompletionContext(*this, PCC_Statement));
3812 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3813 Results.EnterNewScope();
3814
3815 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3816 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3817 CodeCompleter->includeGlobals());
3818
3819 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3820
3821 // "else" block
3822 CodeCompletionBuilder Builder(Results.getAllocator());
3823 Builder.AddTypedTextChunk("else");
3824 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3825 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3826 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3827 Builder.AddPlaceholderChunk("statements");
3828 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3829 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3830 Results.AddResult(Builder.TakeString());
3831
3832 // "else if" block
3833 Builder.AddTypedTextChunk("else");
3834 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3835 Builder.AddTextChunk("if");
3836 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3837 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3838 if (getLangOptions().CPlusPlus)
3839 Builder.AddPlaceholderChunk("condition");
3840 else
3841 Builder.AddPlaceholderChunk("expression");
3842 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3843 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3844 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3845 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3846 Builder.AddPlaceholderChunk("statements");
3847 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3848 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3849 Results.AddResult(Builder.TakeString());
3850
3851 Results.ExitScope();
3852
3853 if (S->getFnParent())
3854 AddPrettyFunctionResults(PP.getLangOptions(), Results);
3855
3856 if (CodeCompleter->includeMacros())
3857 AddMacroResults(PP, Results);
3858
3859 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3860 Results.data(),Results.size());
3861}
3862
Richard Trieuf81e5a92011-09-09 02:00:50 +00003863void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003864 if (LHS)
3865 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3866 else
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003867 CodeCompleteOrdinaryName(S, PCC_Expression);
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00003868}
3869
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003870void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
Douglas Gregor81b747b2009-09-17 21:32:03 +00003871 bool EnteringContext) {
3872 if (!SS.getScopeRep() || !CodeCompleter)
3873 return;
3874
Douglas Gregor86d9a522009-09-21 16:56:56 +00003875 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3876 if (!Ctx)
3877 return;
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003878
3879 // Try to instantiate any non-dependent declaration contexts before
3880 // we look in them.
John McCall77bb1aa2010-05-01 00:40:08 +00003881 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
Douglas Gregord1cd31a2009-12-11 18:28:39 +00003882 return;
3883
Douglas Gregor218937c2011-02-01 19:23:04 +00003884 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3885 CodeCompletionContext::CCC_Name);
Douglas Gregorf6961522010-08-27 21:18:54 +00003886 Results.EnterNewScope();
Douglas Gregor52779fb2010-09-23 23:01:17 +00003887
Douglas Gregor86d9a522009-09-21 16:56:56 +00003888 // The "template" keyword can follow "::" in the grammar, but only
3889 // put it into the grammar if the nested-name-specifier is dependent.
3890 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3891 if (!Results.empty() && NNS->isDependent())
Douglas Gregora4477812010-01-14 16:01:26 +00003892 Results.AddResult("template");
Douglas Gregorf6961522010-08-27 21:18:54 +00003893
3894 // Add calls to overridden virtual functions, if there are any.
3895 //
3896 // FIXME: This isn't wonderful, because we don't know whether we're actually
3897 // in a context that permits expressions. This is a general issue with
3898 // qualified-id completions.
3899 if (!EnteringContext)
3900 MaybeAddOverrideCalls(*this, Ctx, Results);
3901 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003902
Douglas Gregorf6961522010-08-27 21:18:54 +00003903 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3904 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3905
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003906 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor430d7a12011-07-25 17:48:11 +00003907 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003908 Results.data(),Results.size());
Douglas Gregor81b747b2009-09-17 21:32:03 +00003909}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003910
3911void Sema::CodeCompleteUsing(Scope *S) {
3912 if (!CodeCompleter)
3913 return;
3914
Douglas Gregor218937c2011-02-01 19:23:04 +00003915 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003916 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3917 &ResultBuilder::IsNestedNameSpecifier);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003918 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003919
3920 // If we aren't in class scope, we could see the "namespace" keyword.
3921 if (!S->isClassScope())
John McCall0a2c5e22010-08-25 06:19:51 +00003922 Results.AddResult(CodeCompletionResult("namespace"));
Douglas Gregor86d9a522009-09-21 16:56:56 +00003923
3924 // After "using", we can see anything that would start a
3925 // nested-name-specifier.
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003926 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003927 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3928 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003929 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003930
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003931 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003932 CodeCompletionContext::CCC_PotentiallyQualifiedName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003933 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003934}
3935
3936void Sema::CodeCompleteUsingDirective(Scope *S) {
3937 if (!CodeCompleter)
3938 return;
3939
Douglas Gregor86d9a522009-09-21 16:56:56 +00003940 // After "using namespace", we expect to see a namespace name or namespace
3941 // alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00003942 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3943 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003944 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003945 Results.EnterNewScope();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00003946 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00003947 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3948 CodeCompleter->includeGlobals());
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003949 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003950 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00003951 CodeCompletionContext::CCC_Namespace,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003952 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003953}
3954
3955void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3956 if (!CodeCompleter)
3957 return;
3958
Douglas Gregor86d9a522009-09-21 16:56:56 +00003959 DeclContext *Ctx = (DeclContext *)S->getEntity();
3960 if (!S->getParent())
3961 Ctx = Context.getTranslationUnitDecl();
3962
Douglas Gregor52779fb2010-09-23 23:01:17 +00003963 bool SuppressedGlobalResults
3964 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3965
Douglas Gregor218937c2011-02-01 19:23:04 +00003966 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00003967 SuppressedGlobalResults
3968 ? CodeCompletionContext::CCC_Namespace
3969 : CodeCompletionContext::CCC_Other,
3970 &ResultBuilder::IsNamespace);
3971
3972 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
Douglas Gregor86d9a522009-09-21 16:56:56 +00003973 // We only want to see those namespaces that have already been defined
3974 // within this scope, because its likely that the user is creating an
3975 // extended namespace declaration. Keep track of the most recent
3976 // definition of each namespace.
3977 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3978 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3979 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3980 NS != NSEnd; ++NS)
3981 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3982
3983 // Add the most recent definition (or extended definition) of each
3984 // namespace to the list of results.
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003985 Results.EnterNewScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003986 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3987 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3988 NS != NSEnd; ++NS)
John McCall0a2c5e22010-08-25 06:19:51 +00003989 Results.AddResult(CodeCompletionResult(NS->second, 0),
Douglas Gregor608300b2010-01-14 16:14:35 +00003990 CurContext, 0, false);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00003991 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00003992 }
3993
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003994 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00003995 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00003996 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00003997}
3998
3999void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4000 if (!CodeCompleter)
4001 return;
4002
Douglas Gregor86d9a522009-09-21 16:56:56 +00004003 // After "namespace", we expect to see a namespace or alias.
Douglas Gregor218937c2011-02-01 19:23:04 +00004004 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4005 CodeCompletionContext::CCC_Namespace,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004006 &ResultBuilder::IsNamespaceOrAlias);
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004007 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004008 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4009 CodeCompleter->includeGlobals());
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004010 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004011 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004012 Results.data(),Results.size());
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004013}
4014
Douglas Gregored8d3222009-09-18 20:05:18 +00004015void Sema::CodeCompleteOperatorName(Scope *S) {
4016 if (!CodeCompleter)
4017 return;
Douglas Gregor86d9a522009-09-21 16:56:56 +00004018
John McCall0a2c5e22010-08-25 06:19:51 +00004019 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004020 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4021 CodeCompletionContext::CCC_Type,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004022 &ResultBuilder::IsType);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004023 Results.EnterNewScope();
Douglas Gregored8d3222009-09-18 20:05:18 +00004024
Douglas Gregor86d9a522009-09-21 16:56:56 +00004025 // Add the names of overloadable operators.
4026#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4027 if (std::strcmp(Spelling, "?")) \
Douglas Gregora4477812010-01-14 16:01:26 +00004028 Results.AddResult(Result(Spelling));
Douglas Gregor86d9a522009-09-21 16:56:56 +00004029#include "clang/Basic/OperatorKinds.def"
4030
4031 // Add any type names visible from the current scope
Douglas Gregor45bcd432010-01-14 03:21:49 +00004032 Results.allowNestedNameSpecifiers();
Douglas Gregor5d2fc402010-01-14 03:27:13 +00004033 CodeCompletionDeclConsumer Consumer(Results, CurContext);
Douglas Gregor8071e422010-08-15 06:18:01 +00004034 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4035 CodeCompleter->includeGlobals());
Douglas Gregor86d9a522009-09-21 16:56:56 +00004036
4037 // Add any type specifiers
Douglas Gregorbca403c2010-01-13 23:51:12 +00004038 AddTypeSpecifierResults(getLangOptions(), Results);
Douglas Gregor8e0a0e42009-09-22 23:31:26 +00004039 Results.ExitScope();
Douglas Gregor86d9a522009-09-21 16:56:56 +00004040
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004041 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor8071e422010-08-15 06:18:01 +00004042 CodeCompletionContext::CCC_Type,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004043 Results.data(),Results.size());
Douglas Gregored8d3222009-09-18 20:05:18 +00004044}
Douglas Gregor49f40bd2009-09-18 19:03:04 +00004045
Douglas Gregor0133f522010-08-28 00:00:50 +00004046void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
Sean Huntcbb67482011-01-08 20:30:50 +00004047 CXXCtorInitializer** Initializers,
Douglas Gregor0133f522010-08-28 00:00:50 +00004048 unsigned NumInitializers) {
Douglas Gregor8987b232011-09-27 23:30:47 +00004049 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregor0133f522010-08-28 00:00:50 +00004050 CXXConstructorDecl *Constructor
4051 = static_cast<CXXConstructorDecl *>(ConstructorD);
4052 if (!Constructor)
4053 return;
4054
Douglas Gregor218937c2011-02-01 19:23:04 +00004055 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00004056 CodeCompletionContext::CCC_PotentiallyQualifiedName);
Douglas Gregor0133f522010-08-28 00:00:50 +00004057 Results.EnterNewScope();
4058
4059 // Fill in any already-initialized fields or base classes.
4060 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4061 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4062 for (unsigned I = 0; I != NumInitializers; ++I) {
4063 if (Initializers[I]->isBaseInitializer())
4064 InitializedBases.insert(
4065 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4066 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00004067 InitializedFields.insert(cast<FieldDecl>(
4068 Initializers[I]->getAnyMember()));
Douglas Gregor0133f522010-08-28 00:00:50 +00004069 }
4070
4071 // Add completions for base classes.
Douglas Gregor218937c2011-02-01 19:23:04 +00004072 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor0c431c82010-08-29 19:27:27 +00004073 bool SawLastInitializer = (NumInitializers == 0);
Douglas Gregor0133f522010-08-28 00:00:50 +00004074 CXXRecordDecl *ClassDecl = Constructor->getParent();
4075 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4076 BaseEnd = ClassDecl->bases_end();
4077 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004078 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4079 SawLastInitializer
4080 = NumInitializers > 0 &&
4081 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4082 Context.hasSameUnqualifiedType(Base->getType(),
4083 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004084 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004085 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004086
Douglas Gregor218937c2011-02-01 19:23:04 +00004087 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004088 Results.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004089 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004090 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4091 Builder.AddPlaceholderChunk("args");
4092 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4093 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004094 SawLastInitializer? CCP_NextInitializer
4095 : CCP_MemberDeclaration));
4096 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004097 }
4098
4099 // Add completions for virtual base classes.
4100 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4101 BaseEnd = ClassDecl->vbases_end();
4102 Base != BaseEnd; ++Base) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004103 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4104 SawLastInitializer
4105 = NumInitializers > 0 &&
4106 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4107 Context.hasSameUnqualifiedType(Base->getType(),
4108 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
Douglas Gregor0133f522010-08-28 00:00:50 +00004109 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004110 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004111
Douglas Gregor218937c2011-02-01 19:23:04 +00004112 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004113 Builder.getAllocator().CopyString(
John McCallf85e1932011-06-15 23:02:42 +00004114 Base->getType().getAsString(Policy)));
Douglas Gregor218937c2011-02-01 19:23:04 +00004115 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4116 Builder.AddPlaceholderChunk("args");
4117 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4118 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004119 SawLastInitializer? CCP_NextInitializer
4120 : CCP_MemberDeclaration));
4121 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004122 }
4123
4124 // Add completions for members.
4125 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4126 FieldEnd = ClassDecl->field_end();
4127 Field != FieldEnd; ++Field) {
Douglas Gregor0c431c82010-08-29 19:27:27 +00004128 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4129 SawLastInitializer
4130 = NumInitializers > 0 &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00004131 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4132 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
Douglas Gregor0133f522010-08-28 00:00:50 +00004133 continue;
Douglas Gregor0c431c82010-08-29 19:27:27 +00004134 }
Douglas Gregor0133f522010-08-28 00:00:50 +00004135
4136 if (!Field->getDeclName())
4137 continue;
4138
Douglas Gregordae68752011-02-01 22:57:45 +00004139 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004140 Field->getIdentifier()->getName()));
4141 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4142 Builder.AddPlaceholderChunk("args");
4143 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4144 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
Douglas Gregor0c431c82010-08-29 19:27:27 +00004145 SawLastInitializer? CCP_NextInitializer
Douglas Gregora67e03f2010-09-09 21:42:20 +00004146 : CCP_MemberDeclaration,
4147 CXCursor_MemberRef));
Douglas Gregor0c431c82010-08-29 19:27:27 +00004148 SawLastInitializer = false;
Douglas Gregor0133f522010-08-28 00:00:50 +00004149 }
4150 Results.ExitScope();
4151
Douglas Gregor52779fb2010-09-23 23:01:17 +00004152 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor0133f522010-08-28 00:00:50 +00004153 Results.data(), Results.size());
4154}
4155
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004156// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4157// true or false.
4158#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
Douglas Gregorbca403c2010-01-13 23:51:12 +00004159static void AddObjCImplementationResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004160 ResultBuilder &Results,
4161 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004162 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004163 // Since we have an implementation, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004164 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004165
Douglas Gregor218937c2011-02-01 19:23:04 +00004166 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004167 if (LangOpts.ObjC2) {
4168 // @dynamic
Douglas Gregor218937c2011-02-01 19:23:04 +00004169 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4170 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4171 Builder.AddPlaceholderChunk("property");
4172 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004173
4174 // @synthesize
Douglas Gregor218937c2011-02-01 19:23:04 +00004175 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4176 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4177 Builder.AddPlaceholderChunk("property");
4178 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004179 }
4180}
4181
Douglas Gregorbca403c2010-01-13 23:51:12 +00004182static void AddObjCInterfaceResults(const LangOptions &LangOpts,
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004183 ResultBuilder &Results,
4184 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004185 typedef CodeCompletionResult Result;
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004186
4187 // Since we have an interface or protocol, we can end it.
Douglas Gregora4477812010-01-14 16:01:26 +00004188 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004189
4190 if (LangOpts.ObjC2) {
4191 // @property
Douglas Gregora4477812010-01-14 16:01:26 +00004192 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004193
4194 // @required
Douglas Gregora4477812010-01-14 16:01:26 +00004195 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004196
4197 // @optional
Douglas Gregora4477812010-01-14 16:01:26 +00004198 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004199 }
4200}
4201
Douglas Gregorbca403c2010-01-13 23:51:12 +00004202static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004203 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004204 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004205
4206 // @class name ;
Douglas Gregor218937c2011-02-01 19:23:04 +00004207 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4208 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4209 Builder.AddPlaceholderChunk("name");
4210 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004211
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004212 if (Results.includeCodePatterns()) {
4213 // @interface name
4214 // FIXME: Could introduce the whole pattern, including superclasses and
4215 // such.
Douglas Gregor218937c2011-02-01 19:23:04 +00004216 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4217 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4218 Builder.AddPlaceholderChunk("class");
4219 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004220
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004221 // @protocol name
Douglas Gregor218937c2011-02-01 19:23:04 +00004222 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4223 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4224 Builder.AddPlaceholderChunk("protocol");
4225 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004226
4227 // @implementation name
Douglas Gregor218937c2011-02-01 19:23:04 +00004228 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4229 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4230 Builder.AddPlaceholderChunk("class");
4231 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004232 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004233
4234 // @compatibility_alias name
Douglas Gregor218937c2011-02-01 19:23:04 +00004235 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4236 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4237 Builder.AddPlaceholderChunk("alias");
4238 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4239 Builder.AddPlaceholderChunk("class");
4240 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004241}
4242
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004243void Sema::CodeCompleteObjCAtDirective(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004244 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004245 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4246 CodeCompletionContext::CCC_Other);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004247 Results.EnterNewScope();
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004248 if (isa<ObjCImplDecl>(CurContext))
Douglas Gregorbca403c2010-01-13 23:51:12 +00004249 AddObjCImplementationResults(getLangOptions(), Results, false);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004250 else if (CurContext->isObjCContainer())
Douglas Gregorbca403c2010-01-13 23:51:12 +00004251 AddObjCInterfaceResults(getLangOptions(), Results, false);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004252 else
Douglas Gregorbca403c2010-01-13 23:51:12 +00004253 AddObjCTopLevelResults(Results, false);
Douglas Gregorc464ae82009-12-07 09:27:33 +00004254 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004255 HandleCodeCompleteResults(this, CodeCompleter,
4256 CodeCompletionContext::CCC_Other,
4257 Results.data(),Results.size());
Douglas Gregorc464ae82009-12-07 09:27:33 +00004258}
4259
Douglas Gregorbca403c2010-01-13 23:51:12 +00004260static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004261 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004262 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004263
4264 // @encode ( type-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004265 const char *EncodeType = "char[]";
4266 if (Results.getSema().getLangOptions().CPlusPlus ||
4267 Results.getSema().getLangOptions().ConstStrings)
4268 EncodeType = " const char[]";
4269 Builder.AddResultTypeChunk(EncodeType);
Douglas Gregor218937c2011-02-01 19:23:04 +00004270 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4271 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4272 Builder.AddPlaceholderChunk("type-name");
4273 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4274 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004275
4276 // @protocol ( protocol-name )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004277 Builder.AddResultTypeChunk("Protocol *");
Douglas Gregor218937c2011-02-01 19:23:04 +00004278 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4279 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4280 Builder.AddPlaceholderChunk("protocol-name");
4281 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4282 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004283
4284 // @selector ( selector )
Douglas Gregor8ca72082011-10-18 21:20:17 +00004285 Builder.AddResultTypeChunk("SEL");
Douglas Gregor218937c2011-02-01 19:23:04 +00004286 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4287 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4288 Builder.AddPlaceholderChunk("selector");
4289 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4290 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004291}
4292
Douglas Gregorbca403c2010-01-13 23:51:12 +00004293static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004294 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004295 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004296
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004297 if (Results.includeCodePatterns()) {
4298 // @try { statements } @catch ( declaration ) { statements } @finally
4299 // { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004300 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4301 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4302 Builder.AddPlaceholderChunk("statements");
4303 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4304 Builder.AddTextChunk("@catch");
4305 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4306 Builder.AddPlaceholderChunk("parameter");
4307 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4308 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4309 Builder.AddPlaceholderChunk("statements");
4310 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4311 Builder.AddTextChunk("@finally");
4312 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4313 Builder.AddPlaceholderChunk("statements");
4314 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4315 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004316 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004317
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004318 // @throw
Douglas Gregor218937c2011-02-01 19:23:04 +00004319 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4320 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4321 Builder.AddPlaceholderChunk("expression");
4322 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004323
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004324 if (Results.includeCodePatterns()) {
4325 // @synchronized ( expression ) { statements }
Douglas Gregor218937c2011-02-01 19:23:04 +00004326 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4327 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4328 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4329 Builder.AddPlaceholderChunk("expression");
4330 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4331 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4332 Builder.AddPlaceholderChunk("statements");
4333 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4334 Results.AddResult(Result(Builder.TakeString()));
Douglas Gregorc8bddde2010-05-28 00:22:41 +00004335 }
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004336}
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004337
Douglas Gregorbca403c2010-01-13 23:51:12 +00004338static void AddObjCVisibilityResults(const LangOptions &LangOpts,
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004339 ResultBuilder &Results,
4340 bool NeedAt) {
John McCall0a2c5e22010-08-25 06:19:51 +00004341 typedef CodeCompletionResult Result;
Douglas Gregora4477812010-01-14 16:01:26 +00004342 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4343 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4344 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004345 if (LangOpts.ObjC2)
Douglas Gregora4477812010-01-14 16:01:26 +00004346 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004347}
4348
4349void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004350 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4351 CodeCompletionContext::CCC_Other);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004352 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004353 AddObjCVisibilityResults(getLangOptions(), Results, false);
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004354 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004355 HandleCodeCompleteResults(this, CodeCompleter,
4356 CodeCompletionContext::CCC_Other,
4357 Results.data(),Results.size());
Douglas Gregorc38c3e12010-01-13 21:54:15 +00004358}
4359
4360void Sema::CodeCompleteObjCAtStatement(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004361 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4362 CodeCompletionContext::CCC_Other);
Douglas Gregorb6ac2452010-01-13 21:24:21 +00004363 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004364 AddObjCStatementResults(Results, false);
4365 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004366 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004367 HandleCodeCompleteResults(this, CodeCompleter,
4368 CodeCompletionContext::CCC_Other,
4369 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004370}
4371
4372void Sema::CodeCompleteObjCAtExpression(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004373 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4374 CodeCompletionContext::CCC_Other);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004375 Results.EnterNewScope();
Douglas Gregorbca403c2010-01-13 23:51:12 +00004376 AddObjCExpressionResults(Results, false);
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004377 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004378 HandleCodeCompleteResults(this, CodeCompleter,
4379 CodeCompletionContext::CCC_Other,
4380 Results.data(),Results.size());
Douglas Gregor9a0c85e2009-12-07 09:51:25 +00004381}
4382
Douglas Gregor988358f2009-11-19 00:14:45 +00004383/// \brief Determine whether the addition of the given flag to an Objective-C
4384/// property's attributes will cause a conflict.
4385static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4386 // Check if we've already added this flag.
4387 if (Attributes & NewFlag)
4388 return true;
4389
4390 Attributes |= NewFlag;
4391
4392 // Check for collisions with "readonly".
4393 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4394 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4395 ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004396 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004397 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004398 ObjCDeclSpec::DQ_PR_retain |
4399 ObjCDeclSpec::DQ_PR_strong)))
Douglas Gregor988358f2009-11-19 00:14:45 +00004400 return true;
4401
John McCallf85e1932011-06-15 23:02:42 +00004402 // Check for more than one of { assign, copy, retain, strong }.
Douglas Gregor988358f2009-11-19 00:14:45 +00004403 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
John McCallf85e1932011-06-15 23:02:42 +00004404 ObjCDeclSpec::DQ_PR_unsafe_unretained |
Douglas Gregor988358f2009-11-19 00:14:45 +00004405 ObjCDeclSpec::DQ_PR_copy |
John McCallf85e1932011-06-15 23:02:42 +00004406 ObjCDeclSpec::DQ_PR_retain|
4407 ObjCDeclSpec::DQ_PR_strong);
Douglas Gregor988358f2009-11-19 00:14:45 +00004408 if (AssignCopyRetMask &&
4409 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
John McCallf85e1932011-06-15 23:02:42 +00004410 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
Douglas Gregor988358f2009-11-19 00:14:45 +00004411 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
John McCallf85e1932011-06-15 23:02:42 +00004412 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4413 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
Douglas Gregor988358f2009-11-19 00:14:45 +00004414 return true;
4415
4416 return false;
4417}
4418
Douglas Gregora93b1082009-11-18 23:08:07 +00004419void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
Steve Naroffece8e712009-10-08 21:55:05 +00004420 if (!CodeCompleter)
4421 return;
Douglas Gregord3c68542009-11-19 01:08:35 +00004422
Steve Naroffece8e712009-10-08 21:55:05 +00004423 unsigned Attributes = ODS.getPropertyAttributes();
4424
John McCall0a2c5e22010-08-25 06:19:51 +00004425 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004426 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4427 CodeCompletionContext::CCC_Other);
Steve Naroffece8e712009-10-08 21:55:05 +00004428 Results.EnterNewScope();
Douglas Gregor988358f2009-11-19 00:14:45 +00004429 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
John McCall0a2c5e22010-08-25 06:19:51 +00004430 Results.AddResult(CodeCompletionResult("readonly"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004431 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
John McCall0a2c5e22010-08-25 06:19:51 +00004432 Results.AddResult(CodeCompletionResult("assign"));
John McCallf85e1932011-06-15 23:02:42 +00004433 if (!ObjCPropertyFlagConflicts(Attributes,
4434 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4435 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004436 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
John McCall0a2c5e22010-08-25 06:19:51 +00004437 Results.AddResult(CodeCompletionResult("readwrite"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004438 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
John McCall0a2c5e22010-08-25 06:19:51 +00004439 Results.AddResult(CodeCompletionResult("retain"));
John McCallf85e1932011-06-15 23:02:42 +00004440 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4441 Results.AddResult(CodeCompletionResult("strong"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004442 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
John McCall0a2c5e22010-08-25 06:19:51 +00004443 Results.AddResult(CodeCompletionResult("copy"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004444 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
John McCall0a2c5e22010-08-25 06:19:51 +00004445 Results.AddResult(CodeCompletionResult("nonatomic"));
Fariborz Jahanian27f45232011-06-11 17:14:27 +00004446 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4447 Results.AddResult(CodeCompletionResult("atomic"));
Douglas Gregor988358f2009-11-19 00:14:45 +00004448 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004449 CodeCompletionBuilder Setter(Results.getAllocator());
4450 Setter.AddTypedTextChunk("setter");
4451 Setter.AddTextChunk(" = ");
4452 Setter.AddPlaceholderChunk("method");
4453 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004454 }
Douglas Gregor988358f2009-11-19 00:14:45 +00004455 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004456 CodeCompletionBuilder Getter(Results.getAllocator());
4457 Getter.AddTypedTextChunk("getter");
4458 Getter.AddTextChunk(" = ");
4459 Getter.AddPlaceholderChunk("method");
4460 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
Douglas Gregor54f01612009-11-19 00:01:57 +00004461 }
Steve Naroffece8e712009-10-08 21:55:05 +00004462 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004463 HandleCodeCompleteResults(this, CodeCompleter,
4464 CodeCompletionContext::CCC_Other,
4465 Results.data(),Results.size());
Steve Naroffece8e712009-10-08 21:55:05 +00004466}
Steve Naroffc4df6d22009-11-07 02:08:14 +00004467
Douglas Gregor4ad96852009-11-19 07:41:15 +00004468/// \brief Descripts the kind of Objective-C method that we want to find
4469/// via code completion.
4470enum ObjCMethodKind {
4471 MK_Any, //< Any kind of method, provided it means other specified criteria.
4472 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4473 MK_OneArgSelector //< One-argument selector.
4474};
4475
Douglas Gregor458433d2010-08-26 15:07:07 +00004476static bool isAcceptableObjCSelector(Selector Sel,
4477 ObjCMethodKind WantKind,
4478 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004479 unsigned NumSelIdents,
4480 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004481 if (NumSelIdents > Sel.getNumArgs())
4482 return false;
4483
4484 switch (WantKind) {
4485 case MK_Any: break;
4486 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4487 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4488 }
4489
Douglas Gregorcf544262010-11-17 21:36:08 +00004490 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4491 return false;
4492
Douglas Gregor458433d2010-08-26 15:07:07 +00004493 for (unsigned I = 0; I != NumSelIdents; ++I)
4494 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4495 return false;
4496
4497 return true;
4498}
4499
Douglas Gregor4ad96852009-11-19 07:41:15 +00004500static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4501 ObjCMethodKind WantKind,
4502 IdentifierInfo **SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004503 unsigned NumSelIdents,
4504 bool AllowSameLength = true) {
Douglas Gregor458433d2010-08-26 15:07:07 +00004505 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004506 NumSelIdents, AllowSameLength);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004507}
Douglas Gregord36adf52010-09-16 16:06:31 +00004508
4509namespace {
4510 /// \brief A set of selectors, which is used to avoid introducing multiple
4511 /// completions with the same selector into the result set.
4512 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4513}
4514
Douglas Gregor36ecb042009-11-17 23:22:23 +00004515/// \brief Add all of the Objective-C methods in the given Objective-C
4516/// container to the set of results.
4517///
4518/// The container will be a class, protocol, category, or implementation of
4519/// any of the above. This mether will recurse to include methods from
4520/// the superclasses of classes along with their categories, protocols, and
4521/// implementations.
4522///
4523/// \param Container the container in which we'll look to find methods.
4524///
4525/// \param WantInstance whether to add instance methods (only); if false, this
4526/// routine will add factory methods (only).
4527///
4528/// \param CurContext the context in which we're performing the lookup that
4529/// finds methods.
4530///
Douglas Gregorcf544262010-11-17 21:36:08 +00004531/// \param AllowSameLength Whether we allow a method to be added to the list
4532/// when it has the same number of parameters as we have selector identifiers.
4533///
Douglas Gregor36ecb042009-11-17 23:22:23 +00004534/// \param Results the structure into which we'll add results.
4535static void AddObjCMethods(ObjCContainerDecl *Container,
4536 bool WantInstanceMethods,
Douglas Gregor4ad96852009-11-19 07:41:15 +00004537 ObjCMethodKind WantKind,
Douglas Gregord3c68542009-11-19 01:08:35 +00004538 IdentifierInfo **SelIdents,
4539 unsigned NumSelIdents,
Douglas Gregor36ecb042009-11-17 23:22:23 +00004540 DeclContext *CurContext,
Douglas Gregord36adf52010-09-16 16:06:31 +00004541 VisitedSelectorSet &Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004542 bool AllowSameLength,
Douglas Gregor408be5a2010-08-25 01:08:01 +00004543 ResultBuilder &Results,
4544 bool InOriginalClass = true) {
John McCall0a2c5e22010-08-25 06:19:51 +00004545 typedef CodeCompletionResult Result;
Douglas Gregor36ecb042009-11-17 23:22:23 +00004546 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4547 MEnd = Container->meth_end();
4548 M != MEnd; ++M) {
Douglas Gregord3c68542009-11-19 01:08:35 +00004549 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4550 // Check whether the selector identifiers we've been given are a
4551 // subset of the identifiers for this particular method.
Douglas Gregorcf544262010-11-17 21:36:08 +00004552 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4553 AllowSameLength))
Douglas Gregord3c68542009-11-19 01:08:35 +00004554 continue;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004555
Douglas Gregord36adf52010-09-16 16:06:31 +00004556 if (!Selectors.insert((*M)->getSelector()))
4557 continue;
4558
Douglas Gregord3c68542009-11-19 01:08:35 +00004559 Result R = Result(*M, 0);
4560 R.StartParameter = NumSelIdents;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004561 R.AllParametersAreInformative = (WantKind != MK_Any);
Douglas Gregor408be5a2010-08-25 01:08:01 +00004562 if (!InOriginalClass)
4563 R.Priority += CCD_InBaseClass;
Douglas Gregord3c68542009-11-19 01:08:35 +00004564 Results.MaybeAddResult(R, CurContext);
4565 }
Douglas Gregor36ecb042009-11-17 23:22:23 +00004566 }
4567
Douglas Gregore396c7b2010-09-16 15:34:59 +00004568 // Visit the protocols of protocols.
4569 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004570 if (Protocol->hasDefinition()) {
4571 const ObjCList<ObjCProtocolDecl> &Protocols
4572 = Protocol->getReferencedProtocols();
4573 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4574 E = Protocols.end();
4575 I != E; ++I)
4576 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4577 NumSelIdents, CurContext, Selectors, AllowSameLength,
4578 Results, false);
4579 }
Douglas Gregore396c7b2010-09-16 15:34:59 +00004580 }
4581
Douglas Gregor36ecb042009-11-17 23:22:23 +00004582 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00004583 if (!IFace || !IFace->hasDefinition())
Douglas Gregor36ecb042009-11-17 23:22:23 +00004584 return;
4585
4586 // Add methods in protocols.
4587 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4588 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4589 E = Protocols.end();
4590 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004591 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004592 CurContext, Selectors, AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004593
4594 // Add methods in categories.
4595 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4596 CatDecl = CatDecl->getNextClassCategory()) {
Douglas Gregor4ad96852009-11-19 07:41:15 +00004597 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004598 NumSelIdents, CurContext, Selectors, AllowSameLength,
4599 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004600
4601 // Add a categories protocol methods.
4602 const ObjCList<ObjCProtocolDecl> &Protocols
4603 = CatDecl->getReferencedProtocols();
4604 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4605 E = Protocols.end();
4606 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00004607 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004608 NumSelIdents, CurContext, Selectors, AllowSameLength,
4609 Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004610
4611 // Add methods in category implementations.
4612 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004613 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004614 NumSelIdents, CurContext, Selectors, AllowSameLength,
4615 Results, InOriginalClass);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004616 }
4617
4618 // Add methods in superclass.
4619 if (IFace->getSuperClass())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004620 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
Douglas Gregorcf544262010-11-17 21:36:08 +00004621 SelIdents, NumSelIdents, CurContext, Selectors,
4622 AllowSameLength, Results, false);
Douglas Gregor36ecb042009-11-17 23:22:23 +00004623
4624 // Add methods in our implementation, if any.
4625 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Douglas Gregor4ad96852009-11-19 07:41:15 +00004626 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00004627 NumSelIdents, CurContext, Selectors, AllowSameLength,
4628 Results, InOriginalClass);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004629}
4630
4631
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004632void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004633 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004634
4635 // Try to find the interface where getters might live.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004636 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004637 if (!Class) {
4638 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004639 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004640 Class = Category->getClassInterface();
4641
4642 if (!Class)
4643 return;
4644 }
4645
4646 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004647 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4648 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004649 Results.EnterNewScope();
4650
Douglas Gregord36adf52010-09-16 16:06:31 +00004651 VisitedSelectorSet Selectors;
4652 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
Douglas Gregorcf544262010-11-17 21:36:08 +00004653 /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004654 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004655 HandleCodeCompleteResults(this, CodeCompleter,
4656 CodeCompletionContext::CCC_Other,
4657 Results.data(),Results.size());
Douglas Gregor4ad96852009-11-19 07:41:15 +00004658}
4659
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004660void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004661 typedef CodeCompletionResult Result;
Douglas Gregor4ad96852009-11-19 07:41:15 +00004662
4663 // Try to find the interface where setters might live.
4664 ObjCInterfaceDecl *Class
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004665 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004666 if (!Class) {
4667 if (ObjCCategoryDecl *Category
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00004668 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Douglas Gregor4ad96852009-11-19 07:41:15 +00004669 Class = Category->getClassInterface();
4670
4671 if (!Class)
4672 return;
4673 }
4674
4675 // Find all of the potential getters.
Douglas Gregor218937c2011-02-01 19:23:04 +00004676 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4677 CodeCompletionContext::CCC_Other);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004678 Results.EnterNewScope();
4679
Douglas Gregord36adf52010-09-16 16:06:31 +00004680 VisitedSelectorSet Selectors;
4681 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00004682 Selectors, /*AllowSameLength=*/true, Results);
Douglas Gregor4ad96852009-11-19 07:41:15 +00004683
4684 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004685 HandleCodeCompleteResults(this, CodeCompleter,
4686 CodeCompletionContext::CCC_Other,
4687 Results.data(),Results.size());
Douglas Gregor36ecb042009-11-17 23:22:23 +00004688}
4689
Douglas Gregorafc45782011-02-15 22:19:42 +00004690void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4691 bool IsParameter) {
John McCall0a2c5e22010-08-25 06:19:51 +00004692 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004693 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4694 CodeCompletionContext::CCC_Type);
Douglas Gregord32b0222010-08-24 01:06:58 +00004695 Results.EnterNewScope();
4696
4697 // Add context-sensitive, Objective-C parameter-passing keywords.
4698 bool AddedInOut = false;
4699 if ((DS.getObjCDeclQualifier() &
4700 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4701 Results.AddResult("in");
4702 Results.AddResult("inout");
4703 AddedInOut = true;
4704 }
4705 if ((DS.getObjCDeclQualifier() &
4706 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4707 Results.AddResult("out");
4708 if (!AddedInOut)
4709 Results.AddResult("inout");
4710 }
4711 if ((DS.getObjCDeclQualifier() &
4712 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4713 ObjCDeclSpec::DQ_Oneway)) == 0) {
4714 Results.AddResult("bycopy");
4715 Results.AddResult("byref");
4716 Results.AddResult("oneway");
4717 }
4718
Douglas Gregorafc45782011-02-15 22:19:42 +00004719 // If we're completing the return type of an Objective-C method and the
4720 // identifier IBAction refers to a macro, provide a completion item for
4721 // an action, e.g.,
4722 // IBAction)<#selector#>:(id)sender
4723 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4724 Context.Idents.get("IBAction").hasMacroDefinition()) {
4725 typedef CodeCompletionString::Chunk Chunk;
4726 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,
4727 CXAvailability_Available);
4728 Builder.AddTypedTextChunk("IBAction");
4729 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4730 Builder.AddPlaceholderChunk("selector");
4731 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
4732 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
4733 Builder.AddTextChunk("id");
4734 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
4735 Builder.AddTextChunk("sender");
4736 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4737 }
4738
Douglas Gregord32b0222010-08-24 01:06:58 +00004739 // Add various builtin type names and specifiers.
4740 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4741 Results.ExitScope();
4742
4743 // Add the various type names
4744 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4745 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4746 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4747 CodeCompleter->includeGlobals());
4748
4749 if (CodeCompleter->includeMacros())
4750 AddMacroResults(PP, Results);
4751
4752 HandleCodeCompleteResults(this, CodeCompleter,
4753 CodeCompletionContext::CCC_Type,
4754 Results.data(), Results.size());
4755}
4756
Douglas Gregor22f56992010-04-06 19:22:33 +00004757/// \brief When we have an expression with type "id", we may assume
4758/// that it has some more-specific class type based on knowledge of
4759/// common uses of Objective-C. This routine returns that class type,
4760/// or NULL if no better result could be determined.
4761static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
Douglas Gregor78edf512010-09-15 16:23:04 +00004762 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
Douglas Gregor22f56992010-04-06 19:22:33 +00004763 if (!Msg)
4764 return 0;
4765
4766 Selector Sel = Msg->getSelector();
4767 if (Sel.isNull())
4768 return 0;
4769
4770 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4771 if (!Id)
4772 return 0;
4773
4774 ObjCMethodDecl *Method = Msg->getMethodDecl();
4775 if (!Method)
4776 return 0;
4777
4778 // Determine the class that we're sending the message to.
Douglas Gregor04badcf2010-04-21 00:45:42 +00004779 ObjCInterfaceDecl *IFace = 0;
4780 switch (Msg->getReceiverKind()) {
4781 case ObjCMessageExpr::Class:
John McCallc12c5bb2010-05-15 11:32:37 +00004782 if (const ObjCObjectType *ObjType
4783 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4784 IFace = ObjType->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00004785 break;
4786
4787 case ObjCMessageExpr::Instance: {
4788 QualType T = Msg->getInstanceReceiver()->getType();
4789 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4790 IFace = Ptr->getInterfaceDecl();
4791 break;
4792 }
4793
4794 case ObjCMessageExpr::SuperInstance:
4795 case ObjCMessageExpr::SuperClass:
4796 break;
Douglas Gregor22f56992010-04-06 19:22:33 +00004797 }
4798
4799 if (!IFace)
4800 return 0;
4801
4802 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4803 if (Method->isInstanceMethod())
4804 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4805 .Case("retain", IFace)
John McCallf85e1932011-06-15 23:02:42 +00004806 .Case("strong", IFace)
Douglas Gregor22f56992010-04-06 19:22:33 +00004807 .Case("autorelease", IFace)
4808 .Case("copy", IFace)
4809 .Case("copyWithZone", IFace)
4810 .Case("mutableCopy", IFace)
4811 .Case("mutableCopyWithZone", IFace)
4812 .Case("awakeFromCoder", IFace)
4813 .Case("replacementObjectFromCoder", IFace)
4814 .Case("class", IFace)
4815 .Case("classForCoder", IFace)
4816 .Case("superclass", Super)
4817 .Default(0);
4818
4819 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4820 .Case("new", IFace)
4821 .Case("alloc", IFace)
4822 .Case("allocWithZone", IFace)
4823 .Case("class", IFace)
4824 .Case("superclass", Super)
4825 .Default(0);
4826}
4827
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004828// Add a special completion for a message send to "super", which fills in the
4829// most likely case of forwarding all of our arguments to the superclass
4830// function.
4831///
4832/// \param S The semantic analysis object.
4833///
4834/// \param S NeedSuperKeyword Whether we need to prefix this completion with
4835/// the "super" keyword. Otherwise, we just need to provide the arguments.
4836///
4837/// \param SelIdents The identifiers in the selector that have already been
4838/// provided as arguments for a send to "super".
4839///
4840/// \param NumSelIdents The number of identifiers in \p SelIdents.
4841///
4842/// \param Results The set of results to augment.
4843///
4844/// \returns the Objective-C method declaration that would be invoked by
4845/// this "super" completion. If NULL, no completion was added.
4846static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4847 IdentifierInfo **SelIdents,
4848 unsigned NumSelIdents,
4849 ResultBuilder &Results) {
4850 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4851 if (!CurMethod)
4852 return 0;
4853
4854 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4855 if (!Class)
4856 return 0;
4857
4858 // Try to find a superclass method with the same selector.
4859 ObjCMethodDecl *SuperMethod = 0;
Douglas Gregor78bcd912011-02-16 00:51:18 +00004860 while ((Class = Class->getSuperClass()) && !SuperMethod) {
4861 // Check in the class
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004862 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4863 CurMethod->isInstanceMethod());
4864
Douglas Gregor78bcd912011-02-16 00:51:18 +00004865 // Check in categories or class extensions.
4866 if (!SuperMethod) {
4867 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
4868 Category = Category->getNextClassCategory())
4869 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
4870 CurMethod->isInstanceMethod())))
4871 break;
4872 }
4873 }
4874
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004875 if (!SuperMethod)
4876 return 0;
4877
4878 // Check whether the superclass method has the same signature.
4879 if (CurMethod->param_size() != SuperMethod->param_size() ||
4880 CurMethod->isVariadic() != SuperMethod->isVariadic())
4881 return 0;
4882
4883 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4884 CurPEnd = CurMethod->param_end(),
4885 SuperP = SuperMethod->param_begin();
4886 CurP != CurPEnd; ++CurP, ++SuperP) {
4887 // Make sure the parameter types are compatible.
4888 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4889 (*SuperP)->getType()))
4890 return 0;
4891
4892 // Make sure we have a parameter name to forward!
4893 if (!(*CurP)->getIdentifier())
4894 return 0;
4895 }
4896
4897 // We have a superclass method. Now, form the send-to-super completion.
Douglas Gregor218937c2011-02-01 19:23:04 +00004898 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004899
4900 // Give this completion a return type.
Douglas Gregor8987b232011-09-27 23:30:47 +00004901 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
4902 Builder);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004903
4904 // If we need the "super" keyword, add it (plus some spacing).
4905 if (NeedSuperKeyword) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004906 Builder.AddTypedTextChunk("super");
4907 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004908 }
4909
4910 Selector Sel = CurMethod->getSelector();
4911 if (Sel.isUnarySelector()) {
4912 if (NeedSuperKeyword)
Douglas Gregordae68752011-02-01 22:57:45 +00004913 Builder.AddTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004914 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004915 else
Douglas Gregordae68752011-02-01 22:57:45 +00004916 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004917 Sel.getNameForSlot(0)));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004918 } else {
4919 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4920 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4921 if (I > NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004922 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004923
4924 if (I < NumSelIdents)
Douglas Gregor218937c2011-02-01 19:23:04 +00004925 Builder.AddInformativeChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004926 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004927 Sel.getNameForSlot(I) + ":"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004928 else if (NeedSuperKeyword || I > NumSelIdents) {
Douglas Gregor218937c2011-02-01 19:23:04 +00004929 Builder.AddTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004930 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004931 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004932 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004933 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004934 } else {
Douglas Gregor218937c2011-02-01 19:23:04 +00004935 Builder.AddTypedTextChunk(
Douglas Gregordae68752011-02-01 22:57:45 +00004936 Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00004937 Sel.getNameForSlot(I) + ":"));
Douglas Gregordae68752011-02-01 22:57:45 +00004938 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00004939 (*CurP)->getIdentifier()->getName()));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004940 }
4941 }
4942 }
4943
Douglas Gregor218937c2011-02-01 19:23:04 +00004944 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004945 SuperMethod->isInstanceMethod()
4946 ? CXCursor_ObjCInstanceMethodDecl
4947 : CXCursor_ObjCClassMethodDecl));
4948 return SuperMethod;
4949}
4950
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004951void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00004952 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00004953 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4954 CodeCompletionContext::CCC_ObjCMessageReceiver,
Douglas Gregor52779fb2010-09-23 23:01:17 +00004955 &ResultBuilder::IsObjCMessageReceiver);
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004956
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004957 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4958 Results.EnterNewScope();
Douglas Gregor8071e422010-08-15 06:18:01 +00004959 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4960 CodeCompleter->includeGlobals());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004961
4962 // If we are in an Objective-C method inside a class that has a superclass,
4963 // add "super" as an option.
4964 if (ObjCMethodDecl *Method = getCurMethodDecl())
4965 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004966 if (Iface->getSuperClass()) {
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004967 Results.AddResult(Result("super"));
Douglas Gregor03d8aec2010-08-27 15:10:57 +00004968
4969 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4970 }
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004971
4972 Results.ExitScope();
4973
4974 if (CodeCompleter->includeMacros())
4975 AddMacroResults(PP, Results);
Douglas Gregorcee9ff12010-09-20 22:39:41 +00004976 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00004977 Results.data(), Results.size());
Douglas Gregor8e254cf2010-05-27 23:06:34 +00004978
4979}
4980
Douglas Gregor2725ca82010-04-21 19:57:20 +00004981void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4982 IdentifierInfo **SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00004983 unsigned NumSelIdents,
4984 bool AtArgumentExpression) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00004985 ObjCInterfaceDecl *CDecl = 0;
4986 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4987 // Figure out which interface we're in.
4988 CDecl = CurMethod->getClassInterface();
4989 if (!CDecl)
4990 return;
4991
4992 // Find the superclass of this class.
4993 CDecl = CDecl->getSuperClass();
4994 if (!CDecl)
4995 return;
4996
4997 if (CurMethod->isInstanceMethod()) {
4998 // We are inside an instance method, which means that the message
4999 // send [super ...] is actually calling an instance method on the
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005000 // current object.
5001 return CodeCompleteObjCInstanceMessage(S, 0,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005002 SelIdents, NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005003 AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005004 CDecl);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005005 }
5006
5007 // Fall through to send to the superclass in CDecl.
5008 } else {
5009 // "super" may be the name of a type or variable. Figure out which
5010 // it is.
5011 IdentifierInfo *Super = &Context.Idents.get("super");
5012 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5013 LookupOrdinaryName);
5014 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5015 // "super" names an interface. Use it.
5016 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
John McCallc12c5bb2010-05-15 11:32:37 +00005017 if (const ObjCObjectType *Iface
5018 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5019 CDecl = Iface->getInterface();
Douglas Gregor2725ca82010-04-21 19:57:20 +00005020 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5021 // "super" names an unresolved type; we can't be more specific.
5022 } else {
5023 // Assume that "super" names some kind of value and parse that way.
5024 CXXScopeSpec SS;
5025 UnqualifiedId id;
5026 id.setIdentifier(Super, SuperLoc);
John McCall60d7b3a2010-08-24 06:29:42 +00005027 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005028 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005029 SelIdents, NumSelIdents,
5030 AtArgumentExpression);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005031 }
5032
5033 // Fall through
5034 }
5035
John McCallb3d87482010-08-24 05:47:05 +00005036 ParsedType Receiver;
Douglas Gregor2725ca82010-04-21 19:57:20 +00005037 if (CDecl)
John McCallb3d87482010-08-24 05:47:05 +00005038 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
Douglas Gregor2725ca82010-04-21 19:57:20 +00005039 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005040 NumSelIdents, AtArgumentExpression,
5041 /*IsSuper=*/true);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005042}
5043
Douglas Gregorb9d77572010-09-21 00:03:25 +00005044/// \brief Given a set of code-completion results for the argument of a message
5045/// send, determine the preferred type (if any) for that argument expression.
5046static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5047 unsigned NumSelIdents) {
5048 typedef CodeCompletionResult Result;
5049 ASTContext &Context = Results.getSema().Context;
5050
5051 QualType PreferredType;
5052 unsigned BestPriority = CCP_Unlikely * 2;
5053 Result *ResultsData = Results.data();
5054 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5055 Result &R = ResultsData[I];
5056 if (R.Kind == Result::RK_Declaration &&
5057 isa<ObjCMethodDecl>(R.Declaration)) {
5058 if (R.Priority <= BestPriority) {
5059 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5060 if (NumSelIdents <= Method->param_size()) {
5061 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5062 ->getType();
5063 if (R.Priority < BestPriority || PreferredType.isNull()) {
5064 BestPriority = R.Priority;
5065 PreferredType = MyPreferredType;
5066 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5067 MyPreferredType)) {
5068 PreferredType = QualType();
5069 }
5070 }
5071 }
5072 }
5073 }
5074
5075 return PreferredType;
5076}
5077
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005078static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5079 ParsedType Receiver,
5080 IdentifierInfo **SelIdents,
5081 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005082 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005083 bool IsSuper,
5084 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005085 typedef CodeCompletionResult Result;
Douglas Gregor24a069f2009-11-17 17:59:40 +00005086 ObjCInterfaceDecl *CDecl = 0;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005087
Douglas Gregor24a069f2009-11-17 17:59:40 +00005088 // If the given name refers to an interface type, retrieve the
5089 // corresponding declaration.
Douglas Gregor2725ca82010-04-21 19:57:20 +00005090 if (Receiver) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005091 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005092 if (!T.isNull())
John McCallc12c5bb2010-05-15 11:32:37 +00005093 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5094 CDecl = Interface->getInterface();
Douglas Gregor24a069f2009-11-17 17:59:40 +00005095 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005096
Douglas Gregor36ecb042009-11-17 23:22:23 +00005097 // Add all of the factory methods in this Objective-C class, its protocols,
5098 // superclasses, categories, implementation, etc.
Steve Naroffc4df6d22009-11-07 02:08:14 +00005099 Results.EnterNewScope();
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005100
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005101 // If this is a send-to-super, try to add the special "super" send
5102 // completion.
5103 if (IsSuper) {
5104 if (ObjCMethodDecl *SuperMethod
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005105 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5106 Results))
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005107 Results.Ignore(SuperMethod);
5108 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005109
Douglas Gregor265f7492010-08-27 15:29:55 +00005110 // If we're inside an Objective-C method definition, prefer its selector to
5111 // others.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005112 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Douglas Gregor265f7492010-08-27 15:29:55 +00005113 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005114
Douglas Gregord36adf52010-09-16 16:06:31 +00005115 VisitedSelectorSet Selectors;
Douglas Gregor13438f92010-04-06 16:40:00 +00005116 if (CDecl)
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005117 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005118 SemaRef.CurContext, Selectors, AtArgumentExpression,
5119 Results);
Douglas Gregor2725ca82010-04-21 19:57:20 +00005120 else {
Douglas Gregor13438f92010-04-06 16:40:00 +00005121 // We're messaging "id" as a type; provide all class/factory methods.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005122
Douglas Gregor719770d2010-04-06 17:30:22 +00005123 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005124 // pool from the AST file.
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005125 if (SemaRef.ExternalSource) {
5126 for (uint32_t I = 0,
5127 N = SemaRef.ExternalSource->GetNumExternalSelectors();
John McCall76bd1f32010-06-01 09:23:16 +00005128 I != N; ++I) {
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005129 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5130 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005131 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005132
5133 SemaRef.ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005134 }
5135 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005136
5137 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5138 MEnd = SemaRef.MethodPool.end();
Sebastian Redldb9d2142010-08-02 23:18:59 +00005139 M != MEnd; ++M) {
5140 for (ObjCMethodList *MethList = &M->second.second;
5141 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005142 MethList = MethList->Next) {
5143 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5144 NumSelIdents))
5145 continue;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005146
Douglas Gregor13438f92010-04-06 16:40:00 +00005147 Result R(MethList->Method, 0);
5148 R.StartParameter = NumSelIdents;
5149 R.AllParametersAreInformative = false;
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005150 Results.MaybeAddResult(R, SemaRef.CurContext);
Douglas Gregor13438f92010-04-06 16:40:00 +00005151 }
5152 }
5153 }
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005154
5155 Results.ExitScope();
5156}
Douglas Gregor13438f92010-04-06 16:40:00 +00005157
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005158void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5159 IdentifierInfo **SelIdents,
5160 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005161 bool AtArgumentExpression,
Douglas Gregorc7b6d882010-09-16 15:14:18 +00005162 bool IsSuper) {
Douglas Gregore081a612011-07-21 01:05:26 +00005163
5164 QualType T = this->GetTypeFromParser(Receiver);
5165
Douglas Gregor218937c2011-02-01 19:23:04 +00005166 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005167 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005168 T, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005169
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005170 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5171 AtArgumentExpression, IsSuper, Results);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005172
5173 // If we're actually at the argument expression (rather than prior to the
5174 // selector), we're actually performing code completion for an expression.
5175 // Determine whether we have a single, best method. If so, we can
5176 // code-complete the expression using the corresponding parameter type as
5177 // our preferred type, improving completion results.
5178 if (AtArgumentExpression) {
5179 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
Douglas Gregore081a612011-07-21 01:05:26 +00005180 NumSelIdents);
Douglas Gregorb9d77572010-09-21 00:03:25 +00005181 if (PreferredType.isNull())
5182 CodeCompleteOrdinaryName(S, PCC_Expression);
5183 else
5184 CodeCompleteExpression(S, PreferredType);
5185 return;
5186 }
5187
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005188 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005189 Results.getCompletionContext(),
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005190 Results.data(), Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005191}
5192
Richard Trieuf81e5a92011-09-09 02:00:50 +00005193void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
Douglas Gregord3c68542009-11-19 01:08:35 +00005194 IdentifierInfo **SelIdents,
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005195 unsigned NumSelIdents,
Douglas Gregor70c5ac72010-09-20 23:34:21 +00005196 bool AtArgumentExpression,
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005197 ObjCInterfaceDecl *Super) {
John McCall0a2c5e22010-08-25 06:19:51 +00005198 typedef CodeCompletionResult Result;
Steve Naroffc4df6d22009-11-07 02:08:14 +00005199
5200 Expr *RecExpr = static_cast<Expr *>(Receiver);
Steve Naroffc4df6d22009-11-07 02:08:14 +00005201
Douglas Gregor36ecb042009-11-17 23:22:23 +00005202 // If necessary, apply function/array conversion to the receiver.
5203 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00005204 if (RecExpr) {
5205 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5206 if (Conv.isInvalid()) // conversion failed. bail.
5207 return;
5208 RecExpr = Conv.take();
5209 }
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005210 QualType ReceiverType = RecExpr? RecExpr->getType()
5211 : Super? Context.getObjCObjectPointerType(
5212 Context.getObjCInterfaceType(Super))
5213 : Context.getObjCIdType();
Steve Naroffc4df6d22009-11-07 02:08:14 +00005214
Douglas Gregorda892642010-11-08 21:12:30 +00005215 // If we're messaging an expression with type "id" or "Class", check
5216 // whether we know something special about the receiver that allows
5217 // us to assume a more-specific receiver type.
5218 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5219 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5220 if (ReceiverType->isObjCClassType())
5221 return CodeCompleteObjCClassMessage(S,
5222 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5223 SelIdents, NumSelIdents,
5224 AtArgumentExpression, Super);
5225
5226 ReceiverType = Context.getObjCObjectPointerType(
5227 Context.getObjCInterfaceType(IFace));
5228 }
5229
Douglas Gregor36ecb042009-11-17 23:22:23 +00005230 // Build the set of methods we can see.
Douglas Gregor218937c2011-02-01 19:23:04 +00005231 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregore081a612011-07-21 01:05:26 +00005232 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
Douglas Gregor0a47d692011-07-26 15:24:30 +00005233 ReceiverType, SelIdents, NumSelIdents));
Douglas Gregore081a612011-07-21 01:05:26 +00005234
Douglas Gregor36ecb042009-11-17 23:22:23 +00005235 Results.EnterNewScope();
Douglas Gregor22f56992010-04-06 19:22:33 +00005236
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005237 // If this is a send-to-super, try to add the special "super" send
5238 // completion.
Douglas Gregor6b0656a2010-10-13 21:24:53 +00005239 if (Super) {
Douglas Gregor03d8aec2010-08-27 15:10:57 +00005240 if (ObjCMethodDecl *SuperMethod
5241 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5242 Results))
5243 Results.Ignore(SuperMethod);
5244 }
5245
Douglas Gregor265f7492010-08-27 15:29:55 +00005246 // If we're inside an Objective-C method definition, prefer its selector to
5247 // others.
5248 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5249 Results.setPreferredSelector(CurMethod->getSelector());
Douglas Gregor36ecb042009-11-17 23:22:23 +00005250
Douglas Gregord36adf52010-09-16 16:06:31 +00005251 // Keep track of the selectors we've already added.
5252 VisitedSelectorSet Selectors;
5253
Douglas Gregorf74a4192009-11-18 00:06:18 +00005254 // Handle messages to Class. This really isn't a message to an instance
5255 // method, so we treat it the same way we would treat a message send to a
5256 // class method.
5257 if (ReceiverType->isObjCClassType() ||
5258 ReceiverType->isObjCQualifiedClassType()) {
5259 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5260 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
Douglas Gregor4ad96852009-11-19 07:41:15 +00005261 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005262 CurContext, Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005263 }
5264 }
5265 // Handle messages to a qualified ID ("id<foo>").
5266 else if (const ObjCObjectPointerType *QualID
5267 = ReceiverType->getAsObjCQualifiedIdType()) {
5268 // Search protocols for instance methods.
5269 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5270 E = QualID->qual_end();
5271 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005272 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005273 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005274 }
5275 // Handle messages to a pointer to interface type.
5276 else if (const ObjCObjectPointerType *IFacePtr
5277 = ReceiverType->getAsObjCInterfacePointerType()) {
5278 // Search the class, its superclasses, etc., for instance methods.
Douglas Gregor4ad96852009-11-19 07:41:15 +00005279 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
Douglas Gregorcf544262010-11-17 21:36:08 +00005280 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5281 Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005282
5283 // Search protocols for instance methods.
5284 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5285 E = IFacePtr->qual_end();
5286 I != E; ++I)
Douglas Gregor4ad96852009-11-19 07:41:15 +00005287 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
Douglas Gregorcf544262010-11-17 21:36:08 +00005288 Selectors, AtArgumentExpression, Results);
Douglas Gregorf74a4192009-11-18 00:06:18 +00005289 }
Douglas Gregor13438f92010-04-06 16:40:00 +00005290 // Handle messages to "id".
5291 else if (ReceiverType->isObjCIdType()) {
Douglas Gregor719770d2010-04-06 17:30:22 +00005292 // We're messaging "id", so provide all instance methods we know
5293 // about as code-completion results.
5294
5295 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005296 // pool from the AST file.
Douglas Gregor719770d2010-04-06 17:30:22 +00005297 if (ExternalSource) {
John McCall76bd1f32010-06-01 09:23:16 +00005298 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5299 I != N; ++I) {
5300 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00005301 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor719770d2010-04-06 17:30:22 +00005302 continue;
5303
Sebastian Redldb9d2142010-08-02 23:18:59 +00005304 ReadMethodPool(Sel);
Douglas Gregor719770d2010-04-06 17:30:22 +00005305 }
5306 }
5307
Sebastian Redldb9d2142010-08-02 23:18:59 +00005308 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5309 MEnd = MethodPool.end();
5310 M != MEnd; ++M) {
5311 for (ObjCMethodList *MethList = &M->second.first;
5312 MethList && MethList->Method;
Douglas Gregor13438f92010-04-06 16:40:00 +00005313 MethList = MethList->Next) {
5314 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5315 NumSelIdents))
5316 continue;
Douglas Gregord36adf52010-09-16 16:06:31 +00005317
5318 if (!Selectors.insert(MethList->Method->getSelector()))
5319 continue;
5320
Douglas Gregor13438f92010-04-06 16:40:00 +00005321 Result R(MethList->Method, 0);
5322 R.StartParameter = NumSelIdents;
5323 R.AllParametersAreInformative = false;
5324 Results.MaybeAddResult(R, CurContext);
5325 }
5326 }
5327 }
Steve Naroffc4df6d22009-11-07 02:08:14 +00005328 Results.ExitScope();
Douglas Gregorb9d77572010-09-21 00:03:25 +00005329
5330
5331 // If we're actually at the argument expression (rather than prior to the
5332 // selector), we're actually performing code completion for an expression.
5333 // Determine whether we have a single, best method. If so, we can
5334 // code-complete the expression using the corresponding parameter type as
5335 // our preferred type, improving completion results.
5336 if (AtArgumentExpression) {
5337 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5338 NumSelIdents);
5339 if (PreferredType.isNull())
5340 CodeCompleteOrdinaryName(S, PCC_Expression);
5341 else
5342 CodeCompleteExpression(S, PreferredType);
5343 return;
5344 }
5345
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005346 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregore081a612011-07-21 01:05:26 +00005347 Results.getCompletionContext(),
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005348 Results.data(),Results.size());
Steve Naroffc4df6d22009-11-07 02:08:14 +00005349}
Douglas Gregor55385fe2009-11-18 04:19:12 +00005350
Douglas Gregorfb629412010-08-23 21:17:50 +00005351void Sema::CodeCompleteObjCForCollection(Scope *S,
5352 DeclGroupPtrTy IterationVar) {
5353 CodeCompleteExpressionData Data;
5354 Data.ObjCCollection = true;
5355
5356 if (IterationVar.getAsOpaquePtr()) {
5357 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5358 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5359 if (*I)
5360 Data.IgnoreDecls.push_back(*I);
5361 }
5362 }
5363
5364 CodeCompleteExpression(S, Data);
5365}
5366
Douglas Gregor458433d2010-08-26 15:07:07 +00005367void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5368 unsigned NumSelIdents) {
5369 // If we have an external source, load the entire class method
5370 // pool from the AST file.
5371 if (ExternalSource) {
5372 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5373 I != N; ++I) {
5374 Selector Sel = ExternalSource->GetExternalSelector(I);
5375 if (Sel.isNull() || MethodPool.count(Sel))
5376 continue;
5377
5378 ReadMethodPool(Sel);
5379 }
5380 }
5381
Douglas Gregor218937c2011-02-01 19:23:04 +00005382 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5383 CodeCompletionContext::CCC_SelectorName);
Douglas Gregor458433d2010-08-26 15:07:07 +00005384 Results.EnterNewScope();
5385 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5386 MEnd = MethodPool.end();
5387 M != MEnd; ++M) {
5388
5389 Selector Sel = M->first;
5390 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5391 continue;
5392
Douglas Gregor218937c2011-02-01 19:23:04 +00005393 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor458433d2010-08-26 15:07:07 +00005394 if (Sel.isUnarySelector()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005395 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00005396 Sel.getNameForSlot(0)));
Douglas Gregor218937c2011-02-01 19:23:04 +00005397 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005398 continue;
5399 }
5400
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005401 std::string Accumulator;
Douglas Gregor458433d2010-08-26 15:07:07 +00005402 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005403 if (I == NumSelIdents) {
5404 if (!Accumulator.empty()) {
Douglas Gregordae68752011-02-01 22:57:45 +00005405 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00005406 Accumulator));
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005407 Accumulator.clear();
5408 }
5409 }
5410
Benjamin Kramera0651c52011-07-26 16:59:25 +00005411 Accumulator += Sel.getNameForSlot(I);
Douglas Gregor2d9e21f2010-08-26 16:46:39 +00005412 Accumulator += ':';
Douglas Gregor458433d2010-08-26 15:07:07 +00005413 }
Douglas Gregordae68752011-02-01 22:57:45 +00005414 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
Douglas Gregor218937c2011-02-01 19:23:04 +00005415 Results.AddResult(Builder.TakeString());
Douglas Gregor458433d2010-08-26 15:07:07 +00005416 }
5417 Results.ExitScope();
5418
5419 HandleCodeCompleteResults(this, CodeCompleter,
5420 CodeCompletionContext::CCC_SelectorName,
5421 Results.data(), Results.size());
5422}
5423
Douglas Gregor55385fe2009-11-18 04:19:12 +00005424/// \brief Add all of the protocol declarations that we find in the given
5425/// (translation unit) context.
5426static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
Douglas Gregor083128f2009-11-18 04:49:41 +00005427 bool OnlyForwardDeclarations,
Douglas Gregor55385fe2009-11-18 04:19:12 +00005428 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005429 typedef CodeCompletionResult Result;
Douglas Gregor55385fe2009-11-18 04:19:12 +00005430
5431 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5432 DEnd = Ctx->decls_end();
5433 D != DEnd; ++D) {
5434 // Record any protocols we find.
5435 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005436 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Douglas Gregor608300b2010-01-14 16:14:35 +00005437 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005438 }
5439}
5440
5441void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5442 unsigned NumProtocols) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005443 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5444 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005445
Douglas Gregor70c23352010-12-09 21:44:02 +00005446 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5447 Results.EnterNewScope();
5448
5449 // Tell the result set to ignore all of the protocols we have
5450 // already seen.
5451 // FIXME: This doesn't work when caching code-completion results.
5452 for (unsigned I = 0; I != NumProtocols; ++I)
5453 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5454 Protocols[I].second))
5455 Results.Ignore(Protocol);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005456
Douglas Gregor70c23352010-12-09 21:44:02 +00005457 // Add all protocols.
5458 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5459 Results);
Douglas Gregor083128f2009-11-18 04:49:41 +00005460
Douglas Gregor70c23352010-12-09 21:44:02 +00005461 Results.ExitScope();
5462 }
5463
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005464 HandleCodeCompleteResults(this, CodeCompleter,
5465 CodeCompletionContext::CCC_ObjCProtocolName,
5466 Results.data(),Results.size());
Douglas Gregor083128f2009-11-18 04:49:41 +00005467}
5468
5469void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005470 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5471 CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor083128f2009-11-18 04:49:41 +00005472
Douglas Gregor70c23352010-12-09 21:44:02 +00005473 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5474 Results.EnterNewScope();
5475
5476 // Add all protocols.
5477 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5478 Results);
Douglas Gregor55385fe2009-11-18 04:19:12 +00005479
Douglas Gregor70c23352010-12-09 21:44:02 +00005480 Results.ExitScope();
5481 }
5482
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005483 HandleCodeCompleteResults(this, CodeCompleter,
5484 CodeCompletionContext::CCC_ObjCProtocolName,
5485 Results.data(),Results.size());
Douglas Gregor55385fe2009-11-18 04:19:12 +00005486}
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005487
5488/// \brief Add all of the Objective-C interface declarations that we find in
5489/// the given (translation unit) context.
5490static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5491 bool OnlyForwardDeclarations,
5492 bool OnlyUnimplemented,
5493 ResultBuilder &Results) {
John McCall0a2c5e22010-08-25 06:19:51 +00005494 typedef CodeCompletionResult Result;
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005495
5496 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5497 DEnd = Ctx->decls_end();
5498 D != DEnd; ++D) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005499 // Record any interfaces we find.
5500 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
Douglas Gregor7723fec2011-12-15 20:29:51 +00005501 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
Douglas Gregordeacbdc2010-08-11 12:19:30 +00005502 (!OnlyUnimplemented || !Class->getImplementation()))
5503 Results.AddResult(Result(Class, 0), CurContext, 0, false);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005504 }
5505}
5506
5507void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005508 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5509 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005510 Results.EnterNewScope();
5511
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005512 if (CodeCompleter->includeGlobals()) {
5513 // Add all classes.
5514 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5515 false, Results);
5516 }
5517
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005518 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005519
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005520 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005521 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005522 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005523}
5524
Douglas Gregorc83c6872010-04-15 22:33:43 +00005525void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5526 SourceLocation ClassNameLoc) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005527 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005528 CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005529 Results.EnterNewScope();
5530
5531 // Make sure that we ignore the class we're currently defining.
5532 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005533 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005534 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005535 Results.Ignore(CurClass);
5536
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005537 if (CodeCompleter->includeGlobals()) {
5538 // Add all classes.
5539 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5540 false, Results);
5541 }
5542
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005543 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005544
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005545 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005546 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005547 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005548}
5549
5550void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
Douglas Gregor218937c2011-02-01 19:23:04 +00005551 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5552 CodeCompletionContext::CCC_Other);
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005553 Results.EnterNewScope();
5554
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005555 if (CodeCompleter->includeGlobals()) {
5556 // Add all unimplemented classes.
5557 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5558 true, Results);
5559 }
5560
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005561 Results.ExitScope();
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005562
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005563 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00005564 CodeCompletionContext::CCC_ObjCInterfaceName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005565 Results.data(),Results.size());
Douglas Gregor3b49aca2009-11-18 16:26:39 +00005566}
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005567
5568void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005569 IdentifierInfo *ClassName,
5570 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005571 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005572
Douglas Gregor218937c2011-02-01 19:23:04 +00005573 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005574 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005575
5576 // Ignore any categories we find that have already been implemented by this
5577 // interface.
5578 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5579 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005580 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005581 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5582 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5583 Category = Category->getNextClassCategory())
5584 CategoryNames.insert(Category->getIdentifier());
5585
5586 // Add all of the categories we know about.
5587 Results.EnterNewScope();
5588 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5589 for (DeclContext::decl_iterator D = TU->decls_begin(),
5590 DEnd = TU->decls_end();
5591 D != DEnd; ++D)
5592 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5593 if (CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005594 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005595 Results.ExitScope();
5596
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005597 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005598 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005599 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005600}
5601
5602void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
Douglas Gregorc83c6872010-04-15 22:33:43 +00005603 IdentifierInfo *ClassName,
5604 SourceLocation ClassNameLoc) {
John McCall0a2c5e22010-08-25 06:19:51 +00005605 typedef CodeCompletionResult Result;
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005606
5607 // Find the corresponding interface. If we couldn't find the interface, the
5608 // program itself is ill-formed. However, we'll try to be helpful still by
5609 // providing the list of all of the categories we know about.
5610 NamedDecl *CurClass
Douglas Gregorc83c6872010-04-15 22:33:43 +00005611 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005612 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5613 if (!Class)
Douglas Gregorc83c6872010-04-15 22:33:43 +00005614 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005615
Douglas Gregor218937c2011-02-01 19:23:04 +00005616 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor3da626b2011-07-07 16:03:39 +00005617 CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005618
5619 // Add all of the categories that have have corresponding interface
5620 // declarations in this class and any of its superclasses, except for
5621 // already-implemented categories in the class itself.
5622 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5623 Results.EnterNewScope();
5624 bool IgnoreImplemented = true;
5625 while (Class) {
5626 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5627 Category = Category->getNextClassCategory())
5628 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5629 CategoryNames.insert(Category->getIdentifier()))
Douglas Gregor608300b2010-01-14 16:14:35 +00005630 Results.AddResult(Result(Category, 0), CurContext, 0, false);
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005631
5632 Class = Class->getSuperClass();
5633 IgnoreImplemented = false;
5634 }
5635 Results.ExitScope();
5636
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005637 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor3da626b2011-07-07 16:03:39 +00005638 CodeCompletionContext::CCC_ObjCCategoryName,
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005639 Results.data(),Results.size());
Douglas Gregor33ced0b2009-11-18 19:08:43 +00005640}
Douglas Gregor322328b2009-11-18 22:32:06 +00005641
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005642void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
John McCall0a2c5e22010-08-25 06:19:51 +00005643 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005644 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5645 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005646
5647 // Figure out where this @synthesize lives.
5648 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005649 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005650 if (!Container ||
5651 (!isa<ObjCImplementationDecl>(Container) &&
5652 !isa<ObjCCategoryImplDecl>(Container)))
5653 return;
5654
5655 // Ignore any properties that have already been implemented.
5656 for (DeclContext::decl_iterator D = Container->decls_begin(),
5657 DEnd = Container->decls_end();
5658 D != DEnd; ++D)
5659 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5660 Results.Ignore(PropertyImpl->getPropertyDecl());
5661
5662 // Add any properties that we find.
Douglas Gregor73449212010-12-09 23:01:55 +00005663 AddedPropertiesSet AddedProperties;
Douglas Gregor322328b2009-11-18 22:32:06 +00005664 Results.EnterNewScope();
5665 if (ObjCImplementationDecl *ClassImpl
5666 = dyn_cast<ObjCImplementationDecl>(Container))
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005667 AddObjCProperties(ClassImpl->getClassInterface(), false,
5668 /*AllowNullaryMethods=*/false, CurContext,
Douglas Gregor73449212010-12-09 23:01:55 +00005669 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005670 else
5671 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
Douglas Gregor4b81cde2011-05-05 15:50:42 +00005672 false, /*AllowNullaryMethods=*/false, CurContext,
5673 AddedProperties, Results);
Douglas Gregor322328b2009-11-18 22:32:06 +00005674 Results.ExitScope();
5675
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005676 HandleCodeCompleteResults(this, CodeCompleter,
5677 CodeCompletionContext::CCC_Other,
5678 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005679}
5680
5681void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005682 IdentifierInfo *PropertyName) {
John McCall0a2c5e22010-08-25 06:19:51 +00005683 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00005684 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5685 CodeCompletionContext::CCC_Other);
Douglas Gregor322328b2009-11-18 22:32:06 +00005686
5687 // Figure out where this @synthesize lives.
5688 ObjCContainerDecl *Container
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00005689 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
Douglas Gregor322328b2009-11-18 22:32:06 +00005690 if (!Container ||
5691 (!isa<ObjCImplementationDecl>(Container) &&
5692 !isa<ObjCCategoryImplDecl>(Container)))
5693 return;
5694
5695 // Figure out which interface we're looking into.
5696 ObjCInterfaceDecl *Class = 0;
5697 if (ObjCImplementationDecl *ClassImpl
5698 = dyn_cast<ObjCImplementationDecl>(Container))
5699 Class = ClassImpl->getClassInterface();
5700 else
5701 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5702 ->getClassInterface();
5703
Douglas Gregore8426052011-04-18 14:40:46 +00005704 // Determine the type of the property we're synthesizing.
5705 QualType PropertyType = Context.getObjCIdType();
5706 if (Class) {
5707 if (ObjCPropertyDecl *Property
5708 = Class->FindPropertyDeclaration(PropertyName)) {
5709 PropertyType
5710 = Property->getType().getNonReferenceType().getUnqualifiedType();
5711
5712 // Give preference to ivars
5713 Results.setPreferredType(PropertyType);
5714 }
5715 }
5716
Douglas Gregor322328b2009-11-18 22:32:06 +00005717 // Add all of the instance variables in this class and its superclasses.
5718 Results.EnterNewScope();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005719 bool SawSimilarlyNamedIvar = false;
5720 std::string NameWithPrefix;
5721 NameWithPrefix += '_';
Benjamin Kramera0651c52011-07-26 16:59:25 +00005722 NameWithPrefix += PropertyName->getName();
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005723 std::string NameWithSuffix = PropertyName->getName().str();
5724 NameWithSuffix += '_';
Douglas Gregor322328b2009-11-18 22:32:06 +00005725 for(; Class; Class = Class->getSuperClass()) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005726 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5727 Ivar = Ivar->getNextIvar()) {
Douglas Gregore8426052011-04-18 14:40:46 +00005728 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5729
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005730 // Determine whether we've seen an ivar with a name similar to the
5731 // property.
Douglas Gregore8426052011-04-18 14:40:46 +00005732 if ((PropertyName == Ivar->getIdentifier() ||
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005733 NameWithPrefix == Ivar->getName() ||
Douglas Gregore8426052011-04-18 14:40:46 +00005734 NameWithSuffix == Ivar->getName())) {
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005735 SawSimilarlyNamedIvar = true;
Douglas Gregore8426052011-04-18 14:40:46 +00005736
5737 // Reduce the priority of this result by one, to give it a slight
5738 // advantage over other results whose names don't match so closely.
5739 if (Results.size() &&
5740 Results.data()[Results.size() - 1].Kind
5741 == CodeCompletionResult::RK_Declaration &&
5742 Results.data()[Results.size() - 1].Declaration == Ivar)
5743 Results.data()[Results.size() - 1].Priority--;
5744 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005745 }
Douglas Gregor322328b2009-11-18 22:32:06 +00005746 }
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005747
5748 if (!SawSimilarlyNamedIvar) {
5749 // Create ivar result _propName, that the user can use to synthesize
Douglas Gregore8426052011-04-18 14:40:46 +00005750 // an ivar of the appropriate type.
5751 unsigned Priority = CCP_MemberDeclaration + 1;
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005752 typedef CodeCompletionResult Result;
5753 CodeCompletionAllocator &Allocator = Results.getAllocator();
5754 CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Available);
5755
Douglas Gregor8987b232011-09-27 23:30:47 +00005756 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8426052011-04-18 14:40:46 +00005757 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005758 Policy, Allocator));
Douglas Gregoraa490cb2011-04-18 14:13:53 +00005759 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5760 Results.AddResult(Result(Builder.TakeString(), Priority,
5761 CXCursor_ObjCIvarDecl));
5762 }
5763
Douglas Gregor322328b2009-11-18 22:32:06 +00005764 Results.ExitScope();
5765
Douglas Gregore6b1bb62010-08-11 21:23:17 +00005766 HandleCodeCompleteResults(this, CodeCompleter,
5767 CodeCompletionContext::CCC_Other,
5768 Results.data(),Results.size());
Douglas Gregor322328b2009-11-18 22:32:06 +00005769}
Douglas Gregore8f5a172010-04-07 00:21:17 +00005770
Douglas Gregor408be5a2010-08-25 01:08:01 +00005771// Mapping from selectors to the methods that implement that selector, along
5772// with the "in original class" flag.
5773typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5774 KnownMethodsMap;
Douglas Gregore8f5a172010-04-07 00:21:17 +00005775
5776/// \brief Find all of the methods that reside in the given container
5777/// (and its superclasses, protocols, etc.) that meet the given
5778/// criteria. Insert those methods into the map of known methods,
5779/// indexed by selector so they can be easily found.
5780static void FindImplementableMethods(ASTContext &Context,
5781 ObjCContainerDecl *Container,
5782 bool WantInstanceMethods,
5783 QualType ReturnType,
Douglas Gregor408be5a2010-08-25 01:08:01 +00005784 KnownMethodsMap &KnownMethods,
5785 bool InOriginalClass = true) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00005786 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5787 // Recurse into protocols.
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00005788 if (!IFace->hasDefinition())
5789 return;
5790
Douglas Gregore8f5a172010-04-07 00:21:17 +00005791 const ObjCList<ObjCProtocolDecl> &Protocols
5792 = IFace->getReferencedProtocols();
5793 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005794 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005795 I != E; ++I)
5796 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005797 KnownMethods, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005798
Douglas Gregorea766182010-10-18 18:21:28 +00005799 // Add methods from any class extensions and categories.
5800 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5801 Cat = Cat->getNextClassCategory())
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00005802 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5803 WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005804 KnownMethods, false);
5805
5806 // Visit the superclass.
5807 if (IFace->getSuperClass())
5808 FindImplementableMethods(Context, IFace->getSuperClass(),
5809 WantInstanceMethods, ReturnType,
5810 KnownMethods, false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005811 }
5812
5813 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5814 // Recurse into protocols.
5815 const ObjCList<ObjCProtocolDecl> &Protocols
5816 = Category->getReferencedProtocols();
5817 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
Douglas Gregorea766182010-10-18 18:21:28 +00005818 E = Protocols.end();
Douglas Gregore8f5a172010-04-07 00:21:17 +00005819 I != E; ++I)
5820 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
Douglas Gregorea766182010-10-18 18:21:28 +00005821 KnownMethods, InOriginalClass);
5822
5823 // If this category is the original class, jump to the interface.
5824 if (InOriginalClass && Category->getClassInterface())
5825 FindImplementableMethods(Context, Category->getClassInterface(),
5826 WantInstanceMethods, ReturnType, KnownMethods,
5827 false);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005828 }
5829
5830 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005831 if (Protocol->hasDefinition()) {
5832 // Recurse into protocols.
5833 const ObjCList<ObjCProtocolDecl> &Protocols
5834 = Protocol->getReferencedProtocols();
5835 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5836 E = Protocols.end();
5837 I != E; ++I)
5838 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
5839 KnownMethods, false);
5840 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00005841 }
5842
5843 // Add methods in this container. This operation occurs last because
5844 // we want the methods from this container to override any methods
5845 // we've previously seen with the same selector.
5846 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5847 MEnd = Container->meth_end();
5848 M != MEnd; ++M) {
5849 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5850 if (!ReturnType.isNull() &&
5851 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5852 continue;
5853
Douglas Gregor408be5a2010-08-25 01:08:01 +00005854 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
Douglas Gregore8f5a172010-04-07 00:21:17 +00005855 }
5856 }
5857}
5858
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005859/// \brief Add the parenthesized return or parameter type chunk to a code
5860/// completion string.
5861static void AddObjCPassingTypeChunk(QualType Type,
5862 ASTContext &Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00005863 const PrintingPolicy &Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005864 CodeCompletionBuilder &Builder) {
5865 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Douglas Gregor8987b232011-09-27 23:30:47 +00005866 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005867 Builder.getAllocator()));
5868 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5869}
5870
5871/// \brief Determine whether the given class is or inherits from a class by
5872/// the given name.
5873static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005874 StringRef Name) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005875 if (!Class)
5876 return false;
5877
5878 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
5879 return true;
5880
5881 return InheritsFromClassNamed(Class->getSuperClass(), Name);
5882}
5883
5884/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
5885/// Key-Value Observing (KVO).
5886static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
5887 bool IsInstanceMethod,
5888 QualType ReturnType,
5889 ASTContext &Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00005890 VisitedSelectorSet &KnownSelectors,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005891 ResultBuilder &Results) {
5892 IdentifierInfo *PropName = Property->getIdentifier();
5893 if (!PropName || PropName->getLength() == 0)
5894 return;
5895
Douglas Gregor8987b232011-09-27 23:30:47 +00005896 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5897
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005898 // Builder that will create each code completion.
5899 typedef CodeCompletionResult Result;
5900 CodeCompletionAllocator &Allocator = Results.getAllocator();
5901 CodeCompletionBuilder Builder(Allocator);
5902
5903 // The selector table.
5904 SelectorTable &Selectors = Context.Selectors;
5905
5906 // The property name, copied into the code completion allocation region
5907 // on demand.
5908 struct KeyHolder {
5909 CodeCompletionAllocator &Allocator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005910 StringRef Key;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005911 const char *CopiedKey;
5912
Chris Lattner5f9e2722011-07-23 10:55:15 +00005913 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005914 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
5915
5916 operator const char *() {
5917 if (CopiedKey)
5918 return CopiedKey;
5919
5920 return CopiedKey = Allocator.CopyString(Key);
5921 }
5922 } Key(Allocator, PropName->getName());
5923
5924 // The uppercased name of the property name.
5925 std::string UpperKey = PropName->getName();
5926 if (!UpperKey.empty())
5927 UpperKey[0] = toupper(UpperKey[0]);
5928
5929 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
5930 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
5931 Property->getType());
5932 bool ReturnTypeMatchesVoid
5933 = ReturnType.isNull() || ReturnType->isVoidType();
5934
5935 // Add the normal accessor -(type)key.
5936 if (IsInstanceMethod &&
Douglas Gregore74c25c2011-05-04 23:50:46 +00005937 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005938 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
5939 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00005940 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005941
5942 Builder.AddTypedTextChunk(Key);
5943 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5944 CXCursor_ObjCInstanceMethodDecl));
5945 }
5946
5947 // If we have an integral or boolean property (or the user has provided
5948 // an integral or boolean return type), add the accessor -(type)isKey.
5949 if (IsInstanceMethod &&
5950 ((!ReturnType.isNull() &&
5951 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
5952 (ReturnType.isNull() &&
5953 (Property->getType()->isIntegerType() ||
5954 Property->getType()->isBooleanType())))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005955 std::string SelectorName = (Twine("is") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005956 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005957 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005958 if (ReturnType.isNull()) {
5959 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5960 Builder.AddTextChunk("BOOL");
5961 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5962 }
5963
5964 Builder.AddTypedTextChunk(
5965 Allocator.CopyString(SelectorId->getName()));
5966 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5967 CXCursor_ObjCInstanceMethodDecl));
5968 }
5969 }
5970
5971 // Add the normal mutator.
5972 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
5973 !Property->getSetterMethodDecl()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005974 std::string SelectorName = (Twine("set") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00005975 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00005976 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005977 if (ReturnType.isNull()) {
5978 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5979 Builder.AddTextChunk("void");
5980 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5981 }
5982
5983 Builder.AddTypedTextChunk(
5984 Allocator.CopyString(SelectorId->getName()));
5985 Builder.AddTypedTextChunk(":");
Douglas Gregor8987b232011-09-27 23:30:47 +00005986 AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builder);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00005987 Builder.AddTextChunk(Key);
5988 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
5989 CXCursor_ObjCInstanceMethodDecl));
5990 }
5991 }
5992
5993 // Indexed and unordered accessors
5994 unsigned IndexedGetterPriority = CCP_CodePattern;
5995 unsigned IndexedSetterPriority = CCP_CodePattern;
5996 unsigned UnorderedGetterPriority = CCP_CodePattern;
5997 unsigned UnorderedSetterPriority = CCP_CodePattern;
5998 if (const ObjCObjectPointerType *ObjCPointer
5999 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6000 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6001 // If this interface type is not provably derived from a known
6002 // collection, penalize the corresponding completions.
6003 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6004 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6005 if (!InheritsFromClassNamed(IFace, "NSArray"))
6006 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6007 }
6008
6009 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6010 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6011 if (!InheritsFromClassNamed(IFace, "NSSet"))
6012 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6013 }
6014 }
6015 } else {
6016 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6017 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6018 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6019 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6020 }
6021
6022 // Add -(NSUInteger)countOf<key>
6023 if (IsInstanceMethod &&
6024 (ReturnType.isNull() || ReturnType->isIntegerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006025 std::string SelectorName = (Twine("countOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006026 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006027 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006028 if (ReturnType.isNull()) {
6029 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6030 Builder.AddTextChunk("NSUInteger");
6031 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6032 }
6033
6034 Builder.AddTypedTextChunk(
6035 Allocator.CopyString(SelectorId->getName()));
6036 Results.AddResult(Result(Builder.TakeString(),
6037 std::min(IndexedGetterPriority,
6038 UnorderedGetterPriority),
6039 CXCursor_ObjCInstanceMethodDecl));
6040 }
6041 }
6042
6043 // Indexed getters
6044 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6045 if (IsInstanceMethod &&
6046 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Douglas Gregor62041592011-02-17 03:19:26 +00006047 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006048 = (Twine("objectIn") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006049 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006050 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006051 if (ReturnType.isNull()) {
6052 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6053 Builder.AddTextChunk("id");
6054 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6055 }
6056
6057 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6058 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6059 Builder.AddTextChunk("NSUInteger");
6060 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6061 Builder.AddTextChunk("index");
6062 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6063 CXCursor_ObjCInstanceMethodDecl));
6064 }
6065 }
6066
6067 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6068 if (IsInstanceMethod &&
6069 (ReturnType.isNull() ||
6070 (ReturnType->isObjCObjectPointerType() &&
6071 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6072 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6073 ->getName() == "NSArray"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006074 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006075 = (Twine(Property->getName()) + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006076 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006077 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006078 if (ReturnType.isNull()) {
6079 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6080 Builder.AddTextChunk("NSArray *");
6081 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6082 }
6083
6084 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6085 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6086 Builder.AddTextChunk("NSIndexSet *");
6087 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6088 Builder.AddTextChunk("indexes");
6089 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6090 CXCursor_ObjCInstanceMethodDecl));
6091 }
6092 }
6093
6094 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6095 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006096 std::string SelectorName = (Twine("get") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006097 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006098 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006099 &Context.Idents.get("range")
6100 };
6101
Douglas Gregore74c25c2011-05-04 23:50:46 +00006102 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006103 if (ReturnType.isNull()) {
6104 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6105 Builder.AddTextChunk("void");
6106 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6107 }
6108
6109 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6110 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6111 Builder.AddPlaceholderChunk("object-type");
6112 Builder.AddTextChunk(" **");
6113 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6114 Builder.AddTextChunk("buffer");
6115 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6116 Builder.AddTypedTextChunk("range:");
6117 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6118 Builder.AddTextChunk("NSRange");
6119 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6120 Builder.AddTextChunk("inRange");
6121 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6122 CXCursor_ObjCInstanceMethodDecl));
6123 }
6124 }
6125
6126 // Mutable indexed accessors
6127
6128 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6129 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006130 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006131 IdentifierInfo *SelectorIds[2] = {
6132 &Context.Idents.get("insertObject"),
Douglas Gregor62041592011-02-17 03:19:26 +00006133 &Context.Idents.get(SelectorName)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006134 };
6135
Douglas Gregore74c25c2011-05-04 23:50:46 +00006136 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006137 if (ReturnType.isNull()) {
6138 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6139 Builder.AddTextChunk("void");
6140 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6141 }
6142
6143 Builder.AddTypedTextChunk("insertObject:");
6144 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6145 Builder.AddPlaceholderChunk("object-type");
6146 Builder.AddTextChunk(" *");
6147 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6148 Builder.AddTextChunk("object");
6149 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6150 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6151 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6152 Builder.AddPlaceholderChunk("NSUInteger");
6153 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6154 Builder.AddTextChunk("index");
6155 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6156 CXCursor_ObjCInstanceMethodDecl));
6157 }
6158 }
6159
6160 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6161 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006162 std::string SelectorName = (Twine("insert") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006163 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006164 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006165 &Context.Idents.get("atIndexes")
6166 };
6167
Douglas Gregore74c25c2011-05-04 23:50:46 +00006168 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006169 if (ReturnType.isNull()) {
6170 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6171 Builder.AddTextChunk("void");
6172 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6173 }
6174
6175 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6176 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6177 Builder.AddTextChunk("NSArray *");
6178 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6179 Builder.AddTextChunk("array");
6180 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6181 Builder.AddTypedTextChunk("atIndexes:");
6182 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6183 Builder.AddPlaceholderChunk("NSIndexSet *");
6184 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6185 Builder.AddTextChunk("indexes");
6186 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6187 CXCursor_ObjCInstanceMethodDecl));
6188 }
6189 }
6190
6191 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6192 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006193 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006194 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006195 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006196 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006197 if (ReturnType.isNull()) {
6198 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6199 Builder.AddTextChunk("void");
6200 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6201 }
6202
6203 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6204 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6205 Builder.AddTextChunk("NSUInteger");
6206 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6207 Builder.AddTextChunk("index");
6208 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6209 CXCursor_ObjCInstanceMethodDecl));
6210 }
6211 }
6212
6213 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6214 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006215 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006216 = (Twine("remove") + UpperKey + "AtIndexes").str();
Douglas Gregor62041592011-02-17 03:19:26 +00006217 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006218 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006219 if (ReturnType.isNull()) {
6220 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6221 Builder.AddTextChunk("void");
6222 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6223 }
6224
6225 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6226 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6227 Builder.AddTextChunk("NSIndexSet *");
6228 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6229 Builder.AddTextChunk("indexes");
6230 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6231 CXCursor_ObjCInstanceMethodDecl));
6232 }
6233 }
6234
6235 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6236 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006237 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006238 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006239 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006240 &Context.Idents.get(SelectorName),
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006241 &Context.Idents.get("withObject")
6242 };
6243
Douglas Gregore74c25c2011-05-04 23:50:46 +00006244 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006245 if (ReturnType.isNull()) {
6246 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6247 Builder.AddTextChunk("void");
6248 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6249 }
6250
6251 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6252 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6253 Builder.AddPlaceholderChunk("NSUInteger");
6254 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6255 Builder.AddTextChunk("index");
6256 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6257 Builder.AddTypedTextChunk("withObject:");
6258 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6259 Builder.AddTextChunk("id");
6260 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6261 Builder.AddTextChunk("object");
6262 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6263 CXCursor_ObjCInstanceMethodDecl));
6264 }
6265 }
6266
6267 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6268 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006269 std::string SelectorName1
Chris Lattner5f9e2722011-07-23 10:55:15 +00006270 = (Twine("replace") + UpperKey + "AtIndexes").str();
6271 std::string SelectorName2 = (Twine("with") + UpperKey).str();
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006272 IdentifierInfo *SelectorIds[2] = {
Douglas Gregor62041592011-02-17 03:19:26 +00006273 &Context.Idents.get(SelectorName1),
6274 &Context.Idents.get(SelectorName2)
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006275 };
6276
Douglas Gregore74c25c2011-05-04 23:50:46 +00006277 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006278 if (ReturnType.isNull()) {
6279 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6280 Builder.AddTextChunk("void");
6281 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6282 }
6283
6284 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6285 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6286 Builder.AddPlaceholderChunk("NSIndexSet *");
6287 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6288 Builder.AddTextChunk("indexes");
6289 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6290 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6291 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6292 Builder.AddTextChunk("NSArray *");
6293 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6294 Builder.AddTextChunk("array");
6295 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6296 CXCursor_ObjCInstanceMethodDecl));
6297 }
6298 }
6299
6300 // Unordered getters
6301 // - (NSEnumerator *)enumeratorOfKey
6302 if (IsInstanceMethod &&
6303 (ReturnType.isNull() ||
6304 (ReturnType->isObjCObjectPointerType() &&
6305 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6306 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6307 ->getName() == "NSEnumerator"))) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006308 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006309 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006310 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006311 if (ReturnType.isNull()) {
6312 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6313 Builder.AddTextChunk("NSEnumerator *");
6314 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6315 }
6316
6317 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6318 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6319 CXCursor_ObjCInstanceMethodDecl));
6320 }
6321 }
6322
6323 // - (type *)memberOfKey:(type *)object
6324 if (IsInstanceMethod &&
6325 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006326 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006327 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006328 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006329 if (ReturnType.isNull()) {
6330 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6331 Builder.AddPlaceholderChunk("object-type");
6332 Builder.AddTextChunk(" *");
6333 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6334 }
6335
6336 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6337 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6338 if (ReturnType.isNull()) {
6339 Builder.AddPlaceholderChunk("object-type");
6340 Builder.AddTextChunk(" *");
6341 } else {
6342 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
Douglas Gregor8987b232011-09-27 23:30:47 +00006343 Policy,
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006344 Builder.getAllocator()));
6345 }
6346 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6347 Builder.AddTextChunk("object");
6348 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6349 CXCursor_ObjCInstanceMethodDecl));
6350 }
6351 }
6352
6353 // Mutable unordered accessors
6354 // - (void)addKeyObject:(type *)object
6355 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006356 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006357 = (Twine("add") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006358 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006359 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006360 if (ReturnType.isNull()) {
6361 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6362 Builder.AddTextChunk("void");
6363 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6364 }
6365
6366 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6367 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6368 Builder.AddPlaceholderChunk("object-type");
6369 Builder.AddTextChunk(" *");
6370 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6371 Builder.AddTextChunk("object");
6372 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6373 CXCursor_ObjCInstanceMethodDecl));
6374 }
6375 }
6376
6377 // - (void)addKey:(NSSet *)objects
6378 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006379 std::string SelectorName = (Twine("add") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006380 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006381 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006382 if (ReturnType.isNull()) {
6383 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6384 Builder.AddTextChunk("void");
6385 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6386 }
6387
6388 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6389 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6390 Builder.AddTextChunk("NSSet *");
6391 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6392 Builder.AddTextChunk("objects");
6393 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6394 CXCursor_ObjCInstanceMethodDecl));
6395 }
6396 }
6397
6398 // - (void)removeKeyObject:(type *)object
6399 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Douglas Gregor62041592011-02-17 03:19:26 +00006400 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006401 = (Twine("remove") + UpperKey + Twine("Object")).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006402 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006403 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006404 if (ReturnType.isNull()) {
6405 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6406 Builder.AddTextChunk("void");
6407 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6408 }
6409
6410 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6411 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6412 Builder.AddPlaceholderChunk("object-type");
6413 Builder.AddTextChunk(" *");
6414 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6415 Builder.AddTextChunk("object");
6416 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6417 CXCursor_ObjCInstanceMethodDecl));
6418 }
6419 }
6420
6421 // - (void)removeKey:(NSSet *)objects
6422 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006423 std::string SelectorName = (Twine("remove") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006424 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006425 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006426 if (ReturnType.isNull()) {
6427 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6428 Builder.AddTextChunk("void");
6429 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6430 }
6431
6432 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6433 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6434 Builder.AddTextChunk("NSSet *");
6435 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6436 Builder.AddTextChunk("objects");
6437 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6438 CXCursor_ObjCInstanceMethodDecl));
6439 }
6440 }
6441
6442 // - (void)intersectKey:(NSSet *)objects
6443 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006444 std::string SelectorName = (Twine("intersect") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006445 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006446 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006447 if (ReturnType.isNull()) {
6448 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6449 Builder.AddTextChunk("void");
6450 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6451 }
6452
6453 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6454 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6455 Builder.AddTextChunk("NSSet *");
6456 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6457 Builder.AddTextChunk("objects");
6458 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6459 CXCursor_ObjCInstanceMethodDecl));
6460 }
6461 }
6462
6463 // Key-Value Observing
6464 // + (NSSet *)keyPathsForValuesAffectingKey
6465 if (!IsInstanceMethod &&
6466 (ReturnType.isNull() ||
6467 (ReturnType->isObjCObjectPointerType() &&
6468 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6469 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6470 ->getName() == "NSSet"))) {
Douglas Gregor62041592011-02-17 03:19:26 +00006471 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006472 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
Douglas Gregor62041592011-02-17 03:19:26 +00006473 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
Douglas Gregore74c25c2011-05-04 23:50:46 +00006474 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006475 if (ReturnType.isNull()) {
6476 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6477 Builder.AddTextChunk("NSSet *");
6478 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6479 }
6480
6481 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6482 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
Douglas Gregor3f828d12011-06-02 04:02:27 +00006483 CXCursor_ObjCClassMethodDecl));
6484 }
6485 }
6486
6487 // + (BOOL)automaticallyNotifiesObserversForKey
6488 if (!IsInstanceMethod &&
6489 (ReturnType.isNull() ||
6490 ReturnType->isIntegerType() ||
6491 ReturnType->isBooleanType())) {
6492 std::string SelectorName
Chris Lattner5f9e2722011-07-23 10:55:15 +00006493 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
Douglas Gregor3f828d12011-06-02 04:02:27 +00006494 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6495 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6496 if (ReturnType.isNull()) {
6497 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6498 Builder.AddTextChunk("BOOL");
6499 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6500 }
6501
6502 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6503 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6504 CXCursor_ObjCClassMethodDecl));
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006505 }
6506 }
6507}
6508
Douglas Gregore8f5a172010-04-07 00:21:17 +00006509void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6510 bool IsInstanceMethod,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006511 ParsedType ReturnTy) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006512 // Determine the return type of the method we're declaring, if
6513 // provided.
6514 QualType ReturnType = GetTypeFromParser(ReturnTy);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00006515 Decl *IDecl = 0;
6516 if (CurContext->isObjCContainer()) {
6517 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6518 IDecl = cast<Decl>(OCD);
6519 }
Douglas Gregorea766182010-10-18 18:21:28 +00006520 // Determine where we should start searching for methods.
6521 ObjCContainerDecl *SearchDecl = 0;
Douglas Gregore8f5a172010-04-07 00:21:17 +00006522 bool IsInImplementation = false;
John McCalld226f652010-08-21 09:40:31 +00006523 if (Decl *D = IDecl) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006524 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6525 SearchDecl = Impl->getClassInterface();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006526 IsInImplementation = true;
6527 } else if (ObjCCategoryImplDecl *CatImpl
Douglas Gregorea766182010-10-18 18:21:28 +00006528 = dyn_cast<ObjCCategoryImplDecl>(D)) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006529 SearchDecl = CatImpl->getCategoryDecl();
Douglas Gregore8f5a172010-04-07 00:21:17 +00006530 IsInImplementation = true;
Douglas Gregorea766182010-10-18 18:21:28 +00006531 } else
Douglas Gregore8f5a172010-04-07 00:21:17 +00006532 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006533 }
6534
6535 if (!SearchDecl && S) {
Douglas Gregorea766182010-10-18 18:21:28 +00006536 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
Douglas Gregore8f5a172010-04-07 00:21:17 +00006537 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006538 }
6539
Douglas Gregorea766182010-10-18 18:21:28 +00006540 if (!SearchDecl) {
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006541 HandleCodeCompleteResults(this, CodeCompleter,
6542 CodeCompletionContext::CCC_Other,
6543 0, 0);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006544 return;
6545 }
6546
6547 // Find all of the methods that we could declare/implement here.
6548 KnownMethodsMap KnownMethods;
6549 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
Douglas Gregorea766182010-10-18 18:21:28 +00006550 ReturnType, KnownMethods);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006551
Douglas Gregore8f5a172010-04-07 00:21:17 +00006552 // Add declarations or definitions for each of the known methods.
John McCall0a2c5e22010-08-25 06:19:51 +00006553 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006554 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6555 CodeCompletionContext::CCC_Other);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006556 Results.EnterNewScope();
Douglas Gregor8987b232011-09-27 23:30:47 +00006557 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006558 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6559 MEnd = KnownMethods.end();
6560 M != MEnd; ++M) {
Douglas Gregor408be5a2010-08-25 01:08:01 +00006561 ObjCMethodDecl *Method = M->second.first;
Douglas Gregor218937c2011-02-01 19:23:04 +00006562 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006563
6564 // If the result type was not already provided, add it to the
6565 // pattern as (type).
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006566 if (ReturnType.isNull())
Douglas Gregor8987b232011-09-27 23:30:47 +00006567 AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,
6568 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006569
6570 Selector Sel = Method->getSelector();
6571
6572 // Add the first part of the selector to the pattern.
Douglas Gregordae68752011-02-01 22:57:45 +00006573 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor813d8342011-02-18 22:29:55 +00006574 Sel.getNameForSlot(0)));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006575
6576 // Add parameters to the pattern.
6577 unsigned I = 0;
6578 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6579 PEnd = Method->param_end();
6580 P != PEnd; (void)++P, ++I) {
6581 // Add the part of the selector name.
6582 if (I == 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006583 Builder.AddTypedTextChunk(":");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006584 else if (I < Sel.getNumArgs()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006585 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6586 Builder.AddTypedTextChunk(
Douglas Gregor813d8342011-02-18 22:29:55 +00006587 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006588 } else
6589 break;
6590
6591 // Add the parameter type.
Douglas Gregor8987b232011-09-27 23:30:47 +00006592 AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,
6593 Builder);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006594
6595 if (IdentifierInfo *Id = (*P)->getIdentifier())
Douglas Gregordae68752011-02-01 22:57:45 +00006596 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006597 }
6598
6599 if (Method->isVariadic()) {
6600 if (Method->param_size() > 0)
Douglas Gregor218937c2011-02-01 19:23:04 +00006601 Builder.AddChunk(CodeCompletionString::CK_Comma);
6602 Builder.AddTextChunk("...");
Douglas Gregore17794f2010-08-31 05:13:43 +00006603 }
Douglas Gregore8f5a172010-04-07 00:21:17 +00006604
Douglas Gregor447107d2010-05-28 00:57:46 +00006605 if (IsInImplementation && Results.includeCodePatterns()) {
Douglas Gregore8f5a172010-04-07 00:21:17 +00006606 // We will be defining the method here, so add a compound statement.
Douglas Gregor218937c2011-02-01 19:23:04 +00006607 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6608 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6609 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006610 if (!Method->getResultType()->isVoidType()) {
6611 // If the result type is not void, add a return clause.
Douglas Gregor218937c2011-02-01 19:23:04 +00006612 Builder.AddTextChunk("return");
6613 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6614 Builder.AddPlaceholderChunk("expression");
6615 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006616 } else
Douglas Gregor218937c2011-02-01 19:23:04 +00006617 Builder.AddPlaceholderChunk("statements");
Douglas Gregore8f5a172010-04-07 00:21:17 +00006618
Douglas Gregor218937c2011-02-01 19:23:04 +00006619 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6620 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Douglas Gregore8f5a172010-04-07 00:21:17 +00006621 }
6622
Douglas Gregor408be5a2010-08-25 01:08:01 +00006623 unsigned Priority = CCP_CodePattern;
6624 if (!M->second.second)
6625 Priority += CCD_InBaseClass;
6626
Douglas Gregor218937c2011-02-01 19:23:04 +00006627 Results.AddResult(Result(Builder.TakeString(), Priority,
Douglas Gregor16ed9ad2010-08-17 16:06:07 +00006628 Method->isInstanceMethod()
6629 ? CXCursor_ObjCInstanceMethodDecl
6630 : CXCursor_ObjCClassMethodDecl));
Douglas Gregore8f5a172010-04-07 00:21:17 +00006631 }
6632
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006633 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6634 // the properties in this class and its categories.
6635 if (Context.getLangOptions().ObjC2) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006636 SmallVector<ObjCContainerDecl *, 4> Containers;
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006637 Containers.push_back(SearchDecl);
6638
Douglas Gregore74c25c2011-05-04 23:50:46 +00006639 VisitedSelectorSet KnownSelectors;
6640 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6641 MEnd = KnownMethods.end();
6642 M != MEnd; ++M)
6643 KnownSelectors.insert(M->first);
6644
6645
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006646 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6647 if (!IFace)
6648 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6649 IFace = Category->getClassInterface();
6650
6651 if (IFace) {
6652 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6653 Category = Category->getNextClassCategory())
6654 Containers.push_back(Category);
6655 }
6656
6657 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6658 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6659 PEnd = Containers[I]->prop_end();
6660 P != PEnd; ++P) {
6661 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
Douglas Gregore74c25c2011-05-04 23:50:46 +00006662 KnownSelectors, Results);
Douglas Gregor577cdfd2011-02-17 00:22:45 +00006663 }
6664 }
6665 }
6666
Douglas Gregore8f5a172010-04-07 00:21:17 +00006667 Results.ExitScope();
6668
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006669 HandleCodeCompleteResults(this, CodeCompleter,
6670 CodeCompletionContext::CCC_Other,
6671 Results.data(),Results.size());
Douglas Gregore8f5a172010-04-07 00:21:17 +00006672}
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006673
6674void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6675 bool IsInstanceMethod,
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006676 bool AtParameterName,
John McCallb3d87482010-08-24 05:47:05 +00006677 ParsedType ReturnTy,
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006678 IdentifierInfo **SelIdents,
6679 unsigned NumSelIdents) {
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006680 // If we have an external source, load the entire class method
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006681 // pool from the AST file.
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006682 if (ExternalSource) {
6683 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6684 I != N; ++I) {
6685 Selector Sel = ExternalSource->GetExternalSelector(I);
Sebastian Redldb9d2142010-08-02 23:18:59 +00006686 if (Sel.isNull() || MethodPool.count(Sel))
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006687 continue;
Sebastian Redldb9d2142010-08-02 23:18:59 +00006688
6689 ReadMethodPool(Sel);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006690 }
6691 }
6692
6693 // Build the set of methods we can see.
John McCall0a2c5e22010-08-25 06:19:51 +00006694 typedef CodeCompletionResult Result;
Douglas Gregor218937c2011-02-01 19:23:04 +00006695 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6696 CodeCompletionContext::CCC_Other);
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006697
6698 if (ReturnTy)
6699 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
Sebastian Redldb9d2142010-08-02 23:18:59 +00006700
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006701 Results.EnterNewScope();
Sebastian Redldb9d2142010-08-02 23:18:59 +00006702 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6703 MEnd = MethodPool.end();
6704 M != MEnd; ++M) {
6705 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6706 &M->second.second;
6707 MethList && MethList->Method;
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006708 MethList = MethList->Next) {
6709 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6710 NumSelIdents))
6711 continue;
6712
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006713 if (AtParameterName) {
6714 // Suggest parameter names we've seen before.
6715 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6716 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6717 if (Param->getIdentifier()) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006718 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregordae68752011-02-01 22:57:45 +00006719 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006720 Param->getIdentifier()->getName()));
6721 Results.AddResult(Builder.TakeString());
Douglas Gregor40ed9a12010-07-08 23:37:41 +00006722 }
6723 }
6724
6725 continue;
6726 }
6727
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006728 Result R(MethList->Method, 0);
6729 R.StartParameter = NumSelIdents;
6730 R.AllParametersAreInformative = false;
6731 R.DeclaringEntity = true;
6732 Results.MaybeAddResult(R, CurContext);
6733 }
6734 }
6735
6736 Results.ExitScope();
Douglas Gregore6b1bb62010-08-11 21:23:17 +00006737 HandleCodeCompleteResults(this, CodeCompleter,
6738 CodeCompletionContext::CCC_Other,
6739 Results.data(),Results.size());
Douglas Gregor1f5537a2010-07-08 23:20:03 +00006740}
Douglas Gregor87c08a52010-08-13 22:48:40 +00006741
Douglas Gregorf29c5232010-08-24 22:20:20 +00006742void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006743 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006744 CodeCompletionContext::CCC_PreprocessorDirective);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006745 Results.EnterNewScope();
6746
6747 // #if <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006748 CodeCompletionBuilder Builder(Results.getAllocator());
6749 Builder.AddTypedTextChunk("if");
6750 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6751 Builder.AddPlaceholderChunk("condition");
6752 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006753
6754 // #ifdef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006755 Builder.AddTypedTextChunk("ifdef");
6756 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6757 Builder.AddPlaceholderChunk("macro");
6758 Results.AddResult(Builder.TakeString());
6759
Douglas Gregorf44e8542010-08-24 19:08:16 +00006760 // #ifndef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006761 Builder.AddTypedTextChunk("ifndef");
6762 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6763 Builder.AddPlaceholderChunk("macro");
6764 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006765
6766 if (InConditional) {
6767 // #elif <condition>
Douglas Gregor218937c2011-02-01 19:23:04 +00006768 Builder.AddTypedTextChunk("elif");
6769 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6770 Builder.AddPlaceholderChunk("condition");
6771 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006772
6773 // #else
Douglas Gregor218937c2011-02-01 19:23:04 +00006774 Builder.AddTypedTextChunk("else");
6775 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006776
6777 // #endif
Douglas Gregor218937c2011-02-01 19:23:04 +00006778 Builder.AddTypedTextChunk("endif");
6779 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006780 }
6781
6782 // #include "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006783 Builder.AddTypedTextChunk("include");
6784 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6785 Builder.AddTextChunk("\"");
6786 Builder.AddPlaceholderChunk("header");
6787 Builder.AddTextChunk("\"");
6788 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006789
6790 // #include <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006791 Builder.AddTypedTextChunk("include");
6792 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6793 Builder.AddTextChunk("<");
6794 Builder.AddPlaceholderChunk("header");
6795 Builder.AddTextChunk(">");
6796 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006797
6798 // #define <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006799 Builder.AddTypedTextChunk("define");
6800 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6801 Builder.AddPlaceholderChunk("macro");
6802 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006803
6804 // #define <macro>(<args>)
Douglas Gregor218937c2011-02-01 19:23:04 +00006805 Builder.AddTypedTextChunk("define");
6806 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6807 Builder.AddPlaceholderChunk("macro");
6808 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6809 Builder.AddPlaceholderChunk("args");
6810 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6811 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006812
6813 // #undef <macro>
Douglas Gregor218937c2011-02-01 19:23:04 +00006814 Builder.AddTypedTextChunk("undef");
6815 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6816 Builder.AddPlaceholderChunk("macro");
6817 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006818
6819 // #line <number>
Douglas Gregor218937c2011-02-01 19:23:04 +00006820 Builder.AddTypedTextChunk("line");
6821 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6822 Builder.AddPlaceholderChunk("number");
6823 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006824
6825 // #line <number> "filename"
Douglas Gregor218937c2011-02-01 19:23:04 +00006826 Builder.AddTypedTextChunk("line");
6827 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6828 Builder.AddPlaceholderChunk("number");
6829 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6830 Builder.AddTextChunk("\"");
6831 Builder.AddPlaceholderChunk("filename");
6832 Builder.AddTextChunk("\"");
6833 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006834
6835 // #error <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006836 Builder.AddTypedTextChunk("error");
6837 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6838 Builder.AddPlaceholderChunk("message");
6839 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006840
6841 // #pragma <arguments>
Douglas Gregor218937c2011-02-01 19:23:04 +00006842 Builder.AddTypedTextChunk("pragma");
6843 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6844 Builder.AddPlaceholderChunk("arguments");
6845 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006846
6847 if (getLangOptions().ObjC1) {
6848 // #import "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006849 Builder.AddTypedTextChunk("import");
6850 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6851 Builder.AddTextChunk("\"");
6852 Builder.AddPlaceholderChunk("header");
6853 Builder.AddTextChunk("\"");
6854 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006855
6856 // #import <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006857 Builder.AddTypedTextChunk("import");
6858 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6859 Builder.AddTextChunk("<");
6860 Builder.AddPlaceholderChunk("header");
6861 Builder.AddTextChunk(">");
6862 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006863 }
6864
6865 // #include_next "header"
Douglas Gregor218937c2011-02-01 19:23:04 +00006866 Builder.AddTypedTextChunk("include_next");
6867 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6868 Builder.AddTextChunk("\"");
6869 Builder.AddPlaceholderChunk("header");
6870 Builder.AddTextChunk("\"");
6871 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006872
6873 // #include_next <header>
Douglas Gregor218937c2011-02-01 19:23:04 +00006874 Builder.AddTypedTextChunk("include_next");
6875 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6876 Builder.AddTextChunk("<");
6877 Builder.AddPlaceholderChunk("header");
6878 Builder.AddTextChunk(">");
6879 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006880
6881 // #warning <message>
Douglas Gregor218937c2011-02-01 19:23:04 +00006882 Builder.AddTypedTextChunk("warning");
6883 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6884 Builder.AddPlaceholderChunk("message");
6885 Results.AddResult(Builder.TakeString());
Douglas Gregorf44e8542010-08-24 19:08:16 +00006886
6887 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
6888 // completions for them. And __include_macros is a Clang-internal extension
6889 // that we don't want to encourage anyone to use.
6890
6891 // FIXME: we don't support #assert or #unassert, so don't suggest them.
6892 Results.ExitScope();
6893
Douglas Gregorf44e8542010-08-24 19:08:16 +00006894 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregor721f3592010-08-25 18:41:16 +00006895 CodeCompletionContext::CCC_PreprocessorDirective,
Douglas Gregorf44e8542010-08-24 19:08:16 +00006896 Results.data(), Results.size());
6897}
6898
6899void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
Douglas Gregorf29c5232010-08-24 22:20:20 +00006900 CodeCompleteOrdinaryName(S,
John McCallf312b1e2010-08-26 23:41:50 +00006901 S->getFnParent()? Sema::PCC_RecoveryInFunction
6902 : Sema::PCC_Namespace);
Douglas Gregorf44e8542010-08-24 19:08:16 +00006903}
6904
Douglas Gregorf29c5232010-08-24 22:20:20 +00006905void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006906 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006907 IsDefinition? CodeCompletionContext::CCC_MacroName
6908 : CodeCompletionContext::CCC_MacroNameUse);
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006909 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
6910 // Add just the names of macros, not their arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00006911 CodeCompletionBuilder Builder(Results.getAllocator());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006912 Results.EnterNewScope();
6913 for (Preprocessor::macro_iterator M = PP.macro_begin(),
6914 MEnd = PP.macro_end();
6915 M != MEnd; ++M) {
Douglas Gregordae68752011-02-01 22:57:45 +00006916 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Douglas Gregor218937c2011-02-01 19:23:04 +00006917 M->first->getName()));
6918 Results.AddResult(Builder.TakeString());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006919 }
6920 Results.ExitScope();
6921 } else if (IsDefinition) {
6922 // FIXME: Can we detect when the user just wrote an include guard above?
6923 }
6924
Douglas Gregor52779fb2010-09-23 23:01:17 +00006925 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00006926 Results.data(), Results.size());
6927}
6928
Douglas Gregorf29c5232010-08-24 22:20:20 +00006929void Sema::CodeCompletePreprocessorExpression() {
Douglas Gregor218937c2011-02-01 19:23:04 +00006930 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
Douglas Gregor52779fb2010-09-23 23:01:17 +00006931 CodeCompletionContext::CCC_PreprocessorExpression);
Douglas Gregorf29c5232010-08-24 22:20:20 +00006932
6933 if (!CodeCompleter || CodeCompleter->includeMacros())
6934 AddMacroResults(PP, Results);
6935
6936 // defined (<macro>)
6937 Results.EnterNewScope();
Douglas Gregor218937c2011-02-01 19:23:04 +00006938 CodeCompletionBuilder Builder(Results.getAllocator());
6939 Builder.AddTypedTextChunk("defined");
6940 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6941 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6942 Builder.AddPlaceholderChunk("macro");
6943 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6944 Results.AddResult(Builder.TakeString());
Douglas Gregorf29c5232010-08-24 22:20:20 +00006945 Results.ExitScope();
6946
6947 HandleCodeCompleteResults(this, CodeCompleter,
6948 CodeCompletionContext::CCC_PreprocessorExpression,
6949 Results.data(), Results.size());
6950}
6951
6952void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
6953 IdentifierInfo *Macro,
6954 MacroInfo *MacroInfo,
6955 unsigned Argument) {
6956 // FIXME: In the future, we could provide "overload" results, much like we
6957 // do for function calls.
6958
Argyrios Kyrtzidis5c5f03e2011-08-18 19:41:28 +00006959 // Now just ignore this. There will be another code-completion callback
6960 // for the expanded tokens.
Douglas Gregorf29c5232010-08-24 22:20:20 +00006961}
6962
Douglas Gregor55817af2010-08-25 17:04:25 +00006963void Sema::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +00006964 HandleCodeCompleteResults(this, CodeCompleter,
Douglas Gregoraf1c6b52010-08-25 17:10:00 +00006965 CodeCompletionContext::CCC_NaturalLanguage,
Douglas Gregor55817af2010-08-25 17:04:25 +00006966 0, 0);
6967}
6968
Douglas Gregordae68752011-02-01 22:57:45 +00006969void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006970 SmallVectorImpl<CodeCompletionResult> &Results) {
Douglas Gregor218937c2011-02-01 19:23:04 +00006971 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery);
Douglas Gregor8071e422010-08-15 06:18:01 +00006972 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
6973 CodeCompletionDeclConsumer Consumer(Builder,
6974 Context.getTranslationUnitDecl());
6975 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
6976 Consumer);
6977 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00006978
6979 if (!CodeCompleter || CodeCompleter->includeMacros())
6980 AddMacroResults(PP, Builder);
6981
6982 Results.clear();
6983 Results.insert(Results.end(),
6984 Builder.data(), Builder.data() + Builder.size());
6985}